code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
package com.joy.app.utils; import android.os.Environment; import java.io.File; /** * 一些目录相关,缓存目录的记录 * User: liulongzhenhai(longzhenhai.liu@qyer.com) * Date: 2015-11-10 */ public class StorageUtil { private static final String HOME_DIR = "/joy/";// 大应用主目录 private static final String WEBVIEW_DIR = "/joy/webview_cache/"; private static final String QYER_TEMP = HOME_DIR + "tmp";// 临时的目录,存放其他临时东西 public static File getExStorageDir() { return Environment.getExternalStorageDirectory(); } public static String getWebViewCachePath() { final String path = new StringBuilder(Environment.getExternalStorageDirectory().toString()).append(WEBVIEW_DIR) .toString(); final File dirFile = new File(path); if (!dirFile.exists()) { dirFile.mkdirs(); } return path; } public static File getQyerTempDir() { File qyerTemp = new File(getExStorageDir(), QYER_TEMP); if (!qyerTemp.exists()) { qyerTemp.mkdirs(); } return qyerTemp; } }
joy-inc/joy-app
app/src/main/java/com/joy/app/utils/StorageUtil.java
Java
apache-2.0
1,150
/* * ================================================================================================= * Copyright (C) 2014 Martin Albedinsky * ================================================================================================= * Licensed under the Apache License, Version 2.0 or later (further "License" only). * ------------------------------------------------------------------------------------------------- * You may use this file only in compliance with the License. More details and copy of this License * you may obtain at * * http://www.apache.org/licenses/LICENSE-2.0 * * You can redistribute, modify or publish any part of the code written within this file but as it * is described in the License, the software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES or CONDITIONS OF ANY KIND. * * See the License for the specific language governing permissions and limitations under the License. * ================================================================================================= */ package com.albedinsky.android.fragment.examples.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v4.view.MenuItemCompat; import android.view.Menu; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.albedinsky.android.fragment.examples.R; import com.albedinsky.android.fragment.manage.FragmentTransition; import com.albedinsky.android.ui.widget.adapter.SimpleSpinnerAdapter; import java.util.ArrayList; import java.util.List; /** * @author Martin Albedinsky */ public final class TransitionsAdapter extends SimpleSpinnerAdapter<FragmentTransition, TextView, TextView> { @SuppressWarnings("unused") private static final String TAG = "TransitionsAdapter"; public TransitionsAdapter(Context context) { super(context); final List<FragmentTransition> items = new ArrayList<>(14); items.add(FragmentTransition.NONE); items.add(FragmentTransition.CROSS_FADE); items.add(FragmentTransition.SLIDE_TO_LEFT); items.add(FragmentTransition.SLIDE_TO_RIGHT); items.add(FragmentTransition.SLIDE_TO_BOTTOM); items.add(FragmentTransition.SLIDE_TO_TOP); items.add(FragmentTransition.SLIDE_TO_LEFT_AND_SCALE_OUT); items.add(FragmentTransition.SLIDE_TO_RIGHT_AND_SCALE_OUT); items.add(FragmentTransition.SLIDE_TO_BOTTOM_AND_SCALE_OUT); items.add(FragmentTransition.SLIDE_TO_TOP_AND_SCALE_OUT); items.add(FragmentTransition.SCALE_IN_AND_SLIDE_TO_LEFT); items.add(FragmentTransition.SCALE_IN_AND_SLIDE_TO_RIGHT); items.add(FragmentTransition.SCALE_IN_AND_SLIDE_TO_BOTTOM); items.add(FragmentTransition.SCALE_IN_AND_SLIDE_TO_TOP); changeItems(items); } @NonNull @Override protected View onCreateView(@NonNull ViewGroup parent, int position) { return inflate(R.layout.item_spinner_transition, parent); } @Override protected void onBindViewHolder(@NonNull TextView view, int position) { super.onBindViewHolder(view, position); view.setPadding(0, 0, 0, 0); } @Override protected void onUpdateViewHolder(@NonNull TextView view, @NonNull FragmentTransition transition, int position) { view.setText(transition.name); } @SuppressWarnings("ConstantConditions") public Menu populateMenu(Menu menu) { final SubMenu subMenu = menu.addSubMenu(Menu.NONE, -1, 0, mResources.getString(R.string.transitions_menu_title)); MenuItemCompat.setShowAsAction( subMenu.getItem().setIcon(R.drawable.ic_action_action_open_with), MenuItemCompat.SHOW_AS_ACTION_ALWAYS ); // Fill sub-menu with items of this adapter. final List<FragmentTransition> transitions = getItems(); for (int i = 0; i < transitions.size(); i++) { final FragmentTransition transition = transitions.get(i); subMenu.add(Menu.NONE, i, Menu.NONE, replaceUnderscoreInName(transition)); } return menu; } private String replaceUnderscoreInName(FragmentTransition transition) { return transition.name.replace("_", " "); } }
android-libraries/android_fragments
examples/src/main/java/com/albedinsky/android/fragment/examples/adapter/TransitionsAdapter.java
Java
apache-2.0
4,096
package org.vaadin.suggestfield.client; import java.io.Serializable; public class SuggestFieldSuggestion implements Serializable { private static final long serialVersionUID = -2477614164160415074L; private String id; private String displayString; private String replacementString; public SuggestFieldSuggestion() { } public SuggestFieldSuggestion(String id, String displayString, String replacementString) { super(); this.id = id; this.displayString = displayString; this.replacementString = replacementString; } public String getDisplayString() { return displayString; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setDisplayString(String displayString) { this.displayString = displayString; } public String getReplacementString() { return replacementString; } public void setReplacementString(String replacementString) { this.replacementString = replacementString; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SuggestFieldSuggestion other = (SuggestFieldSuggestion) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
markoradinovic/suggestfield
suggestfield/src/main/java/org/vaadin/suggestfield/client/SuggestFieldSuggestion.java
Java
apache-2.0
1,584
/** * Copyright 2014 Diego Ceccarelli * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Copyright 2014 Diego Ceccarelli * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package it.unipi.di.acube.smaph.datasets.wikitofreebase; import static org.junit.Assert.assertEquals; import org.junit.Test; import it.unipi.di.acube.smaph.datasets.wikitofreebase.WikipediaLabelToFreebaseRecord; /** * @author Diego Ceccarelli <diego.ceccarelli@isti.cnr.it> * * Created on Mar 15, 2014 */ public class WikipediaLabelToFreebaseIdTest { @Test public void test() { WikipediaLabelToFreebaseRecord converter = new WikipediaLabelToFreebaseRecord(); assertEquals( "/wikipedia/en_title/101_Dalmatians_(1996_film)", converter .convert("/wikipedia/en_title/101_Dalmatians_$00281996_film$0029")); assertEquals("/wikipedia/en_title/C._Z._Guest", converter.convert("/wikipedia/en_title/C$002E_Z$002E_Guest")); assertEquals("/wikipedia/en_title/Takashi_Kondō", converter.convert("/wikipedia/en_title/Takashi_Kond$014D")); } @Test public void parse() { WikipediaLabelToFreebaseRecord record = WikipediaLabelToFreebaseRecord .parse("/m/02qlpsg\t\"Ferris Jacobs, Jr.\"@en\t\"/wikipedia/en_title/Ferris_Jacobs$002C_Jr$002E\""); assertEquals("/m/02qlpsg", record.getFreebaseId()); assertEquals("Ferris Jacobs, Jr.", record.getLabel()); assertEquals("/wikipedia/en_title/Ferris_Jacobs$002C_Jr$002E", record.getWikipediaLabel()); assertEquals("Ferris_Jacobs,_Jr.", record.getCleanWikipediaLabel()); } }
marcocor/smaph
src/test/java/it/unipi/di/acube/smaph/datasets/wikitofreebase/WikipediaLabelToFreebaseIdTest.java
Java
apache-2.0
2,599
package com.sys1yagi.android_roughly_java8.activities.helpers; import com.sys1yagi.android_roughly_java8.R; import com.sys1yagi.android_roughly_java8.models.Todo; import com.sys1yagi.android_roughly_java8.tools.DateProvider; import com.sys1yagi.android_roughly_java8.tools.FileManager; import com.sys1yagi.android_roughly_java8.tools.IdGenerator; import org.joda.time.DateTime; import android.content.Context; import android.support.annotation.StringRes; import java.io.File; import javax.inject.Inject; import javax.inject.Singleton; import rx.Observable; @Singleton public class TodoHelper { @Inject FileManager fileManager; @Inject DateProvider dateProvider; @Inject IdGenerator idGenerator; @Inject public TodoHelper() { } public Todo addTodo(String title) { Todo todo = new Todo(); todo.setId(idGenerator.generate()); todo.setTitle(title); todo.setCreatedAt(dateProvider.now()); todo.setUpdatedAt(dateProvider.now()); todo.setChecked(false); File file = fileManager.saveJsonToFileDir(todo, todo.getId()); if (file != null) { return todo; } return null; } public void updateTodo(Todo todo) { fileManager.saveJsonToFileDir(todo, todo.getId()); } public boolean removeTodo(Todo todo) { return fileManager.removeFromFileDir(todo.getId()); } public Observable<Todo> list() { return fileManager .getFileDirFiles() .filter(file -> file.getName().startsWith(Todo.PREFIX)) .map(file -> fileManager.loadJsonFromFileDir(file.getName(), Todo.class)); } public int compare(Todo lhs, Todo rhs) { long l = lhs.getUpdatedAt(); long r = rhs.getUpdatedAt(); return -(l == r ? 0 : l < r ? -1 : 1); } public String getReadableDate(Context context, long time, @StringRes int resId) { String date = new DateTime(time).toString(context.getString(R.string.date)); return context.getString(resId, date); } }
sys1yagi/android-roughly-java8
app/src/main/java/com/sys1yagi/android_roughly_java8/activities/helpers/TodoHelper.java
Java
apache-2.0
2,095
package com.dda.mobilesafe.engine; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import com.dda.mobilesafe.bean.AppInfo; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by nuo on 2016/5/20. */ public class AppInfos { public static List<AppInfo> getAppInfos(Context context) { List<AppInfo> packageAppInfos = new ArrayList<>(); //获取到包的管理者 PackageManager packageManager = context.getPackageManager(); //获取到安装包 List<PackageInfo> installedPackages = packageManager.getInstalledPackages(0); for (PackageInfo installedPackage : installedPackages) { AppInfo appInfo = new AppInfo(); //获取到应用程序的图标 Drawable drawable = installedPackage.applicationInfo.loadIcon(packageManager); appInfo.setIcon(drawable); //获取到应用程序的名 字 String apkName = installedPackage.applicationInfo.loadLabel(packageManager).toString() + installedPackage.applicationInfo.uid; appInfo.setApkName(apkName); //获取到应用程序的包名 String packageName = installedPackage.packageName; appInfo.setApkPackageName(packageName); //获取到apk资源的路径 String sourceDir = installedPackage.applicationInfo.sourceDir; File file = new File(sourceDir); //aok的长度 long apkSize = file.length(); appInfo.setApkSize(apkSize); // System.out.println("-----------------------------"); // System.out.println("程序的名字:" + apkName); // System.out.println("程序的包名:" + packageName); // System.out.println("程序的大小:" + apkSize); //获取到安装应用程序的标记 int flags = installedPackage.applicationInfo.flags; if ((flags & ApplicationInfo.FLAG_SYSTEM) != 0) { //表示系统app appInfo.setUserApp(false); } else { //表示用户app appInfo.setUserApp(true); } if ((flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { //表示在sd卡 appInfo.setIsRom(false); } else { //表示在手机内存 appInfo.setIsRom(true); } packageAppInfos.add(appInfo); } return packageAppInfos; } }
dengdunan/MobileSafe
app/src/main/java/com/dda/mobilesafe/engine/AppInfos.java
Java
apache-2.0
2,695
package edu.uw.zookeeper.safari.peer.protocol; import static com.google.common.base.Preconditions.checkNotNull; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufOutputStream; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import edu.uw.zookeeper.net.Encoder; @SuppressWarnings("rawtypes") public final class MessagePacketEncoder implements Encoder<MessagePacket, MessagePacket> { public static MessagePacketEncoder defaults(ObjectMapper mapper) { return new MessagePacketEncoder( mapper.writer()); } protected final ObjectWriter writer; public MessagePacketEncoder(ObjectWriter writer) { this.writer = checkNotNull(writer); } @Override public Class<? extends MessagePacket> encodeType() { return MessagePacket.class; } @Override public void encode(MessagePacket input, ByteBuf output) throws IOException { ByteBufOutputStream stream = new ByteBufOutputStream(output); try { writer.writeValue(stream, input); } finally { stream.close(); } } }
lisaglendenning/safari
src/main/java/edu/uw/zookeeper/safari/peer/protocol/MessagePacketEncoder.java
Java
apache-2.0
1,214
package com.example.zjy.adapter; import android.content.Context; import com.example.zjy.bantang.R; import com.example.zjy.bean.UserCommentBean; import com.example.zjy.niklauslibrary.lvhelper.UniversalAdapter; import com.example.zjy.niklauslibrary.util.CirImageViewUtils; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by zjy on 2016/12/27. */ public class FooterLvAdapter extends UniversalAdapter<UserCommentBean.DataBean> { private Context context; public FooterLvAdapter(Context context) { super(context, R.layout.footer_item_list); this.context = context; } @Override public void bindView(ViewHolder viewHolder, UserCommentBean.DataBean data) { if(data != null) { viewHolder.setText(R.id.tv_nickname, data.getUser().getNickname()); viewHolder.setText(R.id.tv_content, data.getConent()); viewHolder.setText(R.id.tv_date, data.getDatestr()); CircleImageView user_icon = (CircleImageView) viewHolder.getView(R.id.user_icon); CirImageViewUtils .loadCirImage(data.getUser().getAvatar(), context, user_icon); } } }
1147576679/findbest
app/src/main/java/com/example/zjy/adapter/FooterLvAdapter.java
Java
apache-2.0
1,176
package uk.ac.cam.cl.dtg.picky.parser; /* * #%L * Picky * %% * Copyright (C) 2015 Daniel Hintze <dh526@cl.cam.ac.uk> * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ public class Entry { private byte[] data; private Attributes attributes = new Attributes(); public Entry(byte[] data) { this.data = data; } public byte[] getData() { return data; } public Attributes getAttributes() { return attributes; } @Override public String toString() { return "Entry [attributes=" + attributes + ", data=" + data.length + "]"; } }
ucam-cl-dtg/picky
picky-core/src/main/java/uk/ac/cam/cl/dtg/picky/parser/Entry.java
Java
apache-2.0
1,077
package com.matpag.dagger.starter.main; import dagger.Module; import dagger.Provides; /** * Created by Mattia Pagini on 07/07/2017. */ @Module public class MainActivityModule { @Provides Boolean getBoolean(){ return false; } }
matpag/DaggerStarterBase
app/src/main/java/com/matpag/dagger/starter/main/MainActivityModule.java
Java
apache-2.0
253
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.collection.pool; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import org.neo4j.function.Factory; import org.neo4j.function.primitive.LongSupplier; public class LinkedQueuePool<R> implements Pool<R> { public interface Monitor<R> { public void updatedCurrentPeakSize( int currentPeakSize ); public void updatedTargetSize( int targetSize ); public void created( R resource ); public void acquired( R resource ); public void disposed( R resource ); public class Adapter<R> implements Monitor<R> { @Override public void updatedCurrentPeakSize( int currentPeakSize ) { } @Override public void updatedTargetSize( int targetSize ) { } @Override public void created( R resource ) { } @Override public void acquired( R resource ) { } @Override public void disposed( R resource ) { } } } public interface CheckStrategy { public boolean shouldCheck(); public class TimeoutCheckStrategy implements CheckStrategy { private final long interval; private long lastCheckTime; private final LongSupplier clock; public TimeoutCheckStrategy( long interval ) { this(interval, new LongSupplier() { @Override public long getAsLong() { return System.currentTimeMillis(); } }); } public TimeoutCheckStrategy( long interval, LongSupplier clock ) { this.interval = interval; this.lastCheckTime = clock.getAsLong(); this.clock = clock; } @Override public boolean shouldCheck() { long currentTime = clock.getAsLong(); if ( currentTime > lastCheckTime + interval ) { lastCheckTime = currentTime; return true; } return false; } } } public static final int DEFAULT_CHECK_INTERVAL = 60 * 1000; private final Queue<R> unused = new ConcurrentLinkedQueue<>(); private final Monitor monitor; private final int minSize; private final Factory<R> factory; private final CheckStrategy checkStrategy; // Guarded by nothing. Those are estimates, losing some values doesn't matter much private final AtomicInteger allocated = new AtomicInteger( 0 ); private final AtomicInteger queueSize = new AtomicInteger( 0 ); private int currentPeakSize; private int targetSize; public LinkedQueuePool( int minSize, Factory<R> factory) { this( minSize, factory, new CheckStrategy.TimeoutCheckStrategy( DEFAULT_CHECK_INTERVAL ), new Monitor.Adapter() ); } public LinkedQueuePool( int minSize, Factory<R> factory, CheckStrategy strategy, Monitor monitor ) { this.minSize = minSize; this.factory = factory; this.currentPeakSize = 0; this.targetSize = minSize; this.checkStrategy = strategy; this.monitor = monitor; } protected R create() { return factory.newInstance(); } protected void dispose( R resource ) { monitor.disposed( resource ); allocated.decrementAndGet(); } @Override public final R acquire() { R resource = unused.poll(); if ( resource == null ) { resource = create(); allocated.incrementAndGet(); monitor.created( resource ); } else { queueSize.decrementAndGet(); } currentPeakSize = Math.max( currentPeakSize, allocated.get() - queueSize.get() ); if ( checkStrategy.shouldCheck() ) { targetSize = Math.max( minSize, currentPeakSize ); monitor.updatedCurrentPeakSize( currentPeakSize ); currentPeakSize = 0; monitor.updatedTargetSize( targetSize ); } monitor.acquired( resource ); return resource; } @Override public void release( R toRelease ) { if ( queueSize.get() < targetSize ) { unused.offer( toRelease ); queueSize.incrementAndGet(); } else { dispose( toRelease ); } } /** * Dispose of all pooled objects. */ public void disposeAll() { for(R resource = unused.poll(); resource != null; resource = unused.poll()) { dispose( resource ); } } public void close( boolean force ) { disposeAll(); } }
HuangLS/neo4j
community/primitive-collections/src/main/java/org/neo4j/collection/pool/LinkedQueuePool.java
Java
apache-2.0
5,897
package com.ehensin.process; public class XmlProcessStageEvent { }
hhbzzd/ehensin
ehensin-seda/src/main/java/com/ehensin/process/XmlProcessStageEvent.java
Java
apache-2.0
74
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate licenses * this file to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.metadata.information; import static io.crate.types.DataTypes.STRING; import io.crate.metadata.ColumnIdent; import io.crate.metadata.RelationName; import io.crate.metadata.SystemTable; public class InformationReferentialConstraintsTableInfo { public static final String NAME = "referential_constraints"; public static final RelationName IDENT = new RelationName(InformationSchemaInfo.NAME, NAME); public static SystemTable<Void> create() { return SystemTable.<Void>builder(IDENT) .add("constraint_catalog", STRING, ignored -> null) .add("constraint_schema", STRING, ignored -> null) .add("constraint_name", STRING, ignored -> null) .add("unique_constraint_catalog", STRING, ignored -> null) .add("unique_constraint_schema", STRING, ignored -> null) .add("unique_constraint_name", STRING, ignored -> null) .add("match_option", STRING, ignored -> null) .add("update_rule", STRING, ignored -> null) .add("delete_rule", STRING, ignored -> null) .setPrimaryKeys( new ColumnIdent("constraint_catalog"), new ColumnIdent("constraint_schema"), new ColumnIdent("constraint_name") ) .build(); } }
crate/crate
server/src/main/java/io/crate/metadata/information/InformationReferentialConstraintsTableInfo.java
Java
apache-2.0
2,336
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.transport; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.EnumMap; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.auth.IAuthenticator; import org.apache.cassandra.auth.ISaslAwareAuthenticator; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.config.EncryptionOptions; import org.apache.cassandra.metrics.ClientMetrics; import org.apache.cassandra.security.SSLFactory; import org.apache.cassandra.service.*; import org.apache.cassandra.transport.messages.EventMessage; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.*; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.execution.ExecutionHandler; import org.jboss.netty.handler.ssl.SslHandler; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.logging.Slf4JLoggerFactory; public class Server implements org.apache.cassandra.service.Server { static { InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); } private static final Logger logger = LoggerFactory.getLogger(Server.class); /** current version of the native protocol we support */ public static final int CURRENT_VERSION = 2; private final ConnectionTracker connectionTracker = new ConnectionTracker(); private final Connection.Factory connectionFactory = new Connection.Factory() { public Connection newConnection(Channel channel, int version) { return new ServerConnection(channel, version, connectionTracker); } }; public final InetSocketAddress socket; private final AtomicBoolean isRunning = new AtomicBoolean(false); private ChannelFactory factory; private ExecutionHandler executionHandler; public Server(InetSocketAddress socket) { this.socket = socket; EventNotifier notifier = new EventNotifier(this); StorageService.instance.register(notifier); MigrationManager.instance.register(notifier); registerMetrics(); } public Server(String hostname, int port) { this(new InetSocketAddress(hostname, port)); } public Server(InetAddress host, int port) { this(new InetSocketAddress(host, port)); } public Server(int port) { this(new InetSocketAddress(port)); } public void start() { if(!isRunning()) { run(); } } public void stop() { if (isRunning.compareAndSet(true, false)) close(); } public boolean isRunning() { return isRunning.get(); } private void run() { // Check that a SaslAuthenticator can be provided by the configured // IAuthenticator. If not, don't start the server. IAuthenticator authenticator = DatabaseDescriptor.getAuthenticator(); if (authenticator.requireAuthentication() && !(authenticator instanceof ISaslAwareAuthenticator)) { logger.error("Not starting native transport as the configured IAuthenticator is not capable of SASL authentication"); isRunning.compareAndSet(true, false); return; } // Configure the server. executionHandler = new ExecutionHandler(new RequestThreadPoolExecutor()); factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); bootstrap.setOption("child.tcpNoDelay", true); // Set up the event pipeline factory. final EncryptionOptions.ClientEncryptionOptions clientEnc = DatabaseDescriptor.getClientEncryptionOptions(); if (clientEnc.enabled) { logger.info("Enabling encrypted CQL connections between client and server"); bootstrap.setPipelineFactory(new SecurePipelineFactory(this, clientEnc)); } else { bootstrap.setPipelineFactory(new PipelineFactory(this)); } // Bind and start to accept incoming connections. logger.info("Starting listening for CQL clients on {}...", socket); Channel channel = bootstrap.bind(socket); connectionTracker.allChannels.add(channel); isRunning.set(true); } private void registerMetrics() { ClientMetrics.instance.addCounter("connectedNativeClients", new Callable<Integer>() { @Override public Integer call() throws Exception { return connectionTracker.getConnectedClients(); } }); } private void close() { // Close opened connections connectionTracker.closeAll(); factory.releaseExternalResources(); factory = null; executionHandler.releaseExternalResources(); executionHandler = null; logger.info("Stop listening for CQL clients"); } public static class ConnectionTracker implements Connection.Tracker { public final ChannelGroup allChannels = new DefaultChannelGroup(); private final EnumMap<Event.Type, ChannelGroup> groups = new EnumMap<Event.Type, ChannelGroup>(Event.Type.class); public ConnectionTracker() { for (Event.Type type : Event.Type.values()) groups.put(type, new DefaultChannelGroup(type.toString())); } public void addConnection(Channel ch, Connection connection) { allChannels.add(ch); } public void register(Event.Type type, Channel ch) { groups.get(type).add(ch); } public void unregister(Channel ch) { for (ChannelGroup group : groups.values()) group.remove(ch); } public void send(Event event) { groups.get(event.type).write(new EventMessage(event)); } public void closeAll() { allChannels.close().awaitUninterruptibly(); } public int getConnectedClients() { /* - When server is running: allChannels contains all clients' connections (channels) plus one additional channel used for the server's own bootstrap. - When server is stopped: the size is 0 */ return allChannels.size() != 0 ? allChannels.size() - 1 : 0; } } private static class PipelineFactory implements ChannelPipelineFactory { // Stateless handlers private static final Message.ProtocolDecoder messageDecoder = new Message.ProtocolDecoder(); private static final Message.ProtocolEncoder messageEncoder = new Message.ProtocolEncoder(); private static final Frame.Decompressor frameDecompressor = new Frame.Decompressor(); private static final Frame.Compressor frameCompressor = new Frame.Compressor(); private static final Frame.Encoder frameEncoder = new Frame.Encoder(); private static final Message.Dispatcher dispatcher = new Message.Dispatcher(); private final Server server; public PipelineFactory(Server server) { this.server = server; } public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); //pipeline.addLast("debug", new LoggingHandler()); pipeline.addLast("frameDecoder", new Frame.Decoder(server.connectionFactory)); pipeline.addLast("frameEncoder", frameEncoder); pipeline.addLast("frameDecompressor", frameDecompressor); pipeline.addLast("frameCompressor", frameCompressor); pipeline.addLast("messageDecoder", messageDecoder); pipeline.addLast("messageEncoder", messageEncoder); pipeline.addLast("executor", server.executionHandler); pipeline.addLast("dispatcher", dispatcher); return pipeline; } } private static class SecurePipelineFactory extends PipelineFactory { private final SSLContext sslContext; private final EncryptionOptions encryptionOptions; public SecurePipelineFactory(Server server, EncryptionOptions encryptionOptions) { super(server); this.encryptionOptions = encryptionOptions; try { this.sslContext = SSLFactory.createSSLContext(encryptionOptions, false); } catch (IOException e) { throw new RuntimeException("Failed to setup secure pipeline", e); } } public ChannelPipeline getPipeline() throws Exception { SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(false); sslEngine.setEnabledCipherSuites(encryptionOptions.cipher_suites); sslEngine.setNeedClientAuth(encryptionOptions.require_client_auth); SslHandler sslHandler = new SslHandler(sslEngine); sslHandler.setIssueHandshake(true); ChannelPipeline pipeline = super.getPipeline(); pipeline.addFirst("ssl", sslHandler); return pipeline; } } private static class EventNotifier implements IEndpointLifecycleSubscriber, IMigrationListener { private final Server server; private static final InetAddress bindAll; static { try { bindAll = InetAddress.getByAddress(new byte[4]); } catch (UnknownHostException e) { throw new AssertionError(e); } } private EventNotifier(Server server) { this.server = server; } private InetAddress getRpcAddress(InetAddress endpoint) { try { InetAddress rpcAddress = InetAddress.getByName(StorageService.instance.getRpcaddress(endpoint)); // If rpcAddress == 0.0.0.0 (i.e. bound on all addresses), returning that is not very helpful, // so return the internal address (which is ok since "we're bound on all addresses"). return rpcAddress.equals(bindAll) ? endpoint : rpcAddress; } catch (UnknownHostException e) { // That should not happen, so log an error, but return the // endpoint address since there's a good change this is right logger.error("Problem retrieving RPC address for {}", endpoint, e); return endpoint; } } public void onJoinCluster(InetAddress endpoint) { server.connectionTracker.send(Event.TopologyChange.newNode(getRpcAddress(endpoint), server.socket.getPort())); } public void onLeaveCluster(InetAddress endpoint) { server.connectionTracker.send(Event.TopologyChange.removedNode(getRpcAddress(endpoint), server.socket.getPort())); } public void onMove(InetAddress endpoint) { server.connectionTracker.send(Event.TopologyChange.movedNode(getRpcAddress(endpoint), server.socket.getPort())); } public void onUp(InetAddress endpoint) { server.connectionTracker.send(Event.StatusChange.nodeUp(getRpcAddress(endpoint), server.socket.getPort())); } public void onDown(InetAddress endpoint) { server.connectionTracker.send(Event.StatusChange.nodeDown(getRpcAddress(endpoint), server.socket.getPort())); } public void onCreateKeyspace(String ksName) { server.connectionTracker.send(new Event.SchemaChange(Event.SchemaChange.Change.CREATED, ksName)); } public void onCreateColumnFamily(String ksName, String cfName) { server.connectionTracker.send(new Event.SchemaChange(Event.SchemaChange.Change.CREATED, ksName, cfName)); } public void onUpdateKeyspace(String ksName) { server.connectionTracker.send(new Event.SchemaChange(Event.SchemaChange.Change.UPDATED, ksName)); } public void onUpdateColumnFamily(String ksName, String cfName) { server.connectionTracker.send(new Event.SchemaChange(Event.SchemaChange.Change.UPDATED, ksName, cfName)); } public void onDropKeyspace(String ksName) { server.connectionTracker.send(new Event.SchemaChange(Event.SchemaChange.Change.DROPPED, ksName)); } public void onDropColumnFamily(String ksName, String cfName) { server.connectionTracker.send(new Event.SchemaChange(Event.SchemaChange.Change.DROPPED, ksName, cfName)); } } }
heiko-braun/cassandra
src/java/org/apache/cassandra/transport/Server.java
Java
apache-2.0
14,186
/* * Project: util4j * * File Created at 2017-06-22 * * Copyright (c) 2001-2017 GuaHao.com Corporation Limited * All rights reserved. * This software is the confidential and proprietary information of * GuaHao Company. ("Confidential Information"). You shall not disclose * such Confidential Information and shall use it only in accordance with * the terms of the license agreement you entered into with GuaHao.com. */ package top.nefkgame.dubbo.service; /** * DemoProvService * * @author zjj * @version V1.0 * @since 2017-06-22 09:57 */ public interface DemoProvService2 { ///////////////////////////// Class Attributes \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ String echo(String hello); //////////////////////////////// Attributes \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ /////////////////////////////// Constructors \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ////////////////////////////// Class Methods \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ////////////////////////////////// Methods \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ //------------------------ Implements: //------------------------ Overrides: //---------------------------- Abstract Methods ----------------------------- //---------------------------- Utility Methods ------------------------------ //---------------------------- Property Methods ----------------------------- }
nefk/util4j
util4j-dubbo/src/test/java/top/nefkgame/dubbo/service/DemoProvService2.java
Java
apache-2.0
1,378
package org.metaborg.spoofax.meta.core.stratego.primitive; import org.apache.commons.vfs2.FileObject; import org.metaborg.core.MetaborgException; import org.metaborg.core.config.ConfigException; import org.metaborg.core.context.IContext; import org.metaborg.core.project.IProject; import org.metaborg.core.project.IProjectService; import org.metaborg.spoofax.core.stratego.primitive.generic.ASpoofaxContextPrimitive; import org.metaborg.spoofax.meta.core.project.ISpoofaxLanguageSpec; import org.metaborg.spoofax.meta.core.project.ISpoofaxLanguageSpecService; import org.metaborg.util.log.ILogger; import org.metaborg.util.log.LoggerUtils; import org.spoofax.interpreter.stratego.Strategy; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import com.google.inject.Inject; import com.google.inject.Provider; public class LegacyLanguageSpecNamePrimitive extends ASpoofaxContextPrimitive implements AutoCloseable { private static final ILogger logger = LoggerUtils.logger(LegacyLanguageSpecNamePrimitive.class); @Inject private static Provider<ISpoofaxLanguageSpecService> languageSpecServiceProvider; private final IProjectService projectService; @Inject public LegacyLanguageSpecNamePrimitive(IProjectService projectService) { super("SSL_EXT_language_spec_name", 0, 0); this.projectService = projectService; } @Override public void close() { languageSpecServiceProvider = null; } @Override protected IStrategoTerm call(IStrategoTerm current, Strategy[] svars, IStrategoTerm[] tvars, ITermFactory factory, IContext context) throws MetaborgException { final FileObject location = context.location(); final IProject project = projectService.get(location); if(project == null) { return null; } if(languageSpecServiceProvider == null) { // Indicates that meta-Spoofax is not available (ISpoofaxLanguageSpecService cannot be injected), but this // should never happen because this primitive is inside meta-Spoofax. Check for null just in case. logger.debug("Language specification service is not available; static injection failed"); return null; } final ISpoofaxLanguageSpecService languageSpecService = languageSpecServiceProvider.get(); if(!languageSpecService.available(project)) { return null; } final ISpoofaxLanguageSpec languageSpec; try { languageSpec = languageSpecService.get(project); } catch(ConfigException e) { throw new MetaborgException("Unable to get language specification name for " + location, e); } if(languageSpec == null) { return null; } return factory.makeString(languageSpec.config().name()); } }
metaborg/spoofax
org.metaborg.spoofax.meta.core/src/main/java/org/metaborg/spoofax/meta/core/stratego/primitive/LegacyLanguageSpecNamePrimitive.java
Java
apache-2.0
2,889
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.exec.expr.fn.impl.conv; import javax.inject.Inject; import org.apache.arrow.vector.holders.BitHolder; import org.apache.arrow.vector.holders.VarBinaryHolder; import com.dremio.exec.expr.SimpleFunction; import com.dremio.exec.expr.annotations.FunctionTemplate; import com.dremio.exec.expr.annotations.FunctionTemplate.FunctionScope; import com.dremio.exec.expr.annotations.FunctionTemplate.NullHandling; import com.dremio.exec.expr.annotations.Output; import com.dremio.exec.expr.annotations.Param; import com.dremio.exec.expr.fn.FunctionErrorContext; @FunctionTemplate(name = "convert_fromBOOLEAN_BYTE", scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL) @SuppressWarnings("unused") // found through classpath search public class BooleanByteConvertFrom implements SimpleFunction { @Param VarBinaryHolder in; @Output BitHolder out; @Inject FunctionErrorContext errorContext; @Override public void setup() { } @Override public void eval() { com.dremio.exec.util.ByteBufUtil.checkBufferLength(errorContext, in.buffer, in.start, in.end, 1); in.buffer.readerIndex(in.start); out.value = in.buffer.readByte()==0 ? 0 : 1; } }
dremio/dremio-oss
sabot/kernel/src/main/java/com/dremio/exec/expr/fn/impl/conv/BooleanByteConvertFrom.java
Java
apache-2.0
1,799
/* LanguageTool, a natural language style checker * Copyright (C) 2013 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.synthesis; import org.jetbrains.annotations.NotNull; import org.languagetool.AnalyzedToken; import org.languagetool.Language; import org.languagetool.tokenizers.de.GermanCompoundTokenizer; import org.languagetool.tools.StringTools; import java.io.IOException; import java.util.*; /** * German word form synthesizer. Also supports compounds. * * @since 2.4 */ public class GermanSynthesizer extends BaseSynthesizer { private final GermanCompoundTokenizer splitter; public GermanSynthesizer(Language lang) { super("/de/german_synth.dict", "/de/german_tags.txt", lang); try { splitter = new GermanCompoundTokenizer(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public String[] synthesize(AnalyzedToken token, String posTag) throws IOException { String[] result = super.synthesize(token, posTag); if (result.length == 0) { return getCompoundForms(token, posTag, false); } return result; } @Override public String[] synthesize(AnalyzedToken token, String posTag, boolean posTagRegExp) throws IOException { String[] result = super.synthesize(token, posTag, posTagRegExp); if (result.length == 0) { return getCompoundForms(token, posTag, posTagRegExp); } return result; } @NotNull private String[] getCompoundForms(AnalyzedToken token, String posTag, boolean posTagRegExp) throws IOException { List<String> parts = splitter.tokenize(token.getToken()); String firstPart = String.join("", parts.subList(0, parts.size() - 1)); String lastPart = StringTools.uppercaseFirstChar(parts.get(parts.size() - 1)); AnalyzedToken lastPartToken = new AnalyzedToken(lastPart, posTag, lastPart); String[] lastPartForms; if (posTagRegExp) { lastPartForms = super.synthesize(lastPartToken, posTag, true); } else { lastPartForms = super.synthesize(lastPartToken, posTag); } Set<String> results = new LinkedHashSet<>(); // avoid dupes for (String part : lastPartForms) { results.add(firstPart + StringTools.lowercaseFirstChar(part)); } return results.toArray(new String[0]); } }
EMResearch/EMB
jdk_8_maven/cs/rest/original/languagetool/languagetool-language-modules/de/src/main/java/org/languagetool/synthesis/GermanSynthesizer.java
Java
apache-2.0
3,046
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.snowball.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CreateJob" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateJobRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * Defines the type of job that you're creating. * </p> */ private String jobType; /** * <p> * Defines the Amazon S3 buckets associated with this job. * </p> * <p> * With <code>IMPORT</code> jobs, you specify the bucket or buckets that your transferred data will be imported * into. * </p> * <p> * With <code>EXPORT</code> jobs, you specify the bucket or buckets that your transferred data will be exported * from. Optionally, you can also specify a <code>KeyRange</code> value. If you choose to export a range, you define * the length of the range by providing either an inclusive <code>BeginMarker</code> value, an inclusive * <code>EndMarker</code> value, or both. Ranges are UTF-8 binary sorted. * </p> */ private JobResource resources; /** * <p> * Defines an optional description of this specific job, for example <code>Important Photos 2016-08-11</code>. * </p> */ private String description; /** * <p> * The ID for the address that you want the Snowball shipped to. * </p> */ private String addressId; /** * <p> * The <code>KmsKeyARN</code> that you want to associate with this job. <code>KmsKeyARN</code>s are created using * the <a href="http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> AWS Key * Management Service (KMS) API action. * </p> */ private String kmsKeyARN; /** * <p> * The <code>RoleARN</code> that you want to associate with this job. <code>RoleArn</code>s are created using the <a * href="http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> AWS Identity and * Access Management (IAM) API action. * </p> */ private String roleARN; /** * <p> * If your job is being created in one of the US regions, you have the option of specifying what size Snowball you'd * like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. * </p> */ private String snowballCapacityPreference; /** * <p> * The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it * represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds are as * follows: * </p> * <ul> * <li> * <p> * In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in about a * day. * </p> * </li> * <li> * <p> * In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are * delivered in about a day. In addition, most countries in the EU have access to standard shipping, which typically * takes less than a week, one way. * </p> * </li> * <li> * <p> * In India, Snowballs are delivered in one to seven days. * </p> * </li> * <li> * <p> * In the US, you have access to one-day shipping and two-day shipping. * </p> * </li> * </ul> */ private String shippingOption; /** * <p> * Defines the Amazon Simple Notification Service (Amazon SNS) notification settings for this job. * </p> */ private Notification notification; /** * <p> * The ID of a cluster. If you're creating a job for a node in a cluster, you need to provide only this * <code>clusterId</code> value. The other job attributes are inherited from the cluster. * </p> */ private String clusterId; /** * <p> * The type of AWS Snowball appliance to use for this job. Currently, the only supported appliance type for cluster * jobs is <code>EDGE</code>. * </p> */ private String snowballType; /** * <p> * The forwarding address ID for a job. This field is not supported in most regions. * </p> */ private String forwardingAddressId; /** * <p> * Defines the type of job that you're creating. * </p> * * @param jobType * Defines the type of job that you're creating. * @see JobType */ public void setJobType(String jobType) { this.jobType = jobType; } /** * <p> * Defines the type of job that you're creating. * </p> * * @return Defines the type of job that you're creating. * @see JobType */ public String getJobType() { return this.jobType; } /** * <p> * Defines the type of job that you're creating. * </p> * * @param jobType * Defines the type of job that you're creating. * @return Returns a reference to this object so that method calls can be chained together. * @see JobType */ public CreateJobRequest withJobType(String jobType) { setJobType(jobType); return this; } /** * <p> * Defines the type of job that you're creating. * </p> * * @param jobType * Defines the type of job that you're creating. * @see JobType */ public void setJobType(JobType jobType) { this.jobType = jobType.toString(); } /** * <p> * Defines the type of job that you're creating. * </p> * * @param jobType * Defines the type of job that you're creating. * @return Returns a reference to this object so that method calls can be chained together. * @see JobType */ public CreateJobRequest withJobType(JobType jobType) { setJobType(jobType); return this; } /** * <p> * Defines the Amazon S3 buckets associated with this job. * </p> * <p> * With <code>IMPORT</code> jobs, you specify the bucket or buckets that your transferred data will be imported * into. * </p> * <p> * With <code>EXPORT</code> jobs, you specify the bucket or buckets that your transferred data will be exported * from. Optionally, you can also specify a <code>KeyRange</code> value. If you choose to export a range, you define * the length of the range by providing either an inclusive <code>BeginMarker</code> value, an inclusive * <code>EndMarker</code> value, or both. Ranges are UTF-8 binary sorted. * </p> * * @param resources * Defines the Amazon S3 buckets associated with this job.</p> * <p> * With <code>IMPORT</code> jobs, you specify the bucket or buckets that your transferred data will be * imported into. * </p> * <p> * With <code>EXPORT</code> jobs, you specify the bucket or buckets that your transferred data will be * exported from. Optionally, you can also specify a <code>KeyRange</code> value. If you choose to export a * range, you define the length of the range by providing either an inclusive <code>BeginMarker</code> value, * an inclusive <code>EndMarker</code> value, or both. Ranges are UTF-8 binary sorted. */ public void setResources(JobResource resources) { this.resources = resources; } /** * <p> * Defines the Amazon S3 buckets associated with this job. * </p> * <p> * With <code>IMPORT</code> jobs, you specify the bucket or buckets that your transferred data will be imported * into. * </p> * <p> * With <code>EXPORT</code> jobs, you specify the bucket or buckets that your transferred data will be exported * from. Optionally, you can also specify a <code>KeyRange</code> value. If you choose to export a range, you define * the length of the range by providing either an inclusive <code>BeginMarker</code> value, an inclusive * <code>EndMarker</code> value, or both. Ranges are UTF-8 binary sorted. * </p> * * @return Defines the Amazon S3 buckets associated with this job.</p> * <p> * With <code>IMPORT</code> jobs, you specify the bucket or buckets that your transferred data will be * imported into. * </p> * <p> * With <code>EXPORT</code> jobs, you specify the bucket or buckets that your transferred data will be * exported from. Optionally, you can also specify a <code>KeyRange</code> value. If you choose to export a * range, you define the length of the range by providing either an inclusive <code>BeginMarker</code> * value, an inclusive <code>EndMarker</code> value, or both. Ranges are UTF-8 binary sorted. */ public JobResource getResources() { return this.resources; } /** * <p> * Defines the Amazon S3 buckets associated with this job. * </p> * <p> * With <code>IMPORT</code> jobs, you specify the bucket or buckets that your transferred data will be imported * into. * </p> * <p> * With <code>EXPORT</code> jobs, you specify the bucket or buckets that your transferred data will be exported * from. Optionally, you can also specify a <code>KeyRange</code> value. If you choose to export a range, you define * the length of the range by providing either an inclusive <code>BeginMarker</code> value, an inclusive * <code>EndMarker</code> value, or both. Ranges are UTF-8 binary sorted. * </p> * * @param resources * Defines the Amazon S3 buckets associated with this job.</p> * <p> * With <code>IMPORT</code> jobs, you specify the bucket or buckets that your transferred data will be * imported into. * </p> * <p> * With <code>EXPORT</code> jobs, you specify the bucket or buckets that your transferred data will be * exported from. Optionally, you can also specify a <code>KeyRange</code> value. If you choose to export a * range, you define the length of the range by providing either an inclusive <code>BeginMarker</code> value, * an inclusive <code>EndMarker</code> value, or both. Ranges are UTF-8 binary sorted. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateJobRequest withResources(JobResource resources) { setResources(resources); return this; } /** * <p> * Defines an optional description of this specific job, for example <code>Important Photos 2016-08-11</code>. * </p> * * @param description * Defines an optional description of this specific job, for example <code>Important Photos 2016-08-11</code> * . */ public void setDescription(String description) { this.description = description; } /** * <p> * Defines an optional description of this specific job, for example <code>Important Photos 2016-08-11</code>. * </p> * * @return Defines an optional description of this specific job, for example * <code>Important Photos 2016-08-11</code>. */ public String getDescription() { return this.description; } /** * <p> * Defines an optional description of this specific job, for example <code>Important Photos 2016-08-11</code>. * </p> * * @param description * Defines an optional description of this specific job, for example <code>Important Photos 2016-08-11</code> * . * @return Returns a reference to this object so that method calls can be chained together. */ public CreateJobRequest withDescription(String description) { setDescription(description); return this; } /** * <p> * The ID for the address that you want the Snowball shipped to. * </p> * * @param addressId * The ID for the address that you want the Snowball shipped to. */ public void setAddressId(String addressId) { this.addressId = addressId; } /** * <p> * The ID for the address that you want the Snowball shipped to. * </p> * * @return The ID for the address that you want the Snowball shipped to. */ public String getAddressId() { return this.addressId; } /** * <p> * The ID for the address that you want the Snowball shipped to. * </p> * * @param addressId * The ID for the address that you want the Snowball shipped to. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateJobRequest withAddressId(String addressId) { setAddressId(addressId); return this; } /** * <p> * The <code>KmsKeyARN</code> that you want to associate with this job. <code>KmsKeyARN</code>s are created using * the <a href="http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> AWS Key * Management Service (KMS) API action. * </p> * * @param kmsKeyARN * The <code>KmsKeyARN</code> that you want to associate with this job. <code>KmsKeyARN</code>s are created * using the <a href="http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> * AWS Key Management Service (KMS) API action. */ public void setKmsKeyARN(String kmsKeyARN) { this.kmsKeyARN = kmsKeyARN; } /** * <p> * The <code>KmsKeyARN</code> that you want to associate with this job. <code>KmsKeyARN</code>s are created using * the <a href="http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> AWS Key * Management Service (KMS) API action. * </p> * * @return The <code>KmsKeyARN</code> that you want to associate with this job. <code>KmsKeyARN</code>s are created * using the <a href="http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> * AWS Key Management Service (KMS) API action. */ public String getKmsKeyARN() { return this.kmsKeyARN; } /** * <p> * The <code>KmsKeyARN</code> that you want to associate with this job. <code>KmsKeyARN</code>s are created using * the <a href="http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> AWS Key * Management Service (KMS) API action. * </p> * * @param kmsKeyARN * The <code>KmsKeyARN</code> that you want to associate with this job. <code>KmsKeyARN</code>s are created * using the <a href="http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html">CreateKey</a> * AWS Key Management Service (KMS) API action. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateJobRequest withKmsKeyARN(String kmsKeyARN) { setKmsKeyARN(kmsKeyARN); return this; } /** * <p> * The <code>RoleARN</code> that you want to associate with this job. <code>RoleArn</code>s are created using the <a * href="http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> AWS Identity and * Access Management (IAM) API action. * </p> * * @param roleARN * The <code>RoleARN</code> that you want to associate with this job. <code>RoleArn</code>s are created using * the <a href="http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> AWS * Identity and Access Management (IAM) API action. */ public void setRoleARN(String roleARN) { this.roleARN = roleARN; } /** * <p> * The <code>RoleARN</code> that you want to associate with this job. <code>RoleArn</code>s are created using the <a * href="http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> AWS Identity and * Access Management (IAM) API action. * </p> * * @return The <code>RoleARN</code> that you want to associate with this job. <code>RoleArn</code>s are created * using the <a href="http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> * AWS Identity and Access Management (IAM) API action. */ public String getRoleARN() { return this.roleARN; } /** * <p> * The <code>RoleARN</code> that you want to associate with this job. <code>RoleArn</code>s are created using the <a * href="http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> AWS Identity and * Access Management (IAM) API action. * </p> * * @param roleARN * The <code>RoleARN</code> that you want to associate with this job. <code>RoleArn</code>s are created using * the <a href="http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html">CreateRole</a> AWS * Identity and Access Management (IAM) API action. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateJobRequest withRoleARN(String roleARN) { setRoleARN(roleARN); return this; } /** * <p> * If your job is being created in one of the US regions, you have the option of specifying what size Snowball you'd * like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. * </p> * * @param snowballCapacityPreference * If your job is being created in one of the US regions, you have the option of specifying what size * Snowball you'd like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. * @see SnowballCapacity */ public void setSnowballCapacityPreference(String snowballCapacityPreference) { this.snowballCapacityPreference = snowballCapacityPreference; } /** * <p> * If your job is being created in one of the US regions, you have the option of specifying what size Snowball you'd * like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. * </p> * * @return If your job is being created in one of the US regions, you have the option of specifying what size * Snowball you'd like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. * @see SnowballCapacity */ public String getSnowballCapacityPreference() { return this.snowballCapacityPreference; } /** * <p> * If your job is being created in one of the US regions, you have the option of specifying what size Snowball you'd * like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. * </p> * * @param snowballCapacityPreference * If your job is being created in one of the US regions, you have the option of specifying what size * Snowball you'd like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. * @return Returns a reference to this object so that method calls can be chained together. * @see SnowballCapacity */ public CreateJobRequest withSnowballCapacityPreference(String snowballCapacityPreference) { setSnowballCapacityPreference(snowballCapacityPreference); return this; } /** * <p> * If your job is being created in one of the US regions, you have the option of specifying what size Snowball you'd * like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. * </p> * * @param snowballCapacityPreference * If your job is being created in one of the US regions, you have the option of specifying what size * Snowball you'd like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. * @see SnowballCapacity */ public void setSnowballCapacityPreference(SnowballCapacity snowballCapacityPreference) { this.snowballCapacityPreference = snowballCapacityPreference.toString(); } /** * <p> * If your job is being created in one of the US regions, you have the option of specifying what size Snowball you'd * like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. * </p> * * @param snowballCapacityPreference * If your job is being created in one of the US regions, you have the option of specifying what size * Snowball you'd like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. * @return Returns a reference to this object so that method calls can be chained together. * @see SnowballCapacity */ public CreateJobRequest withSnowballCapacityPreference(SnowballCapacity snowballCapacityPreference) { setSnowballCapacityPreference(snowballCapacityPreference); return this; } /** * <p> * The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it * represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds are as * follows: * </p> * <ul> * <li> * <p> * In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in about a * day. * </p> * </li> * <li> * <p> * In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are * delivered in about a day. In addition, most countries in the EU have access to standard shipping, which typically * takes less than a week, one way. * </p> * </li> * <li> * <p> * In India, Snowballs are delivered in one to seven days. * </p> * </li> * <li> * <p> * In the US, you have access to one-day shipping and two-day shipping. * </p> * </li> * </ul> * * @param shippingOption * The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it * represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds * are as follows:</p> * <ul> * <li> * <p> * In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in * about a day. * </p> * </li> * <li> * <p> * In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are * delivered in about a day. In addition, most countries in the EU have access to standard shipping, which * typically takes less than a week, one way. * </p> * </li> * <li> * <p> * In India, Snowballs are delivered in one to seven days. * </p> * </li> * <li> * <p> * In the US, you have access to one-day shipping and two-day shipping. * </p> * </li> * @see ShippingOption */ public void setShippingOption(String shippingOption) { this.shippingOption = shippingOption; } /** * <p> * The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it * represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds are as * follows: * </p> * <ul> * <li> * <p> * In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in about a * day. * </p> * </li> * <li> * <p> * In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are * delivered in about a day. In addition, most countries in the EU have access to standard shipping, which typically * takes less than a week, one way. * </p> * </li> * <li> * <p> * In India, Snowballs are delivered in one to seven days. * </p> * </li> * <li> * <p> * In the US, you have access to one-day shipping and two-day shipping. * </p> * </li> * </ul> * * @return The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it * represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds * are as follows:</p> * <ul> * <li> * <p> * In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in * about a day. * </p> * </li> * <li> * <p> * In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are * delivered in about a day. In addition, most countries in the EU have access to standard shipping, which * typically takes less than a week, one way. * </p> * </li> * <li> * <p> * In India, Snowballs are delivered in one to seven days. * </p> * </li> * <li> * <p> * In the US, you have access to one-day shipping and two-day shipping. * </p> * </li> * @see ShippingOption */ public String getShippingOption() { return this.shippingOption; } /** * <p> * The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it * represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds are as * follows: * </p> * <ul> * <li> * <p> * In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in about a * day. * </p> * </li> * <li> * <p> * In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are * delivered in about a day. In addition, most countries in the EU have access to standard shipping, which typically * takes less than a week, one way. * </p> * </li> * <li> * <p> * In India, Snowballs are delivered in one to seven days. * </p> * </li> * <li> * <p> * In the US, you have access to one-day shipping and two-day shipping. * </p> * </li> * </ul> * * @param shippingOption * The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it * represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds * are as follows:</p> * <ul> * <li> * <p> * In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in * about a day. * </p> * </li> * <li> * <p> * In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are * delivered in about a day. In addition, most countries in the EU have access to standard shipping, which * typically takes less than a week, one way. * </p> * </li> * <li> * <p> * In India, Snowballs are delivered in one to seven days. * </p> * </li> * <li> * <p> * In the US, you have access to one-day shipping and two-day shipping. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see ShippingOption */ public CreateJobRequest withShippingOption(String shippingOption) { setShippingOption(shippingOption); return this; } /** * <p> * The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it * represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds are as * follows: * </p> * <ul> * <li> * <p> * In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in about a * day. * </p> * </li> * <li> * <p> * In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are * delivered in about a day. In addition, most countries in the EU have access to standard shipping, which typically * takes less than a week, one way. * </p> * </li> * <li> * <p> * In India, Snowballs are delivered in one to seven days. * </p> * </li> * <li> * <p> * In the US, you have access to one-day shipping and two-day shipping. * </p> * </li> * </ul> * * @param shippingOption * The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it * represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds * are as follows:</p> * <ul> * <li> * <p> * In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in * about a day. * </p> * </li> * <li> * <p> * In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are * delivered in about a day. In addition, most countries in the EU have access to standard shipping, which * typically takes less than a week, one way. * </p> * </li> * <li> * <p> * In India, Snowballs are delivered in one to seven days. * </p> * </li> * <li> * <p> * In the US, you have access to one-day shipping and two-day shipping. * </p> * </li> * @see ShippingOption */ public void setShippingOption(ShippingOption shippingOption) { this.shippingOption = shippingOption.toString(); } /** * <p> * The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it * represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds are as * follows: * </p> * <ul> * <li> * <p> * In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in about a * day. * </p> * </li> * <li> * <p> * In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are * delivered in about a day. In addition, most countries in the EU have access to standard shipping, which typically * takes less than a week, one way. * </p> * </li> * <li> * <p> * In India, Snowballs are delivered in one to seven days. * </p> * </li> * <li> * <p> * In the US, you have access to one-day shipping and two-day shipping. * </p> * </li> * </ul> * * @param shippingOption * The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it * represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds * are as follows:</p> * <ul> * <li> * <p> * In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in * about a day. * </p> * </li> * <li> * <p> * In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are * delivered in about a day. In addition, most countries in the EU have access to standard shipping, which * typically takes less than a week, one way. * </p> * </li> * <li> * <p> * In India, Snowballs are delivered in one to seven days. * </p> * </li> * <li> * <p> * In the US, you have access to one-day shipping and two-day shipping. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see ShippingOption */ public CreateJobRequest withShippingOption(ShippingOption shippingOption) { setShippingOption(shippingOption); return this; } /** * <p> * Defines the Amazon Simple Notification Service (Amazon SNS) notification settings for this job. * </p> * * @param notification * Defines the Amazon Simple Notification Service (Amazon SNS) notification settings for this job. */ public void setNotification(Notification notification) { this.notification = notification; } /** * <p> * Defines the Amazon Simple Notification Service (Amazon SNS) notification settings for this job. * </p> * * @return Defines the Amazon Simple Notification Service (Amazon SNS) notification settings for this job. */ public Notification getNotification() { return this.notification; } /** * <p> * Defines the Amazon Simple Notification Service (Amazon SNS) notification settings for this job. * </p> * * @param notification * Defines the Amazon Simple Notification Service (Amazon SNS) notification settings for this job. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateJobRequest withNotification(Notification notification) { setNotification(notification); return this; } /** * <p> * The ID of a cluster. If you're creating a job for a node in a cluster, you need to provide only this * <code>clusterId</code> value. The other job attributes are inherited from the cluster. * </p> * * @param clusterId * The ID of a cluster. If you're creating a job for a node in a cluster, you need to provide only this * <code>clusterId</code> value. The other job attributes are inherited from the cluster. */ public void setClusterId(String clusterId) { this.clusterId = clusterId; } /** * <p> * The ID of a cluster. If you're creating a job for a node in a cluster, you need to provide only this * <code>clusterId</code> value. The other job attributes are inherited from the cluster. * </p> * * @return The ID of a cluster. If you're creating a job for a node in a cluster, you need to provide only this * <code>clusterId</code> value. The other job attributes are inherited from the cluster. */ public String getClusterId() { return this.clusterId; } /** * <p> * The ID of a cluster. If you're creating a job for a node in a cluster, you need to provide only this * <code>clusterId</code> value. The other job attributes are inherited from the cluster. * </p> * * @param clusterId * The ID of a cluster. If you're creating a job for a node in a cluster, you need to provide only this * <code>clusterId</code> value. The other job attributes are inherited from the cluster. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateJobRequest withClusterId(String clusterId) { setClusterId(clusterId); return this; } /** * <p> * The type of AWS Snowball appliance to use for this job. Currently, the only supported appliance type for cluster * jobs is <code>EDGE</code>. * </p> * * @param snowballType * The type of AWS Snowball appliance to use for this job. Currently, the only supported appliance type for * cluster jobs is <code>EDGE</code>. * @see SnowballType */ public void setSnowballType(String snowballType) { this.snowballType = snowballType; } /** * <p> * The type of AWS Snowball appliance to use for this job. Currently, the only supported appliance type for cluster * jobs is <code>EDGE</code>. * </p> * * @return The type of AWS Snowball appliance to use for this job. Currently, the only supported appliance type for * cluster jobs is <code>EDGE</code>. * @see SnowballType */ public String getSnowballType() { return this.snowballType; } /** * <p> * The type of AWS Snowball appliance to use for this job. Currently, the only supported appliance type for cluster * jobs is <code>EDGE</code>. * </p> * * @param snowballType * The type of AWS Snowball appliance to use for this job. Currently, the only supported appliance type for * cluster jobs is <code>EDGE</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see SnowballType */ public CreateJobRequest withSnowballType(String snowballType) { setSnowballType(snowballType); return this; } /** * <p> * The type of AWS Snowball appliance to use for this job. Currently, the only supported appliance type for cluster * jobs is <code>EDGE</code>. * </p> * * @param snowballType * The type of AWS Snowball appliance to use for this job. Currently, the only supported appliance type for * cluster jobs is <code>EDGE</code>. * @see SnowballType */ public void setSnowballType(SnowballType snowballType) { this.snowballType = snowballType.toString(); } /** * <p> * The type of AWS Snowball appliance to use for this job. Currently, the only supported appliance type for cluster * jobs is <code>EDGE</code>. * </p> * * @param snowballType * The type of AWS Snowball appliance to use for this job. Currently, the only supported appliance type for * cluster jobs is <code>EDGE</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see SnowballType */ public CreateJobRequest withSnowballType(SnowballType snowballType) { setSnowballType(snowballType); return this; } /** * <p> * The forwarding address ID for a job. This field is not supported in most regions. * </p> * * @param forwardingAddressId * The forwarding address ID for a job. This field is not supported in most regions. */ public void setForwardingAddressId(String forwardingAddressId) { this.forwardingAddressId = forwardingAddressId; } /** * <p> * The forwarding address ID for a job. This field is not supported in most regions. * </p> * * @return The forwarding address ID for a job. This field is not supported in most regions. */ public String getForwardingAddressId() { return this.forwardingAddressId; } /** * <p> * The forwarding address ID for a job. This field is not supported in most regions. * </p> * * @param forwardingAddressId * The forwarding address ID for a job. This field is not supported in most regions. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateJobRequest withForwardingAddressId(String forwardingAddressId) { setForwardingAddressId(forwardingAddressId); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getJobType() != null) sb.append("JobType: ").append(getJobType()).append(","); if (getResources() != null) sb.append("Resources: ").append(getResources()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getAddressId() != null) sb.append("AddressId: ").append(getAddressId()).append(","); if (getKmsKeyARN() != null) sb.append("KmsKeyARN: ").append(getKmsKeyARN()).append(","); if (getRoleARN() != null) sb.append("RoleARN: ").append(getRoleARN()).append(","); if (getSnowballCapacityPreference() != null) sb.append("SnowballCapacityPreference: ").append(getSnowballCapacityPreference()).append(","); if (getShippingOption() != null) sb.append("ShippingOption: ").append(getShippingOption()).append(","); if (getNotification() != null) sb.append("Notification: ").append(getNotification()).append(","); if (getClusterId() != null) sb.append("ClusterId: ").append(getClusterId()).append(","); if (getSnowballType() != null) sb.append("SnowballType: ").append(getSnowballType()).append(","); if (getForwardingAddressId() != null) sb.append("ForwardingAddressId: ").append(getForwardingAddressId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateJobRequest == false) return false; CreateJobRequest other = (CreateJobRequest) obj; if (other.getJobType() == null ^ this.getJobType() == null) return false; if (other.getJobType() != null && other.getJobType().equals(this.getJobType()) == false) return false; if (other.getResources() == null ^ this.getResources() == null) return false; if (other.getResources() != null && other.getResources().equals(this.getResources()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getAddressId() == null ^ this.getAddressId() == null) return false; if (other.getAddressId() != null && other.getAddressId().equals(this.getAddressId()) == false) return false; if (other.getKmsKeyARN() == null ^ this.getKmsKeyARN() == null) return false; if (other.getKmsKeyARN() != null && other.getKmsKeyARN().equals(this.getKmsKeyARN()) == false) return false; if (other.getRoleARN() == null ^ this.getRoleARN() == null) return false; if (other.getRoleARN() != null && other.getRoleARN().equals(this.getRoleARN()) == false) return false; if (other.getSnowballCapacityPreference() == null ^ this.getSnowballCapacityPreference() == null) return false; if (other.getSnowballCapacityPreference() != null && other.getSnowballCapacityPreference().equals(this.getSnowballCapacityPreference()) == false) return false; if (other.getShippingOption() == null ^ this.getShippingOption() == null) return false; if (other.getShippingOption() != null && other.getShippingOption().equals(this.getShippingOption()) == false) return false; if (other.getNotification() == null ^ this.getNotification() == null) return false; if (other.getNotification() != null && other.getNotification().equals(this.getNotification()) == false) return false; if (other.getClusterId() == null ^ this.getClusterId() == null) return false; if (other.getClusterId() != null && other.getClusterId().equals(this.getClusterId()) == false) return false; if (other.getSnowballType() == null ^ this.getSnowballType() == null) return false; if (other.getSnowballType() != null && other.getSnowballType().equals(this.getSnowballType()) == false) return false; if (other.getForwardingAddressId() == null ^ this.getForwardingAddressId() == null) return false; if (other.getForwardingAddressId() != null && other.getForwardingAddressId().equals(this.getForwardingAddressId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getJobType() == null) ? 0 : getJobType().hashCode()); hashCode = prime * hashCode + ((getResources() == null) ? 0 : getResources().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getAddressId() == null) ? 0 : getAddressId().hashCode()); hashCode = prime * hashCode + ((getKmsKeyARN() == null) ? 0 : getKmsKeyARN().hashCode()); hashCode = prime * hashCode + ((getRoleARN() == null) ? 0 : getRoleARN().hashCode()); hashCode = prime * hashCode + ((getSnowballCapacityPreference() == null) ? 0 : getSnowballCapacityPreference().hashCode()); hashCode = prime * hashCode + ((getShippingOption() == null) ? 0 : getShippingOption().hashCode()); hashCode = prime * hashCode + ((getNotification() == null) ? 0 : getNotification().hashCode()); hashCode = prime * hashCode + ((getClusterId() == null) ? 0 : getClusterId().hashCode()); hashCode = prime * hashCode + ((getSnowballType() == null) ? 0 : getSnowballType().hashCode()); hashCode = prime * hashCode + ((getForwardingAddressId() == null) ? 0 : getForwardingAddressId().hashCode()); return hashCode; } @Override public CreateJobRequest clone() { return (CreateJobRequest) super.clone(); } }
dagnir/aws-sdk-java
aws-java-sdk-snowball/src/main/java/com/amazonaws/services/snowball/model/CreateJobRequest.java
Java
apache-2.0
48,384
package com.n2quest.kadachepta.model; /** * Created by n2quest on 15/08/16. */ public class MyplaylistItem { String idPlaylist; String namePlaylist; int isPrivate; public MyplaylistItem (String idPlaylist, String namePlaylist, int isPrivate){ super(); this.idPlaylist = idPlaylist; this.namePlaylist = namePlaylist; this.isPrivate = isPrivate; } public String getIdPlaylist(){ return idPlaylist; } public void setIdPlaylist(String idPlaylist){ this.idPlaylist = idPlaylist; } public String getNamePlaylist(){ return namePlaylist; } public void setNamePlaylist(String namePlaylist){ this.namePlaylist = namePlaylist; } public int getIsPrivate(){ return isPrivate; } public void setIsPrivate(int isPrivate){ this.isPrivate = isPrivate; } }
n2questinc/kadachepta
kadacheptaApp/app/src/main/java/com/n2quest/kadachepta/model/MyplaylistItem.java
Java
apache-2.0
899
package yuown.spring.derby.security; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandlerImpl; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class YuownAuthenticationDeniedHandler extends AccessDeniedHandlerImpl { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { super.handle(request, response, accessDeniedException); } }
yuown/derby-app
src/main/java/yuown/spring/derby/security/YuownAuthenticationDeniedHandler.java
Java
apache-2.0
672
/* * Copyright 2010 Outerthought bvba * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lilyproject.repository.api; /** * A value type represents the type of the value of a {@link FieldType}. * * <p>It consists of: * <ul> * <li>A {@link PrimitiveValueType}: this is a particular kind of value like a string, long, ... It could * also be a composite value, e.g. a coordinate with x and y values. * <li>a multi-value flag: to indicate if the value should be multi-value, in which case the value is a * java.util.List. * <li>a hierarchical flag: to indicate if the value should be a hierarchical path, in which case the value is * a {@link HierarchyPath}. * </ul> * * <p>The reason for having the separate concept of a {@link PrimitiveValueType} is so that we could have a multi-value * and/or hierarchical variant of any kind of value. * * <p>A field can be either multi-value or hierarchical, or both at the same time. In the last case, the value * is a java.util.List of {@link HierarchyPath} objects, not the other way round. * * <p>So you can have a multi-valued string, a multi-valued date, a single-valued hierarchical string path, * a multi-valued hierarchical string path, ... * * <p>It is the responsibility of a ValueType to convert the values to/from byte representation, as used for * storage in the repository. This should delegate to the PrimitiveValueType for the conversion of a single value. * * <p>It is not necessary to create value types in the repository, they simply exist for any kind of primitive * value type. You can get access to ValueType instances via {@link TypeManager#getValueType(String, boolean, boolean)}. * */ public interface ValueType { /** * Is this a multi-value value type. */ boolean isMultiValue(); /** * Is this a hierarchical value type. See also {@link HierarchyPath}. */ boolean isHierarchical(); /** * Is this a primitive value type. A value type is primitive if it is not hierarchical and not multi-value, thus * if its values directly correspond to the {@link #getPrimitive PrimitiveValueType}. This is a shortcut method * to avoid checking the other flags individually. */ boolean isPrimitive(); /** * Decodes a byte[] to an object of the type represented by this {@link ValueType}. See {@link ValueType#getType()} */ public Object fromBytes(byte[] value); /** * Encodes an object of the type represented by this {@link ValueType} to a byte[]. */ byte[] toBytes(Object value); /** * Gets the primitive value type. */ PrimitiveValueType getPrimitive(); /** * Returns the Java {@link Class} object for the values of this value type. * * <p>For multi-value fields (including those which are hierarchical), this will be java.util.List. * For single-valued hierarchical fields this is {@link HierarchyPath}. In all other cases, this is the same * as {@link PrimitiveValueType#getType}. */ Class getType(); /** * Returns an encoded byte[] representing this value type. */ byte[] toBytes(); boolean equals(Object obj); }
ekoontz/Lily
cr/repository/api/src/main/java/org/lilyproject/repository/api/ValueType.java
Java
apache-2.0
3,735
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; public interface RouterOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.Router) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * BGP information specific to this router. * </pre> * * <code>optional .google.cloud.compute.v1.RouterBgp bgp = 97483;</code> * * @return Whether the bgp field is set. */ boolean hasBgp(); /** * * * <pre> * BGP information specific to this router. * </pre> * * <code>optional .google.cloud.compute.v1.RouterBgp bgp = 97483;</code> * * @return The bgp. */ com.google.cloud.compute.v1.RouterBgp getBgp(); /** * * * <pre> * BGP information specific to this router. * </pre> * * <code>optional .google.cloud.compute.v1.RouterBgp bgp = 97483;</code> */ com.google.cloud.compute.v1.RouterBgpOrBuilder getBgpOrBuilder(); /** * * * <pre> * BGP information that must be configured into the routing stack to establish BGP peering. This information must specify the peer ASN and either the interface name, IP address, or peer IP address. Please refer to RFC4273. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterBgpPeer bgp_peers = 452695773;</code> */ java.util.List<com.google.cloud.compute.v1.RouterBgpPeer> getBgpPeersList(); /** * * * <pre> * BGP information that must be configured into the routing stack to establish BGP peering. This information must specify the peer ASN and either the interface name, IP address, or peer IP address. Please refer to RFC4273. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterBgpPeer bgp_peers = 452695773;</code> */ com.google.cloud.compute.v1.RouterBgpPeer getBgpPeers(int index); /** * * * <pre> * BGP information that must be configured into the routing stack to establish BGP peering. This information must specify the peer ASN and either the interface name, IP address, or peer IP address. Please refer to RFC4273. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterBgpPeer bgp_peers = 452695773;</code> */ int getBgpPeersCount(); /** * * * <pre> * BGP information that must be configured into the routing stack to establish BGP peering. This information must specify the peer ASN and either the interface name, IP address, or peer IP address. Please refer to RFC4273. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterBgpPeer bgp_peers = 452695773;</code> */ java.util.List<? extends com.google.cloud.compute.v1.RouterBgpPeerOrBuilder> getBgpPeersOrBuilderList(); /** * * * <pre> * BGP information that must be configured into the routing stack to establish BGP peering. This information must specify the peer ASN and either the interface name, IP address, or peer IP address. Please refer to RFC4273. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterBgpPeer bgp_peers = 452695773;</code> */ com.google.cloud.compute.v1.RouterBgpPeerOrBuilder getBgpPeersOrBuilder(int index); /** * * * <pre> * [Output Only] Creation timestamp in RFC3339 text format. * </pre> * * <code>optional string creation_timestamp = 30525366;</code> * * @return Whether the creationTimestamp field is set. */ boolean hasCreationTimestamp(); /** * * * <pre> * [Output Only] Creation timestamp in RFC3339 text format. * </pre> * * <code>optional string creation_timestamp = 30525366;</code> * * @return The creationTimestamp. */ java.lang.String getCreationTimestamp(); /** * * * <pre> * [Output Only] Creation timestamp in RFC3339 text format. * </pre> * * <code>optional string creation_timestamp = 30525366;</code> * * @return The bytes for creationTimestamp. */ com.google.protobuf.ByteString getCreationTimestampBytes(); /** * * * <pre> * An optional description of this resource. Provide this property when you create the resource. * </pre> * * <code>optional string description = 422937596;</code> * * @return Whether the description field is set. */ boolean hasDescription(); /** * * * <pre> * An optional description of this resource. Provide this property when you create the resource. * </pre> * * <code>optional string description = 422937596;</code> * * @return The description. */ java.lang.String getDescription(); /** * * * <pre> * An optional description of this resource. Provide this property when you create the resource. * </pre> * * <code>optional string description = 422937596;</code> * * @return The bytes for description. */ com.google.protobuf.ByteString getDescriptionBytes(); /** * * * <pre> * Indicates if a router is dedicated for use with encrypted VLAN attachments (interconnectAttachments). Not currently available publicly. * </pre> * * <code>optional bool encrypted_interconnect_router = 297996575;</code> * * @return Whether the encryptedInterconnectRouter field is set. */ boolean hasEncryptedInterconnectRouter(); /** * * * <pre> * Indicates if a router is dedicated for use with encrypted VLAN attachments (interconnectAttachments). Not currently available publicly. * </pre> * * <code>optional bool encrypted_interconnect_router = 297996575;</code> * * @return The encryptedInterconnectRouter. */ boolean getEncryptedInterconnectRouter(); /** * * * <pre> * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * </pre> * * <code>optional uint64 id = 3355;</code> * * @return Whether the id field is set. */ boolean hasId(); /** * * * <pre> * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * </pre> * * <code>optional uint64 id = 3355;</code> * * @return The id. */ long getId(); /** * * * <pre> * Router interfaces. Each interface requires either one linked resource, (for example, linkedVpnTunnel), or IP address and IP address range (for example, ipRange), or both. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterInterface interfaces = 12073562;</code> */ java.util.List<com.google.cloud.compute.v1.RouterInterface> getInterfacesList(); /** * * * <pre> * Router interfaces. Each interface requires either one linked resource, (for example, linkedVpnTunnel), or IP address and IP address range (for example, ipRange), or both. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterInterface interfaces = 12073562;</code> */ com.google.cloud.compute.v1.RouterInterface getInterfaces(int index); /** * * * <pre> * Router interfaces. Each interface requires either one linked resource, (for example, linkedVpnTunnel), or IP address and IP address range (for example, ipRange), or both. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterInterface interfaces = 12073562;</code> */ int getInterfacesCount(); /** * * * <pre> * Router interfaces. Each interface requires either one linked resource, (for example, linkedVpnTunnel), or IP address and IP address range (for example, ipRange), or both. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterInterface interfaces = 12073562;</code> */ java.util.List<? extends com.google.cloud.compute.v1.RouterInterfaceOrBuilder> getInterfacesOrBuilderList(); /** * * * <pre> * Router interfaces. Each interface requires either one linked resource, (for example, linkedVpnTunnel), or IP address and IP address range (for example, ipRange), or both. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterInterface interfaces = 12073562;</code> */ com.google.cloud.compute.v1.RouterInterfaceOrBuilder getInterfacesOrBuilder(int index); /** * * * <pre> * [Output Only] Type of resource. Always compute#router for routers. * </pre> * * <code>optional string kind = 3292052;</code> * * @return Whether the kind field is set. */ boolean hasKind(); /** * * * <pre> * [Output Only] Type of resource. Always compute#router for routers. * </pre> * * <code>optional string kind = 3292052;</code> * * @return The kind. */ java.lang.String getKind(); /** * * * <pre> * [Output Only] Type of resource. Always compute#router for routers. * </pre> * * <code>optional string kind = 3292052;</code> * * @return The bytes for kind. */ com.google.protobuf.ByteString getKindBytes(); /** * * * <pre> * Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. * </pre> * * <code>optional string name = 3373707;</code> * * @return Whether the name field is set. */ boolean hasName(); /** * * * <pre> * Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. * </pre> * * <code>optional string name = 3373707;</code> * * @return The name. */ java.lang.String getName(); /** * * * <pre> * Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. * </pre> * * <code>optional string name = 3373707;</code> * * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); /** * * * <pre> * A list of NAT services created in this router. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterNat nats = 3373938;</code> */ java.util.List<com.google.cloud.compute.v1.RouterNat> getNatsList(); /** * * * <pre> * A list of NAT services created in this router. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterNat nats = 3373938;</code> */ com.google.cloud.compute.v1.RouterNat getNats(int index); /** * * * <pre> * A list of NAT services created in this router. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterNat nats = 3373938;</code> */ int getNatsCount(); /** * * * <pre> * A list of NAT services created in this router. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterNat nats = 3373938;</code> */ java.util.List<? extends com.google.cloud.compute.v1.RouterNatOrBuilder> getNatsOrBuilderList(); /** * * * <pre> * A list of NAT services created in this router. * </pre> * * <code>repeated .google.cloud.compute.v1.RouterNat nats = 3373938;</code> */ com.google.cloud.compute.v1.RouterNatOrBuilder getNatsOrBuilder(int index); /** * * * <pre> * URI of the network to which this router belongs. * </pre> * * <code>optional string network = 232872494;</code> * * @return Whether the network field is set. */ boolean hasNetwork(); /** * * * <pre> * URI of the network to which this router belongs. * </pre> * * <code>optional string network = 232872494;</code> * * @return The network. */ java.lang.String getNetwork(); /** * * * <pre> * URI of the network to which this router belongs. * </pre> * * <code>optional string network = 232872494;</code> * * @return The bytes for network. */ com.google.protobuf.ByteString getNetworkBytes(); /** * * * <pre> * [Output Only] URI of the region where the router resides. You must specify this field as part of the HTTP request URL. It is not settable as a field in the request body. * </pre> * * <code>optional string region = 138946292;</code> * * @return Whether the region field is set. */ boolean hasRegion(); /** * * * <pre> * [Output Only] URI of the region where the router resides. You must specify this field as part of the HTTP request URL. It is not settable as a field in the request body. * </pre> * * <code>optional string region = 138946292;</code> * * @return The region. */ java.lang.String getRegion(); /** * * * <pre> * [Output Only] URI of the region where the router resides. You must specify this field as part of the HTTP request URL. It is not settable as a field in the request body. * </pre> * * <code>optional string region = 138946292;</code> * * @return The bytes for region. */ com.google.protobuf.ByteString getRegionBytes(); /** * * * <pre> * [Output Only] Server-defined URL for the resource. * </pre> * * <code>optional string self_link = 456214797;</code> * * @return Whether the selfLink field is set. */ boolean hasSelfLink(); /** * * * <pre> * [Output Only] Server-defined URL for the resource. * </pre> * * <code>optional string self_link = 456214797;</code> * * @return The selfLink. */ java.lang.String getSelfLink(); /** * * * <pre> * [Output Only] Server-defined URL for the resource. * </pre> * * <code>optional string self_link = 456214797;</code> * * @return The bytes for selfLink. */ com.google.protobuf.ByteString getSelfLinkBytes(); }
googleapis/java-compute
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/RouterOrBuilder.java
Java
apache-2.0
15,073
package com.atlassian.plugins.codegen.modules.common.component; import java.io.IOException; import com.atlassian.plugins.codegen.AbstractCodegenTestCase; import com.atlassian.plugins.codegen.modules.PluginModuleLocation; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertTrue; //TODO: update test to use Dom4J /** * @since 3.6 */ public class ComponentImportTest extends AbstractCodegenTestCase<ComponentImportProperties> { @Before public void runGenerator() throws Exception { setCreator(new ComponentImportModuleCreator()); setModuleLocation(new PluginModuleLocation.Builder(srcDir) .resourcesDirectory(resourcesDir) .testDirectory(testDir) .templateDirectory(templateDir) .build()); setProps(new ComponentImportProperties("com.atlassian.SomeInterface")); props.setIncludeExamples(false); creator.createModule(moduleLocation, props); } @Test public void pluginXmlContainsModule() throws IOException { String pluginXmlContent = FileUtils.readFileToString(pluginXml); assertTrue("module not found in plugin xml", pluginXmlContent.contains("<component-import")); assertTrue("module class not found in plugin xml", pluginXmlContent.contains("interface=\"com.atlassian.SomeInterface\"")); } }
mrdon/AMPS
plugin-module-codegen-engine/src/test/java/com/atlassian/plugins/codegen/modules/common/component/ComponentImportTest.java
Java
apache-2.0
1,439
package com.cowthan.algrithm.algs4; /************************************************************************* * Compilation: javac Transaction.java * Execution: java Transaction * * Data type for commercial transactions. * *************************************************************************/ import java.util.Arrays; import java.util.Comparator; import com.cowthan.algrithm.std.In; import com.cowthan.algrithm.std.StdIn; import com.cowthan.algrithm.std.StdOut; public class Transaction implements Comparable<Transaction> { private final String who; // customer private final Date when; // date private final double amount; // amount public Transaction(String who, Date when, double amount) { this.who = who; this.when = when; this.amount = amount; } // create new transaction by parsing string of the form: name, // date, real number, separated by whitespace public Transaction(String transaction) { String[] a = transaction.split("\\s+"); who = a[0]; when = new Date(a[1]); amount = Double.parseDouble(a[2]); } // accessor methods public String who() { return who; } public Date when() { return when; } public double amount() { return amount; } public String toString() { return String.format("%-10s %10s %8.2f", who, when, amount); } public int compareTo(Transaction that) { if (this.amount < that.amount) return -1; else if (this.amount > that.amount) return +1; else return 0; } // is this Transaction equal to x? public boolean equals(Object x) { if (x == this) return true; if (x == null) return false; if (x.getClass() != this.getClass()) return false; Transaction that = (Transaction) x; return (this.amount == that.amount) && (this.who.equals(that.who)) && (this.when.equals(that.when)); } public int hashCode() { int hash = 17; hash = 31*hash + who.hashCode(); hash = 31*hash + when.hashCode(); hash = 31*hash + ((Double) amount).hashCode(); return hash; } // ascending order of account number public static class WhoOrder implements Comparator<Transaction> { public int compare(Transaction v, Transaction w) { return v.who.compareTo(w.who); } } // ascending order of time public static class WhenOrder implements Comparator<Transaction> { public int compare(Transaction v, Transaction w) { return v.when.compareTo(w.when); } } // ascending order of ammount public static class HowMuchOrder implements Comparator<Transaction> { public int compare(Transaction v, Transaction w) { if (v.amount < w.amount) return -1; else if (v.amount > w.amount) return +1; else return 0; } } // test client public static void main(String[] args) { Transaction[] a = new Transaction[4]; a[0] = new Transaction("Turing 6/17/1990 644.08"); a[1] = new Transaction("Tarjan 3/26/2002 4121.85"); a[2] = new Transaction("Knuth 6/14/1999 288.34"); a[3] = new Transaction("Dijkstra 8/22/2007 2678.40"); StdOut.println("Unsorted"); for (int i = 0; i < a.length; i++) StdOut.println(a[i]); StdOut.println(); StdOut.println("Sort by date"); Arrays.sort(a, new Transaction.WhenOrder()); for (int i = 0; i < a.length; i++) StdOut.println(a[i]); StdOut.println(); StdOut.println("Sort by customer"); Arrays.sort(a, new Transaction.WhoOrder()); for (int i = 0; i < a.length; i++) StdOut.println(a[i]); StdOut.println(); StdOut.println("Sort by amount"); Arrays.sort(a, new Transaction.HowMuchOrder()); for (int i = 0; i < a.length; i++) StdOut.println(a[i]); StdOut.println(); } }
cowthan/JavaAyo
src/com/cowthan/algrithm/algs4/Transaction.java
Java
apache-2.0
4,204
package com.xht.android.serverhelp.util; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Environment; import android.support.v4.util.LruCache; import android.text.TextUtils; import android.util.Log; import android.widget.ImageView; import com.xht.android.serverhelp.ceche.DiskLruCache; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * 图片异步加载类 * * @author Leslie.Fang * */ public class AsyncImageLoader { private Context context; // 内存缓存默认 5M static final int MEM_CACHE_DEFAULT_SIZE = 10 * 1024 * 1024; // 文件缓存默认 10M static final int DISK_CACHE_DEFAULT_SIZE = 20 * 1024 * 1024; // 一级内存缓存基于 LruCache private LruCache<String, Bitmap> memCache; // 二级文件缓存基于 DiskLruCache private DiskLruCache diskCache; public AsyncImageLoader(Context context) { this.context = context; initMemCache(); initDiskLruCache(); } /** * 初始化内存缓存 */ private void initMemCache() { memCache = new LruCache<String, Bitmap>(MEM_CACHE_DEFAULT_SIZE) { @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getByteCount(); } }; } /** * 初始化文件缓存 */ private void initDiskLruCache() { try { File cacheDir = getDiskCacheDir(context, "bitmap"); if (!cacheDir.exists()) { cacheDir.mkdirs(); } diskCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, DISK_CACHE_DEFAULT_SIZE); } catch (IOException e) { e.printStackTrace(); } } /** * 从内存缓存中拿 * * @param url */ public Bitmap getBitmapFromMem(String url) { return memCache.get(url); } /** * 加入到内存缓存中 * * @param url * @param bitmap */ public void putBitmapToMem(String url, Bitmap bitmap) { memCache.put(url, bitmap); } /** * 从文件缓存中拿 * * @param url */ public Bitmap getBitmapFromDisk(String url) { try { String key = hashKeyForDisk(url); DiskLruCache.Snapshot snapShot = diskCache.get(key); if (snapShot != null) { InputStream is = snapShot.getInputStream(0); Bitmap bitmap = BitmapFactory.decodeStream(is); return bitmap; } } catch (IOException e) { e.printStackTrace(); } return null; } /** * 从 url 加载图片 * * @param imageView * @param imageUrl */ public Bitmap loadImage(ImageView imageView, String imageUrl) { // 先从内存中拿 Bitmap bitmap = getBitmapFromMem(imageUrl); if (bitmap != null) { Log.i("leslie", "image exists in memory"); return bitmap; } // 再从文件中找 bitmap = getBitmapFromDisk(imageUrl); if (bitmap != null) { Log.i("leslie", "image exists in file"); // 重新缓存到内存中 putBitmapToMem(imageUrl, bitmap); return bitmap; } // 内存和文件中都没有再从网络下载 if (!TextUtils.isEmpty(imageUrl)) { new ImageDownloadTask(imageView).execute(imageUrl); } return null; } class ImageDownloadTask extends AsyncTask<String, Integer, Bitmap> { private String imageUrl; private ImageView imageView; public ImageDownloadTask(ImageView imageView) { this.imageView = imageView; } @Override protected Bitmap doInBackground(String... params) { try { imageUrl = params[0]; String key = hashKeyForDisk(imageUrl); // 下载成功后直接将图片流写入文件缓存 DiskLruCache.Editor editor = diskCache.edit(key); if (editor != null) { OutputStream outputStream = editor.newOutputStream(0); if (downloadUrlToStream(imageUrl, outputStream)) { editor.commit(); } else { editor.abort(); } } diskCache.flush(); Bitmap bitmap = getBitmapFromDisk(imageUrl); if (bitmap != null) { // 将图片加入到内存缓存中 putBitmapToMem(imageUrl, bitmap); } return bitmap; } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap result) { super.onPostExecute(result); if (result != null) { // 通过 tag 来防止图片错位 if (imageView.getTag() != null && imageView.getTag().equals(imageUrl)) { imageView.setImageBitmap(result); } } } private boolean downloadUrlToStream(String urlString, OutputStream outputStream) { HttpURLConnection urlConnection = null; BufferedOutputStream out = null; BufferedInputStream in = null; try { final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024); out = new BufferedOutputStream(outputStream, 8 * 1024); int b; while ((b = in.read()) != -1) { out.write(b); } return true; } catch (final IOException e) { e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (final IOException e) { e.printStackTrace(); } } return false; } } private File getDiskCacheDir(Context context, String uniqueName) { String cachePath; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) { cachePath = context.getExternalCacheDir().getPath(); } else { cachePath = context.getCacheDir().getPath(); } return new File(cachePath + File.separator + uniqueName); } private int getAppVersion(Context context) { try { PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return info.versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } return 1; } private String hashKeyForDisk(String key) { String cacheKey; try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(key.getBytes()); cacheKey = bytesToHexString(mDigest.digest()); } catch (NoSuchAlgorithmException e) { cacheKey = String.valueOf(key.hashCode()); } return cacheKey; } private String bytesToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } }
caichengan/ServerHelp
app/src/main/java/com/xht/android/serverhelp/util/AsyncImageLoader.java
Java
apache-2.0
8,521
package com.atlassian.jgitflow.core.extension.impl; import java.util.Arrays; import java.util.List; import com.atlassian.jgitflow.core.extension.ExtensionCommand; import com.atlassian.jgitflow.core.extension.JGitFlowExtension; import com.google.common.collect.Iterables; import static com.google.common.collect.Lists.newArrayList; public abstract class EmptyJGitFlowExtension implements JGitFlowExtension { private final List<ExtensionCommand> before; private final List<ExtensionCommand> after; private final List<ExtensionCommand> beforeFetch; private final List<ExtensionCommand> afterFetch; private final List<ExtensionCommand> afterPush; protected EmptyJGitFlowExtension() { this.before = newArrayList(); this.after = newArrayList(); this.beforeFetch = newArrayList(); this.afterFetch = newArrayList(); this.afterPush = newArrayList(); } public void addBeforeCommands(ExtensionCommand ... commands) { before.addAll(Arrays.asList(commands)); } public void addAfterCommands(ExtensionCommand ... commands) { after.addAll(Arrays.asList(commands)); } public void addBeforeFetchCommands(ExtensionCommand ... commands) { beforeFetch.addAll(Arrays.asList(commands)); } public void addAfterFetchCommands(ExtensionCommand ... commands) { afterFetch.addAll(Arrays.asList(commands)); } public void addAfterPushCommands(ExtensionCommand ... commands) { afterPush.addAll(Arrays.asList(commands)); } @Override public Iterable<ExtensionCommand> before() { return Iterables.unmodifiableIterable(before); } @Override public Iterable<ExtensionCommand> after() { return Iterables.unmodifiableIterable(after); } @Override public Iterable<ExtensionCommand> beforeFetch() { return Iterables.unmodifiableIterable(beforeFetch); } @Override public Iterable<ExtensionCommand> afterFetch() { return Iterables.unmodifiableIterable(afterFetch); } @Override public Iterable<ExtensionCommand> afterPush() { return Iterables.unmodifiableIterable(afterPush); } }
ctrimble/jgit-flow
jgit-flow-core/src/main/java/com/atlassian/jgitflow/core/extension/impl/EmptyJGitFlowExtension.java
Java
apache-2.0
2,250
/* * Copyright 2019 Esri. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.esri.samples.orbit_the_camera_around_an_object; import java.io.File; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.Slider; import com.esri.arcgisruntime.ArcGISRuntimeEnvironment; import com.esri.arcgisruntime.geometry.Point; import com.esri.arcgisruntime.geometry.SpatialReferences; import com.esri.arcgisruntime.mapping.ArcGISScene; import com.esri.arcgisruntime.mapping.ArcGISTiledElevationSource; import com.esri.arcgisruntime.mapping.BasemapStyle; import com.esri.arcgisruntime.mapping.Surface; import com.esri.arcgisruntime.mapping.view.DrawStatus; import com.esri.arcgisruntime.mapping.view.DrawStatusChangedEvent; import com.esri.arcgisruntime.mapping.view.DrawStatusChangedListener; import com.esri.arcgisruntime.mapping.view.Graphic; import com.esri.arcgisruntime.mapping.view.GraphicsOverlay; import com.esri.arcgisruntime.mapping.view.LayerSceneProperties; import com.esri.arcgisruntime.mapping.view.OrbitGeoElementCameraController; import com.esri.arcgisruntime.mapping.view.SceneView; import com.esri.arcgisruntime.symbology.ModelSceneSymbol; import com.esri.arcgisruntime.symbology.SimpleRenderer; public class OrbitTheCameraAroundAnObjectController { @FXML private SceneView sceneView; @FXML private CheckBox allowDistanceInteractionCheckBox; @FXML private Slider cameraHeadingSlider; @FXML private Slider planePitchSlider; private OrbitGeoElementCameraController orbitCameraController; public void initialize() { try { // authentication with an API key or named user is required to access basemaps and other location services String yourAPIKey = System.getProperty("apiKey"); ArcGISRuntimeEnvironment.setApiKey(yourAPIKey); // create a scene with a basemap style and set it to the scene view ArcGISScene scene = new ArcGISScene(BasemapStyle.ARCGIS_IMAGERY); sceneView.setArcGISScene(scene); // add a base surface with elevation data Surface surface = new Surface(); ArcGISTiledElevationSource elevationSource = new ArcGISTiledElevationSource("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"); surface.getElevationSources().add(elevationSource); scene.setBaseSurface(surface); // create a graphics overlay for the scene GraphicsOverlay sceneGraphicsOverlay = new GraphicsOverlay(); sceneGraphicsOverlay.getSceneProperties().setSurfacePlacement(LayerSceneProperties.SurfacePlacement.RELATIVE); sceneView.getGraphicsOverlays().add(sceneGraphicsOverlay); // create a renderer to control the plane's orientation by its attributes SimpleRenderer renderer = new SimpleRenderer(); renderer.getSceneProperties().setHeadingExpression("[HEADING]"); renderer.getSceneProperties().setPitchExpression("[PITCH]"); sceneGraphicsOverlay.setRenderer(renderer); // create a graphic of a plane model String modelURI = new File(System.getProperty("data.dir"), "./samples-data/bristol/Collada/Bristol.dae").getAbsolutePath(); ModelSceneSymbol plane3DSymbol = new ModelSceneSymbol(modelURI, 1.0); plane3DSymbol.loadAsync(); // position the plane over a runway Graphic plane = new Graphic(new Point(6.637, 45.399, 100, SpatialReferences.getWgs84()), plane3DSymbol); // initialize the plane's heading to line up with the runway plane.getAttributes().put("HEADING", 45.0); sceneGraphicsOverlay.getGraphics().add(plane); // control the plane's pitch with a slider planePitchSlider.valueProperty().addListener(o -> plane.getAttributes().put("PITCH", planePitchSlider.getValue())); // listener for the view to stop loading and to add the camera controller DrawStatusChangedListener listener = new DrawStatusChangedListener() { @Override public void drawStatusChanged(DrawStatusChangedEvent drawStatusChangedEvent) { if (drawStatusChangedEvent.getDrawStatus() == DrawStatus.COMPLETED) { // create an orbit geoelement camera controller with the plane as the target orbitCameraController = new OrbitGeoElementCameraController(plane, 50.0); // restrict the camera's heading to stay behind the plane orbitCameraController.setMinCameraHeadingOffset(-45); orbitCameraController.setMaxCameraHeadingOffset(45); // restrict the camera's pitch so it doesn't go completely vertical or collide with the ground orbitCameraController.setMinCameraPitchOffset(10); orbitCameraController.setMaxCameraPitchOffset(100); // restrict the camera to stay between 10 and 1000 meters from the plane orbitCameraController.setMinCameraDistance(10); orbitCameraController.setMaxCameraDistance(100); // position the plane a third from the bottom of the screen orbitCameraController.setTargetVerticalScreenFactor(0.33f); // don't pitch the camera when the plane pitches orbitCameraController.setAutoPitchEnabled(false); // set the orbit camera controller to the scene view sceneView.setCameraController(orbitCameraController); // set the camera's heading using a slider cameraHeadingSlider.valueProperty().addListener(o -> orbitCameraController.setCameraHeadingOffset(cameraHeadingSlider.getValue())); // update camera heading slider position whilst interacting with the camera heading sceneView.addViewpointChangedListener( event -> cameraHeadingSlider.setValue(orbitCameraController.getCameraHeadingOffset())); // stop listening for the view to load sceneView.removeDrawStatusChangedListener(this); } } }; sceneView.addDrawStatusChangedListener(listener); } catch (Exception e) { // on any exception, print the stack trace e.printStackTrace(); } } /** * Animates the camera to a cockpit view. The camera's target is offset to the cockpit (instead of the plane's * center). The camera is moved onto the target position to create a swivelling camera effect. Auto pitch is * enabled so the camera pitches when the plane pitches. */ @FXML private void handleCockpitViewButtonClicked() { // disable camera distance interaction checkbox allowDistanceInteractionCheckBox.setDisable(true); // allow the camera to get closer to the target orbitCameraController.setMinCameraDistance(0); // pitch the camera when the plane pitches orbitCameraController.setAutoPitchEnabled(true); // animate the camera target to the cockpit instead of the center of the plane orbitCameraController.setTargetOffsetsAsync(0, -2, 1.1, 1); // animate the camera so that it is 0.01m from the target (cockpit), facing forward (0 deg heading), and aligned // with the horizon (90 deg pitch) orbitCameraController.moveCameraAsync(0 - orbitCameraController.getCameraDistance(), 0 - orbitCameraController.getCameraHeadingOffset(), 90 - orbitCameraController.getCameraPitchOffset(), 1).addDoneListener(() -> { // once the camera is in the cockpit, only allow the camera's heading to change orbitCameraController.setMinCameraPitchOffset(90); orbitCameraController.setMaxCameraPitchOffset(90); }); } /** * Configures the camera controller for a "follow" view. The camera targets the center of the plane with a default * position directly behind and slightly above the plane. Auto pitch is disabled so the camera does not pitch when * the plane pitches. */ @FXML private void handleCenterViewButtonClicked() { allowDistanceInteractionCheckBox.setDisable(false); orbitCameraController.setAutoPitchEnabled(false); orbitCameraController.setTargetOffsetX(0); orbitCameraController.setTargetOffsetY(0); orbitCameraController.setTargetOffsetZ(0); orbitCameraController.setCameraHeadingOffset(0); orbitCameraController.setCameraPitchOffset(45); orbitCameraController.setMinCameraPitchOffset(10); orbitCameraController.setMaxCameraPitchOffset(100); orbitCameraController.setMinCameraDistance(10.0); orbitCameraController.setCameraDistance(50.0); } /** * Toggle interactive distance. When distance interaction is disabled, the user cannot zoom in with the mouse. */ @FXML private void handleDistanceInteractionCheckBoxToggle() { orbitCameraController.setCameraDistanceInteractive(allowDistanceInteractionCheckBox.isSelected()); } /** * Disposes of application resources. */ void terminate() { // release resources when the application closes if (sceneView != null) { sceneView.dispose(); } } }
Esri/arcgis-runtime-samples-java
scene/orbit-the-camera-around-an-object/src/main/java/com/esri/samples/orbit_the_camera_around_an_object/OrbitTheCameraAroundAnObjectController.java
Java
apache-2.0
9,459
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package leap.orm.df; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import leap.core.BeanFactory; import leap.core.annotation.Inject; import leap.core.annotation.M; import leap.lang.Args; import leap.lang.Strings; import leap.orm.OrmContext; import leap.orm.OrmMetadata; import leap.orm.dmo.Dmo; import leap.orm.domain.Domain; import leap.orm.mapping.EntityMapping; import leap.orm.mapping.FieldMapping; public class DefaultDataFactory implements DataFactory,DataGeneratorContext { private final Map<String, DataGenerator> generatorCache = new ConcurrentHashMap<String, DataGenerator>(); protected final OrmContext context; protected final OrmMetadata metadata; protected @Inject @M BeanFactory beanFactory; protected @Inject @M DataGenerator defaultGenerator; protected @Inject @M DomainDatas domainDatas; @Inject(name = "domain") protected @M DataGenerator domainGenerator; public DefaultDataFactory(Dmo dmo){ this.context = dmo.getOrmContext(); this.metadata = context.getMetadata(); } @Override public DomainDatas getDomainDatas() { return domainDatas; } @Override public <T> T generate(Class<T> entityClass) { Args.notNull(entityClass,"entity class"); EntityMapping em = metadata.getEntityMapping(entityClass); T bean = em.getBeanType().newInstance(); for(FieldMapping fm : em.getFieldMappings()){ if(fm.isAutoGenerateValue()){ continue; } Object value = generateFieldValue(em, fm); if(null != value){ fm.getBeanProperty().setValue(bean, value); } } return bean; } protected Object generateFieldValue(EntityMapping em,FieldMapping fm) { String cacheKey = Strings.lowerCase(em.getEntityName() + "." + fm.getFieldName()); DataGenerator generator = generatorCache.get(cacheKey); if(null == generator){ Domain domain = fm.getDomain(); if(null != domain){ generator = beanFactory.tryGetBean(DataGenerator.class, domain.getName()); if(null == generator){ DomainData data = domainDatas.tryGetDomainData(domain); if(null != data){ generator = domainGenerator; } } } if(null == generator){ generator = defaultGenerator; } generatorCache.put(cacheKey, generator); } return generator.generateValue(this, em, fm); } }
leapframework/framework
data/orm/src/main/java/leap/orm/df/DefaultDataFactory.java
Java
apache-2.0
3,004
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.spin.json; import org.camunda.spin.SpinList; /** * @author Stefan Hentschel */ public interface SpinJsonPathQuery { /** * Fetches the node from the result of JsonPath. * * @return {@link SpinJsonNode} representation of the found node * @throws SpinJsonPathException if node value is not a valid json path expression or the path is not found. */ SpinJsonNode element(); /** * Fetches the list of nodes from the result of JsonPath. * * @return {@link SpinList} list of found nodes * @throws SpinJsonDataFormatException if node value is not Array. */ SpinList<SpinJsonNode> elementList(); /** * Fetches the string value from the result of JsonPath. * * @return String value of found node * @throws SpinJsonDataFormatException if node value is not String. */ String stringValue(); /** * Fetches the number value from the result of JsonPath. * * @return Number value of found node * @throws SpinJsonDataFormatException if node value is not Number. */ Number numberValue(); /** * Fetches the boolean value from the result of JsonPath. * * @return Boolean value of found node * @throws SpinJsonDataFormatException if node value is not Boolean. */ Boolean boolValue(); }
camunda/camunda-spin
core/src/main/java/org/camunda/spin/json/SpinJsonPathQuery.java
Java
apache-2.0
2,095
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.optaplanner.core.impl.heuristic.selector.common.iterator; import java.util.Collections; import java.util.ListIterator; import org.optaplanner.core.impl.heuristic.move.Move; import org.optaplanner.core.impl.heuristic.selector.ListIterableSelector; public abstract class AbstractOriginalSwapIterator<Solution_, Move_ extends Move<Solution_>, SubSelection_> extends UpcomingSelectionIterator<Move_> { public static <Solution_, SubSelection_> long getSize(ListIterableSelector<Solution_, SubSelection_> leftSubSelector, ListIterableSelector<Solution_, SubSelection_> rightSubSelector) { if (leftSubSelector != rightSubSelector) { return leftSubSelector.getSize() * rightSubSelector.getSize(); } else { long leftSize = leftSubSelector.getSize(); return leftSize * (leftSize - 1L) / 2L; } } protected final ListIterable<SubSelection_> leftSubSelector; protected final ListIterable<SubSelection_> rightSubSelector; protected final boolean leftEqualsRight; private final ListIterator<SubSelection_> leftSubSelectionIterator; private ListIterator<SubSelection_> rightSubSelectionIterator; private SubSelection_ leftSubSelection; public AbstractOriginalSwapIterator(ListIterable<SubSelection_> leftSubSelector, ListIterable<SubSelection_> rightSubSelector) { this.leftSubSelector = leftSubSelector; this.rightSubSelector = rightSubSelector; leftEqualsRight = (leftSubSelector == rightSubSelector); leftSubSelectionIterator = leftSubSelector.listIterator(); rightSubSelectionIterator = Collections.<SubSelection_> emptyList().listIterator(); // Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording) } @Override protected Move_ createUpcomingSelection() { if (!rightSubSelectionIterator.hasNext()) { if (!leftSubSelectionIterator.hasNext()) { return noUpcomingSelection(); } leftSubSelection = leftSubSelectionIterator.next(); if (!leftEqualsRight) { rightSubSelectionIterator = rightSubSelector.listIterator(); if (!rightSubSelectionIterator.hasNext()) { return noUpcomingSelection(); } } else { // Select A-B, A-C, B-C. Do not select B-A, C-A, C-B. Do not select A-A, B-B, C-C. if (!leftSubSelectionIterator.hasNext()) { return noUpcomingSelection(); } rightSubSelectionIterator = rightSubSelector.listIterator(leftSubSelectionIterator.nextIndex()); // rightEntityIterator's first hasNext() always returns true because of the nextIndex() } } SubSelection_ rightSubSelection = rightSubSelectionIterator.next(); return newSwapSelection(leftSubSelection, rightSubSelection); } protected abstract Move_ newSwapSelection(SubSelection_ leftSubSelection, SubSelection_ rightSubSelection); }
tkobayas/optaplanner
optaplanner-core/src/main/java/org/optaplanner/core/impl/heuristic/selector/common/iterator/AbstractOriginalSwapIterator.java
Java
apache-2.0
3,740
package com.google.cloud.dataproc.v1; import static io.grpc.stub.ClientCalls.asyncUnaryCall; import static io.grpc.stub.ClientCalls.asyncServerStreamingCall; import static io.grpc.stub.ClientCalls.asyncClientStreamingCall; import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall; import static io.grpc.stub.ClientCalls.blockingUnaryCall; import static io.grpc.stub.ClientCalls.blockingServerStreamingCall; import static io.grpc.stub.ClientCalls.futureUnaryCall; import static io.grpc.MethodDescriptor.generateFullMethodName; import static io.grpc.stub.ServerCalls.asyncUnaryCall; import static io.grpc.stub.ServerCalls.asyncServerStreamingCall; import static io.grpc.stub.ServerCalls.asyncClientStreamingCall; import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall; /** * <pre> * The JobController provides methods to manage jobs. * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler (version 1.0.3)", comments = "Source: google/cloud/dataproc/v1/jobs.proto") public class JobControllerGrpc { private JobControllerGrpc() {} public static final String SERVICE_NAME = "google.cloud.dataproc.v1.JobController"; // Static method descriptors that strictly reflect the proto. @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static final io.grpc.MethodDescriptor<com.google.cloud.dataproc.v1.SubmitJobRequest, com.google.cloud.dataproc.v1.Job> METHOD_SUBMIT_JOB = io.grpc.MethodDescriptor.create( io.grpc.MethodDescriptor.MethodType.UNARY, generateFullMethodName( "google.cloud.dataproc.v1.JobController", "SubmitJob"), io.grpc.protobuf.ProtoUtils.marshaller(com.google.cloud.dataproc.v1.SubmitJobRequest.getDefaultInstance()), io.grpc.protobuf.ProtoUtils.marshaller(com.google.cloud.dataproc.v1.Job.getDefaultInstance())); @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static final io.grpc.MethodDescriptor<com.google.cloud.dataproc.v1.GetJobRequest, com.google.cloud.dataproc.v1.Job> METHOD_GET_JOB = io.grpc.MethodDescriptor.create( io.grpc.MethodDescriptor.MethodType.UNARY, generateFullMethodName( "google.cloud.dataproc.v1.JobController", "GetJob"), io.grpc.protobuf.ProtoUtils.marshaller(com.google.cloud.dataproc.v1.GetJobRequest.getDefaultInstance()), io.grpc.protobuf.ProtoUtils.marshaller(com.google.cloud.dataproc.v1.Job.getDefaultInstance())); @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static final io.grpc.MethodDescriptor<com.google.cloud.dataproc.v1.ListJobsRequest, com.google.cloud.dataproc.v1.ListJobsResponse> METHOD_LIST_JOBS = io.grpc.MethodDescriptor.create( io.grpc.MethodDescriptor.MethodType.UNARY, generateFullMethodName( "google.cloud.dataproc.v1.JobController", "ListJobs"), io.grpc.protobuf.ProtoUtils.marshaller(com.google.cloud.dataproc.v1.ListJobsRequest.getDefaultInstance()), io.grpc.protobuf.ProtoUtils.marshaller(com.google.cloud.dataproc.v1.ListJobsResponse.getDefaultInstance())); @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static final io.grpc.MethodDescriptor<com.google.cloud.dataproc.v1.CancelJobRequest, com.google.cloud.dataproc.v1.Job> METHOD_CANCEL_JOB = io.grpc.MethodDescriptor.create( io.grpc.MethodDescriptor.MethodType.UNARY, generateFullMethodName( "google.cloud.dataproc.v1.JobController", "CancelJob"), io.grpc.protobuf.ProtoUtils.marshaller(com.google.cloud.dataproc.v1.CancelJobRequest.getDefaultInstance()), io.grpc.protobuf.ProtoUtils.marshaller(com.google.cloud.dataproc.v1.Job.getDefaultInstance())); @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static final io.grpc.MethodDescriptor<com.google.cloud.dataproc.v1.DeleteJobRequest, com.google.protobuf.Empty> METHOD_DELETE_JOB = io.grpc.MethodDescriptor.create( io.grpc.MethodDescriptor.MethodType.UNARY, generateFullMethodName( "google.cloud.dataproc.v1.JobController", "DeleteJob"), io.grpc.protobuf.ProtoUtils.marshaller(com.google.cloud.dataproc.v1.DeleteJobRequest.getDefaultInstance()), io.grpc.protobuf.ProtoUtils.marshaller(com.google.protobuf.Empty.getDefaultInstance())); /** * Creates a new async stub that supports all call types for the service */ public static JobControllerStub newStub(io.grpc.Channel channel) { return new JobControllerStub(channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static JobControllerBlockingStub newBlockingStub( io.grpc.Channel channel) { return new JobControllerBlockingStub(channel); } /** * Creates a new ListenableFuture-style stub that supports unary and streaming output calls on the service */ public static JobControllerFutureStub newFutureStub( io.grpc.Channel channel) { return new JobControllerFutureStub(channel); } /** * <pre> * The JobController provides methods to manage jobs. * </pre> */ public static abstract class JobControllerImplBase implements io.grpc.BindableService { /** * <pre> * Submits a job to a cluster. * </pre> */ public void submitJob(com.google.cloud.dataproc.v1.SubmitJobRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.Job> responseObserver) { asyncUnimplementedUnaryCall(METHOD_SUBMIT_JOB, responseObserver); } /** * <pre> * Gets the resource representation for a job in a project. * </pre> */ public void getJob(com.google.cloud.dataproc.v1.GetJobRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.Job> responseObserver) { asyncUnimplementedUnaryCall(METHOD_GET_JOB, responseObserver); } /** * <pre> * Lists regions/{region}/jobs in a project. * </pre> */ public void listJobs(com.google.cloud.dataproc.v1.ListJobsRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.ListJobsResponse> responseObserver) { asyncUnimplementedUnaryCall(METHOD_LIST_JOBS, responseObserver); } /** * <pre> * Starts a job cancellation request. To access the job resource * after cancellation, call * [regions/{region}/jobs.list](/dataproc/reference/rest/v1/projects.regions.jobs/list) or * [regions/{region}/jobs.get](/dataproc/reference/rest/v1/projects.regions.jobs/get). * </pre> */ public void cancelJob(com.google.cloud.dataproc.v1.CancelJobRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.Job> responseObserver) { asyncUnimplementedUnaryCall(METHOD_CANCEL_JOB, responseObserver); } /** * <pre> * Deletes the job from the project. If the job is active, the delete fails, * and the response returns `FAILED_PRECONDITION`. * </pre> */ public void deleteJob(com.google.cloud.dataproc.v1.DeleteJobRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { asyncUnimplementedUnaryCall(METHOD_DELETE_JOB, responseObserver); } @java.lang.Override public io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( METHOD_SUBMIT_JOB, asyncUnaryCall( new MethodHandlers< com.google.cloud.dataproc.v1.SubmitJobRequest, com.google.cloud.dataproc.v1.Job>( this, METHODID_SUBMIT_JOB))) .addMethod( METHOD_GET_JOB, asyncUnaryCall( new MethodHandlers< com.google.cloud.dataproc.v1.GetJobRequest, com.google.cloud.dataproc.v1.Job>( this, METHODID_GET_JOB))) .addMethod( METHOD_LIST_JOBS, asyncUnaryCall( new MethodHandlers< com.google.cloud.dataproc.v1.ListJobsRequest, com.google.cloud.dataproc.v1.ListJobsResponse>( this, METHODID_LIST_JOBS))) .addMethod( METHOD_CANCEL_JOB, asyncUnaryCall( new MethodHandlers< com.google.cloud.dataproc.v1.CancelJobRequest, com.google.cloud.dataproc.v1.Job>( this, METHODID_CANCEL_JOB))) .addMethod( METHOD_DELETE_JOB, asyncUnaryCall( new MethodHandlers< com.google.cloud.dataproc.v1.DeleteJobRequest, com.google.protobuf.Empty>( this, METHODID_DELETE_JOB))) .build(); } } /** * <pre> * The JobController provides methods to manage jobs. * </pre> */ public static final class JobControllerStub extends io.grpc.stub.AbstractStub<JobControllerStub> { private JobControllerStub(io.grpc.Channel channel) { super(channel); } private JobControllerStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected JobControllerStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new JobControllerStub(channel, callOptions); } /** * <pre> * Submits a job to a cluster. * </pre> */ public void submitJob(com.google.cloud.dataproc.v1.SubmitJobRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.Job> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_SUBMIT_JOB, getCallOptions()), request, responseObserver); } /** * <pre> * Gets the resource representation for a job in a project. * </pre> */ public void getJob(com.google.cloud.dataproc.v1.GetJobRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.Job> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_GET_JOB, getCallOptions()), request, responseObserver); } /** * <pre> * Lists regions/{region}/jobs in a project. * </pre> */ public void listJobs(com.google.cloud.dataproc.v1.ListJobsRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.ListJobsResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_LIST_JOBS, getCallOptions()), request, responseObserver); } /** * <pre> * Starts a job cancellation request. To access the job resource * after cancellation, call * [regions/{region}/jobs.list](/dataproc/reference/rest/v1/projects.regions.jobs/list) or * [regions/{region}/jobs.get](/dataproc/reference/rest/v1/projects.regions.jobs/get). * </pre> */ public void cancelJob(com.google.cloud.dataproc.v1.CancelJobRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.Job> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_CANCEL_JOB, getCallOptions()), request, responseObserver); } /** * <pre> * Deletes the job from the project. If the job is active, the delete fails, * and the response returns `FAILED_PRECONDITION`. * </pre> */ public void deleteJob(com.google.cloud.dataproc.v1.DeleteJobRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_DELETE_JOB, getCallOptions()), request, responseObserver); } } /** * <pre> * The JobController provides methods to manage jobs. * </pre> */ public static final class JobControllerBlockingStub extends io.grpc.stub.AbstractStub<JobControllerBlockingStub> { private JobControllerBlockingStub(io.grpc.Channel channel) { super(channel); } private JobControllerBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected JobControllerBlockingStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new JobControllerBlockingStub(channel, callOptions); } /** * <pre> * Submits a job to a cluster. * </pre> */ public com.google.cloud.dataproc.v1.Job submitJob(com.google.cloud.dataproc.v1.SubmitJobRequest request) { return blockingUnaryCall( getChannel(), METHOD_SUBMIT_JOB, getCallOptions(), request); } /** * <pre> * Gets the resource representation for a job in a project. * </pre> */ public com.google.cloud.dataproc.v1.Job getJob(com.google.cloud.dataproc.v1.GetJobRequest request) { return blockingUnaryCall( getChannel(), METHOD_GET_JOB, getCallOptions(), request); } /** * <pre> * Lists regions/{region}/jobs in a project. * </pre> */ public com.google.cloud.dataproc.v1.ListJobsResponse listJobs(com.google.cloud.dataproc.v1.ListJobsRequest request) { return blockingUnaryCall( getChannel(), METHOD_LIST_JOBS, getCallOptions(), request); } /** * <pre> * Starts a job cancellation request. To access the job resource * after cancellation, call * [regions/{region}/jobs.list](/dataproc/reference/rest/v1/projects.regions.jobs/list) or * [regions/{region}/jobs.get](/dataproc/reference/rest/v1/projects.regions.jobs/get). * </pre> */ public com.google.cloud.dataproc.v1.Job cancelJob(com.google.cloud.dataproc.v1.CancelJobRequest request) { return blockingUnaryCall( getChannel(), METHOD_CANCEL_JOB, getCallOptions(), request); } /** * <pre> * Deletes the job from the project. If the job is active, the delete fails, * and the response returns `FAILED_PRECONDITION`. * </pre> */ public com.google.protobuf.Empty deleteJob(com.google.cloud.dataproc.v1.DeleteJobRequest request) { return blockingUnaryCall( getChannel(), METHOD_DELETE_JOB, getCallOptions(), request); } } /** * <pre> * The JobController provides methods to manage jobs. * </pre> */ public static final class JobControllerFutureStub extends io.grpc.stub.AbstractStub<JobControllerFutureStub> { private JobControllerFutureStub(io.grpc.Channel channel) { super(channel); } private JobControllerFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected JobControllerFutureStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new JobControllerFutureStub(channel, callOptions); } /** * <pre> * Submits a job to a cluster. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.cloud.dataproc.v1.Job> submitJob( com.google.cloud.dataproc.v1.SubmitJobRequest request) { return futureUnaryCall( getChannel().newCall(METHOD_SUBMIT_JOB, getCallOptions()), request); } /** * <pre> * Gets the resource representation for a job in a project. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.cloud.dataproc.v1.Job> getJob( com.google.cloud.dataproc.v1.GetJobRequest request) { return futureUnaryCall( getChannel().newCall(METHOD_GET_JOB, getCallOptions()), request); } /** * <pre> * Lists regions/{region}/jobs in a project. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.cloud.dataproc.v1.ListJobsResponse> listJobs( com.google.cloud.dataproc.v1.ListJobsRequest request) { return futureUnaryCall( getChannel().newCall(METHOD_LIST_JOBS, getCallOptions()), request); } /** * <pre> * Starts a job cancellation request. To access the job resource * after cancellation, call * [regions/{region}/jobs.list](/dataproc/reference/rest/v1/projects.regions.jobs/list) or * [regions/{region}/jobs.get](/dataproc/reference/rest/v1/projects.regions.jobs/get). * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.cloud.dataproc.v1.Job> cancelJob( com.google.cloud.dataproc.v1.CancelJobRequest request) { return futureUnaryCall( getChannel().newCall(METHOD_CANCEL_JOB, getCallOptions()), request); } /** * <pre> * Deletes the job from the project. If the job is active, the delete fails, * and the response returns `FAILED_PRECONDITION`. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty> deleteJob( com.google.cloud.dataproc.v1.DeleteJobRequest request) { return futureUnaryCall( getChannel().newCall(METHOD_DELETE_JOB, getCallOptions()), request); } } private static final int METHODID_SUBMIT_JOB = 0; private static final int METHODID_GET_JOB = 1; private static final int METHODID_LIST_JOBS = 2; private static final int METHODID_CANCEL_JOB = 3; private static final int METHODID_DELETE_JOB = 4; private static class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final JobControllerImplBase serviceImpl; private final int methodId; public MethodHandlers(JobControllerImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_SUBMIT_JOB: serviceImpl.submitJob((com.google.cloud.dataproc.v1.SubmitJobRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.Job>) responseObserver); break; case METHODID_GET_JOB: serviceImpl.getJob((com.google.cloud.dataproc.v1.GetJobRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.Job>) responseObserver); break; case METHODID_LIST_JOBS: serviceImpl.listJobs((com.google.cloud.dataproc.v1.ListJobsRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.ListJobsResponse>) responseObserver); break; case METHODID_CANCEL_JOB: serviceImpl.cancelJob((com.google.cloud.dataproc.v1.CancelJobRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.dataproc.v1.Job>) responseObserver); break; case METHODID_DELETE_JOB: serviceImpl.deleteJob((com.google.cloud.dataproc.v1.DeleteJobRequest) request, (io.grpc.stub.StreamObserver<com.google.protobuf.Empty>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } public static io.grpc.ServiceDescriptor getServiceDescriptor() { return new io.grpc.ServiceDescriptor(SERVICE_NAME, METHOD_SUBMIT_JOB, METHOD_GET_JOB, METHOD_LIST_JOBS, METHOD_CANCEL_JOB, METHOD_DELETE_JOB); } }
speedycontrol/googleapis
output/com/google/cloud/dataproc/v1/JobControllerGrpc.java
Java
apache-2.0
20,203
/////////////////////////////////////////////////////////////////////////// // __ _ _ ________ // // / / ____ ____ _(_)____/ | / / ____/ // // / / / __ \/ __ `/ / ___/ |/ / / __ // // / /___/ /_/ / /_/ / / /__/ /| / /_/ / // // /_____/\____/\__, /_/\___/_/ |_/\____/ // // /____/ // // // // The Next Generation Logic Library // // // /////////////////////////////////////////////////////////////////////////// // // // Copyright 2015-20xx Christoph Zengler // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // // implied. See the License for the specific language governing // // permissions and limitations under the License. // // // /////////////////////////////////////////////////////////////////////////// package org.logicng.transformations.simplification; import static org.logicng.formulas.FType.dual; import org.logicng.formulas.Equivalence; import org.logicng.formulas.FType; import org.logicng.formulas.Formula; import org.logicng.formulas.FormulaFactory; import org.logicng.formulas.FormulaTransformation; import org.logicng.formulas.Implication; import org.logicng.formulas.Not; import org.logicng.formulas.cache.TransformationCacheEntry; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; /** * A formula transformation which performs simplifications by applying the distributive laws. * @version 2.0.0 * @since 1.3 */ public final class DistributiveSimplifier implements FormulaTransformation { @Override public Formula apply(final Formula formula, final boolean cache) { final FormulaFactory f = formula.factory(); final Formula result; switch (formula.type()) { case FALSE: case TRUE: case LITERAL: case PBC: result = formula; break; case EQUIV: final Equivalence equiv = (Equivalence) formula; result = f.equivalence(this.apply(equiv.left(), cache), this.apply(equiv.right(), cache)); break; case IMPL: final Implication impl = (Implication) formula; result = f.implication(this.apply(impl.left(), cache), this.apply(impl.right(), cache)); break; case NOT: final Not not = (Not) formula; result = f.not(this.apply(not.operand(), cache)); break; case OR: case AND: result = distributeNAry(formula, cache, f); break; default: throw new IllegalStateException("Unknown formula type: " + formula.type()); } if (cache) { formula.setTransformationCacheEntry(TransformationCacheEntry.DISTRIBUTIVE_SIMPLIFICATION, result); } return result; } private Formula distributeNAry(final Formula formula, final boolean cache, final FormulaFactory f) { final Formula result; final FType outerType = formula.type(); final FType innerType = dual(outerType); final Set<Formula> operands = new LinkedHashSet<>(); for (final Formula op : formula) { operands.add(this.apply(op, cache)); } final Map<Formula, Set<Formula>> part2Operands = new LinkedHashMap<>(); Formula mostCommon = null; int mostCommonAmount = 0; for (final Formula op : operands) { if (op.type() == innerType) { for (final Formula part : op) { final Set<Formula> partOperands = part2Operands.computeIfAbsent(part, k -> new LinkedHashSet<>()); partOperands.add(op); if (partOperands.size() > mostCommonAmount) { mostCommon = part; mostCommonAmount = partOperands.size(); } } } } if (mostCommon == null || mostCommonAmount == 1) { result = f.naryOperator(outerType, operands); return result; } operands.removeAll(part2Operands.get(mostCommon)); final Set<Formula> relevantFormulas = new LinkedHashSet<>(); for (final Formula preRelevantFormula : part2Operands.get(mostCommon)) { final Set<Formula> relevantParts = new LinkedHashSet<>(); for (final Formula part : preRelevantFormula) { if (!part.equals(mostCommon)) { relevantParts.add(part); } } relevantFormulas.add(f.naryOperator(innerType, relevantParts)); } operands.add(f.naryOperator(innerType, mostCommon, f.naryOperator(outerType, relevantFormulas))); result = f.naryOperator(outerType, operands); return result; } }
logic-ng/LogicNG
src/main/java/org/logicng/transformations/simplification/DistributiveSimplifier.java
Java
apache-2.0
6,155
package liu.study.api.java.io.classes; import java.io.FileDescriptor; public class XFileDescriptor { private FileDescriptor f; }
xiaotangai/KnowledgeBase
src/main/java/liu/study/api/java/io/classes/XFileDescriptor.java
Java
apache-2.0
133
package br.com.caelum.vraptor.ioc.cdi.extensions; import java.lang.reflect.Method; import java.util.Set; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Default; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.AnnotatedMethod; import javax.enterprise.inject.spi.AnnotatedType; import javax.enterprise.util.AnnotationLiteral; import org.apache.deltaspike.core.util.metadata.builder.AnnotatedTypeBuilder; import org.junit.Test; import static org.junit.Assert.assertTrue; import br.com.caelum.vraptor.ioc.ComponentFactory; @SuppressWarnings({"serial","rawtypes","unchecked"}) public class ComponentFactoryExtensionTest { @Test public void shouldAddRequestScopeAndDefaultToProducerMethod() throws InterruptedException{ ProcessAnnotatedTypeMock pat = ProcessAnnotatedTypeFactory.create(NonScopedFactory.class); AnnotatedTypeBuilder builder = new AnnotatedTypeBuilder().readFromType(pat.getAnnotatedType()); ComponentFactoryExtension extension = new ComponentFactoryExtension(builder); extension.addProducesToComponentFactory(pat); pat.setAnnotatedType(builder.create()); AnnotatedMethod producer = getProducer(pat.getAnnotatedType()); assertTrue(producer.isAnnotationPresent(Produces.class)); assertTrue(producer.isAnnotationPresent(RequestScoped.class)); } @Test public void shouldAddClassScopeAndDefaultToProducerMethod(){ ProcessAnnotatedTypeMock pat = ProcessAnnotatedTypeFactory.create(ScopedFactory.class); AnnotatedTypeBuilder builder = new AnnotatedTypeBuilder().readFromType(pat.getAnnotatedType()); ComponentFactoryExtension extension = new ComponentFactoryExtension(builder); extension.addProducesToComponentFactory(pat); pat.setAnnotatedType(builder.create()); AnnotatedMethod producer = getProducer(pat.getAnnotatedType()); assertTrue(producer.isAnnotationPresent(Produces.class)); assertTrue(producer.isAnnotationPresent(ApplicationScoped.class)); } private AnnotatedMethod getProducer(AnnotatedType annotatedType){ /* * for some reason the AnnotatedType has 2 methods * getInstance with different return types. */ Set<AnnotatedMethod> methods = annotatedType.getMethods(); for (AnnotatedMethod annotatedMethod : methods) { Method javaMethod = annotatedMethod.getJavaMember(); if(javaMethod.getReturnType().equals(String.class) && javaMethod.getName().equals("getInstance")){ return annotatedMethod; } } throw new RuntimeException("You should use a ComponentFactory"); } private static class NonScopedFactory implements ComponentFactory<String>{ public String getInstance() { return null; } } @ApplicationScoped private static class ScopedFactory implements ComponentFactory<String>{ public String getInstance() { return null; } } }
caelum/vraptor-cdi-provider
src/test/java/br/com/caelum/vraptor/ioc/cdi/extensions/ComponentFactoryExtensionTest.java
Java
apache-2.0
2,861
package com.watcher; /** * Application Exception. * Created by Zhao Jinyan on 2016-12-29. */ class WatcherException extends Exception { WatcherException(String message){ super(message); } WatcherException(String message, Throwable throwable){ super(message, throwable); } }
ZhaoJingyan/FileWatcher
src/main/java/com/watcher/WatcherException.java
Java
apache-2.0
313
package com.cognizant.cognizantits.qcconnection.qcupdation; import com4j.Com4jObject; import com4j.DISPID; import com4j.IID; import com4j.NativeType; import com4j.ReturnValue; import com4j.VTID; @IID("{0D6A3C6E-D8D9-4F10-BF51-FB7FBD3666A7}") public abstract interface IAnalysisItemFolder extends IBaseField { @DISPID(14) @VTID(20) public abstract String name(); @DISPID(14) @VTID(21) public abstract void name(String paramString); @DISPID(15) @VTID(22) public abstract int parentId(); @DISPID(15) @VTID(23) public abstract void parentId(int paramInt); @DISPID(16) @VTID(24) public abstract boolean _public(); @DISPID(16) @VTID(25) public abstract void _public(boolean paramBoolean); @DISPID(17) @VTID(26) @ReturnValue(type=NativeType.Dispatch) public abstract Com4jObject analysisItemFolderFactory(); @DISPID(18) @VTID(27) @ReturnValue(type=NativeType.Dispatch) public abstract Com4jObject analysisItemFactory(); @DISPID(19) @VTID(28) public abstract String description(); @DISPID(19) @VTID(29) public abstract void description(String paramString); } /* Location: D:\Prabu\jars\QC.jar * Qualified Name: qcupdation.IAnalysisItemFolder * JD-Core Version: 0.7.0.1 */
CognizantQAHub/Cognizant-Intelligent-Test-Scripter
QcConnection/src/main/java/com/cognizant/cognizantits/qcconnection/qcupdation/IAnalysisItemFolder.java
Java
apache-2.0
1,280
/* # Licensed Materials - Property of IBM # Copyright IBM Corp. 2015 */ package com.ibm.streamsx.topology.messaging.kafka; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.ibm.streams.operator.Tuple; import com.ibm.streamsx.topology.TStream; import com.ibm.streamsx.topology.Topology; import com.ibm.streamsx.topology.TopologyElement; import com.ibm.streamsx.topology.builder.BOperatorInvocation; import com.ibm.streamsx.topology.builder.BOutputPort; import com.ibm.streamsx.topology.function.Function; import com.ibm.streamsx.topology.function.Supplier; import com.ibm.streamsx.topology.logic.Value; import com.ibm.streamsx.topology.spl.SPL; import com.ibm.streamsx.topology.spl.SPLStream; import com.ibm.streamsx.topology.tuple.Message; import com.ibm.streamsx.topology.tuple.SimpleMessage; /** * A simple connector to an Apache Kafka cluster for consuming Kafka messages * -- subscribing to Kafka topics and creating a {@code TStream<Message>}. * <p> * A single connector is for a specific Kafka cluster as specified in * the consumer configuration. * <p> * A connector can create any number of consumers in the topology. * A consumer can subscribe to one or more topics. * <p> * Sample use: * <pre> * Topology top = ... * Properties consumerConfig = ... * KafkaConsumer cc = new KafkaConsumer(top, consumerConfig); * // with Java8 Lambda expressions... * TStream<Message> rcvdMsgs = cc.consumer(()->"myTopic"); * // without Java8... * TStream<Message> rcvdMsgs = cc.consumer(new Value<String>("myTopic")); * </pre> * * @see <a href="http://kafka.apache.org">http://kafka.apache.org</a> * @see <a * href="http://ibmstreams.github.io/streamsx.messaging/">com.ibm.streamsx.messaging</a> */ public class KafkaConsumer { private static final String PROP_FILE_PARAM = "etc/kafkaStreams/emptyConsumerProperties"; private final TopologyElement te; private final Map<String,Object> config; private boolean addedFileDependency; void addPropertiesFile() { if (!addedFileDependency) { addedFileDependency = true; Util.addPropertiesFile(te, PROP_FILE_PARAM); } } /** * Create a consumer connector for subscribing to topics. * <p> * See the Apache Kafka documentation for {@code KafkaConsumer} * configuration properties at <a href="http://kafka.apache.org">http://kafka.apache.org</a>. * Configuration property values are strings. * <p> * Minimal configuration typically includes: * <ul> * <li><code>zookeeper.connect</code></li> * <li><code>group.id</code></li> * <li><code>zookeeper.session.timeout.ms</code></li> * <li><code>zookeeper.sync.time.ms</code></li> * <li><code>auto.commit.interval.ms</code></li> * </ul> * @param te {@link TopologyElement} * @param config KafkaConsumer configuration information. */ public KafkaConsumer(TopologyElement te, Map<String, Object> config) { this.te = te; this.config = new HashMap<>(); this.config.putAll(config); } /** * Get the connector's {@code KafkaConsumer} configuration information. * @return the unmodifiable configuration */ public Map<String,Object> getConfig() { return Collections.unmodifiableMap(config); } /** * Subscribe to a topic and create a stream of messages. * <p> * Same as {@code subscribe(new Value<Integer>(1), topic)} * @param topic the topic to subscribe to. May be a submission parameter. * @return TStream&lt;Message> * @see Value * @see Topology#createSubmissionParameter(String, Class) */ public TStream<Message> subscribe(Supplier<String> topic) { return subscribe(new Value<Integer>(1), topic); } /** * Subscribe to a topic and create a stream of messages. * <p> * N.B., A topology that includes this will not support * {@code StreamsContext.Type.EMBEDDED}. * <p> * N.B. due to com.ibm.streamsx.messaging * <a href="https://github.com/IBMStreams/streamsx.messaging/issues/118">issue#118</a>, * multiple consumers will have issues in * {@code StreamsContext.Type.STANDALONE}. * <p> * N.B. due to com.ibm.streamsx.messaging * <a href="https://github.com/IBMStreams/streamsx.messaging/issues/117">issue#117</a>, * a consumer in {@code StreamsContext.Type.STANDALONE} subsequently results * in an orphaned @{code standalone} processes that continues as the lead * group/topic consumer thereby preventing subsequent instances of the * group/topic consumer from receiving messages. * <p> * N.B. due to com.ibm.streamsx.messaging * <a href="https://github.com/IBMStreams/streamsx.messaging/issues/114">issue#114</a>, * a consumer essentially ignores messages generated by producers where the * optional {@code key} is {@code null}. * e.g., Kafka's {@code kafka-console-producer.sh} tool generates * {@code key==null} messages. * * @param threadsPerTopic number of threads to allocate to processing each * topic. May be a submission parameter. * @param topic the topic to subscribe to. May be a submission parameter. * @return TStream&lt;Message> * The generated {@code Message} tuples have a non-null {@code topic}. * The tuple's {@code key} will be null if the Kafka message * lacked a key or it's key was the empty string. * @throws IllegalArgumentException if topic is null. * @throws IllegalArgumentException if threadsPerTopic is null. * @see Value * @see Topology#createSubmissionParameter(String, Class) */ public TStream<Message> subscribe(Supplier<Integer> threadsPerTopic, Supplier<String> topic) { if (topic == null) throw new IllegalArgumentException("topic"); if (threadsPerTopic == null || (threadsPerTopic.get() != null && threadsPerTopic.get() <= 0)) throw new IllegalArgumentException("threadsPerTopic"); Map<String, Object> params = new HashMap<>(); params.put("topic", topic); params.put("threadsPerTopic", threadsPerTopic); if (!config.isEmpty()) params.put("kafkaProperty", Util.toKafkaProperty(config)); // workaround streamsx.messaging issue #107 params.put("propertiesFile", PROP_FILE_PARAM); addPropertiesFile(); // Use SPL.invoke to avoid adding a compile time dependency // to com.ibm.streamsx.messaging since JavaPrimitive.invoke*() // lack "kind" based variants. String kind = "com.ibm.streamsx.messaging.kafka::KafkaConsumer"; String className = "com.ibm.streamsx.messaging.kafka.KafkaSource"; SPLStream rawKafka = SPL.invokeSource( te, kind, params, KafkaSchemas.KAFKA); SPL.tagOpAsJavaPrimitive(toOp(rawKafka), kind, className); TStream<Message> rcvdMsgs = toMessageStream(rawKafka); rcvdMsgs.colocate(rawKafka); // workaround streamsx.messaging issue#118 w/java8 // isolate even in the single consumer case since we don't // know if others may be subsequently created. rcvdMsgs = rcvdMsgs.isolate(); return rcvdMsgs; } private BOperatorInvocation toOp(SPLStream splStream) { BOutputPort oport = (BOutputPort) splStream.output(); return (BOperatorInvocation) oport.operator(); } /** * Convert an {@link SPLStream} with schema {@link KafkaSchemas.KAFKA} * to a TStream&lt;{@link Message}>. * The returned stream will contain a {@code Message} tuple for * each tuple on {@code stream}. * A runtime error will occur if the schema of {@code stream} doesn't * have the attributes defined by {@code KafkaSchemas.KAFKA}. * @param stream Stream to be converted to a TStream&lt;Message>. * @return Stream of {@code Message} tuples from {@code stream}. */ private static TStream<Message> toMessageStream(SPLStream stream) { return stream.convert(new Function<Tuple, Message>() { private static final long serialVersionUID = 1L; @Override public Message apply(Tuple tuple) { return new SimpleMessage(tuple.getString("message"), fromSplValue(tuple.getString("key")), tuple.getString("topic")); } private String fromSplValue(String s) { // SPL doesn't allow null value. For our use, // assume an empty string meant null. return (s==null || s.isEmpty()) ? null : s; } }); } }
dlaboss/streamsx.topology
java/src/com/ibm/streamsx/topology/messaging/kafka/KafkaConsumer.java
Java
apache-2.0
8,942
/* * Copyright © 2016 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.common.security; import co.cask.cdap.common.conf.CConfiguration; import co.cask.cdap.common.conf.Constants; import co.cask.cdap.proto.NamespaceConfig; import co.cask.cdap.proto.NamespaceMeta; /** * Encapsulates information necessary to impersonate a user - principal and keytab path. */ public final class ImpersonationInfo { private final String principal; private final String keytabURI; /** * Creates {@link ImpersonationInfo} using the specified principal and keytab path. */ public ImpersonationInfo(String principal, String keytabURI) { this.principal = principal; this.keytabURI = keytabURI; } /** * Creates {@link ImpersonationInfo} for the specified namespace. If the info is not configured at the namespace * level is empty, returns the info configured at the cdap level. */ public ImpersonationInfo(NamespaceMeta namespaceMeta, CConfiguration cConf) { NamespaceConfig namespaceConfig = namespaceMeta.getConfig(); String configuredPrincipal = namespaceConfig.getPrincipal(); String configuredKeytabURI = namespaceConfig.getKeytabURI(); if (configuredPrincipal != null && configuredKeytabURI != null) { this.principal = configuredPrincipal; this.keytabURI = configuredKeytabURI; } else if (configuredPrincipal == null && configuredKeytabURI == null) { this.principal = cConf.get(Constants.Security.CFG_CDAP_MASTER_KRB_PRINCIPAL); this.keytabURI = cConf.get(Constants.Security.CFG_CDAP_MASTER_KRB_KEYTAB_PATH); } else { // Ideally, this should never happen, because we make the check upon namespace create. // This can technically happen if someone modifies the namespace store directly (i.e. hbase shell PUT). throw new IllegalStateException( String.format("Either neither or both of the following two configurations must be configured. " + "Configured principal: %s, Configured keytabURI: %s", configuredPrincipal, configuredKeytabURI)); } } public String getPrincipal() { return principal; } public String getKeytabURI() { return keytabURI; } @Override public String toString() { return "ImpersonationInfo{" + "principal='" + principal + '\'' + ", keytabURI='" + keytabURI + '\'' + '}'; } }
caskdata/cdap
cdap-common/src/main/java/co/cask/cdap/common/security/ImpersonationInfo.java
Java
apache-2.0
2,940
package com.brickgit.cookiecrush; public class Chain { public static final int SHORTEST_LENGTH = 3; public static final int DIRECTION_RIGHT = 0; public static final int DIRECTION_DOWN = 1; public int direction; public Cookie head; public Cookie tail; public Chain(int direction, Cookie head, Cookie tail) { this.direction = direction; this.head = head; this.tail = tail; } @Override public String toString() { return "Chain " + direction + " (" + head.coord.row + ", " + head.coord.column + ") -> (" + tail.coord.row + ", " + tail.coord.column + ")"; } }
brickgit/CookieCrush
app/src/main/java/com/brickgit/cookiecrush/Chain.java
Java
apache-2.0
677
/* Copyright 2016 Google Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.codegen.transformer; import com.google.api.codegen.ReleaseLevel; import com.google.api.codegen.config.FieldConfig; import com.google.api.codegen.config.GapicInterfaceConfig; import com.google.api.codegen.config.GapicMethodConfig; import com.google.api.codegen.config.GrpcStreamingConfig; import com.google.api.codegen.config.InterfaceConfig; import com.google.api.codegen.config.OneofConfig; import com.google.api.codegen.config.PageStreamingConfig; import com.google.api.codegen.config.ResourceNameConfig; import com.google.api.codegen.config.ResourceNameType; import com.google.api.codegen.config.SingleResourceNameConfig; import com.google.api.codegen.config.VisibilityConfig; import com.google.api.codegen.util.CommentReformatter; import com.google.api.codegen.util.CommonRenderingUtil; import com.google.api.codegen.util.Name; import com.google.api.codegen.util.NameFormatter; import com.google.api.codegen.util.NameFormatterDelegator; import com.google.api.codegen.util.NamePath; import com.google.api.codegen.util.SymbolTable; import com.google.api.codegen.util.TypeNameConverter; import com.google.api.codegen.viewmodel.ServiceMethodType; import com.google.api.tools.framework.aspects.documentation.model.DocumentationUtil; import com.google.api.tools.framework.model.EnumType; import com.google.api.tools.framework.model.Field; import com.google.api.tools.framework.model.Interface; import com.google.api.tools.framework.model.MessageType; import com.google.api.tools.framework.model.Method; import com.google.api.tools.framework.model.ProtoElement; import com.google.api.tools.framework.model.ProtoFile; import com.google.api.tools.framework.model.TypeRef; import com.google.common.collect.ImmutableList; import io.grpc.Status; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A SurfaceNamer provides language-specific names for specific components of a view for a surface. * * <p>Naming is composed of two steps: * * <p>1. Composing a Name instance with the name pieces 2. Formatting the Name for the particular * type of identifier needed. * * <p>This class delegates step 2 to the provided name formatter, which generally would be a * language-specific namer. */ public class SurfaceNamer extends NameFormatterDelegator { private final ModelTypeFormatter modelTypeFormatter; private final TypeNameConverter typeNameConverter; private final CommentReformatter commentReformatter; private final String rootPackageName; private final String packageName; public SurfaceNamer( NameFormatter languageNamer, ModelTypeFormatter modelTypeFormatter, TypeNameConverter typeNameConverter, CommentReformatter commentReformatter, String rootPackageName, String packageName) { super(languageNamer); this.modelTypeFormatter = modelTypeFormatter; this.typeNameConverter = typeNameConverter; this.commentReformatter = commentReformatter; this.rootPackageName = rootPackageName; this.packageName = packageName; } public SurfaceNamer cloneWithPackageName(String packageName) { throw new UnsupportedOperationException("clone needs to be overridden"); } public ModelTypeFormatter getModelTypeFormatter() { return modelTypeFormatter; } public TypeNameConverter getTypeNameConverter() { return typeNameConverter; } public String getPackageName() { return packageName; } public String getRootPackageName() { return rootPackageName; } public String getStubPackageName() { return rootPackageName + ".stub"; } public String getNotImplementedString(String feature) { return "$ NOT IMPLEMENTED: " + feature + " $"; } /////////////////////////////////////// Service names /////////////////////////////////////////// /** * Returns the service name with common suffixes removed. * * <p>For example: "LoggingServiceV2" becomes Name("Logging") */ public Name getReducedServiceName(String interfaceSimpleName) { String name = interfaceSimpleName.replaceAll("V[0-9]+$", ""); name = name.replaceAll("Service$", ""); return Name.upperCamel(name); } /** Returns the service name exported by the package */ public String getPackageServiceName(Interface apiInterface) { return getNotImplementedString("SurfaceNamer.getPackageServiceName"); } /** Human-friendly name of this API interface */ public String getServicePhraseName(Interface apiInterface) { return Name.upperCamel(apiInterface.getSimpleName()).toPhrase(); } /////////////////////////////////////// Constructors ///////////////////////////////////////////// /** * The name of the constructor for the apiInterface client. The client is VKit generated, not * GRPC. */ public String getApiWrapperClassConstructorName(Interface apiInterface) { return publicClassName(Name.upperCamel(apiInterface.getSimpleName(), "Client")); } /** Constructor name for the type with the given nickname. */ public String getTypeConstructor(String typeNickname) { return typeNickname; } //////////////////////////////////// Package & module names ///////////////////////////////////// /** The local (unqualified) name of the package */ public String getLocalPackageName() { return getNotImplementedString("SurfaceNamer.getLocalPackageName"); } /** * The name of a variable that holds an instance of the module that contains the implementation of * a particular proto interface. */ public String getApiWrapperModuleName() { return getNotImplementedString("SurfaceNamer.getApiWrapperModuleName"); } /** * The version of a variable that holds an instance of the module that contains the implementation * of a particular proto interface. So far it is used by just NodeJS. */ public String getApiWrapperModuleVersion() { return getNotImplementedString("SurfaceNamer.getApiWrapperModuleVersion"); } /** The qualified namespace of an API interface. */ public String getNamespace(Interface apiInterface) { NamePath namePath = typeNameConverter.getNamePath(modelTypeFormatter.getFullNameFor(apiInterface)); return qualifiedName(namePath.withoutHead()); } public String getGapicImplNamespace() { return getNotImplementedString("SurfaceNamer.getGapicImplNamespace"); } /** The qualified namespace of an API. */ public String getTopLevelNamespace() { return getNotImplementedString("SurfaceNamer.getTopLevelNamespace"); } /** The versioned namespace of an api. Example: google.cloud.vision_v1 */ public String getVersionedDirectoryNamespace() { return getNotImplementedString("SurfaceNamer.getVersionedDirectoryNamespace"); } /** The modules of the package. */ public ImmutableList<String> getApiModules() { return ImmutableList.<String>of(); } /** The top level modules of the package. */ public List<String> getTopLevelApiModules() { return ImmutableList.of(); } /** The name of the gapic package. */ public String getGapicPackageName(String configPackageName) { return "gapic-" + configPackageName; } /** The name of the module for the version of an API. */ public String getModuleVersionName() { return getNotImplementedString("SurfaceNamer.getModuleVersionName"); } /** The name of the module for the service of an API. */ public String getModuleServiceName() { return getNotImplementedString("SurfaceNamer.getModuleServiceName"); } /////////////////////////////////// Protos methods ///////////////////////////////////////////// /** The function name to set the given proto field. */ public String getFieldSetFunctionName(FeatureConfig featureConfig, FieldConfig fieldConfig) { Field field = fieldConfig.getField(); if (featureConfig.useResourceNameFormatOption(fieldConfig)) { return getResourceNameFieldSetFunctionName(fieldConfig.getMessageFieldConfig()); } else { return getFieldSetFunctionName(field); } } /** The function name to set the given proto field. */ public String getFieldSetFunctionName(Field field) { return getFieldSetFunctionName(field.getType(), Name.from(field.getSimpleName())); } /** The function name to set a field having the given type and name. */ public String getFieldSetFunctionName(TypeRef type, Name identifier) { if (type.isMap()) { return publicMethodName(Name.from("put", "all").join(identifier)); } else if (type.isRepeated()) { return publicMethodName(Name.from("add", "all").join(identifier)); } else { return publicMethodName(Name.from("set").join(identifier)); } } /** The function name to add an element to a map or repeated field. */ public String getFieldAddFunctionName(Field field) { return getFieldAddFunctionName(field.getType(), Name.from(field.getSimpleName())); } /** The function name to add an element to a map or repeated field. */ public String getFieldAddFunctionName(TypeRef type, Name identifier) { return getNotImplementedString("SurfaceNamer.getFieldAddFunctionName"); } /** The function name to set a field that is a resource name class. */ public String getResourceNameFieldSetFunctionName(FieldConfig fieldConfig) { TypeRef type = fieldConfig.getField().getType(); Name identifier = Name.from(fieldConfig.getField().getSimpleName()); Name resourceName = getResourceTypeNameObject(fieldConfig.getResourceNameConfig()); if (type.isMap()) { return getNotImplementedString("SurfaceNamer.getResourceNameFieldSetFunctionName:map-type"); } else if (type.isRepeated()) { return publicMethodName( Name.from("add", "all").join(identifier).join("with").join(resourceName).join("list")); } else { return publicMethodName(Name.from("set").join(identifier).join("with").join(resourceName)); } } /** The function name to get the given proto field. */ public String getFieldGetFunctionName(FeatureConfig featureConfig, FieldConfig fieldConfig) { Field field = fieldConfig.getField(); if (featureConfig.useResourceNameFormatOption(fieldConfig)) { return getResourceNameFieldGetFunctionName(fieldConfig.getMessageFieldConfig()); } else { return getFieldGetFunctionName(field); } } /** The function name to get the given proto field. */ public String getFieldGetFunctionName(Field field) { return getFieldGetFunctionName(field.getType(), Name.from(field.getSimpleName())); } /** The function name to get a field having the given type and name. */ public String getFieldGetFunctionName(TypeRef type, Name identifier) { if (type.isRepeated() && !type.isMap()) { return publicMethodName(Name.from("get").join(identifier).join("list")); } else if (type.isMap()) { return publicMethodName(Name.from("get").join(identifier).join("map")); } else { return publicMethodName(Name.from("get").join(identifier)); } } /** The function name to get a field that is a resource name class. */ public String getResourceNameFieldGetFunctionName(FieldConfig fieldConfig) { TypeRef type = fieldConfig.getField().getType(); Name identifier = Name.from(fieldConfig.getField().getSimpleName()); Name resourceName = getResourceTypeNameObject(fieldConfig.getResourceNameConfig()); if (type.isMap()) { return getNotImplementedString("SurfaceNamer.getResourceNameFieldGetFunctionName:map-type"); } else if (type.isRepeated()) { return publicMethodName( Name.from("get").join(identifier).join("list_as").join(resourceName).join("list")); } else { return publicMethodName(Name.from("get").join(identifier).join("as").join(resourceName)); } } /** * The function name to get the count of elements in the given field. * * @throws IllegalArgumentException if the field is not a repeated field. */ public String getFieldCountGetFunctionName(Field field) { if (field.isRepeated()) { return publicMethodName(Name.from("get", field.getSimpleName(), "count")); } else { throw new IllegalArgumentException( "Non-repeated field " + field.getSimpleName() + " has no count function."); } } /** * The function name to get an element by index from the given field. * * @throws IllegalArgumentException if the field is not a repeated field. */ public String getByIndexGetFunctionName(Field field) { if (field.isRepeated()) { return publicMethodName(Name.from("get", field.getSimpleName())); } else { throw new IllegalArgumentException( "Non-repeated field " + field.getSimpleName() + " has no get-by-index function."); } } ///////////////////////////////// Function & Callable names ///////////////////////////////////// /** The function name to retrieve default client option */ public String getDefaultApiSettingsFunctionName(Interface apiInterface) { return getNotImplementedString("SurfaceNamer.getDefaultClientOptionFunctionName"); } /** The method name to create a rerouted gRPC client. Used in C# */ public String getReroutedGrpcMethodName(GapicMethodConfig methodConfig) { return getNotImplementedString("SurfaceNamer.getReroutedGrpcMethodName"); } /** The type name of a rerouted gRPC type. Used in C# */ public String getReroutedGrpcTypeName(ModelTypeTable typeTable, GapicMethodConfig methodConfig) { return getNotImplementedString("SurfaceNamer.getReroutedGrpcTypeName"); } /** The name of the surface method which can call the given API method. */ public String getApiMethodName(Method method, VisibilityConfig visibility) { return getApiMethodName(Name.upperCamel(method.getSimpleName()), visibility); } /** The name of the async surface method which can call the given API method. */ public String getAsyncApiMethodName(Method method, VisibilityConfig visibility) { return getApiMethodName(Name.upperCamel(method.getSimpleName()).join("async"), visibility); } protected String getApiMethodName(Name name, VisibilityConfig visibility) { switch (visibility) { case PUBLIC: return publicMethodName(name); case PACKAGE: case PRIVATE: return privateMethodName(name); default: throw new IllegalArgumentException("cannot name method with visibility: " + visibility); } } /** * The name of the iterate method of the PagedListResponse type for a field, returning the * resource type iterate method if available */ public String getPagedResponseIterateMethod( FeatureConfig featureConfig, FieldConfig fieldConfig) { if (featureConfig.useResourceNameFormatOption(fieldConfig)) { Name resourceName = getResourceTypeNameObject(fieldConfig.getResourceNameConfig()); return publicMethodName(Name.from("iterate_all_as").join(resourceName)); } else { return getPagedResponseIterateMethod(); } } /** The name of the iterate method of the PagedListResponse type for a field */ public String getPagedResponseIterateMethod() { return publicMethodName(Name.from("iterate_all_elements")); } /** * The name of the get values method of the Page type for a field, returning the resource type get * values method if available */ public String getPageGetValuesMethod(FeatureConfig featureConfig, FieldConfig fieldConfig) { if (featureConfig.useResourceNameFormatOption(fieldConfig)) { Name resourceName = getResourceTypeNameObject(fieldConfig.getResourceNameConfig()); return publicMethodName(Name.from("get_values_as").join(resourceName)); } else { return getPageGetValuesMethod(); } } /** The name of the get values method of the Page type for a field */ public String getPageGetValuesMethod() { return publicMethodName(Name.from("get_values")); } public String getResourceTypeParseMethodName( ModelTypeTable typeTable, FieldConfig resourceFieldConfig) { return getNotImplementedString("SurfaceNamer.getResourceTypeParseMethodName"); } /** The name of the create method for the resource one-of for the given field config */ public String getResourceOneofCreateMethod(ModelTypeTable typeTable, FieldConfig fieldConfig) { return getAndSaveResourceTypeName(typeTable, fieldConfig.getMessageFieldConfig()) + "." + publicMethodName(Name.from("from")); } /** The method name of the retry filter for the given key */ public String retryFilterMethodName(String key) { return privateMethodName(Name.from(key).join("retry").join("filter")); } /** The method name of the retry backoff for the given key */ public String retryBackoffMethodName(String key) { return privateMethodName(Name.from("get").join(key).join("retry").join("backoff")); } /** The method name of the timeout backoff for the given key */ public String timeoutBackoffMethodName(String key) { return privateMethodName(Name.from("get").join(key).join("timeout").join("backoff")); } /** The name of the GRPC streaming surface method which can call the given API method. */ public String getGrpcStreamingApiMethodName(Method method, VisibilityConfig visibility) { return getApiMethodName(method, visibility); } /** The name of the return type of the given grpc streaming method. */ public String getGrpcStreamingApiReturnTypeName(Method method) { return publicClassName( Name.upperCamel(method.getOutputType().getMessageType().getSimpleName())); } /** The name of the callable for the paged callable variant of the given method. */ public String getPagedCallableName(Method method) { return privateFieldName(Name.upperCamel(method.getSimpleName(), "PagedCallable")); } /** The name of the paged callable variant of the given method. */ public String getPagedCallableMethodName(Method method) { return publicMethodName(Name.upperCamel(method.getSimpleName(), "PagedCallable")); } /** The name of the plain callable variant of the given method. */ public String getCallableMethodName(Method method) { return publicMethodName(Name.upperCamel(method.getSimpleName(), "Callable")); } /** The name of the plain callable variant of the given method. */ public String getCallableAsyncMethodName(Method method) { return publicMethodName(Name.upperCamel(method.getSimpleName(), "CallableAsync")); } /** The name of the operation callable variant of the given method. */ public String getOperationCallableMethodName(Method method) { return publicMethodName(Name.upperCamel(method.getSimpleName(), "OperationCallable")); } /** The name of the plain callable for the given method. */ public String getCallableName(Method method) { return privateFieldName(Name.upperCamel(method.getSimpleName(), "Callable")); } /** The name of the operation callable for the given method. */ public String getOperationCallableName(Method method) { return privateFieldName(Name.upperCamel(method.getSimpleName(), "OperationCallable")); } public String getDirectCallableName(Method method) { return privateFieldName(Name.upperCamel("Direct", method.getSimpleName(), "Callable")); } /** The name of the settings member name for the given method. */ public String getSettingsMemberName(Method method) { return publicMethodName(Name.upperCamel(method.getSimpleName(), "Settings")); } /** The getter function name for the settings for the given method. */ public String getSettingsFunctionName(Method method) { return getSettingsMemberName(method); } /** The name of a method to apply modifications to this method request. */ public String getModifyMethodName(Method method) { return getNotImplementedString("SurfaceNamer.getModifyMethodName"); } /** The function name to retrieve default call option */ public String getDefaultCallSettingsFunctionName(Interface apiInterface) { return publicMethodName(Name.upperCamel(apiInterface.getSimpleName(), "Settings")); } /** The name of the IAM resource getter function. */ public String getIamResourceGetterFunctionName(Field field) { return getNotImplementedString("SurfaceNamer.getIamResourceGetterFunctionName"); } /** The name of the function that will create a stub. */ public String getCreateStubFunctionName(Interface apiInterface) { return privateMethodName( Name.upperCamel("Create", apiInterface.getSimpleName(), "Stub", "Function")); } /** Function used to register the GRPC server. */ public String getServerRegisterFunctionName(Interface apiInterface) { return getNotImplementedString("SurfaceNamer.getServerRegisterFunctionName"); } /** The name of the LRO surface method which can call the given API method. */ public String getLroApiMethodName(Method method, VisibilityConfig visibility) { return getAsyncApiMethodName(method, visibility); } public String getByteLengthFunctionName(TypeRef typeRef) { return getNotImplementedString("SurfaceNamer.getByteLengthFunctionName"); } /////////////////////////////////////// Variable names ////////////////////////////////////////// /** * The name of a variable to hold a value for the given proto message field (such as a flattened * parameter). */ public String getVariableName(Field field) { return localVarName(Name.from(field.getSimpleName())); } /** * The name of a variable that holds an instance of the class that implements a particular proto * interface. */ public String getApiWrapperVariableName(GapicInterfaceConfig interfaceConfig) { return localVarName(Name.upperCamel(getInterfaceName(interfaceConfig), "Client")); } /** * The name of a variable that holds the settings class for a particular proto interface; not used * in most languages. */ public String getApiSettingsVariableName(GapicInterfaceConfig interfaceConfig) { return localVarName(Name.upperCamel(getInterfaceName(interfaceConfig), "Settings")); } /** * The name of the builder class for the settings class for a particular proto interface; not used * in most languages. */ public String getApiSettingsBuilderVarName(GapicInterfaceConfig interfaceConfig) { return localVarName(Name.upperCamel(getInterfaceName(interfaceConfig), "SettingsBuilder")); } /** The variable name for the given identifier that is formatted. */ public String getFormattedVariableName(Name identifier) { return localVarName(Name.from("formatted").join(identifier)); } /** The variable name of the rerouted gRPC client. Used in C# */ public String getReroutedGrpcClientVarName(GapicMethodConfig methodConfig) { return getNotImplementedString("SurfaceNamer.getGrpcClientName"); } /** The name of the variable that will hold the stub for an API interface. */ public String getStubName(Interface apiInterface) { return privateFieldName(Name.upperCamel(apiInterface.getSimpleName(), "Stub")); } /** The name of the array which will hold the methods for a given stub. */ public String getStubMethodsArrayName(Interface apiInterface) { return privateMethodName(Name.upperCamel(apiInterface.getSimpleName(), "Stub", "Methods")); } /** The parameter name for the given lower-case field name. */ public String getParamName(String var) { return localVarName(Name.from(var)); } public String getPropertyName(String var) { return publicMethodName(Name.from(var)); } /* The name of a retry definition */ public String getRetryDefinitionName(String retryDefinitionKey) { return privateMethodName(Name.from(retryDefinitionKey)); } /** The name of the variable to hold the grpc client of an API interface. */ public String getGrpcClientVariableName(Interface apiInterface) { return localVarName(Name.upperCamel(apiInterface.getSimpleName(), "Client")); } /** The name of the field. */ public String getFieldName(Field field) { return publicFieldName(Name.from(field.getSimpleName())); } /** The page streaming descriptor name for the given method. */ public String getPageStreamingDescriptorName(Method method) { return privateFieldName(Name.upperCamel(method.getSimpleName(), "PageStreamingDescriptor")); } /** The page streaming factory name for the given method. */ public String getPagedListResponseFactoryName(Method method) { return privateFieldName(Name.upperCamel(method.getSimpleName(), "PagedListResponseFactory")); } /** The variable name of the gRPC request object. */ public String getRequestVariableName(Method method) { return getNotImplementedString("SurfaceNamer.getRequestVariableName"); } /////////////////////////////////////// Type names ///////////////////////////////////////////// protected String getInterfaceName(InterfaceConfig interfaceConfig) { return interfaceConfig.getName(); } /** The name of the class that implements a particular proto interface. */ public String getApiWrapperClassName(InterfaceConfig interfaceConfig) { return publicClassName(Name.upperCamel(getInterfaceName(interfaceConfig), "Client")); } /** The name of the implementation class that implements a particular proto interface. */ public String getApiWrapperClassImplName(InterfaceConfig interfaceConfig) { return getNotImplementedString("SurfaceNamer.getApiWrapperClassImplName"); } /** The name of the class that implements snippets for a particular proto interface. */ public String getApiSnippetsClassName(Interface apiInterface) { return publicClassName(Name.upperCamel(apiInterface.getSimpleName(), "ApiSnippets")); } /** * The name of the settings class for a particular proto interface; not used in most languages. */ public String getApiSettingsClassName(GapicInterfaceConfig interfaceConfig) { return publicClassName(Name.upperCamel(getInterfaceName(interfaceConfig), "Settings")); } /** * The name of the stub interface for a particular proto interface; not used in most languages. */ public String getApiStubInterfaceName(GapicInterfaceConfig interfaceConfig) { return publicClassName(Name.upperCamel(interfaceConfig.getRawName(), "Stub")); } /** The name of the grpc stub for a particular proto interface; not used in most languages. */ public String getApiGrpcStubClassName(GapicInterfaceConfig interfaceConfig) { return publicClassName(Name.upperCamel("Grpc", interfaceConfig.getRawName(), "Stub")); } /** The name of the class that contains paged list response wrappers. */ public String getPagedResponseWrappersClassName() { return publicClassName(Name.upperCamel("PagedResponseWrappers")); } /** The sample application class name. */ public String getSampleAppClassName() { return publicClassName(Name.upperCamel("SampleApp")); } /** * The type name of the Grpc service class This needs to match what Grpc generates for the * particular language. */ public String getGrpcServiceClassName(Interface apiInterface) { NamePath namePath = typeNameConverter.getNamePath(modelTypeFormatter.getFullNameFor(apiInterface)); String grpcContainerName = publicClassName(Name.upperCamelKeepUpperAcronyms(namePath.getHead(), "Grpc")); String serviceClassName = publicClassName(Name.upperCamelKeepUpperAcronyms(apiInterface.getSimpleName(), "ImplBase")); return qualifiedName(namePath.withHead(grpcContainerName).append(serviceClassName)); } /** * The fully qualified class name of an API interface. * * <p>TODO: Support the general pattern of package + class name in NameFormatter. */ public String getFullyQualifiedApiWrapperClassName(GapicInterfaceConfig interfaceConfig) { return getNotImplementedString("SurfaceNamer.getFullyQualifiedApiWrapperClassName"); } public String getTopLevelAliasedApiClassName( GapicInterfaceConfig interfaceConfig, boolean packageHasMultipleServices) { return getNotImplementedString("SurfaceNamer.getTopLevelAliasedApiClassName"); } public String getVersionAliasedApiClassName( GapicInterfaceConfig interfaceConfig, boolean packageHasMultipleServices) { return getNotImplementedString("SurfaceNamer.getVersionAliasedApiClassName"); } protected Name getResourceTypeNameObject(ResourceNameConfig resourceNameConfig) { String entityName = resourceNameConfig.getEntityName(); ResourceNameType resourceNameType = resourceNameConfig.getResourceNameType(); switch (resourceNameType) { case ANY: return getAnyResourceTypeName(); case FIXED: return Name.from(entityName).join("name_fixed"); case ONEOF: // Remove suffix "_oneof". This allows the collection oneof config to "share" an entity name // with a collection config. entityName = removeSuffix(entityName, "_oneof"); return Name.from(entityName).join("name_oneof"); case SINGLE: return Name.from(entityName).join("name"); case NONE: default: throw new UnsupportedOperationException("unexpected entity name type"); } } protected Name getAnyResourceTypeName() { return Name.from("resource_name"); } public String getResourceTypeName(ResourceNameConfig resourceNameConfig) { return publicClassName(getResourceTypeNameObject(resourceNameConfig)); } /** * The type name of the Grpc server class. This needs to match what Grpc generates for the * particular language. */ public String getGrpcServerTypeName(Interface apiInterface) { return getNotImplementedString("SurfaceNamer.getGrpcServerTypeName"); } /** The imported name of the default client config. */ public String getClientConfigName(Interface apiInterface) { return getNotImplementedString("SurfaceNamer.getClientConfigName"); } /** * The type name of the Grpc client class. This needs to match what Grpc generates for the * particular language. */ public String getGrpcClientTypeName(Interface apiInterface) { return getNotImplementedString("SurfaceNamer.getGrpcClientTypeName"); } /** * Gets the type name of the Grpc client class, saves it to the type table provided, and returns * the nickname. */ public String getAndSaveNicknameForGrpcClientTypeName( ModelTypeTable typeTable, Interface apiInterface) { return typeTable.getAndSaveNicknameFor(getGrpcClientTypeName(apiInterface)); } /** * The type name of the Grpc container class. This needs to match what Grpc generates for the * particular language. */ public String getGrpcContainerTypeName(Interface apiInterface) { NamePath namePath = typeNameConverter.getNamePath(modelTypeFormatter.getFullNameFor(apiInterface)); String publicClassName = publicClassName(Name.upperCamelKeepUpperAcronyms(namePath.getHead(), "Grpc")); return qualifiedName(namePath.withHead(publicClassName)); } /** The type name for the method param */ public String getParamTypeName(ModelTypeTable typeTable, TypeRef type) { return getNotImplementedString("SurfaceNamer.getParamTypeName"); } /** The type name for the message property */ public String getMessagePropertyTypeName(ModelTypeTable typeTable, TypeRef type) { return getParamTypeName(typeTable, type); } /** The type name for retry settings. */ public String getRetrySettingsTypeName() { return getNotImplementedString("SurfaceNamer.getRetrySettingsClassName"); } /** The type name for an optional array argument; not used in most languages. */ public String getOptionalArrayTypeName() { return getNotImplementedString("SurfaceNamer.getOptionalArrayTypeName"); } /** The return type name in a dynamic language for the given method. */ public String getDynamicLangReturnTypeName(Method method, GapicMethodConfig methodConfig) { return getNotImplementedString("SurfaceNamer.getDynamicReturnTypeName"); } /** The return type name in a static language for the given method. */ public String getStaticLangReturnTypeName(Method method, GapicMethodConfig methodConfig) { return getNotImplementedString("SurfaceNamer.getStaticLangReturnTypeName"); } /** The return type name in a static language that is used by the caller */ public String getStaticLangCallerReturnTypeName(Method method, GapicMethodConfig methodConfig) { return getStaticLangReturnTypeName(method, methodConfig); } /** The async return type name in a static language for the given method. */ public String getStaticLangAsyncReturnTypeName(Method method, GapicMethodConfig methodConfig) { return getNotImplementedString("SurfaceNamer.getStaticLangAsyncReturnTypeName"); } /** * Computes the nickname of the operation response type name for the given method, saves it in the * given type table, and returns it. */ public String getAndSaveOperationResponseTypeName( Method method, ModelTypeTable typeTable, GapicMethodConfig methodConfig) { return getNotImplementedString("SurfaceNamer.getAndSaveOperationResponseTypeName"); } /** * In languages with pointers, strip the pointer, leaving only the base type. Eg, in C, "int*" * would become "int". */ public String valueType(String type) { return getNotImplementedString("SurfaceNamer.valueType"); } /** The async return type name in a static language that is used by the caller */ public String getStaticLangCallerAsyncReturnTypeName( Method method, GapicMethodConfig methodConfig) { return getStaticLangAsyncReturnTypeName(method, methodConfig); } /** The name used in Grpc for the given API method. This needs to match what Grpc generates. */ public String getGrpcMethodName(Method method) { // This might seem silly, but it makes clear what we're dealing with (upper camel). // This is language-independent because of gRPC conventions. return Name.upperCamelKeepUpperAcronyms(method.getSimpleName()).toUpperCamel(); } /** The GRPC streaming server type name for a given method. */ public String getStreamingServerName(Method method) { return getNotImplementedString("SurfaceNamer.getStreamingServerName"); } /** The type name of call options */ public String getCallSettingsTypeName(Interface apiInterface) { return publicClassName(Name.upperCamel(apiInterface.getSimpleName(), "Settings")); } /** The name of the return type of the given grpc streaming method. */ public String getGrpcStreamingApiReturnTypeName(Method method, ModelTypeTable typeTable) { return publicClassName( Name.upperCamel(method.getOutputType().getMessageType().getSimpleName())); } /** * The generic-aware response type name for the given type. For example, in Java, this will be the * type used for Future&lt;...&gt;. */ public String getGenericAwareResponseTypeName(TypeRef outputType) { return getNotImplementedString("SurfaceNamer.getGenericAwareResponseType"); } /** * Computes the nickname of the paged response type name for the given method and resources field, * saves it in the given type table, and returns it. */ public String getAndSavePagedResponseTypeName( Method method, ModelTypeTable typeTable, FieldConfig resourcesFieldConfig) { return getNotImplementedString("SurfaceNamer.getAndSavePagedResponseTypeName"); } /** The inner type name of the paged response type for the given method and resources field. */ public String getPagedResponseTypeInnerName( Method method, ModelTypeTable typeTable, Field resourcesField) { return getNotImplementedString("SurfaceNamer.getAndSavePagedResponseTypeInnerName"); } /** The inner type name of the page type for the given method and resources field. */ public String getPageTypeInnerName(Method method, ModelTypeTable typeTable, Field resourceField) { return getNotImplementedString("SurfaceNamer.getPageTypeInnerName"); } /** * The inner type name of the fixed size collection type for the given method and resources field. */ public String getFixedSizeCollectionTypeInnerName( Method method, ModelTypeTable typeTable, Field resourceField) { return getNotImplementedString("SurfaceNamer.getPageTypeInnerName"); } /** * Computes the nickname of the async response type name for the given resource type, saves it in * the given type table, and returns it. */ public String getAndSaveAsyncPagedResponseTypeName( Method method, ModelTypeTable typeTable, FieldConfig resourcesFieldConfig) { return getNotImplementedString("SurfaceNamer.getAndSavePagedAsyncResponseTypeName"); } /** * Computes the nickname of the response type name for the given resource type, as used by the * caller, saves it in the given type table, and returns it. */ public String getAndSaveCallerPagedResponseTypeName( Method method, ModelTypeTable typeTable, FieldConfig resourcesFieldConfig) { return getAndSavePagedResponseTypeName(method, typeTable, resourcesFieldConfig); } /** * Computes the nickname of the response type name for the given resource type, as used by the * caller, saves it in the given type table, and returns it. */ public String getAndSaveCallerAsyncPagedResponseTypeName( Method method, ModelTypeTable typeTable, FieldConfig resourcesFieldConfig) { return getAndSaveAsyncPagedResponseTypeName(method, typeTable, resourcesFieldConfig); } /** The class name of the generated resource type from the entity name. */ public String getAndSaveResourceTypeName(ModelTypeTable typeTable, FieldConfig fieldConfig) { String resourceClassName = publicClassName(getResourceTypeNameObject(fieldConfig.getResourceNameConfig())); return typeTable.getAndSaveNicknameForTypedResourceName(fieldConfig, resourceClassName); } /** The class name of the generated resource type from the entity name. */ public String getAndSaveElementResourceTypeName( ModelTypeTable typeTable, FieldConfig fieldConfig) { String resourceClassName = publicClassName(getResourceTypeNameObject(fieldConfig.getResourceNameConfig())); return typeTable.getAndSaveNicknameForResourceNameElementType(fieldConfig, resourceClassName); } /** The fully qualified type name for the stub of an API interface. */ public String getFullyQualifiedStubType(Interface apiInterface) { return getNotImplementedString("SurfaceNamer.getFullyQualifiedStubType"); } /** The type name of the API callable class for this service method type. */ public String getApiCallableTypeName(ServiceMethodType serviceMethodType) { return getNotImplementedString("SurfaceNamer.getApiCallableTypeName"); } public String getDirectCallableTypeName(ServiceMethodType serviceMethodType) { return getNotImplementedString("SurfaceNamer.getDirectCallableTypeName"); } public String getCreateCallableFunctionName(ServiceMethodType serviceMethodType) { return getNotImplementedString("SurfaceNamer.getCreateCallableFunctionName"); } /** Return the type name used to discriminate oneof variants. */ public String getOneofVariantTypeName(OneofConfig oneof) { return getNotImplementedString("SurfaceNamer.getOneofVariantTypeName"); } /** * The formatted name of a type used in long running operations, i.e. the operation payload and * metadata, */ public String getLongRunningOperationTypeName(ModelTypeTable typeTable, TypeRef type) { return getNotImplementedString("SurfaceNamer.getLongRunningOperationTypeName"); } /** The type name for the gPRC request. */ public String getRequestTypeName(ModelTypeTable typeTable, TypeRef type) { return getNotImplementedString("SurfaceNamer.getRequestTypeName"); } public String getMessageTypeName(ModelTypeTable typeTable, MessageType message) { return typeTable.getNicknameFor(TypeRef.of(message)); } public String getEnumTypeName(ModelTypeTable typeTable, EnumType enumType) { return typeTable.getNicknameFor(TypeRef.of(enumType)); } public String getStreamTypeName(GrpcStreamingConfig.GrpcStreamingType type) { return getNotImplementedString("SurfaceNamer.getStreamTypeName"); } public String getFullyQualifiedCredentialsClassName() { return getNotImplementedString("SurfaceNamer.getFullyQualifiedCredentialsClassName"); } /////////////////////////////////////// Resource names ////////////////////////////////////////// public String getResourceParameterName(ResourceNameConfig resourceNameConfig) { return localVarName(getResourceTypeNameObject(resourceNameConfig)); } public String getResourcePropertyName(ResourceNameConfig resourceNameConfig) { return publicMethodName(getResourceTypeNameObject(resourceNameConfig)); } public String getResourceEnumName(ResourceNameConfig resourceNameConfig) { return getResourceTypeNameObject(resourceNameConfig).toUpperUnderscore().toUpperCase(); } /** The parameter name of the IAM resource. */ public String getIamResourceParamName(Field field) { return localVarName(Name.upperCamel(field.getParent().getSimpleName())); } /////////////////////////////////////// Path Template //////////////////////////////////////// /** * The name of a path template constant for the given collection, to be held in an API wrapper * class. */ public String getPathTemplateName( Interface apiInterface, SingleResourceNameConfig resourceNameConfig) { return inittedConstantName(Name.from(resourceNameConfig.getEntityName(), "path", "template")); } /** The name of a getter function to get a particular path template for the given collection. */ public String getPathTemplateNameGetter( Interface apiInterface, SingleResourceNameConfig resourceNameConfig) { return publicMethodName( Name.from("get", resourceNameConfig.getEntityName(), "name", "template")); } /** The name of the path template resource, in human format. */ public String getPathTemplateResourcePhraseName(SingleResourceNameConfig resourceNameConfig) { return Name.from(resourceNameConfig.getEntityName()).toPhrase(); } /** The function name to format the entity for the given collection. */ public String getFormatFunctionName( Interface apiInterface, SingleResourceNameConfig resourceNameConfig) { return staticFunctionName(Name.from("format", resourceNameConfig.getEntityName(), "name")); } /** * The function name to parse a variable from the string representing the entity for the given * collection. */ public String getParseFunctionName(String var, SingleResourceNameConfig resourceNameConfig) { return staticFunctionName( Name.from("parse", var, "from", resourceNameConfig.getEntityName(), "name")); } /** The entity name for the given collection. */ public String getEntityName(SingleResourceNameConfig resourceNameConfig) { return localVarName(Name.from(resourceNameConfig.getEntityName())); } /** The parameter name for the entity for the given collection config. */ public String getEntityNameParamName(SingleResourceNameConfig resourceNameConfig) { return localVarName(Name.from(resourceNameConfig.getEntityName(), "name")); } /////////////////////////////////////// Page Streaming //////////////////////////////////////// /** The formatted field name of a page streaming request token. */ public String getRequestTokenFieldName(PageStreamingConfig pageStreaming) { return keyName(Name.from(pageStreaming.getRequestTokenField().getSimpleName())); } /** The formatted name of a page streaming page size field. */ public String getPageSizeFieldName(PageStreamingConfig pageStreaming) { return keyName(Name.from(pageStreaming.getPageSizeField().getSimpleName())); } /** The formatted field name of a page streaming response token. */ public String getResponseTokenFieldName(PageStreamingConfig pageStreaming) { return keyName(Name.from(pageStreaming.getResponseTokenField().getSimpleName())); } /** The formatted name of a page streaming resources field. */ public String getResourcesFieldName(PageStreamingConfig pageStreaming) { return keyName(Name.from(pageStreaming.getResourcesFieldName())); } ///////////////////////////////////// Constant & Keyword //////////////////////////////////////// /** The name of the constant to hold the batching descriptor for the given method. */ public String getBatchingDescriptorConstName(Method method) { return inittedConstantName(Name.upperCamel(method.getSimpleName()).join("bundling_desc")); } /** The key to use in a dictionary for the given method. */ public String getMethodKey(Method method) { return keyName(Name.upperCamel(method.getSimpleName())); } /** The key to use in a dictionary for the given field. */ public String getFieldKey(Field field) { return keyName(Name.from(field.getSimpleName())); } /** The path to the client config for the given interface. */ public String getClientConfigPath(Interface apiInterface) { return getNotImplementedString("SurfaceNamer.getClientConfigPath"); } /** * The type name of the method constant in the Grpc container class. This needs to match what Grpc * generates for the particular language. */ public String getGrpcMethodConstant(Method method) { return inittedConstantName( Name.from("method").join(Name.upperCamelKeepUpperAcronyms(method.getSimpleName()))); } /** The keyword controlling the visiblity, eg "public", "protected". */ public String getVisiblityKeyword(VisibilityConfig visibility) { switch (visibility) { case PUBLIC: return "public"; case PACKAGE: return "/* package-private */"; case PRIVATE: return "private"; default: throw new IllegalArgumentException("invalid visibility: " + visibility); } } /** The public access modifier for the current language. */ public String getPublicAccessModifier() { return "public"; } /** The private access modifier for the current language. */ public String getPrivateAccessModifier() { return "private"; } /** The name of an RPC status code */ public String getStatusCodeName(Status.Code code) { return privateMethodName(Name.upperUnderscore(code.toString())); } /** The name of the constant to hold the page streaming descriptor for the given method. */ public String getPageStreamingDescriptorConstName(Method method) { return inittedConstantName(Name.upperCamel(method.getSimpleName()).join("page_str_desc")); } /** The name of the constant to hold the page streaming factory for the given method. */ public String getPagedListResponseFactoryConstName(Method method) { return inittedConstantName(Name.upperCamel(method.getSimpleName()).join("page_str_fact")); } /** The string used to identify the method in the gRPC stub. Not all languages will use this. */ public String getGrpcStubCallString(Interface apiInterface, Method method) { return getNotImplementedString("SurfaceNamer.getGrpcStubCallString"); } /** The string of the package path */ public String getPackagePath() { return getNotImplementedString("SurfaceNamer.getPackagePath"); } ///////////////////////////////////////// Imports /////////////////////////////////////////////// /** Returns true if the request object param type for the given field should be imported. */ public boolean shouldImportRequestObjectParamType(Field field) { return true; } /** * Returns true if the request object param element type for the given field should be imported. */ public boolean shouldImportRequestObjectParamElementType(Field field) { return true; } public String getServiceFileImportName(String filename) { return getNotImplementedString("SurfaceNamer.getServiceFileImportName"); } public String getProtoFileImportName(String filename) { return getNotImplementedString("SurfaceNamer.getProtoFileImportName"); } /** The name of the import for a specific grpcClient */ public String getGrpcClientImportName(Interface apiInterface) { return getNotImplementedString("SurfaceNamer.getGrpcClientImportName"); } public String getVersionIndexFileImportName() { return getNotImplementedString("SurfaceNamer.getVersionIndexFileImportName"); } public String getTopLevelIndexFileImportName() { return getNotImplementedString("SurfaceNamer.getTopLevelIndexFileImportName"); } public String getCredentialsClassImportName() { return getNotImplementedString("SurfaceNamer.getCredentialsClassImportName"); } /////////////////////////////////// Docs & Annotations ////////////////////////////////////////// /** The documentation name of a parameter for the given lower-case field name. */ public String getParamDocName(String var) { return localVarName(Name.from(var)); } /** Converts the given text to doc lines in the format of the current language. */ public List<String> getDocLines(String text) { return CommonRenderingUtil.getDocLines(commentReformatter.reformat(text)); } /** Provides the doc lines for the given proto element in the current language. */ public List<String> getDocLines(ProtoElement element) { return getDocLines(DocumentationUtil.getScopedDescription(element)); } /** Provides the doc lines for the given field in the current language. */ public List<String> getDocLines(Field field) { return getDocLines(DocumentationUtil.getScopedDescription(field)); } /** Provides the doc lines for the given method element in the current language. */ public List<String> getDocLines(Method method, GapicMethodConfig methodConfig) { return getDocLines(method); } /** The doc lines that declare what exception(s) are thrown for an API method. */ public List<String> getThrowsDocLines(GapicMethodConfig methodConfig) { return new ArrayList<>(); } /** The doc lines that describe the return value for an API method. */ public List<String> getReturnDocLines( GapicInterfaceContext context, GapicMethodConfig methodConfig, Synchronicity synchronicity) { return Collections.singletonList(getNotImplementedString("SurfaceNamer.getReturnDocLines")); } public String getReleaseAnnotation(ReleaseLevel releaseLevel) { return getNotImplementedString("SurfaceNamer.getReleaseAnnotation"); } /** The name of a type with with qualifying articles and descriptions. */ public String getTypeNameDoc(ModelTypeTable typeTable, TypeRef type) { return getNotImplementedString("SurfaceNamer.getTypeNameDoc"); } /** Get the url to the protobuf file located in github. */ public String getFileUrl(ProtoFile file) { String filePath = file.getSimpleName(); if (filePath.startsWith("google/protobuf")) { return "https://github.com/google/protobuf/blob/master/src/" + filePath; } else { return "https://github.com/googleapis/googleapis/blob/master/" + filePath; } } //////////////////////////////////////// File names //////////////////////////////////////////// /** The file name for an API interface. */ public String getServiceFileName(GapicInterfaceConfig interfaceConfig) { return getNotImplementedString("SurfaceNamer.getServiceFileName"); } public String getSourceFilePath(String path, String publicClassName) { return getNotImplementedString("SurfaceNamer.getSourceFilePath"); } /** The language-specific file name for a proto file. */ public String getProtoFileName(ProtoFile file) { return getNotImplementedString("SurfaceNamer.getProtoFileName"); } ////////////////////////////////////////// Test ///////////////////////////////////////////// public String getTestPackageName() { return getNotImplementedString("SurfaceNamer.getTestPackageName"); } /** The test case name for the given method. */ public String getTestCaseName(SymbolTable symbolTable, Method method) { Name testCaseName = symbolTable.getNewSymbol(Name.upperCamel(method.getSimpleName(), "Test")); return publicMethodName(testCaseName); } /** The exception test case name for the given method. */ public String getExceptionTestCaseName(SymbolTable symbolTable, Method method) { Name testCaseName = symbolTable.getNewSymbol(Name.upperCamel(method.getSimpleName(), "ExceptionTest")); return publicMethodName(testCaseName); } /** The unit test class name for the given API interface. */ public String getUnitTestClassName(GapicInterfaceConfig interfaceConfig) { return publicClassName(Name.upperCamel(getInterfaceName(interfaceConfig), "Client", "Test")); } /** The smoke test class name for the given API interface. */ public String getSmokeTestClassName(GapicInterfaceConfig interfaceConfig) { return publicClassName(Name.upperCamel(getInterfaceName(interfaceConfig), "Smoke", "Test")); } /** The class name of the mock gRPC service for the given API interface. */ public String getMockServiceClassName(Interface apiInterface) { return publicClassName(Name.upperCamelKeepUpperAcronyms("Mock", apiInterface.getSimpleName())); } /** The class name of a variable to hold the mock gRPC service for the given API interface. */ public String getMockServiceVarName(Interface apiInterface) { return localVarName(Name.upperCamelKeepUpperAcronyms("Mock", apiInterface.getSimpleName())); } /** The class name of the mock gRPC service implementation for the given API interface. */ public String getMockGrpcServiceImplName(Interface apiInterface) { return publicClassName( Name.upperCamelKeepUpperAcronyms("Mock", apiInterface.getSimpleName(), "Impl")); } /** Inject random value generator code to the given string. */ public String injectRandomStringGeneratorCode(String randomString) { return getNotImplementedString("SurfaceNamer.injectRandomStringGeneratorCode"); } ////////////////////////////////////////// Examples //////////////////////////////////////////// /** The name of the example package */ public String getExamplePackageName() { return getNotImplementedString("SurfaceNamer.getExamplePackageName"); } /** The local (unqualified) name of the example package */ public String getLocalExamplePackageName() { return getNotImplementedString("SurfaceNamer.getLocalExamplePackageName"); } /** * The name of example of the constructor for the service client. The client is VKit generated, * not GRPC. */ public String getApiWrapperClassConstructorExampleName(Interface apiInterface) { return getApiWrapperClassConstructorName(apiInterface); } /** The name of the example for the paged callable variant. */ public String getPagedCallableMethodExampleName(Interface apiInterface, Method method) { return getPagedCallableMethodName(method); } /** The name of the example for the plain callable variant. */ public String getCallableMethodExampleName(Interface apiInterface, Method method) { return getCallableMethodName(method); } /** The name of the example for the operation callable variant of the given method. */ public String getOperationCallableMethodExampleName(Interface apiInterface, Method method) { return getOperationCallableMethodName(method); } /** The name of the example for the method. */ public String getApiMethodExampleName(Interface apiInterface, Method method) { return getApiMethodName(method, VisibilityConfig.PUBLIC); } /** The name of the example for the async variant of the given method. */ public String getAsyncApiMethodExampleName(Interface apiInterface, Method method) { return getAsyncApiMethodName(method, VisibilityConfig.PUBLIC); } /** * The name of the example of the GRPC streaming surface method which can call the given API * method. */ public String getGrpcStreamingApiMethodExampleName(Interface apiInterface, Method method) { return getGrpcStreamingApiMethodName(method, VisibilityConfig.PUBLIC); } /** The example name of the IAM resource getter function. */ public String getIamResourceGetterFunctionExampleName(Interface apiInterface, Field field) { return getIamResourceGetterFunctionName(field); } /** The file name for the example of an API interface. */ public String getExampleFileName(Interface apiInterface) { return getNotImplementedString("SurfaceNamer.getExampleFileName"); } ////////////////////////////////////////// Utility ///////////////////////////////////////////// /** Indicates whether the specified method supports retry settings. */ public boolean methodHasRetrySettings(GapicMethodConfig methodConfig) { return true; } /** Indicates whether the specified method supports timeout settings. */ public boolean methodHasTimeoutSettings(GapicMethodConfig methodConfig) { return true; } private static String removeSuffix(String original, String suffix) { if (original.endsWith(suffix)) { original = original.substring(0, original.length() - suffix.length()); } return original; } /** Converts the given text to a quoted string. */ public String quoted(String text) { return "\"" + text + "\""; } /** Make the given type name able to accept nulls, if it is a primitive type */ public String makePrimitiveTypeNullable(String typeName, TypeRef type) { return typeName; } /** Is this type a primitive, according to target language. */ public boolean isPrimitive(TypeRef type) { return type.isPrimitive(); } /** The default value for an optional field, null if no default value required. */ public String getOptionalFieldDefaultValue(FieldConfig fieldConfig, GapicMethodContext context) { return getNotImplementedString("SurfaceNamer.getOptionalFieldDefaultValue"); } public String getToStringMethod() { return getNotImplementedString("SurfaceNamer.getToStringMethod"); } }
shinfan/toolkit
src/main/java/com/google/api/codegen/transformer/SurfaceNamer.java
Java
apache-2.0
58,588
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.appmesh.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * Deletes a virtual node input. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteVirtualNode" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteVirtualNodeRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the service mesh to delete the virtual node in. * </p> */ private String meshName; /** * <p> * The AWS IAM account ID of the service mesh owner. If the account ID is not your own, then it's the ID of the * account that shared the mesh with your account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working with shared meshes</a>. * </p> */ private String meshOwner; /** * <p> * The name of the virtual node to delete. * </p> */ private String virtualNodeName; /** * <p> * The name of the service mesh to delete the virtual node in. * </p> * * @param meshName * The name of the service mesh to delete the virtual node in. */ public void setMeshName(String meshName) { this.meshName = meshName; } /** * <p> * The name of the service mesh to delete the virtual node in. * </p> * * @return The name of the service mesh to delete the virtual node in. */ public String getMeshName() { return this.meshName; } /** * <p> * The name of the service mesh to delete the virtual node in. * </p> * * @param meshName * The name of the service mesh to delete the virtual node in. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteVirtualNodeRequest withMeshName(String meshName) { setMeshName(meshName); return this; } /** * <p> * The AWS IAM account ID of the service mesh owner. If the account ID is not your own, then it's the ID of the * account that shared the mesh with your account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working with shared meshes</a>. * </p> * * @param meshOwner * The AWS IAM account ID of the service mesh owner. If the account ID is not your own, then it's the ID of * the account that shared the mesh with your account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working with shared meshes</a>. */ public void setMeshOwner(String meshOwner) { this.meshOwner = meshOwner; } /** * <p> * The AWS IAM account ID of the service mesh owner. If the account ID is not your own, then it's the ID of the * account that shared the mesh with your account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working with shared meshes</a>. * </p> * * @return The AWS IAM account ID of the service mesh owner. If the account ID is not your own, then it's the ID of * the account that shared the mesh with your account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working with shared meshes</a>. */ public String getMeshOwner() { return this.meshOwner; } /** * <p> * The AWS IAM account ID of the service mesh owner. If the account ID is not your own, then it's the ID of the * account that shared the mesh with your account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working with shared meshes</a>. * </p> * * @param meshOwner * The AWS IAM account ID of the service mesh owner. If the account ID is not your own, then it's the ID of * the account that shared the mesh with your account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working with shared meshes</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteVirtualNodeRequest withMeshOwner(String meshOwner) { setMeshOwner(meshOwner); return this; } /** * <p> * The name of the virtual node to delete. * </p> * * @param virtualNodeName * The name of the virtual node to delete. */ public void setVirtualNodeName(String virtualNodeName) { this.virtualNodeName = virtualNodeName; } /** * <p> * The name of the virtual node to delete. * </p> * * @return The name of the virtual node to delete. */ public String getVirtualNodeName() { return this.virtualNodeName; } /** * <p> * The name of the virtual node to delete. * </p> * * @param virtualNodeName * The name of the virtual node to delete. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteVirtualNodeRequest withVirtualNodeName(String virtualNodeName) { setVirtualNodeName(virtualNodeName); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getMeshName() != null) sb.append("MeshName: ").append(getMeshName()).append(","); if (getMeshOwner() != null) sb.append("MeshOwner: ").append(getMeshOwner()).append(","); if (getVirtualNodeName() != null) sb.append("VirtualNodeName: ").append(getVirtualNodeName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteVirtualNodeRequest == false) return false; DeleteVirtualNodeRequest other = (DeleteVirtualNodeRequest) obj; if (other.getMeshName() == null ^ this.getMeshName() == null) return false; if (other.getMeshName() != null && other.getMeshName().equals(this.getMeshName()) == false) return false; if (other.getMeshOwner() == null ^ this.getMeshOwner() == null) return false; if (other.getMeshOwner() != null && other.getMeshOwner().equals(this.getMeshOwner()) == false) return false; if (other.getVirtualNodeName() == null ^ this.getVirtualNodeName() == null) return false; if (other.getVirtualNodeName() != null && other.getVirtualNodeName().equals(this.getVirtualNodeName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMeshName() == null) ? 0 : getMeshName().hashCode()); hashCode = prime * hashCode + ((getMeshOwner() == null) ? 0 : getMeshOwner().hashCode()); hashCode = prime * hashCode + ((getVirtualNodeName() == null) ? 0 : getVirtualNodeName().hashCode()); return hashCode; } @Override public DeleteVirtualNodeRequest clone() { return (DeleteVirtualNodeRequest) super.clone(); } }
aws/aws-sdk-java
aws-java-sdk-appmesh/src/main/java/com/amazonaws/services/appmesh/model/DeleteVirtualNodeRequest.java
Java
apache-2.0
8,802
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.cc.dexlib2.immutable.value; import org.cc.dexlib2.base.value.BaseEnumEncodedValue; import org.cc.dexlib2.iface.reference.FieldReference; import org.cc.dexlib2.iface.value.EnumEncodedValue; import javax.annotation.Nonnull; public class ImmutableEnumEncodedValue extends BaseEnumEncodedValue implements ImmutableEncodedValue { @Nonnull protected final FieldReference value; public ImmutableEnumEncodedValue(@Nonnull FieldReference value) { this.value = value; } public static ImmutableEnumEncodedValue of(EnumEncodedValue enumEncodedValue) { if (enumEncodedValue instanceof ImmutableEnumEncodedValue) { return (ImmutableEnumEncodedValue)enumEncodedValue; } return new ImmutableEnumEncodedValue(enumEncodedValue.getValue()); } @Nonnull @Override public FieldReference getValue() { return value; } }
CvvT/AppTroy
app/src/main/java/org/cc/dexlib2/immutable/value/ImmutableEnumEncodedValue.java
Java
apache-2.0
2,446
package com.therealdanvega.blog.web.rest; import com.therealdanvega.blog.MvnblogApp; import com.therealdanvega.blog.domain.User; import com.therealdanvega.blog.repository.UserRepository; import com.therealdanvega.blog.service.UserService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import javax.inject.Inject; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the UserResource REST controller. * * @see UserResource */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MvnblogApp.class) @WebAppConfiguration @IntegrationTest public class UserResourceIntTest { @Inject private UserRepository userRepository; @Inject private UserService userService; private MockMvc restUserMockMvc; @Before public void setup() { UserResource userResource = new UserResource(); ReflectionTestUtils.setField(userResource, "userRepository", userRepository); ReflectionTestUtils.setField(userResource, "userService", userService); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource).build(); } @Test public void testGetExistingUser() throws Exception { restUserMockMvc.perform(get("/api/users/admin") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.lastName").value("Administrator")); } @Test public void testGetUnknownUser() throws Exception { restUserMockMvc.perform(get("/api/users/unknown") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } }
cfaddict/jhipster-course
sample-app/mvnblog/src/test/java/com/therealdanvega/blog/web/rest/UserResourceIntTest.java
Java
apache-2.0
2,515
package db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class SimpleWeatherOpenHelper extends SQLiteOpenHelper{ //Province±í½¨±íÓï¾ä public static final String CREATE_PROVINCE = "create table Province (" + "id integer primary key autoincrement, " + "province_name text, " + "province_code text)"; //City±í½¨±íÓï¾ä public static final String CREATE_CITY = "create table City (" + "id integer primary key autoincrement, " + "city_name text, " + "city_code text, " + "province_id integer)"; //Country±í½¨±íÓï¾ä public static final String CREATE_COUNTRY = "create table Country (" + "id integer primary key autoincrement, " + "country_name text, " + "country_code text, " + "city_id integer)"; public SimpleWeatherOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase arg0) { // TODO Auto-generated method stub arg0.execSQL(CREATE_PROVINCE); arg0.execSQL(CREATE_CITY); arg0.execSQL(CREATE_COUNTRY); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub } }
shudaizisd/SimpleWeather
src/db/SimpleWeatherOpenHelper.java
Java
apache-2.0
1,396
package ru.testing.client.websocket; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import org.apache.log4j.Logger; import org.controlsfx.control.PopOver; import ru.testing.client.controllers.SendMessagesController; import ru.testing.client.controllers.TabWsMessagesController; import java.io.IOException; /** * Send message history pop over */ public class SendMessagesPopOver extends PopOver { private static final Logger LOGGER = Logger.getLogger(SendMessagesPopOver.class); private SendMessagesController controller; public SendMessagesPopOver(TabWsMessagesController tabWsMessagesController) { // Pop over settings setDetachable(false); setArrowLocation(ArrowLocation.TOP_RIGHT); setOnHidden(event -> tabWsMessagesController.getSendMsgHistoryBtn().setSelected(false)); try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/views/popover.send.messages.fxml")); Parent root = loader.load(); controller = loader.getController(); controller.setCheckListViewCellFactory(tabWsMessagesController); setContentNode(root); } catch (IOException e) { LOGGER.error(String.format("Error load sent messages pop over: %s", e.getMessage())); } } /** * Get sent message controller * * @return SendMessagesController */ public SendMessagesController getController() { return controller; } }
alexandr85/javafx-ws-client
src/main/java/ru/testing/client/websocket/SendMessagesPopOver.java
Java
apache-2.0
1,495
package utils; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.widget.Toast; import com.kimcy929.app.permission.R; /** * Created by kimcy on 14/09/2015. */ public class PermissionAction { public static void actionAppInfo(Context context, String packagename) { Intent i = new Intent(); i.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); i.addCategory(Intent.CATEGORY_DEFAULT); i.setData(Uri.parse("package:" + packagename)); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(i); } catch (Exception ex) { } } public static void actionUninstallApp(Context context, String packageName) { try { Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); intent.setData(Uri.parse("package:" + packageName)); context.startActivity(intent); } catch (Exception e) { } } public static void searchOnMarket(Context context, String packageName) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("market://details?id=" + packageName)); context.startActivity(intent); } public static void launchApp(Context context, String packageName) { PackageManager pm = context.getPackageManager(); Intent intent = pm.getLaunchIntentForPackage(packageName); if (intent != null) context.startActivity(intent); else Toast.makeText(context, context.getResources().getString(R.string.can_not_open_app), Toast.LENGTH_SHORT).show(); } }
kimcy929/AppPermissions
GetPermissionInfo/src/main/java/utils/PermissionAction.java
Java
apache-2.0
1,717
package hadoop; import java.io.IOException; import lightLogger.Logger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.util.LineReader; import utils.Points; /** * Reads and deserializes the output of PointOutputFormat. * * @author Christof Pieloth * */ public class PointInputFormat extends FileInputFormat<NullWritable, PointWritable> { @Override public RecordReader<NullWritable, PointWritable> createRecordReader( InputSplit arg0, TaskAttemptContext arg1) throws IOException, InterruptedException { return new PointRecordReader(); } protected static class PointRecordReader extends RecordReader<NullWritable, PointWritable> { private CompressionCodecFactory compressionCodecs = null; private long start; private long pos; private long end; private LineReader in; private int maxLineLength; private NullWritable key = NullWritable.get(); private PointWritable value = null; private Text line; public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException { FileSplit split = (FileSplit) genericSplit; Configuration job = context.getConfiguration(); this.maxLineLength = job.getInt( "mapred.linerecordreader.maxlength", Integer.MAX_VALUE); start = split.getStart(); end = start + split.getLength(); final Path file = split.getPath(); compressionCodecs = new CompressionCodecFactory(job); final CompressionCodec codec = compressionCodecs.getCodec(file); // open the file and seek to the start of the split FileSystem fs = file.getFileSystem(job); FSDataInputStream fileIn = fs.open(split.getPath()); boolean skipFirstLine = false; if (codec != null) { in = new LineReader(codec.createInputStream(fileIn), job); end = Long.MAX_VALUE; } else { if (start != 0) { skipFirstLine = true; --start; fileIn.seek(start); } in = new LineReader(fileIn, job); } if (skipFirstLine) { // skip first line and re-establish "start". start += in.readLine(new Text(), 0, (int) Math.min((long) Integer.MAX_VALUE, end - start)); } this.pos = start; } public boolean nextKeyValue() throws IOException { if (key == null) { key = NullWritable.get(); } if (line == null) { line = new Text(); } int newSize = 0; while (pos < end) { newSize = in.readLine(line, maxLineLength, Math.max( (int) Math.min(Integer.MAX_VALUE, end - pos), maxLineLength)); if (newSize == 0) { break; } pos += newSize; if (newSize < maxLineLength) { break; } // line too long. try again Logger.logInfo(this.getClass(), "Skipped line of size " + newSize + " at pos " + (pos - newSize)); } if (newSize == 0) { key = null; value = null; return false; } else { return true; } } @Override public NullWritable getCurrentKey() { return key; } @Override public PointWritable getCurrentValue() { this.value = new PointWritable(Points.createPoint(this.line.toString())); return this.value; } /** * Get the progress within the split */ public float getProgress() { if (start == end) { return 0.0f; } else { return Math.min(1.0f, (pos - start) / (float) (end - start)); } } public synchronized void close() throws IOException { if (in != null) { in.close(); } } } }
cpieloth/GPGPU-on-Hadoop
k-means/src/hadoop/PointInputFormat.java
Java
apache-2.0
3,993
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdds.scm.exceptions; // Exceptions thrown by SCM.
littlezhou/hadoop
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/exceptions/package-info.java
Java
apache-2.0
883
/* * The Gemma project. * * Copyright (c) 2006-2012 University of British Columbia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ubic.gemma.model.genome.gene; public class Multifunctionality implements java.io.Serializable { private static final long serialVersionUID = 1842256912459855071L; private Double score; private Double rank; private Integer numGoTerms; private Long id; /** * No-arg constructor added to satisfy javabean contract * * @author Paul */ @SuppressWarnings("WeakerAccess") // Required by spring public Multifunctionality() { } public Long getId() { return this.id; } public void setId( Long id ) { this.id = id; } /** * @return The number of GO terms the gene has, after propagation, but excluding the roots */ public Integer getNumGoTerms() { return this.numGoTerms; } public void setNumGoTerms( Integer numGoTerms ) { this.numGoTerms = numGoTerms; } /** * @return The relative rank of the gene among other genes in the taxon, based on the multifunctionality score (not the * number of GO terms, though that would generally give a similar result). A rank of 1 means the * "most multifunctional", while 0 is assigned to the least multifunctional gene. */ public Double getRank() { return this.rank; } public void setRank( Double rank ) { this.rank = rank; } /** * @return The multifunctionality of the gene, as scored using the "optimal ranking" method of Gillis and Pavlidis (2011). * It is a value from 0 to 1, where 1 is the highest multifunctionality. Note that this score is not very useful by * itself as it really only makes sense as a relative measure among genes. Thus the rank should be used for display. */ public Double getScore() { return this.score; } public void setScore( Double score ) { this.score = score; } @Override public int hashCode() { int hashCode = 0; hashCode = 29 * hashCode + ( id == null ? 0 : id.hashCode() ); return hashCode; } @Override public boolean equals( Object object ) { if ( this == object ) { return true; } if ( !( object instanceof Multifunctionality ) ) { return false; } final Multifunctionality that = ( Multifunctionality ) object; return this.id != null && that.getId() != null && this.id.equals( that.getId() ); } @Override public String toString() { return String.format( "terms=%d score=%.2f rank=%.3f", this.numGoTerms, this.score, this.rank ); } public static final class Factory { public static Multifunctionality newInstance() { return new Multifunctionality(); } } }
ppavlidis/Gemma
gemma-core/src/main/java/ubic/gemma/model/genome/gene/Multifunctionality.java
Java
apache-2.0
3,416
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.magicConstant; import com.intellij.analysis.AnalysisScope; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.ExternalAnnotationsManager; import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInspection.*; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.SdkModificator; import com.intellij.openapi.projectRoots.impl.JavaSdkImpl; import com.intellij.openapi.roots.JdkOrderEntry; import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.impl.JavaConstantExpressionEvaluator; import com.intellij.psi.impl.cache.impl.id.IdIndex; import com.intellij.psi.impl.cache.impl.id.IdIndexEntry; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.javadoc.PsiDocTag; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.*; import com.intellij.slicer.*; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.FileBasedIndex; import gnu.trove.THashSet; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.stream.Collectors; public class MagicConstantInspection extends BaseJavaLocalInspectionTool { private static final Key<Boolean> NO_ANNOTATIONS_FOUND = Key.create("REPORTED_NO_ANNOTATIONS_FOUND"); @Nls @NotNull @Override public String getGroupDisplayName() { return GroupNames.BUGS_GROUP_NAME; } @Nls @NotNull @Override public String getDisplayName() { return "Magic Constant"; } @NotNull @Override public String getShortName() { return "MagicConstant"; } @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { return new JavaElementVisitor() { @Override public void visitJavaFile(PsiJavaFile file) { checkAnnotationsJarAttached(file, holder); } @Override public void visitCallExpression(PsiCallExpression callExpression) { checkCall(callExpression, holder); } @Override public void visitAssignmentExpression(PsiAssignmentExpression expression) { PsiExpression r = expression.getRExpression(); if (r == null) return; PsiExpression l = expression.getLExpression(); if (!(l instanceof PsiReferenceExpression)) return; PsiElement resolved = ((PsiReferenceExpression)l).resolve(); if (!(resolved instanceof PsiModifierListOwner)) return; PsiModifierListOwner owner = (PsiModifierListOwner)resolved; PsiType type = expression.getType(); checkExpression(r, owner, type, holder); } @Override public void visitReturnStatement(PsiReturnStatement statement) { PsiExpression value = statement.getReturnValue(); if (value == null) return; PsiElement element = PsiTreeUtil.getParentOfType(statement, PsiMethod.class, PsiLambdaExpression.class); PsiMethod method = element instanceof PsiMethod ? (PsiMethod)element : LambdaUtil.getFunctionalInterfaceMethod(element); if (method == null) return; checkExpression(value, method, value.getType(), holder); } @Override public void visitNameValuePair(PsiNameValuePair pair) { PsiAnnotationMemberValue value = pair.getValue(); if (!(value instanceof PsiExpression)) return; PsiReference ref = pair.getReference(); if (ref == null) return; PsiMethod method = (PsiMethod)ref.resolve(); if (method == null) return; checkExpression((PsiExpression)value, method, method.getReturnType(), holder); } @Override public void visitBinaryExpression(PsiBinaryExpression expression) { IElementType tokenType = expression.getOperationTokenType(); if (tokenType != JavaTokenType.EQEQ && tokenType != JavaTokenType.NE) return; PsiExpression l = expression.getLOperand(); PsiExpression r = expression.getROperand(); if (r == null) return; checkBinary(l, r); checkBinary(r, l); } private void checkBinary(@NotNull PsiExpression l, @NotNull PsiExpression r) { if (l instanceof PsiReference) { PsiElement resolved = ((PsiReference)l).resolve(); if (resolved instanceof PsiModifierListOwner) { checkExpression(r, (PsiModifierListOwner)resolved, getType((PsiModifierListOwner)resolved), holder); } } else if (l instanceof PsiMethodCallExpression) { PsiMethod method = ((PsiMethodCallExpression)l).resolveMethod(); if (method != null) { checkExpression(r, method, method.getReturnType(), holder); } } } }; } @Override public void cleanup(@NotNull Project project) { super.cleanup(project); project.putUserData(NO_ANNOTATIONS_FOUND, null); } private static void checkAnnotationsJarAttached(@NotNull PsiFile file, @NotNull ProblemsHolder holder) { final Project project = file.getProject(); if (!holder.isOnTheFly()) { final Boolean found = project.getUserData(NO_ANNOTATIONS_FOUND); if (found != null) return; } PsiClass event = JavaPsiFacade.getInstance(project).findClass("java.awt.event.InputEvent", GlobalSearchScope.allScope(project)); if (event == null) return; // no jdk to attach PsiMethod[] methods = event.findMethodsByName("getModifiers", false); if (methods.length != 1) return; // no jdk to attach PsiMethod getModifiers = methods[0]; PsiAnnotation annotation = ExternalAnnotationsManager.getInstance(project).findExternalAnnotation(getModifiers, MagicConstant.class.getName()); if (annotation != null) return; final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(getModifiers); if (virtualFile == null) return; // no jdk to attach final List<OrderEntry> entries = ProjectRootManager.getInstance(project).getFileIndex().getOrderEntriesForFile(virtualFile); Sdk jdk = null; for (OrderEntry orderEntry : entries) { if (orderEntry instanceof JdkOrderEntry) { jdk = ((JdkOrderEntry)orderEntry).getJdk(); if (jdk != null) break; } } if (jdk == null) return; // no jdk to attach if (!holder.isOnTheFly()) { project.putUserData(NO_ANNOTATIONS_FOUND, Boolean.TRUE); } final Sdk finalJdk = jdk; String path = finalJdk.getHomePath(); String text = "No IDEA annotations attached to the JDK " + finalJdk.getName() + (path == null ? "" : " (" + FileUtil.toSystemDependentName(path) + ")") +", some issues will not be found"; holder.registerProblem(file, text, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new LocalQuickFix() { @NotNull @Override public String getName() { return "Attach annotations"; } @NotNull @Override public String getFamilyName() { return getName(); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { ApplicationManager.getApplication().runWriteAction(() -> { SdkModificator modificator = finalJdk.getSdkModificator(); JavaSdkImpl.attachJdkAnnotations(modificator); modificator.commitChanges(); }); } }); } private static void checkExpression(@NotNull PsiExpression expression, @NotNull PsiModifierListOwner owner, @Nullable PsiType type, @NotNull ProblemsHolder holder) { AllowedValues allowed = getAllowedValues(owner, type, null); if (allowed == null) return; PsiElement scope = PsiUtil.getTopLevelEnclosingCodeBlock(expression, null); if (scope == null) scope = expression; if (!isAllowed(scope, expression, allowed, expression.getManager(), null)) { registerProblem(expression, allowed, holder); } } private static void checkCall(@NotNull PsiCallExpression methodCall, @NotNull ProblemsHolder holder) { PsiMethod method = methodCall.resolveMethod(); if (method == null) return; PsiParameter[] parameters = method.getParameterList().getParameters(); PsiExpression[] arguments = methodCall.getArgumentList().getExpressions(); for (int i = 0; i < parameters.length; i++) { PsiParameter parameter = parameters[i]; AllowedValues values = getAllowedValues(parameter, parameter.getType(), null); if (values == null) continue; if (i >= arguments.length) break; PsiExpression argument = arguments[i]; argument = PsiUtil.deparenthesizeExpression(argument); if (argument == null) continue; checkMagicParameterArgument(parameter, argument, values, holder); } } static class AllowedValues { @NotNull final PsiAnnotationMemberValue[] values; final boolean canBeOred; final boolean resolvesToZero; //true if one if the values resolves to literal 0, e.g. "int PLAIN = 0" private AllowedValues(@NotNull PsiAnnotationMemberValue[] values, boolean canBeOred) { this.values = values; this.canBeOred = canBeOred; resolvesToZero = resolvesToZero(); } private boolean resolvesToZero() { for (PsiAnnotationMemberValue value : values) { if (value instanceof PsiExpression) { Object evaluated = JavaConstantExpressionEvaluator.computeConstantExpression((PsiExpression)value, null, false); if (evaluated instanceof Integer && ((Integer)evaluated).intValue() == 0) { return true; } } } return false; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AllowedValues a2 = (AllowedValues)o; if (canBeOred != a2.canBeOred) { return false; } Set<PsiAnnotationMemberValue> v1 = new THashSet<>(Arrays.asList(values)); Set<PsiAnnotationMemberValue> v2 = new THashSet<>(Arrays.asList(a2.values)); if (v1.size() != v2.size()) { return false; } for (PsiAnnotationMemberValue value : v1) { for (PsiAnnotationMemberValue value2 : v2) { if (same(value, value2, value.getManager())) { v2.remove(value2); break; } } } return v2.isEmpty(); } @Override public int hashCode() { int result = Arrays.hashCode(values); result = 31 * result + (canBeOred ? 1 : 0); return result; } boolean isSubsetOf(@NotNull AllowedValues other, @NotNull PsiManager manager) { for (PsiAnnotationMemberValue value : values) { boolean found = false; for (PsiAnnotationMemberValue otherValue : other.values) { if (same(value, otherValue, manager)) { found = true; break; } } if (!found) return false; } return true; } } private static AllowedValues getAllowedValuesFromMagic(@NotNull PsiType type, @NotNull PsiAnnotation magic, @NotNull PsiManager manager) { PsiAnnotationMemberValue[] allowedValues; final boolean canBeOred; if (TypeConversionUtil.getTypeRank(type) <= TypeConversionUtil.LONG_RANK) { PsiAnnotationMemberValue intValues = magic.findAttributeValue("intValues"); allowedValues = intValues instanceof PsiArrayInitializerMemberValue ? ((PsiArrayInitializerMemberValue)intValues).getInitializers() : PsiAnnotationMemberValue.EMPTY_ARRAY; if (allowedValues.length == 0) { PsiAnnotationMemberValue orValue = magic.findAttributeValue("flags"); allowedValues = orValue instanceof PsiArrayInitializerMemberValue ? ((PsiArrayInitializerMemberValue)orValue).getInitializers() : PsiAnnotationMemberValue.EMPTY_ARRAY; canBeOred = true; } else { canBeOred = false; } } else if (type.equals(PsiType.getJavaLangString(manager, GlobalSearchScope.allScope(manager.getProject())))) { PsiAnnotationMemberValue strValuesAttr = magic.findAttributeValue("stringValues"); allowedValues = strValuesAttr instanceof PsiArrayInitializerMemberValue ? ((PsiArrayInitializerMemberValue)strValuesAttr).getInitializers() : PsiAnnotationMemberValue.EMPTY_ARRAY; canBeOred = false; } else { return null; //other types not supported } if (allowedValues.length != 0) { return new AllowedValues(allowedValues, canBeOred); } // last resort: try valuesFromClass PsiAnnotationMemberValue[] values = readFromClass("valuesFromClass", magic, type, manager); boolean ored = false; if (values == null) { values = readFromClass("flagsFromClass", magic, type, manager); ored = true; } if (values == null) return null; return new AllowedValues(values, ored); } private static PsiAnnotationMemberValue[] readFromClass(@NonNls @NotNull String attributeName, @NotNull PsiAnnotation magic, @NotNull PsiType type, @NotNull PsiManager manager) { PsiAnnotationMemberValue fromClassAttr = magic.findAttributeValue(attributeName); PsiType fromClassType = fromClassAttr instanceof PsiClassObjectAccessExpression ? ((PsiClassObjectAccessExpression)fromClassAttr).getOperand().getType() : null; PsiClass fromClass = fromClassType instanceof PsiClassType ? ((PsiClassType)fromClassType).resolve() : null; if (fromClass == null) return null; String fqn = fromClass.getQualifiedName(); if (fqn == null) return null; List<PsiAnnotationMemberValue> constants = new ArrayList<>(); for (PsiField field : fromClass.getFields()) { if (!field.hasModifierProperty(PsiModifier.PUBLIC) || !field.hasModifierProperty(PsiModifier.STATIC) || !field.hasModifierProperty(PsiModifier.FINAL)) continue; PsiType fieldType = field.getType(); if (!Comparing.equal(fieldType, type)) continue; PsiAssignmentExpression e = (PsiAssignmentExpression)JavaPsiFacade.getElementFactory(manager.getProject()).createExpressionFromText("x="+fqn + "." + field.getName(), field); PsiReferenceExpression refToField = (PsiReferenceExpression)e.getRExpression(); constants.add(refToField); } if (constants.isEmpty()) return null; return constants.toArray(new PsiAnnotationMemberValue[constants.size()]); } static AllowedValues getAllowedValues(@NotNull PsiModifierListOwner element, @Nullable PsiType type, @Nullable Set<PsiClass> visited) { PsiAnnotation[] annotations = getAllAnnotations(element); PsiManager manager = element.getManager(); for (PsiAnnotation annotation : annotations) { PsiJavaCodeReferenceElement ref = annotation.getNameReferenceElement(); PsiElement resolved = ref == null ? null : ref.resolve(); if (!(resolved instanceof PsiClass) || !((PsiClass)resolved).isAnnotationType()) continue; PsiClass aClass = (PsiClass)resolved; AllowedValues values; if (type != null && MagicConstant.class.getName().equals(aClass.getQualifiedName())) { values = getAllowedValuesFromMagic(type, annotation, manager); if (values != null) return values; } if (visited == null) visited = new THashSet<>(); if (!visited.add(aClass)) continue; values = getAllowedValues(aClass, type, visited); if (values != null) return values; } return parseBeanInfo(element, manager); } @NotNull private static PsiAnnotation[] getAllAnnotations(@NotNull PsiModifierListOwner element) { return CachedValuesManager.getCachedValue(element, () -> CachedValueProvider.Result.create(AnnotationUtil.getAllAnnotations(element, true, null, false), PsiModificationTracker.MODIFICATION_COUNT)); } private static AllowedValues parseBeanInfo(@NotNull PsiModifierListOwner owner, @NotNull PsiManager manager) { PsiFile containingFile = owner.getContainingFile(); if (containingFile != null && !containsBeanInfoText((PsiFile)containingFile.getNavigationElement())) { return null; } PsiMethod method = null; if (owner instanceof PsiParameter) { PsiParameter parameter = (PsiParameter)owner; PsiElement scope = parameter.getDeclarationScope(); if (!(scope instanceof PsiMethod)) return null; PsiElement nav = scope.getNavigationElement(); if (!(nav instanceof PsiMethod)) return null; method = (PsiMethod)nav; if (method.isConstructor()) { // not a property, try the @ConstructorProperties({"prop"}) PsiAnnotation annotation = AnnotationUtil.findAnnotation(method, "java.beans.ConstructorProperties"); if (annotation == null) return null; PsiAnnotationMemberValue value = annotation.findAttributeValue("value"); if (!(value instanceof PsiArrayInitializerMemberValue)) return null; PsiAnnotationMemberValue[] initializers = ((PsiArrayInitializerMemberValue)value).getInitializers(); PsiElement parent = parameter.getParent(); if (!(parent instanceof PsiParameterList)) return null; int index = ((PsiParameterList)parent).getParameterIndex(parameter); if (index >= initializers.length) return null; PsiAnnotationMemberValue initializer = initializers[index]; if (!(initializer instanceof PsiLiteralExpression)) return null; Object val = ((PsiLiteralExpression)initializer).getValue(); if (!(val instanceof String)) return null; PsiMethod setter = PropertyUtil.findPropertySetter(method.getContainingClass(), (String)val, false, false); if (setter == null) return null; // try the @beaninfo of the corresponding setter PsiElement navigationElement = setter.getNavigationElement(); if (!(navigationElement instanceof PsiMethod)) return null; method = (PsiMethod)navigationElement; } } else if (owner instanceof PsiMethod) { PsiElement nav = owner.getNavigationElement(); if (!(nav instanceof PsiMethod)) return null; method = (PsiMethod)nav; } if (method == null) return null; PsiClass aClass = method.getContainingClass(); if (aClass == null) return null; if (PropertyUtil.isSimplePropertyGetter(method)) { List<PsiMethod> setters = PropertyUtil.getSetters(aClass, PropertyUtil.getPropertyNameByGetter(method)); if (setters.size() != 1) return null; method = setters.get(0); } if (!PropertyUtil.isSimplePropertySetter(method)) return null; PsiDocComment doc = method.getDocComment(); if (doc == null) return null; PsiDocTag beaninfo = doc.findTagByName("beaninfo"); if (beaninfo == null) return null; String data = StringUtil.join(beaninfo.getDataElements(), PsiElement::getText, "\n"); int enumIndex = StringUtil.indexOfSubstringEnd(data, "enum:"); if (enumIndex == -1) return null; data = data.substring(enumIndex); int colon = data.indexOf(':'); int last = colon == -1 ? data.length() : data.substring(0,colon).lastIndexOf('\n'); data = data.substring(0, last); List<PsiAnnotationMemberValue> values = new ArrayList<>(); for (String line : StringUtil.splitByLines(data)) { List<String> words = StringUtil.split(line, " ", true, true); if (words.size() != 2) continue; String ref = words.get(1); PsiExpression constRef = JavaPsiFacade.getElementFactory(manager.getProject()).createExpressionFromText(ref, aClass); if (!(constRef instanceof PsiReferenceExpression)) continue; PsiReferenceExpression expr = (PsiReferenceExpression)constRef; values.add(expr); } if (values.isEmpty()) return null; PsiAnnotationMemberValue[] array = values.toArray(new PsiAnnotationMemberValue[values.size()]); return new AllowedValues(array, false); } private static boolean containsBeanInfoText(@NotNull PsiFile file) { return CachedValuesManager.getCachedValue(file, () -> { Collection<VirtualFile> files = FileBasedIndex.getInstance().getContainingFiles(IdIndex.NAME, new IdIndexEntry("beaninfo", true), GlobalSearchScope.fileScope(file)); return CachedValueProvider.Result.create(!files.isEmpty(), file); }); } private static PsiType getType(@NotNull PsiModifierListOwner element) { return element instanceof PsiVariable ? ((PsiVariable)element).getType() : element instanceof PsiMethod ? ((PsiMethod)element).getReturnType() : null; } private static void checkMagicParameterArgument(@NotNull PsiParameter parameter, @NotNull PsiExpression argument, @NotNull AllowedValues allowedValues, @NotNull ProblemsHolder holder) { final PsiManager manager = PsiManager.getInstance(holder.getProject()); if (!argument.getTextRange().isEmpty() && !isAllowed(parameter.getDeclarationScope(), argument, allowedValues, manager, null)) { registerProblem(argument, allowedValues, holder); } } private static void registerProblem(@NotNull PsiExpression argument, @NotNull AllowedValues allowedValues, @NotNull ProblemsHolder holder) { String values = StringUtil.join(allowedValues.values, value -> { if (value instanceof PsiReferenceExpression) { PsiElement resolved = ((PsiReferenceExpression)value).resolve(); if (resolved instanceof PsiVariable) { return PsiFormatUtil.formatVariable((PsiVariable)resolved, PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_CONTAINING_CLASS, PsiSubstitutor.EMPTY); } } return value.getText(); }, ", "); String message = "Should be one of: " + values + (allowedValues.canBeOred ? " or their combination" : ""); holder.registerProblem(argument, message, suggestMagicConstant(argument, allowedValues)); } @Nullable // null means no quickfix available private static LocalQuickFix suggestMagicConstant(@NotNull PsiExpression argument, @NotNull AllowedValues allowedValues) { Object argumentValue = JavaConstantExpressionEvaluator.computeConstantExpression(argument, null, false); if (argumentValue == null) return null; if (!allowedValues.canBeOred) { for (PsiAnnotationMemberValue value : allowedValues.values) { if (value instanceof PsiExpression) { Object constantValue = JavaConstantExpressionEvaluator.computeConstantExpression((PsiExpression)value, null, false); if (constantValue != null && constantValue.equals(argumentValue)) { return new ReplaceWithMagicConstantFix(argument, value); } } } } else { Long longArgument = evaluateLongConstant(argument); if (longArgument == null) { return null; } // try to find ored flags long remainingFlags = longArgument.longValue(); List<PsiAnnotationMemberValue> flags = new ArrayList<>(); for (PsiAnnotationMemberValue value : allowedValues.values) { if (value instanceof PsiExpression) { Long constantValue = evaluateLongConstant((PsiExpression)value); if (constantValue == null) { continue; } if ((remainingFlags & constantValue) == constantValue) { flags.add(value); remainingFlags &= ~constantValue; } } } if (remainingFlags == 0) { // found flags to combine with OR, suggest the fix if (flags.size() > 1) { for (int i = flags.size() - 1; i >= 0; i--) { PsiAnnotationMemberValue flag = flags.get(i); Long flagValue = evaluateLongConstant((PsiExpression)flag); if (flagValue != null && flagValue == 0) { // no sense in ORing with '0' flags.remove(i); } } } if (!flags.isEmpty()) { return new ReplaceWithMagicConstantFix(argument, flags.toArray(PsiAnnotationMemberValue.EMPTY_ARRAY)); } } } return null; } private static Long evaluateLongConstant(@NotNull PsiExpression expression) { Object constantValue = JavaConstantExpressionEvaluator.computeConstantExpression(expression, null, false); if (constantValue instanceof Long || constantValue instanceof Integer || constantValue instanceof Short || constantValue instanceof Byte) { return ((Number)constantValue).longValue(); } return null; } private static boolean isAllowed(@NotNull final PsiElement scope, @NotNull final PsiExpression argument, @NotNull final AllowedValues allowedValues, @NotNull final PsiManager manager, @Nullable Set<PsiExpression> visited) { if (isGoodExpression(argument, allowedValues, scope, manager, visited)) return true; return processValuesFlownTo(argument, scope, manager, expression -> isGoodExpression(expression, allowedValues, scope, manager, visited)); } private static boolean isGoodExpression(@NotNull PsiExpression argument, @NotNull AllowedValues allowedValues, @NotNull PsiElement scope, @NotNull PsiManager manager, @Nullable Set<PsiExpression> visited) { PsiExpression expression = PsiUtil.deparenthesizeExpression(argument); if (expression == null) return true; if (visited == null) visited = new THashSet<>(); if (!visited.add(expression)) return true; if (expression instanceof PsiConditionalExpression) { PsiExpression thenExpression = ((PsiConditionalExpression)expression).getThenExpression(); boolean thenAllowed = thenExpression == null || isAllowed(scope, thenExpression, allowedValues, manager, visited); if (!thenAllowed) return false; PsiExpression elseExpression = ((PsiConditionalExpression)expression).getElseExpression(); return elseExpression == null || isAllowed(scope, elseExpression, allowedValues, manager, visited); } if (isOneOf(expression, allowedValues, manager)) return true; if (allowedValues.canBeOred) { PsiExpression zero = getLiteralExpression(expression, manager, "0"); if (same(expression, zero, manager) // if for some crazy reason the constant with value "0" is included to allowed values for flags, do not treat literal "0" as allowed value anymore // see e.g. Font.BOLD=1, Font.ITALIC=2, Font.PLAIN=0 && !allowedValues.resolvesToZero) return true; PsiExpression minusOne = getLiteralExpression(expression, manager, "-1"); if (same(expression, minusOne, manager)) return true; if (expression instanceof PsiPolyadicExpression) { IElementType tokenType = ((PsiPolyadicExpression)expression).getOperationTokenType(); if (JavaTokenType.OR.equals(tokenType) || JavaTokenType.AND.equals(tokenType) || JavaTokenType.PLUS.equals(tokenType)) { for (PsiExpression operand : ((PsiPolyadicExpression)expression).getOperands()) { if (!isAllowed(scope, operand, allowedValues, manager, visited)) return false; } return true; } } if (expression instanceof PsiPrefixExpression && JavaTokenType.TILDE.equals(((PsiPrefixExpression)expression).getOperationTokenType())) { PsiExpression operand = ((PsiPrefixExpression)expression).getOperand(); return operand == null || isAllowed(scope, operand, allowedValues, manager, visited); } } PsiElement resolved = null; if (expression instanceof PsiReference) { resolved = ((PsiReference)expression).resolve(); } else if (expression instanceof PsiCallExpression) { resolved = ((PsiCallExpression)expression).resolveMethod(); } AllowedValues allowedForRef; if (resolved instanceof PsiModifierListOwner && (allowedForRef = getAllowedValues((PsiModifierListOwner)resolved, getType((PsiModifierListOwner)resolved), null)) != null && allowedForRef.isSubsetOf(allowedValues, manager)) return true; return PsiType.NULL.equals(expression.getType()); } private static final Key<Map<String, PsiExpression>> LITERAL_EXPRESSION_CACHE = Key.create("LITERAL_EXPRESSION_CACHE"); @NotNull private static PsiExpression getLiteralExpression(@NotNull PsiExpression context, @NotNull PsiManager manager, @NotNull String text) { Map<String, PsiExpression> cache = LITERAL_EXPRESSION_CACHE.get(manager); if (cache == null) { cache = ContainerUtil.createConcurrentSoftValueMap(); cache = manager.putUserDataIfAbsent(LITERAL_EXPRESSION_CACHE, cache); } PsiExpression expression = cache.get(text); if (expression == null) { expression = JavaPsiFacade.getElementFactory(manager.getProject()).createExpressionFromText(text, context); cache.put(text, expression); } return expression; } private static boolean isOneOf(@NotNull PsiExpression expression, @NotNull AllowedValues allowedValues, @NotNull PsiManager manager) { for (PsiAnnotationMemberValue allowedValue : allowedValues.values) { if (same(allowedValue, expression, manager)) return true; } return false; } private static boolean same(@NotNull PsiElement e1, @NotNull PsiElement e2, @NotNull PsiManager manager) { if (e1 instanceof PsiLiteralExpression && e2 instanceof PsiLiteralExpression) { return Comparing.equal(((PsiLiteralExpression)e1).getValue(), ((PsiLiteralExpression)e2).getValue()); } if (e1 instanceof PsiPrefixExpression && e2 instanceof PsiPrefixExpression && ((PsiPrefixExpression)e1).getOperationTokenType() == ((PsiPrefixExpression)e2).getOperationTokenType()) { PsiExpression loperand = ((PsiPrefixExpression)e1).getOperand(); PsiExpression roperand = ((PsiPrefixExpression)e2).getOperand(); return loperand != null && roperand != null && same(loperand, roperand, manager); } if (e1 instanceof PsiReference && e2 instanceof PsiReference) { e1 = ((PsiReference)e1).resolve(); e2 = ((PsiReference)e2).resolve(); } return manager.areElementsEquivalent(e2, e1); } private static boolean processValuesFlownTo(@NotNull final PsiExpression argument, @NotNull PsiElement scope, @NotNull PsiManager manager, @NotNull final Processor<PsiExpression> processor) { SliceAnalysisParams params = new SliceAnalysisParams(); params.dataFlowToThis = true; params.scope = new AnalysisScope(new LocalSearchScope(scope), manager.getProject()); SliceRootNode rootNode = new SliceRootNode(manager.getProject(), new DuplicateMap(), LanguageSlicing.getProvider(argument).createRootUsage(argument, params)); Collection<? extends AbstractTreeNode> children = rootNode.getChildren().iterator().next().getChildren(); for (AbstractTreeNode child : children) { SliceUsage usage = (SliceUsage)child.getValue(); PsiElement element = usage.getElement(); if (element instanceof PsiExpression && !processor.process((PsiExpression)element)) return false; } return !children.isEmpty(); } private static class ReplaceWithMagicConstantFix extends LocalQuickFixOnPsiElement { private final List<SmartPsiElementPointer<PsiAnnotationMemberValue>> myMemberValuePointers; ReplaceWithMagicConstantFix(@NotNull PsiExpression argument, @NotNull PsiAnnotationMemberValue... values) { super(argument); myMemberValuePointers = Arrays.stream(values).map( value -> SmartPointerManager.getInstance(argument.getProject()).createSmartPsiElementPointer(value)).collect(Collectors.toList()); } @Nls @NotNull @Override public String getFamilyName() { return "Replace with magic constant"; } @NotNull @Override public String getText() { List<String> names = myMemberValuePointers.stream().map(SmartPsiElementPointer::getElement).map(PsiElement::getText).collect(Collectors.toList()); String expression = StringUtil.join(names, " | "); return "Replace with '" + expression + "'"; } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; List<PsiAnnotationMemberValue> values = myMemberValuePointers.stream().map(SmartPsiElementPointer::getElement).collect(Collectors.toList()); String text = StringUtil.join(Collections.nCopies(values.size(), "0"), " | "); PsiExpression concatExp = PsiElementFactory.SERVICE.getInstance(project).createExpressionFromText(text, startElement); List<PsiLiteralExpression> expressionsToReplace = new ArrayList<>(values.size()); concatExp.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitLiteralExpression(PsiLiteralExpression expression) { super.visitLiteralExpression(expression); if (Integer.valueOf(0).equals(expression.getValue())) { expressionsToReplace.add(expression); } } }); Iterator<PsiAnnotationMemberValue> iterator = values.iterator(); List<PsiElement> resolved = new ArrayList<>(); for (PsiLiteralExpression toReplace : expressionsToReplace) { PsiAnnotationMemberValue value = iterator.next(); resolved.add(((PsiReference)value).resolve()); PsiExpression replaced = (PsiExpression)toReplace.replace(value); if (toReplace == concatExp) { concatExp = replaced; } } PsiElement newStartElement = startElement.replace(concatExp); Iterator<PsiElement> resolvedValuesIterator = resolved.iterator(); newStartElement.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceExpression(PsiReferenceExpression expression) { PsiElement bound = expression.bindToElement(resolvedValuesIterator.next()); JavaCodeStyleManager.getInstance(project).shortenClassReferences(bound); } }); } @Override public boolean isAvailable(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { boolean allValid = !myMemberValuePointers.stream().map(SmartPsiElementPointer::getElement).anyMatch(p -> p == null || !p.isValid()); return allValid && super.isAvailable(project, file, startElement, endElement); } } }
michaelgallacher/intellij-community
java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicConstantInspection.java
Java
apache-2.0
37,529
package net.bytebuddy.instrumentation.method.bytecode.stack.constant; import net.bytebuddy.instrumentation.Instrumentation; import net.bytebuddy.instrumentation.method.bytecode.stack.StackManipulation; import net.bytebuddy.test.utility.MockitoRule; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.Mock; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import java.util.Arrays; import java.util.Collection; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.mockito.Mockito.*; @RunWith(Parameterized.class) public class FloatConstantOpcodeTest { private final float value; private final int opcode; @Rule public TestRule mockitoRule = new MockitoRule(this); @Mock private MethodVisitor methodVisitor; @Mock private Instrumentation.Context instrumentationContext; public FloatConstantOpcodeTest(float value, int opcode) { this.value = value; this.opcode = opcode; } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {0f, Opcodes.FCONST_0}, {1f, Opcodes.FCONST_1}, {2f, Opcodes.FCONST_2} }); } @After public void tearDown() throws Exception { verifyZeroInteractions(instrumentationContext); } @Test public void testConstant() throws Exception { StackManipulation.Size size = FloatConstant.forValue(value).apply(methodVisitor, instrumentationContext); assertThat(size.getSizeImpact(), is(1)); assertThat(size.getMaximalSize(), is(1)); verify(methodVisitor).visitInsn(opcode); verifyNoMoreInteractions(methodVisitor); } }
RobAustin/byte-buddy
byte-buddy-dep/src/test/java/net/bytebuddy/instrumentation/method/bytecode/stack/constant/FloatConstantOpcodeTest.java
Java
apache-2.0
1,922
package com.example.dbflute.mysql.friends.seasar.batch.allcore; /** * @author jflute * @since 0.9.1 (2009/02/07 Saturday) */ public class BatchReturn { // =================================================================================== // Attribute // ========= private int batchReturnCode; // =================================================================================== // Constructor // =========== private BatchReturn(int batchReturnCode) { this.batchReturnCode = batchReturnCode; } public static BatchReturn create(int batchErrorCode) { return new BatchReturn(batchErrorCode); } // =================================================================================== // Basic Override // ============== @Override public String toString() { return "{" + batchReturnCode + "}"; } // =================================================================================== // Accessor // ======== public int getBatchReturnCode() { return batchReturnCode; } }
hajimeni/dbflute-solr-example
src/main/java/com/example/dbflute/mysql/friends/seasar/batch/allcore/BatchReturn.java
Java
apache-2.0
1,673
package com.omottec.demoapp.view.statuslayout; import android.view.View; /** * Created by qinbingbing on 30/06/2017. */ public interface OnRetryListener { void onRetry(View view); }
omottec/DemoApp
app/src/main/java/com/omottec/demoapp/view/statuslayout/OnRetryListener.java
Java
apache-2.0
191
/* * Copyright 2018 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.centraldogma.client.armeria; import static java.util.Objects.requireNonNull; import java.util.List; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linecorp.armeria.client.Endpoint; import com.linecorp.armeria.client.endpoint.DynamicEndpointGroup; import com.linecorp.armeria.client.endpoint.EndpointGroup; import com.linecorp.armeria.client.endpoint.EndpointSelectionStrategy; import com.linecorp.centraldogma.client.CentralDogma; import com.linecorp.centraldogma.client.Watcher; import com.linecorp.centraldogma.common.Query; /** * A {@link DynamicEndpointGroup} implementation that retrieves the {@link Endpoint} list from an entry in * Central Dogma. The entry can be a JSON file or a plain text file. * * <p>For example, the following JSON array will be served as a list of {@link Endpoint}s: * <pre>{@code * [ * "host1:port1", * "host2:port2", * "host3:port3" * ] * }</pre> * * <p>The JSON array file could be retrieved as an {@link EndpointGroup} using the following code: * <pre>{@code * CentralDogmaEndpointGroup<JsonNode> endpointGroup = CentralDogmaEndpointGroup.of( * centralDogma, "myProject", "myRepo", * Query.ofJson("/endpoints.json"), * EndpointListDecoder.JSON); * endpointGroup.awaitInitialEndpoints(); * endpointGroup.endpoints(); * }</pre> * * @param <T> the type of the file in Central Dogma */ public final class CentralDogmaEndpointGroup<T> extends DynamicEndpointGroup { private static final Logger logger = LoggerFactory.getLogger(CentralDogmaEndpointGroup.class); private final Watcher<T> instanceListWatcher; private final EndpointListDecoder<T> endpointListDecoder; /** * Creates a new {@link CentralDogmaEndpointGroup}. * * @param watcher a {@link Watcher} * @param endpointListDecoder an {@link EndpointListDecoder} */ public static <T> CentralDogmaEndpointGroup<T> ofWatcher(Watcher<T> watcher, EndpointListDecoder<T> endpointListDecoder) { return new CentralDogmaEndpointGroup<>(EndpointSelectionStrategy.weightedRoundRobin(), watcher, endpointListDecoder); } /** * Creates a new {@link CentralDogmaEndpointGroup}. * * @param centralDogma a {@link CentralDogma} * @param projectName a Central Dogma project name * @param repositoryName a Central Dogma repository name * @param query a {@link Query} to route file * @param endpointListDecoder an {@link EndpointListDecoder} */ public static <T> CentralDogmaEndpointGroup<T> of(CentralDogma centralDogma, String projectName, String repositoryName, Query<T> query, EndpointListDecoder<T> endpointListDecoder) { return ofWatcher(centralDogma.forRepo(projectName, repositoryName) .watcher(query) .start(), endpointListDecoder); } /** * Returns a new {@link CentralDogmaEndpointGroupBuilder} with the {@link Watcher} * and {@link EndpointListDecoder}. You can create a {@link Watcher} using {@link CentralDogma}: * * <pre>{@code * CentralDogma centralDogma = ... * Query<T> query = ... // The query to the entry that contains the list of endpoints. * Watcher watcher = centralDogma.fileWatcher(projectName, repositoryName, query); * }</pre> */ public static <T> CentralDogmaEndpointGroupBuilder<T> builder(Watcher<T> watcher, EndpointListDecoder<T> endpointListDecoder) { return new CentralDogmaEndpointGroupBuilder<>(watcher, endpointListDecoder); } CentralDogmaEndpointGroup(EndpointSelectionStrategy strategy, Watcher<T> instanceListWatcher, EndpointListDecoder<T> endpointListDecoder) { super(strategy); this.instanceListWatcher = requireNonNull(instanceListWatcher, "instanceListWatcher"); this.endpointListDecoder = requireNonNull(endpointListDecoder, "endpointListDecoder"); registerWatcher(); } private void registerWatcher() { instanceListWatcher.watch((revision, instances) -> { try { final List<Endpoint> newEndpoints = endpointListDecoder.decode(instances); if (newEndpoints.isEmpty()) { logger.info("Not refreshing the endpoint list of {} because it's empty. {}", instanceListWatcher, revision); return; } setEndpoints(newEndpoints); } catch (Exception e) { logger.warn("Failed to re-retrieve the endpoint list from Central Dogma.", e); } }); instanceListWatcher.initialValueFuture().exceptionally(e -> { logger.warn("Failed to retrieve the initial instance list from Central Dogma.", e); return null; }); } @Override protected void doCloseAsync(CompletableFuture<?> future) { instanceListWatcher.close(); future.complete(null); } }
line/centraldogma
client/java-armeria/src/main/java/com/linecorp/centraldogma/client/armeria/CentralDogmaEndpointGroup.java
Java
apache-2.0
6,111
package fr.javatronic.blog.massive.annotation2; import fr.javatronic.blog.processor.Annotation_002; @Annotation_002 public class Class_177 { }
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation2/Class_177.java
Java
apache-2.0
145
package br.com.siscob.mb; import br.com.siscob.model.Condominio; import br.com.siscob.model.Usuario; import br.com.siscob.neg.BoletoNeg; import br.com.siscob.neg.UsuarioNeg; import br.com.siscob.util.FacesUtil; import static com.sun.corba.se.spi.presentation.rmi.StubAdapter.request; import static com.sun.faces.facelets.util.Path.context; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletResponse; import org.jrimum.bopepo.BancosSuportados; import org.jrimum.bopepo.Boleto; import org.jrimum.bopepo.view.BoletoViewer; import org.jrimum.domkee.comum.pessoa.endereco.CEP; import org.jrimum.domkee.comum.pessoa.endereco.Endereco; import org.jrimum.domkee.financeiro.banco.ParametrosBancariosMap; import org.jrimum.domkee.financeiro.banco.febraban.Agencia; import org.jrimum.domkee.financeiro.banco.febraban.Carteira; import org.jrimum.domkee.financeiro.banco.febraban.Cedente; import org.jrimum.domkee.financeiro.banco.febraban.ContaBancaria; import org.jrimum.domkee.financeiro.banco.febraban.NumeroDaConta; import org.jrimum.domkee.financeiro.banco.febraban.Sacado; import org.jrimum.domkee.financeiro.banco.febraban.Titulo; @ManagedBean @ViewScoped public class DashBoardBean implements Serializable { public DashBoardBean() { try { boletos = new ArrayList(); usuario = FacesUtil.obterUsuarioSessao(); if (usuario.getPermissao().equals("ROLE_USER")) { boletos = boletoNeg.consultar(usuario); usuarioNeg.atualizarUltimoAcesso(usuario); } else { ultimosAcessos = usuarioNeg.consultarUltimosAcessos(); } } catch (Exception ex) { Logger.getLogger(DashBoardBean.class.getName()).log(Level.SEVERE, null, ex); } } public BoletoViewer gerarBoleto() { Condominio condominio = usuario.getCondominio(); Cedente cedente = new Cedente(condominio.getNome(), condominio.getCnpj()); Sacado sacado = new Sacado(usuario.getNome(), usuario.getCpf()); Endereco enderecoSac = new Endereco(); enderecoSac.setUF(condominio.getEndereco().getUf()); enderecoSac.setLocalidade(condominio.getEndereco().getCidade()); enderecoSac.setCep(new CEP(condominio.getEndereco().getCep())); enderecoSac.setBairro(condominio.getEndereco().getBairro()); enderecoSac.setLogradouro(condominio.getEndereco().getLogradouro()); enderecoSac.setNumero(condominio.getEndereco().getNumero()); sacado.addEndereco(enderecoSac); ContaBancaria contaBancaria = new ContaBancaria(boleto.getContaId().getBanco().create()); contaBancaria.setNumeroDaConta(new NumeroDaConta(Integer.valueOf(boleto.getContaId().getConta()), boleto.getContaId().getDigitoCc())); contaBancaria.setCarteira(new Carteira(Integer.valueOf(boleto.getContaId().getCarteira()))); Agencia agencia; if (boleto.getContaId().getDigitoAg().isEmpty()) { agencia = new Agencia(Integer.valueOf(boleto.getContaId().getAgencia())); } else { agencia = new Agencia(boleto.getContaId().getAgencia(), boleto.getContaId().getDigitoAg()); } contaBancaria.setAgencia(agencia); Titulo tituloBopepo = new Titulo(contaBancaria, sacado, cedente); tituloBopepo.setNossoNumero(boleto.getNossoNumero()); tituloBopepo.setValor(BigDecimal.valueOf(boleto.getValor())); tituloBopepo.setDataDoDocumento(boleto.getDataDocumento()); tituloBopepo.setDataDoVencimento(boleto.getDataVencimento()); tituloBopepo.setTipoDeDocumento(boleto.getTipoTitulo()); tituloBopepo.setAceite(boleto.getAceite()); tituloBopepo.setDesconto(BigDecimal.valueOf(boleto.getDesconto())); tituloBopepo.setDeducao(BigDecimal.valueOf(boleto.getDeducao())); tituloBopepo.setMora(BigDecimal.valueOf(boleto.getMora())); tituloBopepo.setAcrecimo(BigDecimal.valueOf(boleto.getAcrescimo())); tituloBopepo.setValorCobrado(BigDecimal.valueOf(boleto.getValorCobrado())); if (boleto.getContaId().getBanco() == BancosSuportados.CAIXA_ECONOMICA_FEDERAL) { tituloBopepo.setParametrosBancarios(new ParametrosBancariosMap("CodigoOperacao", boleto.getContaId().getCodigoOperacao())); } Boleto boletoBopero = new Boleto(tituloBopepo); boletoBopero.setLocalPagamento(boleto.getLocalPagamento()); if (condominio.isResponsabilidadeCedente()) { boletoBopero.setInstrucao1("Responsabilidade do Cedente"); } boletoBopero.setInstrucao2(boleto.getInstrucaoPagamento()); boletoBopero.setInstrucao7(tituloBopepo.getParametrosBancarios().getValor("CodigoOperacao").toString()); boletoBopero.setInstrucao8(tituloBopepo.getParametrosBancarios().getValor("CodigoOperacao").toString()); String caminhoRelatorio = FacesUtil.getServletContext().getRealPath("/relatorios"); String caminhoTemplatePdf = caminhoRelatorio + File.separator + "BoletoTemplateCustom.pdf"; File templatePersonalizado = new File(caminhoTemplatePdf); return new BoletoViewer(boletoBopero, templatePersonalizado); } public String download() { if (boleto == null) { FacesUtil.exibirMensagemAlerta("Atenção", "Selecione um boleto!"); return null; } try { BoletoViewer boletoViewer = gerarBoleto(); byte pdfAsBytes[] = boletoViewer.getPdfAsByteArray(); HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=boleto.pdf"); OutputStream output = response.getOutputStream(); output.write(pdfAsBytes); response.flushBuffer(); FacesContext.getCurrentInstance().responseComplete(); } catch (IOException e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); FacesUtil.exibirMensagemErro("Erro", ex.getMessage()); } return null; } public List getBoletos() { return boletos; } public void setBoletos(List boletos) { this.boletos = boletos; } public br.com.siscob.model.Boleto getBoleto() { return boleto; } public void setBoleto(br.com.siscob.model.Boleto boleto) { this.boleto = boleto; } public List getUltimosAcessos() { return ultimosAcessos; } public void setUltimosAcessos(List ultimosAcessos) { this.ultimosAcessos = ultimosAcessos; } private static final long serialVersionUID = 0x734ceca6bf651b45L; private final BoletoNeg boletoNeg = new BoletoNeg(); private final UsuarioNeg usuarioNeg = new UsuarioNeg(); private List boletos; private br.com.siscob.model.Boleto boleto; private Usuario usuario; private List ultimosAcessos; }
douglas-queiroz/CondominiumWeb
src/java/br/com/siscob/mb/DashBoardBean.java
Java
apache-2.0
7,451
/* * This source file was generated by FireStorm/DAO. * * If you purchase a full license for FireStorm/DAO you can customize this header file. * * For more information please visit http://www.codefutures.com/products/firestorm */ package co.edu.sena.model.dao.dto; import co.edu.sena.controller.dao.*; import co.edu.sena.controller.factory.*; import co.edu.sena.controller.dao.exceptions.*; import java.io.Serializable; import java.util.*; public class TipoInstructor implements Serializable { /** * This attribute maps to the column modalidad in the tipo_instructor table. */ protected String modalidad; /** * This attribute maps to the column estado in the tipo_instructor table. */ protected short estado; /** * Method 'TipoInstructor' * */ public TipoInstructor() { } /** * Method 'getModalidad' * * @return String */ public String getModalidad() { return modalidad; } /** * Method 'setModalidad' * * @param modalidad */ public void setModalidad(String modalidad) { this.modalidad = modalidad; } /** * Method 'getEstado' * * @return short */ public short getEstado() { return estado; } /** * Method 'setEstado' * * @param estado */ public void setEstado(short estado) { this.estado = estado; } /** * Method 'equals' * * @param _other * @return boolean */ public boolean equals(Object _other) { if (_other == null) { return false; } if (_other == this) { return true; } if (!(_other instanceof TipoInstructor)) { return false; } final TipoInstructor _cast = (TipoInstructor) _other; if (modalidad == null ? _cast.modalidad != modalidad : !modalidad.equals( _cast.modalidad )) { return false; } if (estado != _cast.estado) { return false; } return true; } /** * Method 'hashCode' * * @return int */ public int hashCode() { int _hashCode = 0; if (modalidad != null) { _hashCode = 29 * _hashCode + modalidad.hashCode(); } _hashCode = 29 * _hashCode + (int) estado; return _hashCode; } /** * Method 'createPk' * * @return TipoInstructorPk */ public TipoInstructorPk createPk() { return new TipoInstructorPk(modalidad); } /** * Method 'toString' * * @return String */ public String toString() { StringBuffer ret = new StringBuffer(); ret.append( "co.edu.sena.model.dao.dto.TipoInstructor: " ); ret.append( "modalidad=" + modalidad ); ret.append( ", estado=" + estado ); return ret.toString(); } }
SENA-CEET/1349397-Trimestre-4
java/JDBC/daoGenerator/src/main/java/co/edu/sena/model/dao/dto/TipoInstructor.java
Java
apache-2.0
2,538
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.interestrate.bond.definition; import org.apache.commons.lang.ObjectUtils; import com.opengamma.analytics.financial.interestrate.InstrumentDerivative; import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitor; import com.opengamma.analytics.financial.legalentity.LegalEntity; import com.opengamma.financial.convention.yield.YieldConvention; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; import com.opengamma.util.tuple.Pair; import com.opengamma.util.tuple.Pairs; /** * Describes a (Treasury) Bill with settlement date. */ public class BillSecurity implements InstrumentDerivative { /** * The bill currency. */ private final Currency _currency; /** * The bill time to settlement. */ private final double _settlementTime; /** * The bill end or maturity time. */ private final double _endTime; /** * The bill nominal. */ private final double _notional; /** * The yield (to maturity) computation convention. */ private final YieldConvention _yieldConvention; /** * The accrual factor in the bill day count between settlement and maturity. */ private final double _accrualFactor; /** * The bill issuer name. */ private final String _issuerName; /** * The bill issuer. */ private final LegalEntity _issuer; /** * The name of the curve used for the bill cash flows (issuer credit). */ private final String _creditCurveName; /** * The name of the curve used for settlement amount discounting. */ private final String _discountingCurveName; /** * Constructor from all details. The legal entity contains only the issuer name. * * @param currency * The bill currency. * @param settlementTime * The bill time to settlement. * @param endTime * The bill end or maturity time. * @param notional * The bill nominal. * @param yieldConvention * The yield (to maturity) computation convention. * @param accrualFactor * The accrual factor in the bill day count between settlement and maturity. * @param issuer * The bill issuer name. * @param creditCurveName * The name of the curve used for the bill cash flows (issuer credit). * @param discountingCurveName * The name of the curve used for settlement amount discounting. * @deprecated Use the constructor that does not take curve names */ @Deprecated public BillSecurity(final Currency currency, final double settlementTime, final double endTime, final double notional, final YieldConvention yieldConvention, final double accrualFactor, final String issuer, final String creditCurveName, final String discountingCurveName) { this(currency, settlementTime, endTime, notional, yieldConvention, accrualFactor, new LegalEntity(null, issuer, null, null, null), creditCurveName, discountingCurveName); } /** * Constructor from all details. * * @param currency * The bill currency. * @param settlementTime * The bill time to settlement. * @param endTime * The bill end or maturity time. * @param notional * The bill nominal. * @param yieldConvention * The yield (to maturity) computation convention. * @param accrualFactor * The accrual factor in the bill day count between settlement and maturity. * @param issuer * The bill issuer name. * @param creditCurveName * The name of the curve used for the bill cash flows (issuer credit). * @param discountingCurveName * The name of the curve used for settlement amount discounting. * @deprecated Use the constructor that does not take curve names */ @Deprecated public BillSecurity(final Currency currency, final double settlementTime, final double endTime, final double notional, final YieldConvention yieldConvention, final double accrualFactor, final LegalEntity issuer, final String creditCurveName, final String discountingCurveName) { ArgumentChecker.notNull(currency, "Currency"); ArgumentChecker.notNull(yieldConvention, "Yield convention"); ArgumentChecker.notNull(issuer, "Issuer"); ArgumentChecker.notNull(creditCurveName, "Credit curve"); ArgumentChecker.notNull(discountingCurveName, "Discounting curve"); ArgumentChecker.isTrue(notional > 0.0, "Notional should be positive"); ArgumentChecker.isTrue(endTime >= settlementTime, "End time should be after settlement time"); ArgumentChecker.isTrue(settlementTime >= 0, "Settlement time should be positive"); _currency = currency; _endTime = endTime; _settlementTime = settlementTime; _notional = notional; _yieldConvention = yieldConvention; _accrualFactor = accrualFactor; _issuerName = issuer.getShortName(); _issuer = issuer; _creditCurveName = creditCurveName; _discountingCurveName = discountingCurveName; } /** * Constructor from all details. The legal entity contains only the issuer name. * * @param currency * The bill currency. * @param settlementTime * The bill time to settlement. * @param endTime * The bill end or maturity time. * @param notional * The bill nominal. * @param yieldConvention * The yield (to maturity) computation convention. * @param accrualFactor * The accrual factor in the bill day count between settlement and maturity. * @param issuer * The bill issuer name. */ public BillSecurity(final Currency currency, final double settlementTime, final double endTime, final double notional, final YieldConvention yieldConvention, final double accrualFactor, final String issuer) { this(currency, settlementTime, endTime, notional, yieldConvention, accrualFactor, new LegalEntity(null, issuer, null, null, null)); } /** * Constructor from all details. * * @param currency * The bill currency. * @param settlementTime * The bill time to settlement. * @param endTime * The bill end or maturity time. * @param notional * The bill nominal. * @param yieldConvention * The yield (to maturity) computation convention. * @param accrualFactor * The accrual factor in the bill day count between settlement and maturity. * @param issuer * The bill issuer name. */ public BillSecurity(final Currency currency, final double settlementTime, final double endTime, final double notional, final YieldConvention yieldConvention, final double accrualFactor, final LegalEntity issuer) { ArgumentChecker.notNull(currency, "Currency"); ArgumentChecker.notNull(yieldConvention, "Yield convention"); ArgumentChecker.notNull(issuer, "Issuer"); ArgumentChecker.isTrue(notional > 0.0, "Notional should be positive"); ArgumentChecker.isTrue(endTime >= settlementTime, "End time should be after settlement time"); ArgumentChecker.isTrue(settlementTime >= 0, "Settlement time should be positive"); _currency = currency; _endTime = endTime; _settlementTime = settlementTime; _notional = notional; _yieldConvention = yieldConvention; _accrualFactor = accrualFactor; _issuerName = issuer.getShortName(); _issuer = issuer; _creditCurveName = null; _discountingCurveName = null; } /** * Get the bill currency. * * @return The currency. */ public Currency getCurrency() { return _currency; } /** * Gets the bill time to settlement. * * @return The time. */ public double getSettlementTime() { return _settlementTime; } /** * Gets the bill end or maturity time. * * @return The time. */ public double getEndTime() { return _endTime; } /** * Gets the bill notional. * * @return The notional. */ public double getNotional() { return _notional; } /** * Gets the yield (to maturity) computation convention. * * @return The convention. */ public YieldConvention getYieldConvention() { return _yieldConvention; } /** * Gets the accrual factor in the bill day count between settlement and maturity. * * @return The accrual factor. */ public double getAccrualFactor() { return _accrualFactor; } /** * Gets the bill issuer name. * * @return The name. */ public String getIssuer() { return _issuerName; } /** * Gets the issuer. * * @return The issuer */ public LegalEntity getIssuerEntity() { return _issuer; } /** * Gets the bill issuer name and currency. * * @return The name/currency. * @deprecated This information is no longer used in the curve providers. */ @Deprecated public Pair<String, Currency> getIssuerCcy() { return Pairs.of(_issuerName, _currency); } /** * Gets the name of the curve used for settlement amount discounting. * * @return The name. * @deprecated Curve names should no longer be set in {@link InstrumentDerivative}s */ @Deprecated public String getDiscountingCurveName() { if (_discountingCurveName == null) { throw new IllegalStateException("Discounting curve name was not set"); } return _discountingCurveName; } /** * Gets the name of the curve used for the bill cash flows (issuer credit). * * @return The name. * @deprecated Curve names should no longer be set in {@link InstrumentDerivative}s */ @Deprecated public String getCreditCurveName() { if (_creditCurveName == null) { throw new IllegalStateException("Credit curve name was not set"); } return _creditCurveName; } @Override public String toString() { return "Bill " + _issuerName + " " + _currency + ": settle" + _settlementTime + " - maturity " + _endTime + " - notional " + _notional; } @Override public <S, T> T accept(final InstrumentDerivativeVisitor<S, T> visitor, final S data) { ArgumentChecker.notNull(visitor, "visitor"); return visitor.visitBillSecurity(this, data); } @Override public <T> T accept(final InstrumentDerivativeVisitor<?, T> visitor) { ArgumentChecker.notNull(visitor, "visitor"); return visitor.visitBillSecurity(this); } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(_accrualFactor); result = prime * result + (int) (temp ^ temp >>> 32); result = prime * result + (_creditCurveName == null ? 0 : _creditCurveName.hashCode()); result = prime * result + _currency.hashCode(); result = prime * result + (_discountingCurveName == null ? 0 : _discountingCurveName.hashCode()); temp = Double.doubleToLongBits(_endTime); result = prime * result + (int) (temp ^ temp >>> 32); result = prime * result + _issuerName.hashCode(); temp = Double.doubleToLongBits(_notional); result = prime * result + (int) (temp ^ temp >>> 32); temp = Double.doubleToLongBits(_settlementTime); result = prime * result + (int) (temp ^ temp >>> 32); result = prime * result + _yieldConvention.hashCode(); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final BillSecurity other = (BillSecurity) obj; if (Double.doubleToLongBits(_accrualFactor) != Double.doubleToLongBits(other._accrualFactor)) { return false; } if (!ObjectUtils.equals(_creditCurveName, other._creditCurveName)) { return false; } if (!ObjectUtils.equals(_currency, other._currency)) { return false; } if (!ObjectUtils.equals(_discountingCurveName, other._discountingCurveName)) { return false; } if (Double.doubleToLongBits(_endTime) != Double.doubleToLongBits(other._endTime)) { return false; } if (_issuerName == null) { if (other._issuerName != null) { return false; } } else if (!_issuerName.equals(other._issuerName)) { return false; } if (Double.doubleToLongBits(_notional) != Double.doubleToLongBits(other._notional)) { return false; } if (Double.doubleToLongBits(_settlementTime) != Double.doubleToLongBits(other._settlementTime)) { return false; } if (!ObjectUtils.equals(_yieldConvention, other._yieldConvention)) { return false; } return true; } }
McLeodMoores/starling
projects/analytics/src/main/java/com/opengamma/analytics/financial/interestrate/bond/definition/BillSecurity.java
Java
apache-2.0
12,857
package net.ssehub.easy.producer.core.persistence; import java.io.File; import org.junit.Assert; import org.junit.Test; import net.ssehub.easy.basics.modelManagement.ModelInfo; import net.ssehub.easy.basics.modelManagement.ModelManagementException; import net.ssehub.easy.basics.modelManagement.Version; import net.ssehub.easy.basics.progress.ProgressObserver; import net.ssehub.easy.instantiation.core.model.buildlangModel.BuildModel; import net.ssehub.easy.instantiation.core.model.buildlangModel.Script; import net.ssehub.easy.instantiation.core.model.templateModel.Template; import net.ssehub.easy.instantiation.core.model.templateModel.TemplateModel; import net.ssehub.easy.producer.core.AllTests; import net.ssehub.easy.producer.core.persistence.standard.PersistenceConstants; import net.ssehub.easy.varModel.management.VarModel; import net.ssehub.easy.varModel.model.Project; import net.ssehub.easy.varModel.persistency.PersistencyConstants; /** * This test case tests whether the plug-ins work correctly together, i.e. whether there are loaded correctly. * A failing tests does not necessary detect a failure inside the code, instead the manifest files or the activators * are maybe broken. * @author El-Sharkawy * */ public class IntegrationTest extends AbstractEASyTest { /** * Project for testing correct behavior of the {@link net.ssehub.easy.dslCore.ModelUtility}s. * Project will not be modified -> Project can be loaded from the origins folder. */ private static final File TEST_PROJECT_MODELUTILITY = new File(AllTests.TESTDATA_DIR_ORIGINS, "ModelUtilityTestProject"); /** * this test checks whether the {@link net.ssehub.easy.dslCore.ModelUtility}s are loaded correctly. */ @Test public void testModelUtilitiesConfiguredCorrectly() { // Files needed for the tests File easyFolder = new File(TEST_PROJECT_MODELUTILITY, PersistenceConstants.EASY_FILES_DEFAULT); String projectName = TEST_PROJECT_MODELUTILITY.getName(); String fileName = projectName + "_0"; File ivmlFile = new File(easyFolder, fileName + PersistencyConstants.PROJECT_FILE_ENDING); // File commentsFile = new File(easyFolder, fileName + PersistencyConstants.COMMENT_FILE_ENDING); File vilFile = new File(easyFolder, fileName + net.ssehub.easy.instantiation.core.model.PersistencyConstants.SCRIPT_FILE_ENDING); File vtlFile = new File(easyFolder, fileName + net.ssehub.easy.instantiation.core.model.PersistencyConstants.TEMPLATE_FILE_ENDING); Version version = new Version(0); // Precondition: Test that the Infos are NOT available ModelInfo<Project> ivmlInfo = VarModel.INSTANCE.availableModels().getModelInfo(projectName, version, ivmlFile.toURI()); ModelInfo<Script> vilInfo = BuildModel.INSTANCE.availableModels().getModelInfo(projectName, version, vilFile.toURI()); ModelInfo<Template> vtlInfo = TemplateModel.INSTANCE.availableModels().getModelInfo(projectName, version, vtlFile.toURI()); Assert.assertNull(ivmlInfo); Assert.assertNull(vilInfo); Assert.assertNull(vtlInfo); try { VarModel.INSTANCE.locations().addLocation(easyFolder, ProgressObserver.NO_OBSERVER); } catch (ModelManagementException exc) { Assert.fail(exc.getLocalizedMessage()); } try { BuildModel.INSTANCE.locations().addLocation(easyFolder, ProgressObserver.NO_OBSERVER); } catch (ModelManagementException exc) { Assert.fail(exc.getLocalizedMessage()); } try { TemplateModel.INSTANCE.locations().addLocation(easyFolder, ProgressObserver.NO_OBSERVER); } catch (ModelManagementException exc) { Assert.fail(exc.getLocalizedMessage()); } // Postcondition: Test that Infos ARE available ivmlInfo = VarModel.INSTANCE.availableModels().getModelInfo(projectName, version, ivmlFile.toURI()); vilInfo = BuildModel.INSTANCE.availableModels().getModelInfo(projectName, version, vilFile.toURI()); vtlInfo = TemplateModel.INSTANCE.availableModels().getModelInfo(projectName, version, vtlFile.toURI()); Assert.assertNotNull("IVML ModelUtility is not working correctly", ivmlInfo); Assert.assertNotNull("VIL ModelUtility is not working correctly", vilInfo); Assert.assertNotNull("VTL ModelUtility is not working correctly", vtlInfo); } }
SSEHUB/EASyProducer
Plugins/EASy-Producer/EASy.Persistence.test/src/net/ssehub/easy/producer/core/persistence/IntegrationTest.java
Java
apache-2.0
4,559
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.crypto.key; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import javax.crypto.KeyGenerator; import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_CRYPTO_JCEKS_KEY_SERIALFILTER; /** * A provider of secret key material for Hadoop applications. Provides an * abstraction to separate key storage from users of encryption. It * is intended to support getting or storing keys in a variety of ways, * including third party bindings. * <P/> * <code>KeyProvider</code> implementations must be thread safe. */ @InterfaceAudience.Public @InterfaceStability.Unstable public abstract class KeyProvider { public static final String DEFAULT_CIPHER_NAME = CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_DEFAULT_CIPHER_KEY; public static final String DEFAULT_CIPHER = CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_DEFAULT_CIPHER_DEFAULT; public static final String DEFAULT_BITLENGTH_NAME = CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_DEFAULT_BITLENGTH_KEY; public static final int DEFAULT_BITLENGTH = CommonConfigurationKeysPublic. HADOOP_SECURITY_KEY_DEFAULT_BITLENGTH_DEFAULT; public static final String JCEKS_KEY_SERIALFILTER_DEFAULT = "java.lang.Enum;" + "java.security.KeyRep;" + "java.security.KeyRep$Type;" + "javax.crypto.spec.SecretKeySpec;" + "org.apache.hadoop.crypto.key.JavaKeyStoreProvider$KeyMetadata;" + "!*"; public static final String JCEKS_KEY_SERIAL_FILTER = "jceks.key.serialFilter"; private final Configuration conf; /** * The combination of both the key version name and the key material. */ public static class KeyVersion { private final String name; private final String versionName; private final byte[] material; protected KeyVersion(String name, String versionName, byte[] material) { this.name = name == null ? null : name.intern(); this.versionName = versionName == null ? null : versionName.intern(); this.material = material; } public String getName() { return name; } public String getVersionName() { return versionName; } public byte[] getMaterial() { return material; } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("key("); buf.append(versionName); buf.append(")="); if (material == null) { buf.append("null"); } else { for(byte b: material) { buf.append(' '); int right = b & 0xff; if (right < 0x10) { buf.append('0'); } buf.append(Integer.toHexString(right)); } } return buf.toString(); } @Override public boolean equals(Object rhs) { if (this == rhs) { return true; } if (rhs == null || getClass() != rhs.getClass()) { return false; } final KeyVersion kv = (KeyVersion) rhs; return new EqualsBuilder(). append(name, kv.name). append(versionName, kv.versionName). append(material, kv.material). isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(). append(name). append(versionName). append(material). toHashCode(); } } /** * Key metadata that is associated with the key. */ public static class Metadata { private final static String CIPHER_FIELD = "cipher"; private final static String BIT_LENGTH_FIELD = "bitLength"; private final static String CREATED_FIELD = "created"; private final static String DESCRIPTION_FIELD = "description"; private final static String VERSIONS_FIELD = "versions"; private final static String ATTRIBUTES_FIELD = "attributes"; private final String cipher; private final int bitLength; private final String description; private final Date created; private int versions; private Map<String, String> attributes; protected Metadata(String cipher, int bitLength, String description, Map<String, String> attributes, Date created, int versions) { this.cipher = cipher; this.bitLength = bitLength; this.description = description; this.attributes = (attributes == null || attributes.isEmpty()) ? null : attributes; this.created = created; this.versions = versions; } public String toString() { final StringBuilder metaSB = new StringBuilder(); metaSB.append("cipher: ").append(cipher).append(", "); metaSB.append("length: ").append(bitLength).append(", "); metaSB.append("description: ").append(description).append(", "); metaSB.append("created: ").append(created).append(", "); metaSB.append("version: ").append(versions).append(", "); metaSB.append("attributes: "); if ((attributes != null) && !attributes.isEmpty()) { for (Map.Entry<String, String> attribute : attributes.entrySet()) { metaSB.append("["); metaSB.append(attribute.getKey()); metaSB.append("="); metaSB.append(attribute.getValue()); metaSB.append("], "); } metaSB.deleteCharAt(metaSB.length() - 2); // remove last ', ' } else { metaSB.append("null"); } return metaSB.toString(); } public String getDescription() { return description; } public Date getCreated() { return created; } public String getCipher() { return cipher; } public Map<String, String> getAttributes() { return (attributes == null) ? Collections.emptyMap() : attributes; } /** * Get the algorithm from the cipher. * @return the algorithm name */ public String getAlgorithm() { int slash = cipher.indexOf('/'); if (slash == - 1) { return cipher; } else { return cipher.substring(0, slash); } } public int getBitLength() { return bitLength; } public int getVersions() { return versions; } protected int addVersion() { return versions++; } /** * Serialize the metadata to a set of bytes. * @return the serialized bytes * @throws IOException */ protected byte[] serialize() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); JsonWriter writer = new JsonWriter( new OutputStreamWriter(buffer, StandardCharsets.UTF_8)); try { writer.beginObject(); if (cipher != null) { writer.name(CIPHER_FIELD).value(cipher); } if (bitLength != 0) { writer.name(BIT_LENGTH_FIELD).value(bitLength); } if (created != null) { writer.name(CREATED_FIELD).value(created.getTime()); } if (description != null) { writer.name(DESCRIPTION_FIELD).value(description); } if (attributes != null && attributes.size() > 0) { writer.name(ATTRIBUTES_FIELD).beginObject(); for (Map.Entry<String, String> attribute : attributes.entrySet()) { writer.name(attribute.getKey()).value(attribute.getValue()); } writer.endObject(); } writer.name(VERSIONS_FIELD).value(versions); writer.endObject(); writer.flush(); } finally { writer.close(); } return buffer.toByteArray(); } /** * Deserialize a new metadata object from a set of bytes. * @param bytes the serialized metadata * @throws IOException */ protected Metadata(byte[] bytes) throws IOException { String cipher = null; int bitLength = 0; Date created = null; int versions = 0; String description = null; Map<String, String> attributes = null; JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(bytes), StandardCharsets.UTF_8)); try { reader.beginObject(); while (reader.hasNext()) { String field = reader.nextName(); if (CIPHER_FIELD.equals(field)) { cipher = reader.nextString(); } else if (BIT_LENGTH_FIELD.equals(field)) { bitLength = reader.nextInt(); } else if (CREATED_FIELD.equals(field)) { created = new Date(reader.nextLong()); } else if (VERSIONS_FIELD.equals(field)) { versions = reader.nextInt(); } else if (DESCRIPTION_FIELD.equals(field)) { description = reader.nextString(); } else if (ATTRIBUTES_FIELD.equalsIgnoreCase(field)) { reader.beginObject(); attributes = new HashMap<String, String>(); while (reader.hasNext()) { attributes.put(reader.nextName(), reader.nextString()); } reader.endObject(); } } reader.endObject(); } finally { reader.close(); } this.cipher = cipher; this.bitLength = bitLength; this.created = created; this.description = description; this.attributes = attributes; this.versions = versions; } } /** * Options when creating key objects. */ public static class Options { private String cipher; private int bitLength; private String description; private Map<String, String> attributes; public Options(Configuration conf) { cipher = conf.get(DEFAULT_CIPHER_NAME, DEFAULT_CIPHER); bitLength = conf.getInt(DEFAULT_BITLENGTH_NAME, DEFAULT_BITLENGTH); } public Options setCipher(String cipher) { this.cipher = cipher; return this; } public Options setBitLength(int bitLength) { this.bitLength = bitLength; return this; } public Options setDescription(String description) { this.description = description; return this; } public Options setAttributes(Map<String, String> attributes) { if (attributes != null) { if (attributes.containsKey(null)) { throw new IllegalArgumentException("attributes cannot have a NULL key"); } this.attributes = new HashMap<String, String>(attributes); } return this; } public String getCipher() { return cipher; } public int getBitLength() { return bitLength; } public String getDescription() { return description; } public Map<String, String> getAttributes() { return (attributes == null) ? Collections.emptyMap() : attributes; } @Override public String toString() { return "Options{" + "cipher='" + cipher + '\'' + ", bitLength=" + bitLength + ", description='" + description + '\'' + ", attributes=" + attributes + '}'; } } /** * Constructor. * * @param conf configuration for the provider */ public KeyProvider(Configuration conf) { this.conf = new Configuration(conf); // Added for HADOOP-15473. Configured serialFilter property fixes // java.security.UnrecoverableKeyException in JDK 8u171. if(System.getProperty(JCEKS_KEY_SERIAL_FILTER) == null) { String serialFilter = conf.get(HADOOP_SECURITY_CRYPTO_JCEKS_KEY_SERIALFILTER, JCEKS_KEY_SERIALFILTER_DEFAULT); System.setProperty(JCEKS_KEY_SERIAL_FILTER, serialFilter); } } /** * Return the provider configuration. * * @return the provider configuration */ public Configuration getConf() { return conf; } /** * A helper function to create an options object. * @param conf the configuration to use * @return a new options object */ public static Options options(Configuration conf) { return new Options(conf); } /** * Indicates whether this provider represents a store * that is intended for transient use - such as the UserProvider * is. These providers are generally used to provide access to * keying material rather than for long term storage. * @return true if transient, false otherwise */ public boolean isTransient() { return false; } /** * Get the key material for a specific version of the key. This method is used * when decrypting data. * @param versionName the name of a specific version of the key * @return the key material * @throws IOException */ public abstract KeyVersion getKeyVersion(String versionName ) throws IOException; /** * Get the key names for all keys. * @return the list of key names * @throws IOException */ public abstract List<String> getKeys() throws IOException; /** * Get key metadata in bulk. * @param names the names of the keys to get * @throws IOException */ public Metadata[] getKeysMetadata(String... names) throws IOException { Metadata[] result = new Metadata[names.length]; for (int i=0; i < names.length; ++i) { result[i] = getMetadata(names[i]); } return result; } /** * Get the key material for all versions of a specific key name. * @return the list of key material * @throws IOException */ public abstract List<KeyVersion> getKeyVersions(String name) throws IOException; /** * Get the current version of the key, which should be used for encrypting new * data. * @param name the base name of the key * @return the version name of the current version of the key or null if the * key version doesn't exist * @throws IOException */ public KeyVersion getCurrentKey(String name) throws IOException { Metadata meta = getMetadata(name); if (meta == null) { return null; } return getKeyVersion(buildVersionName(name, meta.getVersions() - 1)); } /** * Get metadata about the key. * @param name the basename of the key * @return the key's metadata or null if the key doesn't exist * @throws IOException */ public abstract Metadata getMetadata(String name) throws IOException; /** * Create a new key. The given key must not already exist. * @param name the base name of the key * @param material the key material for the first version of the key. * @param options the options for the new key. * @return the version name of the first version of the key. * @throws IOException */ public abstract KeyVersion createKey(String name, byte[] material, Options options) throws IOException; /** * Get the algorithm from the cipher. * * @return the algorithm name */ private String getAlgorithm(String cipher) { int slash = cipher.indexOf('/'); if (slash == -1) { return cipher; } else { return cipher.substring(0, slash); } } /** * Generates a key material. * * @param size length of the key. * @param algorithm algorithm to use for generating the key. * @return the generated key. * @throws NoSuchAlgorithmException */ protected byte[] generateKey(int size, String algorithm) throws NoSuchAlgorithmException { algorithm = getAlgorithm(algorithm); KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm); keyGenerator.init(size); byte[] key = keyGenerator.generateKey().getEncoded(); return key; } /** * Create a new key generating the material for it. * The given key must not already exist. * <p/> * This implementation generates the key material and calls the * {@link #createKey(String, byte[], Options)} method. * * @param name the base name of the key * @param options the options for the new key. * @return the version name of the first version of the key. * @throws IOException * @throws NoSuchAlgorithmException */ public KeyVersion createKey(String name, Options options) throws NoSuchAlgorithmException, IOException { byte[] material = generateKey(options.getBitLength(), options.getCipher()); return createKey(name, material, options); } /** * Delete the given key. * @param name the name of the key to delete * @throws IOException */ public abstract void deleteKey(String name) throws IOException; /** * Roll a new version of the given key. * @param name the basename of the key * @param material the new key material * @return the name of the new version of the key * @throws IOException */ public abstract KeyVersion rollNewVersion(String name, byte[] material ) throws IOException; /** * Can be used by implementing classes to close any resources * that require closing */ public void close() throws IOException { // NOP } /** * Roll a new version of the given key generating the material for it. * <p/> * This implementation generates the key material and calls the * {@link #rollNewVersion(String, byte[])} method. * * @param name the basename of the key * @return the name of the new version of the key * @throws IOException */ public KeyVersion rollNewVersion(String name) throws NoSuchAlgorithmException, IOException { Metadata meta = getMetadata(name); if (meta == null) { throw new IOException("Can't find Metadata for key " + name); } byte[] material = generateKey(meta.getBitLength(), meta.getCipher()); return rollNewVersion(name, material); } /** * Can be used by implementing classes to invalidate the caches. This could be * used after rollNewVersion to provide a strong guarantee to return the new * version of the given key. * * @param name the basename of the key * @throws IOException */ public void invalidateCache(String name) throws IOException { // NOP } /** * Ensures that any changes to the keys are written to persistent store. * @throws IOException */ public abstract void flush() throws IOException; /** * Split the versionName in to a base name. Converts "/aaa/bbb/3" to * "/aaa/bbb". * @param versionName the version name to split * @return the base name of the key * @throws IOException */ public static String getBaseName(String versionName) throws IOException { int div = versionName.lastIndexOf('@'); if (div == -1) { throw new IOException("No version in key path " + versionName); } return versionName.substring(0, div); } /** * Build a version string from a basename and version number. Converts * "/aaa/bbb" and 3 to "/aaa/bbb@3". * @param name the basename of the key * @param version the version of the key * @return the versionName of the key. */ protected static String buildVersionName(String name, int version) { return name + "@" + version; } /** * Find the provider with the given key. * @param providerList the list of providers * @param keyName the key name we are looking for * @return the KeyProvider that has the key */ public static KeyProvider findProvider(List<KeyProvider> providerList, String keyName) throws IOException { for(KeyProvider provider: providerList) { if (provider.getMetadata(keyName) != null) { return provider; } } throw new IOException("Can't find KeyProvider for key " + keyName); } /** * Does this provider require a password? This means that a password is * required for normal operation, and it has not been found through normal * means. If true, the password should be provided by the caller using * setPassword(). * @return Whether or not the provider requires a password * @throws IOException */ public boolean needsPassword() throws IOException { return false; } /** * If a password for the provider is needed, but is not provided, this will * return a warning and instructions for supplying said password to the * provider. * @return A warning and instructions for supplying the password */ public String noPasswordWarning() { return null; } /** * If a password for the provider is needed, but is not provided, this will * return an error message and instructions for supplying said password to * the provider. * @return An error message and instructions for supplying the password */ public String noPasswordError() { return null; } }
szegedim/hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/crypto/key/KeyProvider.java
Java
apache-2.0
22,201
package hello; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.net.URL; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HelloControllerIT { @LocalServerPort private int port; private URL base; @Autowired private TestRestTemplate template; @Before public void setUp() throws Exception { this.base = new URL("http://localhost:" + port + "/"); } @Test public void getHello() throws Exception { ResponseEntity<String> response = template.getForEntity(base.toString(), String.class); assertThat(response.getBody(), equalTo("Greetings from Spring Boot!")); } }
bazelbuild/rules_jvm_external
examples/spring_boot/src/test/java/hello/HelloControllerIT.java
Java
apache-2.0
1,153
/** * */ package com.juxtapose.example.ch11.partition; import java.io.Serializable; /** * * @author bruce.liu(mailto:jxta.liu@gmail.com) * 2014-1-11下午02:37:55 */ public class DestinationCreditBill implements Serializable{ /** * */ private static final long serialVersionUID = 5253572139260172440L; private String id; private String accountID = ""; /** 银行卡账户ID */ private String name = ""; /** 持卡人姓名 */ private double amount = 0; /** 消费金额 */ private String date; /** 消费日期 ,格式YYYY-MM-DD HH:MM:SS*/ private String address; /** 消费场所 **/ public DestinationCreditBill(){} public DestinationCreditBill(String accountID, String name, double amount, String date, String address){ this.accountID = accountID; this.name = name; this.amount = amount; this.date = date; this.address = address; } public String getAccountID() { return accountID; } public void setAccountID(String accountID) { this.accountID = accountID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getId() { return id; } public void setId(String id) { this.id = id; } /** * */ public String toString(){ StringBuffer sb = new StringBuffer(); sb.append("accountID=" + getAccountID() + ";name=" + getName() + ";amount=" + getAmount() + ";date=" + getDate() + ";address=" + getAddress()); return sb.toString(); } }
lihongjie/spring-tutorial
SpringBatchSample/spring-batch-example/src/main/java/com/juxtapose/example/ch11/partition/DestinationCreditBill.java
Java
apache-2.0
1,905
/* * Copyright 2012 Will Benedict, Felix Berger and Roger Kapsi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ardverk.gibson; import java.util.HashMap; import java.util.Map; import org.mongodb.morphia.converters.SimpleValueConverter; import org.mongodb.morphia.converters.TypeConverter; import org.mongodb.morphia.mapping.MappedField; import org.mongodb.morphia.mapping.MappingException; /** * This is a JSON serializer for {@link StackTraceElement}s. */ class StackTraceElementConverter extends TypeConverter implements SimpleValueConverter { public StackTraceElementConverter() { super(StackTraceElement.class); } @Override protected boolean isSupported(Class<?> clazz, MappedField extra) { return clazz.isAssignableFrom(StackTraceElement.class); } @Override public Object decode(@SuppressWarnings("rawtypes") Class type, Object value, MappedField extra) throws MappingException { if (value == null) { return null; } @SuppressWarnings("unchecked") Map<String, ?> map = (Map<String, ?>)value; String clazz = (String)map.get("class"); String method = (String)map.get("method"); String file = (String)map.get("file"); int line = (Integer)map.get("line"); return new StackTraceElement(clazz, method, file, line); } @Override public Object encode(Object value, MappedField extra) { if (value == null) { return null; } StackTraceElement element = (StackTraceElement)value; Map<String, Object> map = new HashMap<String, Object>(4, 1.0f); map.put("class", element.getClassName()); map.put("method", element.getMethodName()); map.put("file", element.getFileName()); map.put("line", element.getLineNumber()); return map; } }
rkapsi/gibson
gibson-core/src/main/java/org/ardverk/gibson/StackTraceElementConverter.java
Java
apache-2.0
2,301
/* * Copyright 2014 WANdisco * * WANdisco licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package c5db.webadmin; import c5db.interfaces.C5Module; import c5db.interfaces.C5Server; import c5db.interfaces.DiscoveryModule; import c5db.interfaces.TabletModule; import c5db.interfaces.discovery.NodeInfo; import c5db.interfaces.tablet.Tablet; import c5db.messages.generated.ModuleType; import com.github.mustachejava.Mustache; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.ListenableFuture; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; /** * Handles the base page display */ @WebServlet(urlPatterns = {"/"}) public class StatusServlet extends HttpServlet { private WebAdminService service; public StatusServlet(WebAdminService service) { this.service = service; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); Mustache template = service.getMustacheFactory().compile("templates/index.mustache"); Writer writer = response.getWriter(); // Collect server status objects from around this place. ImmutableMap<ModuleType, C5Module> modules = service.getServer().getModules(); ImmutableMap<Long, NodeInfo> nodes = getNodes(); Collection<Tablet> tablets = getTablets(); TopLevelHolder templateContext = new TopLevelHolder(service.getServer(), modules, nodes, tablets); template.execute(writer, templateContext); writer.flush(); } catch (ExecutionException | InterruptedException | TimeoutException e) { throw new IOException("Getting status", e); } } private Collection<Tablet> getTablets() throws ExecutionException, InterruptedException { TabletModule tabletModule = service.getTabletModule(); if (tabletModule == null) { return null; } return tabletModule.getTablets(); } private ImmutableMap<Long, NodeInfo> getNodes() throws InterruptedException, ExecutionException { DiscoveryModule discoveryModule = service.getDiscoveryModule(); if (discoveryModule == null) { return null; } ListenableFuture<ImmutableMap<Long, NodeInfo>> nodeFuture = discoveryModule.getState(); return nodeFuture.get(); } private static class TopLevelHolder { public final C5Server server; private final Map<ModuleType, C5Module> modules; private final ImmutableMap<Long, NodeInfo> nodes; public final Collection<Tablet> tablets; private TopLevelHolder(C5Server server, ImmutableMap<ModuleType, C5Module> modules, ImmutableMap<Long, NodeInfo> nodes, Collection<Tablet> tablets) { this.server = server; this.modules = modules; this.nodes = nodes; this.tablets = tablets; } public Collection<Map.Entry<ModuleType, C5Module>> getModules() { if (modules == null) { return null; } return modules.entrySet(); } public Collection<NodeInfo> getNodes() { if (nodes == null) { return null; } return nodes.values(); } } }
cloud-software-foundation/c5
c5db/src/main/java/c5db/webadmin/StatusServlet.java
Java
apache-2.0
4,145
package com.diamondq.common.jaxrs.model; import java.util.Collections; import java.util.Map; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AbstractConstructorJAXRSApplicationInfo implements JAXRSApplicationInfo { private static final Logger sLogger = LoggerFactory.getLogger(AbstractConstructorJAXRSApplicationInfo.class); private final Set<Class<?>> mClasses; private final Set<Object> mSingletons; private final Map<String, Object> mProperties; public AbstractConstructorJAXRSApplicationInfo(@Nullable Set<Class<?>> pClasses, @Nullable Set<Object> pSingletons, @Nullable Map<String, Object> pProperties) { mClasses = (pClasses != null ? pClasses : Collections.emptySet()); mSingletons = (pSingletons != null ? pSingletons : Collections.emptySet()); mProperties = (pProperties != null ? pProperties : Collections.emptyMap()); } /** * @see com.diamondq.common.jaxrs.model.JAXRSApplicationInfo#getClasses() */ @Override public Set<Class<?>> getClasses() { sLogger.trace("getClasses() from {}", this); return mClasses; } /** * @see com.diamondq.common.jaxrs.model.JAXRSApplicationInfo#getSingletons() */ @Override public Set<Object> getSingletons() { sLogger.trace("getSingletons() from {}", this); return mSingletons; } /** * @see com.diamondq.common.jaxrs.model.JAXRSApplicationInfo#getProperties() */ @Override public Map<String, Object> getProperties() { sLogger.trace("getProperties() from {}", this); return mProperties; } }
diamondq/dq-common-java
jaxrs/common-jaxrs.common/src/main/java/com/diamondq/common/jaxrs/model/AbstractConstructorJAXRSApplicationInfo.java
Java
apache-2.0
1,714
package com.fpt.mic.mobile.checker.app.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.Window; import com.fpt.mic.mobile.checker.app.R; import com.fpt.mic.mobile.checker.app.business.ApiBusiness; import com.fpt.mic.mobile.checker.app.utils.DialogUtils; import com.fpt.mic.mobile.checker.app.utils.Settings; public class SplashScreen extends Activity { final int CHECK_TIMEOUT = 1000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_splash_screen); Runnable runnable = new Runnable() { @Override public void run() { startCheck(); } }; (new Handler()).postDelayed(runnable, 1000); } void startCheck() { Runnable checkInternetRunnable = new Runnable() { @Override public void run() { final Runnable self = this; ApiBusiness apiBusiness = new ApiBusiness(); apiBusiness.checkConnection(new ApiBusiness.IOnConnectionResult() { @Override public void onConnectionResult(boolean result) { if (result) { openMainActivity(); } else { DialogUtils.showAlert(SplashScreen.this, getApplicationContext().getText(R.string.noConnection).toString(), new DialogUtils.IOnOkClicked() { @Override public void onClick() { // Try again (new Handler()).postDelayed(self, CHECK_TIMEOUT); } }, new DialogUtils.IOnCancelClicked() { @Override public void onClick() { finish(); } }, new DialogUtils.IOnNeutralClicked() { @Override public void onClick() { setCustomServerIp(new IServerSetUpDone() { @Override public void onServerSetUp() { // Try again with new set up (new Handler()).postDelayed(self, CHECK_TIMEOUT); } }); } }); } } }); } }; (new Handler()).postDelayed(checkInternetRunnable, CHECK_TIMEOUT); } private void setCustomServerIp(final IServerSetUpDone cb) { DialogUtils.showInputBox(this, "Cài đặt", Settings.getServerIp(), "Vui lòng nhập địa chỉ IP của server", new DialogUtils.IOnTextInput() { @Override public void onInput(String text) { Settings.setServerIp(text); cb.onServerSetUp(); } }); } void openMainActivity() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } @Override public void onBackPressed() { // Prevent exit app in splash screen // super.onBackPressed(); } public interface IServerSetUpDone { void onServerSetUp(); } }
trungdq88/insurance-card
Source code/CheckerMobileApp/app/src/main/java/com/fpt/mic/mobile/checker/app/activity/SplashScreen.java
Java
apache-2.0
4,045
package org.deeplearning4j.earlystopping.saver; import org.deeplearning4j.earlystopping.EarlyStoppingModelSaver; import org.deeplearning4j.nn.api.Model; import java.io.IOException; /** Save the best (and latest) models for early stopping training to memory for later retrieval * <b>Note</b>: Assumes that network is cloneable via .clone() method * @param <T> Type of model. For example, {@link org.deeplearning4j.nn.multilayer.MultiLayerNetwork} or {@link org.deeplearning4j.nn.graph.ComputationGraph} */ public class InMemoryModelSaver<T extends Model> implements EarlyStoppingModelSaver<T> { private transient T bestModel; private transient T latestModel; @Override @SuppressWarnings("unchecked") public void saveBestModel(T net, double score) throws IOException { try{ //Necessary because close is protected :S bestModel = (T)(net.getClass().getDeclaredMethod("clone")).invoke(net); }catch(Exception e){ throw new RuntimeException(e); } } @Override @SuppressWarnings("unchecked") public void saveLatestModel(T net, double score) throws IOException { try{ //Necessary because close is protected :S latestModel = (T)(net.getClass().getDeclaredMethod("clone")).invoke(net); }catch(Exception e){ throw new RuntimeException(e); } } @Override public T getBestModel() throws IOException { return bestModel; } @Override public T getLatestModel() throws IOException { return latestModel; } @Override public String toString(){ return "InMemoryModelSaver()"; } }
xuzhongxing/deeplearning4j
deeplearning4j-nn/src/main/java/org/deeplearning4j/earlystopping/saver/InMemoryModelSaver.java
Java
apache-2.0
1,687
/* * Copyright 2004-2008 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package jp.sys_link.action; import org.seasar.struts.annotation.Execute; public class IndexAction { @Execute(validator = false) public String index() { return "index.jsp"; } }
systemlink/link_board
src/main/java/jp/sys_link/action/IndexAction.java
Java
apache-2.0
820
/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.simulator.test; import com.hazelcast.config.Config; import com.hazelcast.config.XmlConfigBuilder; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.simulator.probes.probes.ProbesConfiguration; import com.hazelcast.simulator.worker.TestContainer; import org.apache.log4j.Logger; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Map; import java.util.UUID; import static com.hazelcast.simulator.utils.CommonUtils.closeQuietly; import static com.hazelcast.simulator.utils.CommonUtils.sleepSeconds; import static com.hazelcast.simulator.utils.PropertyBindingSupport.bindProperties; import static java.lang.String.format; /** * A utility class to run a test locally. * * This is purely meant for developing purposes, e.g. when you are writing a test and you want to see quickly if it works at all * without needing to deploy it through an agent on a worker. * * @param <E> class of the test */ public class TestRunner<E> { private static final Logger LOGGER = Logger.getLogger(TestRunner.class); private final StopThread stopThread = new StopThread(); private final TestContextImpl testContext = new TestContextImpl(); private final TestContainer testInvoker; private final E test; private int durationSeconds = 60; private HazelcastInstance hazelcastInstance; public TestRunner(E test) { this(test, null); } public TestRunner(E test, Map<String, String> properties) { if (test == null) { throw new NullPointerException("test can't be null"); } TestCase testCase = null; if (properties != null) { testCase = new TestCase("TestRunner", properties); bindProperties(test, testCase, null); } this.testInvoker = new TestContainer<TestContext>(test, testContext, new ProbesConfiguration(), testCase); this.test = test; } public E getTest() { return test; } public long getDurationSeconds() { return durationSeconds; } public HazelcastInstance getHazelcastInstance() { return hazelcastInstance; } public TestRunner withHazelcastInstance(HazelcastInstance hz) { if (hz == null) { throw new NullPointerException("hz can't be null"); } this.hazelcastInstance = hz; return this; } public TestRunner withHazelcastConfigFile(File file) throws IOException { if (file == null) { throw new NullPointerException("file can't be null"); } if (!file.exists()) { throw new IllegalArgumentException(format("file [%s] doesn't exist", file.getAbsolutePath())); } FileInputStream inputStream = new FileInputStream(file); try { Config config = new XmlConfigBuilder(inputStream).build(); hazelcastInstance = Hazelcast.newHazelcastInstance(config); } finally { closeQuietly(inputStream); } return this; } public TestRunner withHazelcastConfig(Config config) { if (config == null) { throw new NullPointerException("config can't be null"); } hazelcastInstance = Hazelcast.newHazelcastInstance(config); return this; } public TestRunner withDuration(int durationSeconds) { if (durationSeconds < 0) { throw new IllegalArgumentException("Duration can't be smaller than 0"); } this.durationSeconds = durationSeconds; return this; } public void run() throws Exception { try { if (hazelcastInstance == null) { hazelcastInstance = Hazelcast.newHazelcastInstance(); } runPhase(TestPhase.SETUP); runPhase(TestPhase.LOCAL_WARMUP); runPhase(TestPhase.GLOBAL_WARMUP); LOGGER.info("Starting run"); stopThread.start(); testInvoker.invoke(TestPhase.RUN); LOGGER.info("Finished run"); runPhase(TestPhase.GLOBAL_VERIFY); runPhase(TestPhase.LOCAL_VERIFY); runPhase(TestPhase.GLOBAL_TEARDOWN); runPhase(TestPhase.LOCAL_TEARDOWN); } finally { LOGGER.info("Shutdown..."); if (hazelcastInstance != null) { hazelcastInstance.shutdown(); } stopThread.interrupt(); stopThread.join(); LOGGER.info("Finished"); } } private void runPhase(TestPhase testPhase) throws Exception { LOGGER.info("Starting " + testPhase.name); testInvoker.invoke(testPhase); LOGGER.info("Finished " + testPhase.name); } private final class StopThread extends Thread { @Override public void run() { testContext.stopped = false; int period = 5; int sleepInterval = durationSeconds / period; for (int i = 1; i <= sleepInterval; i++) { sleepSeconds(period); int elapsed = i * period; float percentage = elapsed * 100f / durationSeconds; LOGGER.info(format("Running %d of %d seconds %-4.2f percent complete", elapsed, durationSeconds, percentage)); } sleepSeconds(durationSeconds % period); testContext.stopped = true; LOGGER.info("Notified test to stop"); } } private final class TestContextImpl implements TestContext { private final String testId = UUID.randomUUID().toString(); private volatile boolean stopped; @Override public HazelcastInstance getTargetInstance() { return hazelcastInstance; } @Override public String getTestId() { return testId; } @Override public boolean isStopped() { return stopped; } @Override public void stop() { stopped = true; } } }
eminn/hazelcast-simulator
simulator/src/main/java/com/hazelcast/simulator/test/TestRunner.java
Java
apache-2.0
6,749
/** * (C) 2013-2015 Stephan Rauh http://www.beyondjava.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.beyondjava.angularFaces.components.puiSync; import de.beyondjava.angularFaces.core.ELTools; import de.beyondjava.angularFaces.core.transformation.AttributeUtilities; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.FacesException; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.render.FacesRenderer; import javax.faces.render.Renderer; @FacesRenderer(componentFamily = "de.beyondjava", rendererType = "de.beyondjava.sync") public class PuiSyncRenderer extends Renderer implements Serializable { private static final long serialVersionUID = 1L; private static final Logger LOGGER = Logger.getLogger("de.beyondjava.angularFaces.PuiSync.PuiSyncRenderer"); @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { String direction = AttributeUtilities.getAttributeAsString(component, "direction"); if ("serverToClient".equalsIgnoreCase(direction)) return; ResponseWriter writer = context.getResponseWriter(); String clientId = component.getClientId(context); writer.startElement("input", component); writer.writeAttribute("id", clientId, null); writer.writeAttribute("name", clientId, null); writer.writeAttribute("type", "hidden", null); String value = AttributeUtilities.getAttributeAsString(component, "value"); if (null == value) { LOGGER.severe("Which value do you want to synchronize?"); throw new FacesException("ngSync: Which value do you want to synchronize?"); } writer.writeAttribute("value", "{{"+value+"|json}}", null); String styleClass = AttributeUtilities.getAttributeAsString(component, "styleClass"); if (null == styleClass) writer.writeAttribute("class", "puisync", "class"); else writer.writeAttribute("class", "puisync " + styleClass, "class"); writer.endElement("input"); } @Override public void decode(FacesContext context, UIComponent component) { String direction = AttributeUtilities.getAttributeAsString(component, "direction"); if ("serverToClient".equalsIgnoreCase(direction)) return; String rootProperty = AttributeUtilities.getAttributeAsString(component, "value"); Map<String, String> parameterMap = context.getExternalContext().getRequestParameterMap(); String json = parameterMap.get(component.getClientId()); Object bean = ELTools.evalAsObject("#{" + rootProperty + "}"); try { Object fromJson = JSONUtilities.readObjectFromJSONString(json, bean.getClass()); if (null == fromJson) { LOGGER.severe("Couldn't convert the JSON object sent from the client to a JSF bean:"); LOGGER.severe("Class of the bean: " + bean.getClass().getName()); LOGGER.severe("JSON: " + json); } else if (rootProperty.contains(".")) { String rootBean = rootProperty.substring(0, rootProperty.lastIndexOf(".")); injectJsonIntoBean(rootBean, rootProperty, bean, fromJson); } else { Method[] methods = fromJson.getClass().getMethods(); for (Method m : methods) { if (m.getName().startsWith("get") && (m.getParameterTypes() != null || m.getParameterTypes().length == 0)) { try { Method setter = bean.getClass().getMethod("s" + m.getName().substring(1), m.getReturnType()); Object attr = m.invoke(fromJson); setter.invoke(bean, attr); } catch (NoSuchMethodException noError) { // most likely this is not an error // LOGGER.log(Level.INFO, "An error occured when trying to inject the JSON object into the JSF bean", noError); } } else if (m.getName().startsWith("is") && (m.getParameterTypes() != null || m.getParameterTypes().length == 0)) { try { Method setter = bean.getClass().getMethod("set" + m.getName().substring(2), m.getReturnType()); Object attr = m.invoke(fromJson); setter.invoke(bean, attr); } catch (NoSuchMethodException noError) { // most likely this is not an error // LOGGER.log(Level.INFO, "An error occured when trying to inject the JSON object into the JSF bean", noError); } } } } } catch (NumberFormatException error) { LOGGER.log(Level.SEVERE, "A number was expected, but something else was sent (" + rootProperty + ")", error); FacesContext.getCurrentInstance().addMessage( null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "A number was expected, but something else was sent (" + rootProperty + ")", "A number was expected, but something else was sent (" + rootProperty + ")")); } catch (IllegalArgumentException error) { LOGGER.log(Level.SEVERE, "Can't parse the data sent from the client (" + rootProperty + ")", error); FacesContext.getCurrentInstance().addMessage( null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Can't parse the data sent from the client (" + rootProperty + ")", "Can't parse the data sent from the client (" + rootProperty + ")")); } catch (Exception anyError) { LOGGER.log(Level.SEVERE, "A technical error occured when trying to read the data sent from the client (" + rootProperty + ")", anyError); FacesContext.getCurrentInstance().addMessage( null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "A technical error occured when trying to read the data sent from the client (" + rootProperty + ")", "A technical error occured when trying to read the data sent from the client (" + rootProperty + ")")); } } private void injectJsonIntoBean(String rootBean, String rootProperty, Object bean, Object fromJson) { Object root = ELTools.evalAsObject("#{" + rootBean + "}"); String nestedBeanName = rootProperty.substring(rootProperty.lastIndexOf('.') + 1); String setterName = "set" + nestedBeanName.substring(0, 1).toUpperCase() + nestedBeanName.substring(1); try { if (root != null) { Method setter = root.getClass().getDeclaredMethod(setterName, bean.getClass()); setter.invoke(root, fromJson); } } catch (ReflectiveOperationException e) { LOGGER.severe("Couln't find setter method: " + setterName); e.printStackTrace(); } } }
stephanrauh/AngularFaces
AngularFaces_2.0/AngularFaces-core/src/main/java/de/beyondjava/angularFaces/components/puiSync/PuiSyncRenderer.java
Java
apache-2.0
6,925
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2020 the original author or authors. */ package org.assertj.core.api.doublearray; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.test.AlwaysEqualComparator.alwaysEqual; import java.util.Comparator; import org.assertj.core.api.DoubleArrayAssert; import org.assertj.core.api.DoubleArrayAssertBaseTest; import org.assertj.core.internal.Objects; import org.junit.jupiter.api.BeforeEach; /** * Tests for <code>{@link DoubleArrayAssert#usingElementComparator(Comparator)}</code>. * * @author Joel Costigliola * @author Mikhail Mazursky */ class DoubleArrayAssert_usingElementComparator_Test extends DoubleArrayAssertBaseTest { private Comparator<Double> comparator = alwaysEqual(); private Objects objectsBefore; @BeforeEach void before() { objectsBefore = getObjects(assertions); } @Override protected DoubleArrayAssert invoke_api_method() { // in that test, the comparator type is not important, we only check that we correctly switch of comparator return assertions.usingElementComparator(comparator); } @Override protected void verify_internal_effects() { assertThat(getObjects(assertions)).isSameAs(objectsBefore); assertThat(getArrays(assertions).getComparator()).isSameAs(comparator); } }
joel-costigliola/assertj-core
src/test/java/org/assertj/core/api/doublearray/DoubleArrayAssert_usingElementComparator_Test.java
Java
apache-2.0
1,855
package com.qihaosou.loading; import android.app.Activity; import android.content.Context; import android.support.v4.app.Fragment; import android.view.View; import android.view.ViewGroup; import com.qihaosou.util.L; /** * Created by zhy on 15/8/27. */ public class LoadingAndRetryManager { public static final int NO_LAYOUT_ID = 0; public static int BASE_LOADING_LAYOUT_ID = NO_LAYOUT_ID; public static int BASE_RETRY_LAYOUT_ID = NO_LAYOUT_ID; public static int BASE_EMPTY_LAYOUT_ID = NO_LAYOUT_ID; public LoadingAndRetryLayout mLoadingAndRetryLayout; public OnLoadingAndRetryListener DEFAULT_LISTENER = new OnLoadingAndRetryListener() { @Override public void setRetryEvent(View retryView) { } }; public LoadingAndRetryManager(Object activityOrFragmentOrView, OnLoadingAndRetryListener listener) { if (listener == null) listener = DEFAULT_LISTENER; ViewGroup contentParent = null; Context context; if (activityOrFragmentOrView instanceof Activity) { Activity activity = (Activity) activityOrFragmentOrView; context = activity; contentParent = (ViewGroup) activity.findViewById(android.R.id.content); } else if (activityOrFragmentOrView instanceof Fragment) { Fragment fragment = (Fragment) activityOrFragmentOrView; context = fragment.getActivity(); contentParent = (ViewGroup) (fragment.getView().getParent()); } else if (activityOrFragmentOrView instanceof View) { View view = (View) activityOrFragmentOrView; contentParent = (ViewGroup) (view.getParent()); L.e("......................."+contentParent); context = view.getContext(); } else { throw new IllegalArgumentException("the argument's type must be Fragment or Activity: init(context)"); } int childCount = contentParent.getChildCount(); //get contentParent int index = 0; View oldContent; if (activityOrFragmentOrView instanceof View) { oldContent = (View) activityOrFragmentOrView; for (int i = 0; i < childCount; i++) { if (contentParent.getChildAt(i) == oldContent) { index = i; break; } } } else { oldContent = contentParent.getChildAt(0); } contentParent.removeView(oldContent); //setup content layout LoadingAndRetryLayout loadingAndRetryLayout = new LoadingAndRetryLayout(context); ViewGroup.LayoutParams lp = oldContent.getLayoutParams(); contentParent.addView(loadingAndRetryLayout, index, lp); loadingAndRetryLayout.setContentView(oldContent); // setup loading,retry,empty layout setupLoadingLayout(listener, loadingAndRetryLayout); setupRetryLayout(listener, loadingAndRetryLayout); setupEmptyLayout(listener, loadingAndRetryLayout); //callback listener.setRetryEvent(loadingAndRetryLayout.getRetryView()); listener.setLoadingEvent(loadingAndRetryLayout.getLoadingView()); listener.setEmptyEvent(loadingAndRetryLayout.getEmptyView()); mLoadingAndRetryLayout = loadingAndRetryLayout; } private void setupEmptyLayout(OnLoadingAndRetryListener listener, LoadingAndRetryLayout loadingAndRetryLayout) { if (listener.isSetEmptyLayout()) { int layoutId = listener.generateEmptyLayoutId(); if (layoutId != NO_LAYOUT_ID) { loadingAndRetryLayout.setEmptyView(layoutId); } else { loadingAndRetryLayout.setEmptyView(listener.generateEmptyLayout()); } } else { if (BASE_EMPTY_LAYOUT_ID != NO_LAYOUT_ID) loadingAndRetryLayout.setEmptyView(BASE_EMPTY_LAYOUT_ID); } } private void setupLoadingLayout(OnLoadingAndRetryListener listener, LoadingAndRetryLayout loadingAndRetryLayout) { if (listener.isSetLoadingLayout()) { int layoutId = listener.generateLoadingLayoutId(); if (layoutId != NO_LAYOUT_ID) { loadingAndRetryLayout.setLoadingView(layoutId); } else { loadingAndRetryLayout.setLoadingView(listener.generateLoadingLayout()); } } else { if (BASE_LOADING_LAYOUT_ID != NO_LAYOUT_ID) loadingAndRetryLayout.setLoadingView(BASE_LOADING_LAYOUT_ID); } } private void setupRetryLayout(OnLoadingAndRetryListener listener, LoadingAndRetryLayout loadingAndRetryLayout) { if (listener.isSetRetryLayout()) { int layoutId = listener.generateRetryLayoutId(); if (layoutId != NO_LAYOUT_ID) { loadingAndRetryLayout.setLoadingView(layoutId); } else { loadingAndRetryLayout.setLoadingView(listener.generateRetryLayout()); } } else { if (BASE_RETRY_LAYOUT_ID != NO_LAYOUT_ID) loadingAndRetryLayout.setRetryView(BASE_RETRY_LAYOUT_ID); } } public static LoadingAndRetryManager generate(Object activityOrFragment, OnLoadingAndRetryListener listener) { return new LoadingAndRetryManager(activityOrFragment, listener); } public void showLoading() { mLoadingAndRetryLayout.showLoading(); } public void showRetry() { mLoadingAndRetryLayout.showRetry(); } public void showContent() { mLoadingAndRetryLayout.showContent(); } public void showEmpty() { mLoadingAndRetryLayout.showEmpty(); } }
duwenjun199081/qihaosou
app/src/main/java/com/qihaosou/loading/LoadingAndRetryManager.java
Java
apache-2.0
5,944
package com.shareyourproxy.api.rx; import rx.Single; /** * Created by Evan on 12/7/15. */ public class JustSingle implements Single.OnSubscribe { @Override public void call(Object o) { } }
ProxyApp/Proxy
Application/src/main/java/com/shareyourproxy/api/rx/JustSingle.java
Java
apache-2.0
206
/* * Copyright 2016 Davide Maestroni * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.dm.jrt.operator; import com.github.dm.jrt.core.JRoutineCore; import com.github.dm.jrt.core.invocation.InvocationFactory; import com.github.dm.jrt.core.runner.Runners; import com.github.dm.jrt.function.BiFunction; import com.github.dm.jrt.function.Supplier; import org.junit.Test; import static com.github.dm.jrt.function.Functions.first; import static com.github.dm.jrt.operator.AccumulateFunctionInvocation.functionFactory; import static org.assertj.core.api.Assertions.assertThat; /** * Accumulate invocation unit tests. * <p> * Created by davide-maestroni on 10/27/2015. */ public class AccumulateFunctionInvocationTest { private static BiFunction<String, String, String> createFunction() { return new BiFunction<String, String, String>() { public String apply(final String s1, final String s2) { return s1 + s2; } }; } @Test public void testFactory() { final BiFunction<String, String, String> function = createFunction(); assertThat(JRoutineCore.with(functionFactory(function)) .applyInvocationConfiguration() .withRunner(Runners.syncRunner()) .configured() .call("test1", "test2", "test3") .next()).isEqualTo("test1test2test3"); assertThat(JRoutineCore.with(functionFactory(new Supplier<String>() { public String get() { return "test0"; } }, function)) .applyInvocationConfiguration() .withRunner(Runners.syncRunner()) .configured() .call("test1", "test2", "test3") .next()).isEqualTo("test0test1test2test3"); } @Test public void testFactoryEquals() { final BiFunction<String, String, String> function = createFunction(); final InvocationFactory<String, String> factory = functionFactory(function); final BiFunction<String, String, String> first = first(); assertThat(factory).isEqualTo(factory); assertThat(factory).isEqualTo(functionFactory(function)); assertThat(functionFactory(function)).isEqualTo(functionFactory(function)); assertThat(functionFactory(first)).isEqualTo(functionFactory(first)); assertThat(factory).isNotEqualTo(functionFactory(first)); assertThat(factory).isNotEqualTo(""); assertThat(factory.hashCode()).isEqualTo(functionFactory(function).hashCode()); assertThat(factory.hashCode()).isNotEqualTo(functionFactory(first).hashCode()); } }
davide-maestroni/jroutine
operator/src/test/java/com/github/dm/jrt/operator/AccumulateFunctionInvocationTest.java
Java
apache-2.0
3,199
package com.google.api.ads.dfp.jaxws.v201511; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * Errors related to incorrect permission. * * * <p>Java class for PermissionError complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PermissionError"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201511}ApiError"> * &lt;sequence> * &lt;element name="reason" type="{https://www.google.com/apis/ads/publisher/v201511}PermissionError.Reason" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PermissionError", propOrder = { "reason" }) public class PermissionError extends ApiError { @XmlSchemaType(name = "string") protected PermissionErrorReason reason; /** * Gets the value of the reason property. * * @return * possible object is * {@link PermissionErrorReason } * */ public PermissionErrorReason getReason() { return reason; } /** * Sets the value of the reason property. * * @param value * allowed object is * {@link PermissionErrorReason } * */ public void setReason(PermissionErrorReason value) { this.reason = value; } }
gawkermedia/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201511/PermissionError.java
Java
apache-2.0
1,664
package com.jasongj.kafka.stream.producer; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringSerializer; import com.jasongj.kafka.producer.HashPartitioner; import com.jasongj.kafka.stream.model.User; import com.jasongj.kafka.stream.serdes.GenericSerializer; public class UserProducer { public static void main(String[] args) throws Exception { Properties props = new Properties(); props.put("bootstrap.servers", "kafka0:19092"); props.put("acks", "all"); props.put("retries", 3); props.put("batch.size", 16384); props.put("linger.ms", 1); props.put("buffer.memory", 33554432); props.put("key.serializer", StringSerializer.class.getName()); props.put("value.serializer", GenericSerializer.class.getName()); props.put("value.serializer.type", User.class.getName()); props.put("partitioner.class", HashPartitioner.class.getName()); Producer<String, User> producer = new KafkaProducer<String, User>(props); List<User> users = readUser(); users.forEach((User user) -> producer.send(new ProducerRecord<String, User>("users", user.getName(), user))); producer.close(); } public static List<User> readUser() throws IOException { List<String> lines = IOUtils.readLines(OrderProducer.class.getResourceAsStream("/users.csv"), Charset.forName("UTF-8")); List<User> users = lines.stream() .filter(StringUtils::isNoneBlank) .map((String line) -> line.split("\\s*,\\s*")) .filter((String[] values) -> values.length == 4) .map((String[] values) -> new User(values[0], values[1], values[2], Integer.parseInt(values[3]))) .collect(Collectors.toList()); return users; } }
habren/KafkaExample
demokafka.0.10.1.0/src/main/java/com/jasongj/kafka/stream/producer/UserProducer.java
Java
apache-2.0
2,014
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.annotation; import java.beans.PropertyDescriptor; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; import org.springframework.beans.TypeConverter; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.InjectionPoint; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.UnsatisfiedDependencyException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.DependencyDescriptor; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.LookupOverride; import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.BridgeMethodResolver; import org.springframework.core.MethodParameter; import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; /** * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation * that autowires annotated fields, setter methods and arbitrary config methods. * Such members to be injected are detected through a Java 5 annotation: by default, * Spring's {@link Autowired @Autowired} and {@link Value @Value} annotations. * * <p>Also supports JSR-330's {@link javax.inject.Inject @Inject} annotation, * if available, as a direct alternative to Spring's own {@code @Autowired}. * * <p>Only one constructor (at max) of any given bean class may carry this * annotation with the 'required' parameter set to {@code true}, * indicating <i>the</i> constructor to autowire when used as a Spring bean. * If multiple <i>non-required</i> constructors carry the annotation, they * will be considered as candidates for autowiring. The constructor with * the greatest number of dependencies that can be satisfied by matching * beans in the Spring container will be chosen. If none of the candidates * can be satisfied, then a default constructor (if present) will be used. * An annotated constructor does not have to be public. * * <p>Fields are injected right after construction of a bean, before any * config methods are invoked. Such a config field does not have to be public. * * <p>Config methods may have an arbitrary name and any number of arguments; each of * those arguments will be autowired with a matching bean in the Spring container. * Bean property setter methods are effectively just a special case of such a * general config method. Config methods do not have to be public. * * <p>Note: A default AutowiredAnnotationBeanPostProcessor will be registered * by the "context:annotation-config" and "context:component-scan" XML tags. * Remove or turn off the default annotation configuration there if you intend * to specify a custom AutowiredAnnotationBeanPostProcessor bean definition. * <p><b>NOTE:</b> Annotation injection will be performed <i>before</i> XML injection; * thus the latter configuration will override the former for properties wired through * both approaches. * * <p>In addition to regular injection points as discussed above, this post-processor * also handles Spring's {@link Lookup @Lookup} annotation which identifies lookup * methods to be replaced by the container at runtime. This is essentially a type-safe * version of {@code getBean(Class, args)} and {@code getBean(String, args)}, * See {@link Lookup @Lookup's javadoc} for details. * * @author Juergen Hoeller * @author Mark Fisher * @author Stephane Nicoll * @since 2.5 * @see #setAutowiredAnnotationType * @see Autowired * @see Value */ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware { protected final Log logger = LogFactory.getLog(getClass()); private final Set<Class<? extends Annotation>> autowiredAnnotationTypes = new LinkedHashSet<Class<? extends Annotation>>(); private String requiredParameterName = "required"; private boolean requiredParameterValue = true; private int order = Ordered.LOWEST_PRECEDENCE - 2; private ConfigurableListableBeanFactory beanFactory; private final Set<String> lookupMethodsChecked = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(256)); private final Map<Class<?>, Constructor<?>[]> candidateConstructorsCache = new ConcurrentHashMap<Class<?>, Constructor<?>[]>(256); private final Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap<String, InjectionMetadata>(256); /** * Create a new AutowiredAnnotationBeanPostProcessor * for Spring's standard {@link Autowired} annotation. * <p>Also supports JSR-330's {@link javax.inject.Inject} annotation, if available. */ @SuppressWarnings("unchecked") public AutowiredAnnotationBeanPostProcessor() { this.autowiredAnnotationTypes.add(Autowired.class); this.autowiredAnnotationTypes.add(Value.class); try { this.autowiredAnnotationTypes.add((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader())); logger.info("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring"); } catch (ClassNotFoundException ex) { // JSR-330 API not available - simply skip. } } /** * Set the 'autowired' annotation type, to be used on constructors, fields, * setter methods and arbitrary config methods. * <p>The default autowired annotation type is the Spring-provided * {@link Autowired} annotation, as well as {@link Value}. * <p>This setter property exists so that developers can provide their own * (non-Spring-specific) annotation type to indicate that a member is * supposed to be autowired. */ public void setAutowiredAnnotationType(Class<? extends Annotation> autowiredAnnotationType) { Assert.notNull(autowiredAnnotationType, "'autowiredAnnotationType' must not be null"); this.autowiredAnnotationTypes.clear(); this.autowiredAnnotationTypes.add(autowiredAnnotationType); } /** * Set the 'autowired' annotation types, to be used on constructors, fields, * setter methods and arbitrary config methods. * <p>The default autowired annotation type is the Spring-provided * {@link Autowired} annotation, as well as {@link Value}. * <p>This setter property exists so that developers can provide their own * (non-Spring-specific) annotation types to indicate that a member is * supposed to be autowired. */ public void setAutowiredAnnotationTypes(Set<Class<? extends Annotation>> autowiredAnnotationTypes) { Assert.notEmpty(autowiredAnnotationTypes, "'autowiredAnnotationTypes' must not be empty"); this.autowiredAnnotationTypes.clear(); this.autowiredAnnotationTypes.addAll(autowiredAnnotationTypes); } /** * Set the name of a parameter of the annotation that specifies * whether it is required. * @see #setRequiredParameterValue(boolean) */ public void setRequiredParameterName(String requiredParameterName) { this.requiredParameterName = requiredParameterName; } /** * Set the boolean value that marks a dependency as required * <p>For example if using 'required=true' (the default), * this value should be {@code true}; but if using * 'optional=false', this value should be {@code false}. * @see #setRequiredParameterName(String) */ public void setRequiredParameterValue(boolean requiredParameterValue) { this.requiredParameterValue = requiredParameterValue; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { throw new IllegalArgumentException( "AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory"); } this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { if (beanType != null) { InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null); metadata.checkConfigMembers(beanDefinition); } } @Override public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName) throws BeansException { if (!this.lookupMethodsChecked.contains(beanName)) { ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { Lookup lookup = method.getAnnotation(Lookup.class); if (lookup != null) { LookupOverride override = new LookupOverride(method, lookup.value()); try { RootBeanDefinition mbd = (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName); mbd.getMethodOverrides().addOverride(override); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(beanName, "Cannot apply @Lookup to beans without corresponding bean definition"); } } } }); this.lookupMethodsChecked.add(beanName); } // Quick check on the concurrent map first, with minimal locking. Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { synchronized (this.candidateConstructorsCache) { candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { Constructor<?>[] rawCandidates = beanClass.getDeclaredConstructors(); List<Constructor<?>> candidates = new ArrayList<Constructor<?>>(rawCandidates.length); Constructor<?> requiredConstructor = null; Constructor<?> defaultConstructor = null; for (Constructor<?> candidate : rawCandidates) { AnnotationAttributes ann = findAutowiredAnnotation(candidate); if (ann == null) { Class<?> userClass = ClassUtils.getUserClass(beanClass); if (userClass != beanClass) { try { Constructor<?> superCtor = userClass.getDeclaredConstructor(candidate.getParameterTypes()); ann = findAutowiredAnnotation(superCtor); } catch (NoSuchMethodException ex) { // Simply proceed, no equivalent superclass constructor found... } } } if (ann != null) { if (requiredConstructor != null) { throw new BeanCreationException(beanName, "Invalid autowire-marked constructor: " + candidate + ". Found constructor with 'required' Autowired annotation already: " + requiredConstructor); } if (candidate.getParameterTypes().length == 0) { throw new IllegalStateException( "Autowired annotation requires at least one argument: " + candidate); } boolean required = determineRequiredStatus(ann); if (required) { if (!candidates.isEmpty()) { throw new BeanCreationException(beanName, "Invalid autowire-marked constructors: " + candidates + ". Found constructor with 'required' Autowired annotation: " + candidate); } requiredConstructor = candidate; } candidates.add(candidate); } else if (candidate.getParameterTypes().length == 0) { defaultConstructor = candidate; } } if (!candidates.isEmpty()) { // Add default constructor to list of optional constructors, as fallback. if (requiredConstructor == null) { if (defaultConstructor != null) { candidates.add(defaultConstructor); } else if (candidates.size() == 1 && logger.isWarnEnabled()) { logger.warn("Inconsistent constructor declaration on bean with name '" + beanName + "': single autowire-marked constructor flagged as optional - this constructor " + "is effectively required since there is no default constructor to fall back to: " + candidates.get(0)); } } candidateConstructors = candidates.toArray(new Constructor<?>[candidates.size()]); } else if (rawCandidates.length == 1 && rawCandidates[0].getParameterTypes().length > 0) { candidateConstructors = new Constructor<?>[] {rawCandidates[0]}; } else { candidateConstructors = new Constructor<?>[0]; } this.candidateConstructorsCache.put(beanClass, candidateConstructors); } } } return (candidateConstructors.length > 0 ? candidateConstructors : null); } @Override public PropertyValues postProcessPropertyValues( PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs); try { metadata.inject(bean, beanName, pvs); } catch (BeanCreationException ex) { throw ex; } catch (Throwable ex) { throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex); } return pvs; } /** * 'Native' processing method for direct calls with an arbitrary target instance, * resolving all of its fields and methods which are annotated with {@code @Autowired}. * @param bean the target instance to process * @throws BeansException if autowiring failed */ public void processInjection(Object bean) throws BeansException { Class<?> clazz = bean.getClass(); InjectionMetadata metadata = findAutowiringMetadata(clazz.getName(), clazz, null); try { metadata.inject(bean, null, null); } catch (BeanCreationException ex) { throw ex; } catch (Throwable ex) { throw new BeanCreationException("Injection of autowired dependencies failed for class [" + clazz + "]", ex); } } private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, PropertyValues pvs) { // Fall back to class name as cache key, for backwards compatibility with custom callers. String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); // Quick check on the concurrent map first, with minimal locking. InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { synchronized (this.injectionMetadataCache) { metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { if (metadata != null) { metadata.clear(pvs); } try { metadata = buildAutowiringMetadata(clazz); this.injectionMetadataCache.put(cacheKey, metadata); } catch (NoClassDefFoundError err) { throw new IllegalStateException("Failed to introspect bean class [" + clazz.getName() + "] for autowiring metadata: could not find class that it depends on", err); } } } } return metadata; } private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) { LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>(); Class<?> targetClass = clazz; do { final LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>(); ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { AnnotationAttributes ann = findAutowiredAnnotation(field); if (ann != null) { if (Modifier.isStatic(field.getModifiers())) { if (logger.isWarnEnabled()) { logger.warn("Autowired annotation is not supported on static fields: " + field); } return; } boolean required = determineRequiredStatus(ann); currElements.add(new AutowiredFieldElement(field, required)); } } }); ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { return; } AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod); if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { if (Modifier.isStatic(method.getModifiers())) { if (logger.isWarnEnabled()) { logger.warn("Autowired annotation is not supported on static methods: " + method); } return; } if (method.getParameterTypes().length == 0) { if (logger.isWarnEnabled()) { logger.warn("Autowired annotation should be used on methods with parameters: " + method); } } boolean required = determineRequiredStatus(ann); PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); currElements.add(new AutowiredMethodElement(method, required, pd)); } } }); elements.addAll(0, currElements); targetClass = targetClass.getSuperclass(); } while (targetClass != null && targetClass != Object.class); return new InjectionMetadata(clazz, elements); } private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) { if (ao.getAnnotations().length > 0) { for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) { AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type); if (attributes != null) { return attributes; } } } return null; } /** * Determine if the annotated field or method requires its dependency. * <p>A 'required' dependency means that autowiring should fail when no beans * are found. Otherwise, the autowiring process will simply bypass the field * or method when no beans are found. * @param ann the Autowired annotation * @return whether the annotation indicates that a dependency is required */ protected boolean determineRequiredStatus(AnnotationAttributes ann) { return (!ann.containsKey(this.requiredParameterName) || this.requiredParameterValue == ann.getBoolean(this.requiredParameterName)); } /** * Obtain all beans of the given type as autowire candidates. * @param type the type of the bean * @return the target beans, or an empty Collection if no bean of this type is found * @throws BeansException if bean retrieval failed */ protected <T> Map<String, T> findAutowireCandidates(Class<T> type) throws BeansException { if (this.beanFactory == null) { throw new IllegalStateException("No BeanFactory configured - " + "override the getBeanOfType method or specify the 'beanFactory' property"); } return BeanFactoryUtils.beansOfTypeIncludingAncestors(this.beanFactory, type); } /** * Register the specified bean as dependent on the autowired beans. */ private void registerDependentBeans(String beanName, Set<String> autowiredBeanNames) { if (beanName != null) { for (String autowiredBeanName : autowiredBeanNames) { if (this.beanFactory.containsBean(autowiredBeanName)) { this.beanFactory.registerDependentBean(autowiredBeanName, beanName); } if (logger.isDebugEnabled()) { logger.debug("Autowiring by type from bean name '" + beanName + "' to bean named '" + autowiredBeanName + "'"); } } } } /** * Resolve the specified cached method argument or field value. */ private Object resolvedCachedArgument(String beanName, Object cachedArgument) { if (cachedArgument instanceof DependencyDescriptor) { DependencyDescriptor descriptor = (DependencyDescriptor) cachedArgument; return this.beanFactory.resolveDependency(descriptor, beanName, null, null); } else if (cachedArgument instanceof RuntimeBeanReference) { return this.beanFactory.getBean(((RuntimeBeanReference) cachedArgument).getBeanName()); } else { return cachedArgument; } } /** * Class representing injection information about an annotated field. */ private class AutowiredFieldElement extends InjectionMetadata.InjectedElement { private final boolean required; private volatile boolean cached = false; private volatile Object cachedFieldValue; public AutowiredFieldElement(Field field, boolean required) { super(field, null); this.required = required; } @Override protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable { Field field = (Field) this.member; Object value; if (this.cached) { value = resolvedCachedArgument(beanName, this.cachedFieldValue); } else { DependencyDescriptor desc = new DependencyDescriptor(field, this.required); desc.setContainingClass(bean.getClass()); Set<String> autowiredBeanNames = new LinkedHashSet<String>(1); TypeConverter typeConverter = beanFactory.getTypeConverter(); try { value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter); } catch (BeansException ex) { throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex); } synchronized (this) { if (!this.cached) { if (value != null || this.required) { this.cachedFieldValue = desc; registerDependentBeans(beanName, autowiredBeanNames); if (autowiredBeanNames.size() == 1) { String autowiredBeanName = autowiredBeanNames.iterator().next(); if (beanFactory.containsBean(autowiredBeanName)) { if (beanFactory.isTypeMatch(autowiredBeanName, field.getType())) { this.cachedFieldValue = new RuntimeBeanReference(autowiredBeanName); } } } } else { this.cachedFieldValue = null; } this.cached = true; } } } if (value != null) { ReflectionUtils.makeAccessible(field); field.set(bean, value); } } } /** * Class representing injection information about an annotated method. */ private class AutowiredMethodElement extends InjectionMetadata.InjectedElement { private final boolean required; private volatile boolean cached = false; private volatile Object[] cachedMethodArguments; public AutowiredMethodElement(Method method, boolean required, PropertyDescriptor pd) { super(method, pd); this.required = required; } @Override protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable { if (checkPropertySkipping(pvs)) { return; } Method method = (Method) this.member; Object[] arguments; if (this.cached) { // Shortcut for avoiding synchronization... arguments = resolveCachedArguments(beanName); } else { Class<?>[] paramTypes = method.getParameterTypes(); arguments = new Object[paramTypes.length]; DependencyDescriptor[] descriptors = new DependencyDescriptor[paramTypes.length]; Set<String> autowiredBeanNames = new LinkedHashSet<String>(paramTypes.length); TypeConverter typeConverter = beanFactory.getTypeConverter(); for (int i = 0; i < arguments.length; i++) { MethodParameter methodParam = new MethodParameter(method, i); DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required); currDesc.setContainingClass(bean.getClass()); descriptors[i] = currDesc; try { Object arg = beanFactory.resolveDependency(currDesc, beanName, autowiredBeanNames, typeConverter); if (arg == null && !this.required) { arguments = null; break; } arguments[i] = arg; } catch (BeansException ex) { throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(methodParam), ex); } } synchronized (this) { if (!this.cached) { if (arguments != null) { this.cachedMethodArguments = new Object[paramTypes.length]; for (int i = 0; i < arguments.length; i++) { this.cachedMethodArguments[i] = descriptors[i]; } registerDependentBeans(beanName, autowiredBeanNames); if (autowiredBeanNames.size() == paramTypes.length) { Iterator<String> it = autowiredBeanNames.iterator(); for (int i = 0; i < paramTypes.length; i++) { String autowiredBeanName = it.next(); if (beanFactory.containsBean(autowiredBeanName)) { if (beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) { this.cachedMethodArguments[i] = new RuntimeBeanReference(autowiredBeanName); } } } } } else { this.cachedMethodArguments = null; } this.cached = true; } } } if (arguments != null) { try { ReflectionUtils.makeAccessible(method); method.invoke(bean, arguments); } catch (InvocationTargetException ex){ throw ex.getTargetException(); } } } private Object[] resolveCachedArguments(String beanName) { if (this.cachedMethodArguments == null) { return null; } Object[] arguments = new Object[this.cachedMethodArguments.length]; for (int i = 0; i < arguments.length; i++) { arguments[i] = resolvedCachedArgument(beanName, this.cachedMethodArguments[i]); } return arguments; } } }
shivpun/spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java
Java
apache-2.0
27,470
package com.cibc.p8.sqlmodel; import java.util.ArrayList; public interface AbstractNode { public String getString(); //»ñÈ¡Ö´ÐеÄSQL public String getExecString(); //½«½á¹û¼¯´øÈëµÄSQLÄÚÈÝ public ELEMENTTYPE getElementType(); static public enum NODETYPE { SELECT, INSERT, DELETE, UPDATE, ALTER, UNDEFINED } static public enum ELEMENTTYPE { SQL, FIX, LOGICAL, JOIN, FUNC, TABLE, UNDEFINED } }
sabotage/SQLParser
src/com/cibc/p8/sqlmodel/AbstractNode.java
Java
apache-2.0
410
/* * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Roger Lawrence * Mike McCabe * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package com.google.javascript.rhino; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.javascript.rhino.jstype.JSType; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; /** * This class implements the root of the intermediate representation. * */ public class Node implements Cloneable, Serializable { private static final long serialVersionUID = 1L; public static final int // Rhino's AST captures data flow. These are the annotations // it used. We've mostly torn them out. LOCAL_BLOCK_PROP = -3, OBJECT_IDS_PROP = -2, CATCH_SCOPE_PROP = -1, LABEL_ID_PROP = 0, TARGET_PROP = 1, BREAK_PROP = 2, CONTINUE_PROP = 3, ENUM_PROP = 4, FUNCTION_PROP = 5, TEMP_PROP = 6, LOCAL_PROP = 7, CODEOFFSET_PROP = 8, FIXUPS_PROP = 9, VARS_PROP = 10, USES_PROP = 11, REGEXP_PROP = 12, CASES_PROP = 13, DEFAULT_PROP = 14, CASEARRAY_PROP = 15, SOURCENAME_PROP = 16, TYPE_PROP = 17, SPECIAL_PROP_PROP = 18, LABEL_PROP = 19, FINALLY_PROP = 20, LOCALCOUNT_PROP = 21, /* the following properties are defined and manipulated by the optimizer - TARGETBLOCK_PROP - the block referenced by a branch node VARIABLE_PROP - the variable referenced by a BIND or NAME node LASTUSE_PROP - that variable node is the last reference before a new def or the end of the block ISNUMBER_PROP - this node generates code on Number children and delivers a Number result (as opposed to Objects) DIRECTCALL_PROP - this call node should emit code to test the function object against the known class and call diret if it matches. */ TARGETBLOCK_PROP = 22, VARIABLE_PROP = 23, LASTUSE_PROP = 24, ISNUMBER_PROP = 25, DIRECTCALL_PROP = 26, SPECIALCALL_PROP = 27, DEBUGSOURCE_PROP = 28, JSDOC_INFO_PROP = 29, // contains a TokenStream.JSDocInfo object VAR_ARGS_NAME = 30, // the name node is a variable length // argument placeholder. SKIP_INDEXES_PROP = 31, // array of skipped indexes of array literal INCRDECR_PROP = 32, // pre or post type of increment/decrement MEMBER_TYPE_PROP = 33, // type of element access operation NAME_PROP = 34, // property name PARENTHESIZED_PROP = 35, // expression is parenthesized QUOTED_PROP = 36, // set to indicate a quoted object lit key OPT_ARG_NAME = 37, // The name node is an optional argument. SYNTHETIC_BLOCK_PROP = 38, // A synthetic block. Used to make // processing simpler, and does not // represent a real block in the source. EMPTY_BLOCK = 39, // Used to indicate BLOCK that replaced // EMPTY nodes. ORIGINALNAME_PROP = 40, // The original name of the node, before // renaming. BRACELESS_TYPE = 41, // The type syntax without curly braces. SIDE_EFFECT_FLAGS = 42, // Function or constructor call side effect // flags // Coding convention props IS_CONSTANT_NAME = 43, // The variable or property is constant. IS_OPTIONAL_PARAM = 44, // The parameter is optional. IS_VAR_ARGS_PARAM = 45, // The parameter is a var_args. IS_NAMESPACE = 46, // The variable creates a namespace. IS_DISPATCHER = 47, // The function is a dispatcher function, // probably generated from Java code, and // should be resolved to the proper // overload if possible. DIRECTIVES = 48, // The ES5 directives on this node. DIRECT_EVAL = 49, // ES5 distinguishes between direct and // indirect calls to eval. FREE_CALL = 50, // A CALL without an explicit "this" value. LAST_PROP = 50; // values of ISNUMBER_PROP to specify // which of the children are Number types public static final int BOTH = 0, LEFT = 1, RIGHT = 2; public static final int // values for SPECIALCALL_PROP NON_SPECIALCALL = 0, SPECIALCALL_EVAL = 1, SPECIALCALL_WITH = 2; public static final int // flags for INCRDECR_PROP DECR_FLAG = 0x1, POST_FLAG = 0x2; public static final int // flags for MEMBER_TYPE_PROP PROPERTY_FLAG = 0x1, // property access: element is valid name ATTRIBUTE_FLAG = 0x2, // x.@y or x..@y DESCENDANTS_FLAG = 0x4; // x..y or x..@i private static final String propToString(int propType) { switch (propType) { case LOCAL_BLOCK_PROP: return "local_block"; case OBJECT_IDS_PROP: return "object_ids_prop"; case CATCH_SCOPE_PROP: return "catch_scope_prop"; case LABEL_ID_PROP: return "label_id_prop"; case TARGET_PROP: return "target"; case BRACELESS_TYPE: return "braceless_type"; case BREAK_PROP: return "break"; case CONTINUE_PROP: return "continue"; case ENUM_PROP: return "enum"; case FUNCTION_PROP: return "function"; case TEMP_PROP: return "temp"; case LOCAL_PROP: return "local"; case CODEOFFSET_PROP: return "codeoffset"; case FIXUPS_PROP: return "fixups"; case VARS_PROP: return "vars"; case VAR_ARGS_NAME: return "var_args_name"; case USES_PROP: return "uses"; case REGEXP_PROP: return "regexp"; case CASES_PROP: return "cases"; case DEFAULT_PROP: return "default"; case CASEARRAY_PROP: return "casearray"; case SOURCENAME_PROP: return "sourcename"; case TYPE_PROP: return "type"; case SPECIAL_PROP_PROP: return "special_prop"; case LABEL_PROP: return "label"; case FINALLY_PROP: return "finally"; case LOCALCOUNT_PROP: return "localcount"; case TARGETBLOCK_PROP: return "targetblock"; case VARIABLE_PROP: return "variable"; case LASTUSE_PROP: return "lastuse"; case ISNUMBER_PROP: return "isnumber"; case DIRECTCALL_PROP: return "directcall"; case SPECIALCALL_PROP: return "specialcall"; case DEBUGSOURCE_PROP: return "debugsource"; case JSDOC_INFO_PROP: return "jsdoc_info"; case SKIP_INDEXES_PROP: return "skip_indexes"; case INCRDECR_PROP: return "incrdecr"; case MEMBER_TYPE_PROP: return "member_type"; case NAME_PROP: return "name"; case PARENTHESIZED_PROP: return "parenthesized"; case QUOTED_PROP: return "quoted"; case OPT_ARG_NAME: return "opt_arg"; case SYNTHETIC_BLOCK_PROP: return "synthetic"; case EMPTY_BLOCK: return "empty_block"; case ORIGINALNAME_PROP: return "originalname"; case SIDE_EFFECT_FLAGS: return "side_effect_flags"; case IS_CONSTANT_NAME: return "is_constant_name"; case IS_OPTIONAL_PARAM: return "is_optional_param"; case IS_VAR_ARGS_PARAM: return "is_var_args_param"; case IS_NAMESPACE: return "is_namespace"; case IS_DISPATCHER: return "is_dispatcher"; case DIRECTIVES: return "directives"; case DIRECT_EVAL: return "direct_eval"; case FREE_CALL: return "free_call"; default: Kit.codeBug(); } return null; } private static class NumberNode extends Node { private static final long serialVersionUID = 1L; NumberNode(double number) { super(Token.NUMBER); this.number = number; } public NumberNode(double number, int lineno, int charno) { super(Token.NUMBER, lineno, charno); this.number = number; } @Override public double getDouble() { return this.number; } @Override public void setDouble(double d) { this.number = d; } @Override boolean isEquivalentTo(Node node, boolean compareJsType, boolean recurse) { return (super.isEquivalentTo(node, compareJsType, recurse) && getDouble() == ((NumberNode) node).getDouble()); } private double number; } private static class StringNode extends Node { private static final long serialVersionUID = 1L; StringNode(int type, String str) { super(type); if (null == str) { throw new IllegalArgumentException("StringNode: str is null"); } this.str = str; } StringNode(int type, String str, int lineno, int charno) { super(type, lineno, charno); if (null == str) { throw new IllegalArgumentException("StringNode: str is null"); } this.str = str; } /** * returns the string content. * @return non null. */ @Override public String getString() { return this.str; } /** * sets the string content. * @param str the new value. Non null. */ @Override public void setString(String str) { if (null == str) { throw new IllegalArgumentException("StringNode: str is null"); } this.str = str; } @Override boolean isEquivalentTo(Node node, boolean compareJsType, boolean recurse) { return (super.isEquivalentTo(node, compareJsType, recurse) && this.str.equals(((StringNode) node).str)); } /** * If the property is not defined, this was not a quoted key. The * QUOTED_PROP int property is only assigned to STRING tokens used as * object lit keys. * @return true if this was a quoted string key in an object literal. */ @Override public boolean isQuotedString() { return getBooleanProp(QUOTED_PROP); } /** * This should only be called for STRING nodes created in object lits. */ @Override public void setQuotedString() { putBooleanProp(QUOTED_PROP, true); } private String str; } // PropListItems must be immutable so that they can be shared. private interface PropListItem { int getType(); PropListItem getNext(); PropListItem chain(PropListItem next); Object getObjectValue(); int getIntValue(); } private static abstract class AbstractPropListItem implements PropListItem, Serializable { private static final long serialVersionUID = 1L; private final PropListItem next; private final int propType; AbstractPropListItem(int propType, PropListItem next) { this.propType = propType; this.next = next; } public int getType() { return propType; } public PropListItem getNext() { return next; } public abstract PropListItem chain(PropListItem next); } // A base class for Object storing props private static class ObjectPropListItem extends AbstractPropListItem { private static final long serialVersionUID = 1L; private final Object objectValue; ObjectPropListItem(int propType, Object objectValue, PropListItem next) { super(propType, next); this.objectValue = objectValue; } @Override public int getIntValue() { throw new UnsupportedOperationException(); } @Override public Object getObjectValue() { return objectValue; } @Override public String toString() { return objectValue == null ? "null" : objectValue.toString(); } @Override public PropListItem chain(PropListItem next) { return new ObjectPropListItem(getType(), objectValue, next); } } // A base class for int storing props private static class IntPropListItem extends AbstractPropListItem { private static final long serialVersionUID = 1L; final int intValue; IntPropListItem(int propType, int intValue, PropListItem next) { super(propType, next); this.intValue = intValue; } @Override public int getIntValue() { return intValue; } @Override public Object getObjectValue() { throw new UnsupportedOperationException(); } @Override public String toString() { return String.valueOf(intValue); } @Override public PropListItem chain(PropListItem next) { return new IntPropListItem(getType(), intValue, next); } } public Node(int nodeType) { type = nodeType; parent = null; sourcePosition = -1; } public Node(int nodeType, Node child) { Preconditions.checkArgument(child.parent == null, "new child has existing parent"); Preconditions.checkArgument(child.next == null, "new child has existing sibling"); type = nodeType; parent = null; first = last = child; child.next = null; child.parent = this; sourcePosition = -1; } public Node(int nodeType, Node left, Node right) { Preconditions.checkArgument(left.parent == null, "first new child has existing parent"); Preconditions.checkArgument(left.next == null, "first new child has existing sibling"); Preconditions.checkArgument(right.parent == null, "second new child has existing parent"); Preconditions.checkArgument(right.next == null, "second new child has existing sibling"); type = nodeType; parent = null; first = left; last = right; left.next = right; left.parent = this; right.next = null; right.parent = this; sourcePosition = -1; } public Node(int nodeType, Node left, Node mid, Node right) { Preconditions.checkArgument(left.parent == null); Preconditions.checkArgument(left.next == null); Preconditions.checkArgument(mid.parent == null); Preconditions.checkArgument(mid.next == null); Preconditions.checkArgument(right.parent == null); Preconditions.checkArgument(right.next == null); type = nodeType; parent = null; first = left; last = right; left.next = mid; left.parent = this; mid.next = right; mid.parent = this; right.next = null; right.parent = this; sourcePosition = -1; } public Node(int nodeType, Node left, Node mid, Node mid2, Node right) { Preconditions.checkArgument(left.parent == null); Preconditions.checkArgument(left.next == null); Preconditions.checkArgument(mid.parent == null); Preconditions.checkArgument(mid.next == null); Preconditions.checkArgument(mid2.parent == null); Preconditions.checkArgument(mid2.next == null); Preconditions.checkArgument(right.parent == null); Preconditions.checkArgument(right.next == null); type = nodeType; parent = null; first = left; last = right; left.next = mid; left.parent = this; mid.next = mid2; mid.parent = this; mid2.next = right; mid2.parent = this; right.next = null; right.parent = this; sourcePosition = -1; } public Node(int nodeType, int lineno, int charno) { type = nodeType; parent = null; sourcePosition = mergeLineCharNo(lineno, charno); } public Node(int nodeType, Node child, int lineno, int charno) { this(nodeType, child); sourcePosition = mergeLineCharNo(lineno, charno); } public Node(int nodeType, Node left, Node right, int lineno, int charno) { this(nodeType, left, right); sourcePosition = mergeLineCharNo(lineno, charno); } public Node(int nodeType, Node left, Node mid, Node right, int lineno, int charno) { this(nodeType, left, mid, right); sourcePosition = mergeLineCharNo(lineno, charno); } public Node(int nodeType, Node left, Node mid, Node mid2, Node right, int lineno, int charno) { this(nodeType, left, mid, mid2, right); sourcePosition = mergeLineCharNo(lineno, charno); } public Node(int nodeType, Node[] children, int lineno, int charno) { this(nodeType, children); sourcePosition = mergeLineCharNo(lineno, charno); } public Node(int nodeType, Node[] children) { this.type = nodeType; parent = null; if (children.length != 0) { this.first = children[0]; this.last = children[children.length - 1]; for (int i = 1; i < children.length; i++) { if (null != children[i - 1].next) { // fail early on loops. implies same node in array twice throw new IllegalArgumentException("duplicate child"); } children[i - 1].next = children[i]; Preconditions.checkArgument(children[i - 1].parent == null); children[i - 1].parent = this; } Preconditions.checkArgument(children[children.length - 1].parent == null); children[children.length - 1].parent = this; if (null != this.last.next) { // fail early on loops. implies same node in array twice throw new IllegalArgumentException("duplicate child"); } } } public static Node newNumber(double number) { return new NumberNode(number); } public static Node newNumber(double number, int lineno, int charno) { return new NumberNode(number, lineno, charno); } public static Node newString(String str) { return new StringNode(Token.STRING, str); } public static Node newString(int type, String str) { return new StringNode(type, str); } public static Node newString(String str, int lineno, int charno) { return new StringNode(Token.STRING, str, lineno, charno); } public static Node newString(int type, String str, int lineno, int charno) { return new StringNode(type, str, lineno, charno); } public int getType() { return type; } public void setType(int type) { this.type = type; } public boolean hasChildren() { return first != null; } public Node getFirstChild() { return first; } public Node getLastChild() { return last; } public Node getNext() { return next; } public Node getChildBefore(Node child) { if (child == first) { return null; } Node n = first; while (n.next != child) { n = n.next; if (n == null) { throw new RuntimeException("node is not a child"); } } return n; } public Node getChildAtIndex(int i) { Node n = first; while (i > 0) { n = n.next; i--; } return n; } public Node getLastSibling() { Node n = this; while (n.next != null) { n = n.next; } return n; } public void addChildToFront(Node child) { Preconditions.checkArgument(child.parent == null); Preconditions.checkArgument(child.next == null); child.parent = this; child.next = first; first = child; if (last == null) { last = child; } } public void addChildToBack(Node child) { Preconditions.checkArgument(child.parent == null); Preconditions.checkArgument(child.next == null); child.parent = this; child.next = null; if (last == null) { first = last = child; return; } last.next = child; last = child; } public void addChildrenToFront(Node children) { for (Node child = children; child != null; child = child.next) { Preconditions.checkArgument(child.parent == null); child.parent = this; } Node lastSib = children.getLastSibling(); lastSib.next = first; first = children; if (last == null) { last = lastSib; } } public void addChildrenToBack(Node children) { for (Node child = children; child != null; child = child.next) { Preconditions.checkArgument(child.parent == null); child.parent = this; } if (last != null) { last.next = children; } last = children.getLastSibling(); if (first == null) { first = children; } } /** * Add 'child' before 'node'. */ public void addChildBefore(Node newChild, Node node) { Preconditions.checkArgument(node != null, "The existing child node of the parent should not be null."); Preconditions.checkArgument(newChild.next == null, "The new child node has siblings."); Preconditions.checkArgument(newChild.parent == null, "The new child node already has a parent."); if (first == node) { newChild.parent = this; newChild.next = first; first = newChild; return; } Node prev = getChildBefore(node); addChildAfter(newChild, prev); } /** * Add 'child' after 'node'. */ public void addChildAfter(Node newChild, Node node) { Preconditions.checkArgument(newChild.next == null, "The new child node has siblings."); Preconditions.checkArgument(newChild.parent == null, "The new child node already has a parent."); newChild.parent = this; newChild.next = node.next; node.next = newChild; if (last == node) { last = newChild; } } /** * Detach a child from its parent and siblings. */ public void removeChild(Node child) { Node prev = getChildBefore(child); if (prev == null) first = first.next; else prev.next = child.next; if (child == last) last = prev; child.next = null; child.parent = null; } /** * Detaches child from Node and replaces it with newChild. */ public void replaceChild(Node child, Node newChild) { Preconditions.checkArgument(newChild.next == null, "The new child node has siblings."); Preconditions.checkArgument(newChild.parent == null, "The new child node already has a parent."); // Copy over important information. newChild.copyInformationFrom(child); newChild.next = child.next; newChild.parent = this; if (child == first) { first = newChild; } else { Node prev = getChildBefore(child); prev.next = newChild; } if (child == last) last = newChild; child.next = null; child.parent = null; } public void replaceChildAfter(Node prevChild, Node newChild) { Preconditions.checkArgument(prevChild.parent == this, "prev is not a child of this node."); Preconditions.checkArgument(newChild.next == null, "The new child node has siblings."); Preconditions.checkArgument(newChild.parent == null, "The new child node already has a parent."); // Copy over important information. newChild.copyInformationFrom(prevChild); Node child = prevChild.next; newChild.next = child.next; newChild.parent = this; prevChild.next = newChild; if (child == last) last = newChild; child.next = null; child.parent = null; } @VisibleForTesting PropListItem lookupProperty(int propType) { PropListItem x = propListHead; while (x != null && propType != x.getType()) { x = x.getNext(); } return x; } /** * Clone the properties from the provided node without copying * the property object. The recieving node may not have any * existing properties. * @param other The node to clone properties from. * @return this node. */ public Node clonePropsFrom(Node other) { Preconditions.checkState(this.propListHead == null, "Node has existing properties."); this.propListHead = other.propListHead; return this; } public void removeProp(int propType) { PropListItem result = removeProp(propListHead, propType); if (result != propListHead) { propListHead = result; } } /** * @param item The item to inspect * @param propType The property to look for * @return The replacement list if the property was removed, or * 'item' otherwise. */ private PropListItem removeProp(PropListItem item, int propType) { if (item == null) { return null; } else if (item.getType() == propType) { return item.getNext(); } else { PropListItem result = removeProp(item.getNext(), propType); if (result != item.getNext()) { return item.chain(result); } else { return item; } } } public Object getProp(int propType) { PropListItem item = lookupProperty(propType); if (item == null) { return null; } return item.getObjectValue(); } public boolean getBooleanProp(int propType) { return getIntProp(propType) != 0; } /** * Returns the integer value for the property, or 0 if the property * is not defined. */ public int getIntProp(int propType) { PropListItem item = lookupProperty(propType); if (item == null) { return 0; } return item.getIntValue(); } public int getExistingIntProp(int propType) { PropListItem item = lookupProperty(propType); if (item == null) { Kit.codeBug(); } return item.getIntValue(); } public void putProp(int propType, Object value) { removeProp(propType); if (value != null) { propListHead = createProp(propType, value, propListHead); } } public void putBooleanProp(int propType, boolean value) { putIntProp(propType, value ? 1 : 0); } public void putIntProp(int propType, int value) { removeProp(propType); if (value != 0) { propListHead = createProp(propType, value, propListHead); } } PropListItem createProp(int propType, Object value, PropListItem next) { return new ObjectPropListItem(propType, value, next); } PropListItem createProp(int propType, int value, PropListItem next) { return new IntPropListItem(propType, value, next); } // Gets all the property types, in sorted order. private int[] getSortedPropTypes() { int count = 0; for (PropListItem x = propListHead; x != null; x = x.getNext()) { count++; } int[] keys = new int[count]; for (PropListItem x = propListHead; x != null; x = x.getNext()) { count--; keys[count] = x.getType(); } Arrays.sort(keys); return keys; } public int getLineno() { return extractLineno(sourcePosition); } public int getCharno() { return extractCharno(sourcePosition); } public int getSourcePosition() { return sourcePosition; } /** Can only be called when <tt>getType() == TokenStream.NUMBER</tt> */ public double getDouble() throws UnsupportedOperationException { if (this.getType() == Token.NUMBER) { throw new IllegalStateException( "Number node not created with Node.newNumber"); } else { throw new UnsupportedOperationException(this + " is not a number node"); } } /** Can only be called when <tt>getType() == TokenStream.NUMBER</tt> */ public void setDouble(double s) throws UnsupportedOperationException { if (this.getType() == Token.NUMBER) { throw new IllegalStateException( "Number node not created with Node.newNumber"); } else { throw new UnsupportedOperationException(this + " is not a string node"); } } /** Can only be called when node has String context. */ public String getString() throws UnsupportedOperationException { if (this.getType() == Token.STRING) { throw new IllegalStateException( "String node not created with Node.newString"); } else { throw new UnsupportedOperationException(this + " is not a string node"); } } /** Can only be called when node has String context. */ public void setString(String s) throws UnsupportedOperationException { if (this.getType() == Token.STRING) { throw new IllegalStateException( "String node not created with Node.newString"); } else { throw new UnsupportedOperationException(this + " is not a string node"); } } @Override public String toString() { return toString(true, true, true); } public String toString( boolean printSource, boolean printAnnotations, boolean printType) { if (Token.printTrees) { StringBuilder sb = new StringBuilder(); toString(sb, printSource, printAnnotations, printType); return sb.toString(); } return String.valueOf(type); } private void toString( StringBuilder sb, boolean printSource, boolean printAnnotations, boolean printType) { if (Token.printTrees) { sb.append(Token.name(type)); if (this instanceof StringNode) { sb.append(' '); sb.append(getString()); } else if (type == Token.FUNCTION) { sb.append(' '); // In the case of JsDoc trees, the first child is often not a string // which causes exceptions to be thrown when calling toString or // toStringTree. if (first == null || first.getType() != Token.NAME) { sb.append("<invalid>"); } else { sb.append(first.getString()); } } else if (this instanceof ScriptOrFnNode) { ScriptOrFnNode sof = (ScriptOrFnNode) this; if (this instanceof FunctionNode) { FunctionNode fn = (FunctionNode) this; sb.append(' '); sb.append(fn.getFunctionName()); } if (printSource) { sb.append(" [source name: "); sb.append(sof.getSourceName()); sb.append("] [encoded source length: "); sb.append(sof.getEncodedSourceEnd() - sof.getEncodedSourceStart()); sb.append("] [base line: "); sb.append(sof.getBaseLineno()); sb.append("] [end line: "); sb.append(sof.getEndLineno()); sb.append(']'); } } else if (type == Token.NUMBER) { sb.append(' '); sb.append(getDouble()); } if (printSource) { int lineno = getLineno(); if (lineno != -1) { sb.append(' '); sb.append(lineno); } } if (printAnnotations) { int[] keys = getSortedPropTypes(); for (int i = 0; i < keys.length; i++) { int type = keys[i]; PropListItem x = lookupProperty(type); sb.append(" ["); sb.append(propToString(type)); sb.append(": "); String value; switch (type) { case TARGETBLOCK_PROP: // can't add this as it recurses value = "target block property"; break; case LOCAL_BLOCK_PROP: // can't add this as it is dull value = "last local block"; break; case ISNUMBER_PROP: switch (x.getIntValue()) { case BOTH: value = "both"; break; case RIGHT: value = "right"; break; case LEFT: value = "left"; break; default: throw Kit.codeBug(); } break; case SPECIALCALL_PROP: switch (x.getIntValue()) { case SPECIALCALL_EVAL: value = "eval"; break; case SPECIALCALL_WITH: value = "with"; break; default: // NON_SPECIALCALL should not be stored throw Kit.codeBug(); } break; default: value = x.toString(); break; } sb.append(value); sb.append(']'); } } if (printType) { if (jsType != null) { String jsTypeString = jsType.toString(); if (jsTypeString != null) { sb.append(" : "); sb.append(jsTypeString); } } } } } public String toStringTree() { return toStringTreeImpl(); } private String toStringTreeImpl() { try { StringBuilder s = new StringBuilder(); appendStringTree(s); return s.toString(); } catch (IOException e) { throw new RuntimeException("Should not happen\n" + e); } } public void appendStringTree(Appendable appendable) throws IOException { toStringTreeHelper(this, 0, appendable); } private static void toStringTreeHelper(Node n, int level, Appendable sb) throws IOException { if (Token.printTrees) { for (int i = 0; i != level; ++i) { sb.append(" "); } sb.append(n.toString()); sb.append('\n'); for (Node cursor = n.getFirstChild(); cursor != null; cursor = cursor.getNext()) { toStringTreeHelper(cursor, level + 1, sb); } } } int type; // type of the node; Token.NAME for example Node next; // next sibling private Node first; // first element of a linked list of children private Node last; // last element of a linked list of children /** * Linked list of properties. Since vast majority of nodes would have * no more then 2 properties, linked list saves memory and provides * fast lookup. If this does not holds, propListHead can be replaced * by UintMap. */ private PropListItem propListHead; /** * COLUMN_BITS represents how many of the lower-order bits of * sourcePosition are reserved for storing the column number. * Bits above these store the line number. * This gives us decent position information for everything except * files already passed through a minimizer, where lines might * be longer than 4096 characters. */ public static final int COLUMN_BITS = 12; /** * MAX_COLUMN_NUMBER represents the maximum column number that can * be represented. JSCompiler's modifications to Rhino cause all * tokens located beyond the maximum column to MAX_COLUMN_NUMBER. */ public static final int MAX_COLUMN_NUMBER = (1 << COLUMN_BITS) - 1; /** * COLUMN_MASK stores a value where bits storing the column number * are set, and bits storing the line are not set. It's handy for * separating column number from line number. */ public static final int COLUMN_MASK = MAX_COLUMN_NUMBER; /** * Source position of this node. The position is encoded with the * column number in the low 12 bits of the integer, and the line * number in the rest. Create some handy constants so we can change this * size if we want. */ private int sourcePosition; private JSType jsType; private Node parent; //========================================================================== // Source position management public void setLineno(int lineno) { int charno = getCharno(); if (charno == -1) { charno = 0; } sourcePosition = mergeLineCharNo(lineno, charno); } public void setCharno(int charno) { sourcePosition = mergeLineCharNo(getLineno(), charno); } public void setSourcePositionForTree(int sourcePosition) { this.sourcePosition = sourcePosition; for (Node child = getFirstChild(); child != null; child = child.getNext()) { child.setSourcePositionForTree(sourcePosition); } } /** * Merges the line number and character number in one integer. The Character * number takes the first 12 bits and the line number takes the rest. If * the character number is greater than <code>2<sup>12</sup>-1</code> it is * adjusted to <code>2<sup>12</sup>-1</code>. */ protected static int mergeLineCharNo(int lineno, int charno) { if (lineno < 0 || charno < 0) { return -1; } else if ((charno & ~COLUMN_MASK) != 0) { return lineno << COLUMN_BITS | COLUMN_MASK; } else { return lineno << COLUMN_BITS | (charno & COLUMN_MASK); } } /** * Extracts the line number and character number from a merged line char * number (see {@link #mergeLineCharNo(int, int)}). */ protected static int extractLineno(int lineCharNo) { if (lineCharNo == -1) { return -1; } else { return lineCharNo >>> COLUMN_BITS; } } /** * Extracts the character number and character number from a merged line * char number (see {@link #mergeLineCharNo(int, int)}). */ protected static int extractCharno(int lineCharNo) { if (lineCharNo == -1) { return -1; } else { return lineCharNo & COLUMN_MASK; } } //========================================================================== // Iteration /** * <p>Return an iterable object that iterates over this nodes's children. * The iterator does not support the optional operation * {@link Iterator#remove()}.</p> * * <p>To iterate over a node's siblings, one can write</p> * <pre>Node n = ...; * for (Node child : n.children()) { ...</pre> */ public Iterable<Node> children() { if (first == null) { return Collections.emptySet(); } else { return new SiblingNodeIterable(first); } } /** * <p>Return an iterable object that iterates over this nodes's siblings. * The iterator does not support the optional operation * {@link Iterator#remove()}.</p> * * <p>To iterate over a node's siblings, one can write</p> * <pre>Node n = ...; * for (Node sibling : n.siblings()) { ...</pre> */ public Iterable<Node> siblings() { return new SiblingNodeIterable(this); } /** * @see Node#siblings() */ private static final class SiblingNodeIterable implements Iterable<Node>, Iterator<Node> { private final Node start; private Node current; private boolean used; SiblingNodeIterable(Node start) { this.start = start; this.current = start; this.used = false; } public Iterator<Node> iterator() { if (!used) { used = true; return this; } else { // We have already used the current object as an iterator; // we must create a new SiblingNodeIterable based on this // iterable's start node. // // Since the primary use case for Node.children is in for // loops, this branch is extremely unlikely. return (new SiblingNodeIterable(start)).iterator(); } } public boolean hasNext() { return current != null; } public Node next() { if (current == null) { throw new NoSuchElementException(); } try { return current; } finally { current = current.getNext(); } } public void remove() { throw new UnsupportedOperationException(); } } // ========================================================================== // Accessors PropListItem getPropListHeadForTesting() { return propListHead; } public Node getParent() { return parent; } /** * Gets the ancestor node relative to this. * * @param level 0 = this, 1 = the parent, etc. */ public Node getAncestor(int level) { Preconditions.checkArgument(level >= 0); Node node = this; while (node != null && level-- > 0) { node = node.getParent(); } return node; } /** * Iterates all of the node's ancestors excluding itself. */ public AncestorIterable getAncestors() { return new AncestorIterable(this.getParent()); } /** * Iterator to go up the ancestor tree. */ public static class AncestorIterable implements Iterable<Node> { private Node cur; /** * @param cur The node to start. */ AncestorIterable(Node cur) { this.cur = cur; } public Iterator<Node> iterator() { return new Iterator<Node>() { public boolean hasNext() { return cur != null; } public Node next() { if (!hasNext()) throw new NoSuchElementException(); Node n = cur; cur = cur.getParent(); return n; } public void remove() { throw new UnsupportedOperationException(); } }; } } /** * Check for one child more efficiently than by iterating over all the * children as is done with Node.getChildCount(). * * @return Whether the node has exactly one child. */ public boolean hasOneChild() { return first != null && first == last; } /** * Check for more than one child more efficiently than by iterating over all * the children as is done with Node.getChildCount(). * * @return Whether the node more than one child. */ public boolean hasMoreThanOneChild() { return first != null && first != last; } public int getChildCount() { int c = 0; for (Node n = first; n != null; n = n.next) c++; return c; } // Intended for testing and verification only. public boolean hasChild(Node child) { for (Node n = first; n != null; n = n.getNext()) { if (child == n) { return true; } } return false; } /** * Checks if the subtree under this node is the same as another subtree. * Returns null if it's equal, or a message describing the differences. */ public String checkTreeEquals(Node node2) { NodeMismatch diff = checkTreeEqualsImpl(node2); if (diff != null) { return "Node tree inequality:" + "\nTree1:\n" + toStringTree() + "\n\nTree2:\n" + node2.toStringTree() + "\n\nSubtree1: " + diff.nodeA.toStringTree() + "\n\nSubtree2: " + diff.nodeB.toStringTree(); } return null; } /** * Helper function to ignore differences in Node subclasses that are no longer * used. */ @SuppressWarnings("unchecked") static private Class getNodeClass(Node n) { Class c = n.getClass(); if (c == FunctionNode.class || c == ScriptOrFnNode.class) { return Node.class; } return c; } /** * Compare this node to node2 recursively and return the first pair of nodes * that differs doing a preorder depth-first traversal. Package private for * testing. Returns null if the nodes are equivalent. */ NodeMismatch checkTreeEqualsImpl(Node node2) { if (!isEquivalentTo(node2, false, false)) { return new NodeMismatch(this, node2); } NodeMismatch res = null; Node n, n2; for (n = first, n2 = node2.first; res == null && n != null; n = n.next, n2 = n2.next) { if (node2 == null) { throw new IllegalStateException(); } res = n.checkTreeEqualsImpl(n2); if (res != null) { return res; } } return res; } /** * Compare this node to node2 recursively and return the first pair of nodes * that differs doing a preorder depth-first traversal. Package private for * testing. Returns null if the nodes are equivalent. */ NodeMismatch checkTreeTypeAwareEqualsImpl(Node node2) { // Do a non-recursive equivalents check. if (!isEquivalentTo(node2, true, false)) { return new NodeMismatch(this, node2); } NodeMismatch res = null; Node n, n2; for (n = first, n2 = node2.first; res == null && n != null; n = n.next, n2 = n2.next) { res = n.checkTreeTypeAwareEqualsImpl(n2); if (res != null) { return res; } } return res; } public static String tokenToName(int token) { switch (token) { case Token.ERROR: return "error"; case Token.EOF: return "eof"; case Token.EOL: return "eol"; case Token.ENTERWITH: return "enterwith"; case Token.LEAVEWITH: return "leavewith"; case Token.RETURN: return "return"; case Token.GOTO: return "goto"; case Token.IFEQ: return "ifeq"; case Token.IFNE: return "ifne"; case Token.SETNAME: return "setname"; case Token.BITOR: return "bitor"; case Token.BITXOR: return "bitxor"; case Token.BITAND: return "bitand"; case Token.EQ: return "eq"; case Token.NE: return "ne"; case Token.LT: return "lt"; case Token.LE: return "le"; case Token.GT: return "gt"; case Token.GE: return "ge"; case Token.LSH: return "lsh"; case Token.RSH: return "rsh"; case Token.URSH: return "ursh"; case Token.ADD: return "add"; case Token.SUB: return "sub"; case Token.MUL: return "mul"; case Token.DIV: return "div"; case Token.MOD: return "mod"; case Token.BITNOT: return "bitnot"; case Token.NEG: return "neg"; case Token.NEW: return "new"; case Token.DELPROP: return "delprop"; case Token.TYPEOF: return "typeof"; case Token.GETPROP: return "getprop"; case Token.SETPROP: return "setprop"; case Token.GETELEM: return "getelem"; case Token.SETELEM: return "setelem"; case Token.CALL: return "call"; case Token.NAME: return "name"; case Token.NUMBER: return "number"; case Token.STRING: return "string"; case Token.NULL: return "null"; case Token.THIS: return "this"; case Token.FALSE: return "false"; case Token.TRUE: return "true"; case Token.SHEQ: return "sheq"; case Token.SHNE: return "shne"; case Token.REGEXP: return "regexp"; case Token.POS: return "pos"; case Token.BINDNAME: return "bindname"; case Token.THROW: return "throw"; case Token.IN: return "in"; case Token.INSTANCEOF: return "instanceof"; case Token.GETVAR: return "getvar"; case Token.SETVAR: return "setvar"; case Token.TRY: return "try"; case Token.TYPEOFNAME: return "typeofname"; case Token.THISFN: return "thisfn"; case Token.SEMI: return "semi"; case Token.LB: return "lb"; case Token.RB: return "rb"; case Token.LC: return "lc"; case Token.RC: return "rc"; case Token.LP: return "lp"; case Token.RP: return "rp"; case Token.COMMA: return "comma"; case Token.ASSIGN: return "assign"; case Token.ASSIGN_BITOR: return "assign_bitor"; case Token.ASSIGN_BITXOR: return "assign_bitxor"; case Token.ASSIGN_BITAND: return "assign_bitand"; case Token.ASSIGN_LSH: return "assign_lsh"; case Token.ASSIGN_RSH: return "assign_rsh"; case Token.ASSIGN_URSH: return "assign_ursh"; case Token.ASSIGN_ADD: return "assign_add"; case Token.ASSIGN_SUB: return "assign_sub"; case Token.ASSIGN_MUL: return "assign_mul"; case Token.ASSIGN_DIV: return "assign_div"; case Token.ASSIGN_MOD: return "assign_mod"; case Token.HOOK: return "hook"; case Token.COLON: return "colon"; case Token.OR: return "or"; case Token.AND: return "and"; case Token.INC: return "inc"; case Token.DEC: return "dec"; case Token.DOT: return "dot"; case Token.FUNCTION: return "function"; case Token.EXPORT: return "export"; case Token.IMPORT: return "import"; case Token.IF: return "if"; case Token.ELSE: return "else"; case Token.SWITCH: return "switch"; case Token.CASE: return "case"; case Token.DEFAULT: return "default"; case Token.WHILE: return "while"; case Token.DO: return "do"; case Token.FOR: return "for"; case Token.BREAK: return "break"; case Token.CONTINUE: return "continue"; case Token.VAR: return "var"; case Token.WITH: return "with"; case Token.CATCH: return "catch"; case Token.FINALLY: return "finally"; case Token.RESERVED: return "reserved"; case Token.NOT: return "not"; case Token.VOID: return "void"; case Token.BLOCK: return "block"; case Token.ARRAYLIT: return "arraylit"; case Token.OBJECTLIT: return "objectlit"; case Token.LABEL: return "label"; case Token.TARGET: return "target"; case Token.LOOP: return "loop"; case Token.EXPR_VOID: return "expr_void"; case Token.EXPR_RESULT: return "expr_result"; case Token.JSR: return "jsr"; case Token.SCRIPT: return "script"; case Token.EMPTY: return "empty"; case Token.GET_REF: return "get_ref"; case Token.REF_SPECIAL: return "ref_special"; } return "<unknown="+token+">"; } /** Returns true if this node is equivalent semantically to another */ public boolean isEquivalentTo(Node node) { return isEquivalentTo(node, false, true); } /** * Returns true if this node is equivalent semantically to another and * the types are equivalent. */ public boolean isEquivalentToTyped(Node node) { return isEquivalentTo(node, true, true); } /** * @param compareJsType Whether to compare the JSTypes of the nodes. * @param recurse Whether to compare the children of the current node, if * not only the the count of the children are compared. * @return Whether this node is equivalent semantically to the provided node. */ boolean isEquivalentTo(Node node, boolean compareJsType, boolean recurse) { if (type != node.getType() || getChildCount() != node.getChildCount() || getNodeClass(this) != getNodeClass(node)) { return false; } if (compareJsType && !JSType.isEquivalent(jsType, node.getJSType())) { return false; } if (type == Token.ARRAYLIT) { try { int[] indices1 = (int[]) getProp(Node.SKIP_INDEXES_PROP); int[] indices2 = (int[]) node.getProp(Node.SKIP_INDEXES_PROP); if (indices1 == null) { if (indices2 != null) { return false; } } else if (indices2 == null) { return false; } else if (indices1.length != indices2.length) { return false; } else { for (int i = 0; i < indices1.length; i++) { if (indices1[i] != indices2[i]) { return false; } } } } catch (Exception e) { return false; } } else if (type == Token.INC || type == Token.DEC) { int post1 = this.getIntProp(INCRDECR_PROP); int post2 = node.getIntProp(INCRDECR_PROP); if (post1 != post2) { return false; } } else if (type == Token.STRING) { int quoted1 = this.getIntProp(QUOTED_PROP); int quoted2 = node.getIntProp(QUOTED_PROP); if (quoted1 != quoted2) { return false; } } else if (type == Token.CALL) { if (this.getBooleanProp(FREE_CALL) != node.getBooleanProp(FREE_CALL)) { return false; } } if (recurse) { Node n, n2; for (n = first, n2 = node.first; n != null; n = n.next, n2 = n2.next) { if (!n.isEquivalentTo(n2, compareJsType, true)) { return false; } } } return true; } public boolean hasSideEffects() { switch (type) { case Token.EXPR_VOID: case Token.COMMA: if (last != null) return last.hasSideEffects(); else return true; case Token.HOOK: if (first == null || first.next == null || first.next.next == null) { Kit.codeBug(); } return first.next.hasSideEffects() && first.next.next.hasSideEffects(); case Token.ERROR: // Avoid cascaded error messages case Token.EXPR_RESULT: case Token.ASSIGN: case Token.ASSIGN_ADD: case Token.ASSIGN_SUB: case Token.ASSIGN_MUL: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITOR: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITAND: case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.ASSIGN_URSH: case Token.ENTERWITH: case Token.LEAVEWITH: case Token.RETURN: case Token.GOTO: case Token.IFEQ: case Token.IFNE: case Token.NEW: case Token.DELPROP: case Token.SETNAME: case Token.SETPROP: case Token.SETELEM: case Token.CALL: case Token.THROW: case Token.RETHROW: case Token.SETVAR: case Token.CATCH_SCOPE: case Token.RETURN_RESULT: case Token.SET_REF: case Token.DEL_REF: case Token.REF_CALL: case Token.TRY: case Token.SEMI: case Token.INC: case Token.DEC: case Token.EXPORT: case Token.IMPORT: case Token.IF: case Token.ELSE: case Token.SWITCH: case Token.WHILE: case Token.DO: case Token.FOR: case Token.BREAK: case Token.CONTINUE: case Token.VAR: case Token.CONST: case Token.WITH: case Token.CATCH: case Token.FINALLY: case Token.BLOCK: case Token.LABEL: case Token.TARGET: case Token.LOOP: case Token.JSR: case Token.SETPROP_OP: case Token.SETELEM_OP: case Token.LOCAL_BLOCK: case Token.SET_REF_OP: return true; default: return false; } } /** * This function takes a set of GETPROP nodes and produces a string that is * each property separated by dots. If the node ultimately under the left * sub-tree is not a simple name, this is not a valid qualified name. * * @return a null if this is not a qualified name, or a dot-separated string * of the name and properties. */ public String getQualifiedName() { if (type == Token.NAME) { return getString(); } else if (type == Token.GETPROP) { String left = getFirstChild().getQualifiedName(); if (left == null) { return null; } return left + "." + getLastChild().getString(); } else if (type == Token.THIS) { return "this"; } else { return null; } } /** * Returns whether a node corresponds to a simple or a qualified name, such as * <code>x</code> or <code>a.b.c</code> or <code>this.a</code>. */ public boolean isQualifiedName() { switch (getType()) { case Token.NAME: case Token.THIS: return true; case Token.GETPROP: return getFirstChild().isQualifiedName(); default: return false; } } /** * Returns whether a node corresponds to a simple or a qualified name without * a "this" reference, such as <code>a.b.c</code>, but not <code>this.a</code> * . */ public boolean isUnscopedQualifiedName() { switch (getType()) { case Token.NAME: return true; case Token.GETPROP: return getFirstChild().isUnscopedQualifiedName(); default: return false; } } // ========================================================================== // Mutators /** * Removes this node from its parent. Equivalent to: * node.getParent().removeChild(); */ public Node detachFromParent() { Preconditions.checkState(parent != null); parent.removeChild(this); return this; } /** * Removes the first child of Node. Equivalent to: * node.removeChild(node.getFirstChild()); * * @return The removed Node. */ public Node removeFirstChild() { Node child = first; if (child != null) { removeChild(child); } return child; } /** * @return A Node that is the head of the list of children. */ public Node removeChildren() { Node children = first; for (Node child = first; child != null; child = child.getNext()) { child.parent = null; } first = null; last = null; return children; } /** * Removes all children from this node and isolates the children from each * other. */ public void detachChildren() { for (Node child = first; child != null;) { Node nextChild = child.getNext(); child.parent = null; child.next = null; child = nextChild; } first = null; last = null; } public Node removeChildAfter(Node prev) { Preconditions.checkArgument(prev.parent == this, "prev is not a child of this node."); Preconditions.checkArgument(prev.next != null, "no next sibling."); Node child = prev.next; prev.next = child.next; if (child == last) last = prev; child.next = null; child.parent = null; return child; } /** * @return A detached clone of the Node, specifically excluding its children. */ public Node cloneNode() { Node result; try { result = (Node) super.clone(); // PropListItem lists are immutable and can be shared so there is no // need to clone them here. result.next = null; result.first = null; result.last = null; result.parent = null; } catch (CloneNotSupportedException e) { throw new RuntimeException(e.getMessage()); } return result; } /** * @return A detached clone of the Node and all its children. */ public Node cloneTree() { Node result = cloneNode(); for (Node n2 = getFirstChild(); n2 != null; n2 = n2.getNext()) { Node n2clone = n2.cloneTree(); n2clone.parent = result; if (result.last != null) { result.last.next = n2clone; } if (result.first == null) { result.first = n2clone; } result.last = n2clone; } return result; } /** * Copies source file and name information from the other * node given to the current node. Used for maintaining * debug information across node append and remove operations. * @return this */ public Node copyInformationFrom(Node other) { if (getProp(ORIGINALNAME_PROP) == null) { putProp(ORIGINALNAME_PROP, other.getProp(ORIGINALNAME_PROP)); } if (getProp(SOURCENAME_PROP) == null) { putProp(SOURCENAME_PROP, other.getProp(SOURCENAME_PROP)); sourcePosition = other.sourcePosition; } return this; } /** * Copies source file and name information from the other node to the * entire tree rooted at this node. * @return this */ public Node copyInformationFromForTree(Node other) { copyInformationFrom(other); for (Node child = getFirstChild(); child != null; child = child.getNext()) { child.copyInformationFromForTree(other); } return this; } //========================================================================== // Custom annotations public JSType getJSType() { return jsType; } public void setJSType(JSType jsType) { this.jsType = jsType; } public FileLevelJsDocBuilder getJsDocBuilderForNode() { return new FileLevelJsDocBuilder(); } /** * An inner class that provides back-door access to the license * property of the JSDocInfo property for this node. This is only * meant to be used for top level script nodes where the * {@link com.google.javascript.jscomp.parsing.JsDocInfoParser} needs to * be able to append directly to the top level node, not just the * current node. */ public class FileLevelJsDocBuilder { public void append(String fileLevelComment) { JSDocInfo jsDocInfo = getJSDocInfo(); if (jsDocInfo == null) { // TODO(user): Is there a way to determine whether to // parse the JsDoc documentation from here? jsDocInfo = new JSDocInfo(false); } String license = jsDocInfo.getLicense(); if (license == null) { license = ""; } jsDocInfo.setLicense(license + fileLevelComment); setJSDocInfo(jsDocInfo); } } /** * Get the {@link JSDocInfo} attached to this node. * @return the information or {@code null} if no JSDoc is attached to this * node */ public JSDocInfo getJSDocInfo() { return (JSDocInfo) getProp(JSDOC_INFO_PROP); } /** * Sets the {@link JSDocInfo} attached to this node. */ public void setJSDocInfo(JSDocInfo info) { putProp(JSDOC_INFO_PROP, info); } /** * Sets whether this node is a variable length argument node. This * method is meaningful only on {@link Token#NAME} nodes * used to define a {@link Token#FUNCTION}'s argument list. */ public void setVarArgs(boolean varArgs) { putBooleanProp(VAR_ARGS_NAME, varArgs); } /** * Returns whether this node is a variable length argument node. This * method's return value is meaningful only on {@link Token#NAME} nodes * used to define a {@link Token#FUNCTION}'s argument list. */ public boolean isVarArgs() { return getBooleanProp(VAR_ARGS_NAME); } /** * Sets whether this node is an optional argument node. This * method is meaningful only on {@link Token#NAME} nodes * used to define a {@link Token#FUNCTION}'s argument list. */ public void setOptionalArg(boolean optionalArg) { putBooleanProp(OPT_ARG_NAME, optionalArg); } /** * Returns whether this node is an optional argument node. This * method's return value is meaningful only on {@link Token#NAME} nodes * used to define a {@link Token#FUNCTION}'s argument list. */ public boolean isOptionalArg() { return getBooleanProp(OPT_ARG_NAME); } /** * Sets whether this is a synthetic block that should not be considered * a real source block. */ public void setIsSyntheticBlock(boolean val) { putBooleanProp(SYNTHETIC_BLOCK_PROP, val); } /** * Returns whether this is a synthetic block that should not be considered * a real source block. */ public boolean isSyntheticBlock() { return getBooleanProp(SYNTHETIC_BLOCK_PROP); } /** * Sets the ES5 directives on this node. */ public void setDirectives(Set<String> val) { putProp(DIRECTIVES, val); } /** * Returns the set of ES5 directives for this node. */ @SuppressWarnings("unchecked") public Set<String> getDirectives() { return (Set<String>) getProp(DIRECTIVES); } /** * Adds a warning to be suppressed. This is indistinguishable * from having a {@code @suppress} tag in the code. */ public void addSuppression(String warning) { if (getJSDocInfo() == null) { setJSDocInfo(new JSDocInfo(false)); } getJSDocInfo().addSuppression(warning); } /** * Sets whether this is a synthetic block that should not be considered * a real source block. */ public void setWasEmptyNode(boolean val) { putBooleanProp(EMPTY_BLOCK, val); } /** * Returns whether this is a synthetic block that should not be considered * a real source block. */ public boolean wasEmptyNode() { return getBooleanProp(EMPTY_BLOCK); } // There are four values of interest: // global state changes // this state changes // arguments state changes // whether the call throws an exception // locality of the result // We want a value of 0 to mean "global state changes and // unknown locality of result". final public static int FLAG_GLOBAL_STATE_UNMODIFIED = 1; final public static int FLAG_THIS_UNMODIFIED = 2; final public static int FLAG_ARGUMENTS_UNMODIFIED = 4; final public static int FLAG_NO_THROWS = 8; final public static int FLAG_LOCAL_RESULTS = 16; final public static int SIDE_EFFECTS_FLAGS_MASK = 31; final public static int SIDE_EFFECTS_ALL = 0; final public static int NO_SIDE_EFFECTS = FLAG_GLOBAL_STATE_UNMODIFIED | FLAG_THIS_UNMODIFIED | FLAG_ARGUMENTS_UNMODIFIED | FLAG_NO_THROWS; /** * Marks this function or constructor call's side effect flags. * This property is only meaningful for {@link Token#CALL} and * {@link Token#NEW} nodes. */ public void setSideEffectFlags(int flags) { Preconditions.checkArgument( getType() == Token.CALL || getType() == Token.NEW, "setIsNoSideEffectsCall only supports CALL and NEW nodes, got " + Token.name(getType())); putIntProp(SIDE_EFFECT_FLAGS, flags); } public void setSideEffectFlags(SideEffectFlags flags) { setSideEffectFlags(flags.valueOf()); } /** * Returns the side effects flags for this node. */ public int getSideEffectFlags() { return getIntProp(SIDE_EFFECT_FLAGS); } /** * A helper class for getting and setting the side-effect flags. * @author johnlenz@google.com (John Lenz) */ public static class SideEffectFlags { private int value = Node.SIDE_EFFECTS_ALL; public SideEffectFlags() { } public SideEffectFlags(int value) { this.value = value; } public int valueOf() { return value; } /** All side-effect occur and the returned results are non-local. */ public void setAllFlags() { value = Node.SIDE_EFFECTS_ALL; } /** No side-effects occur and the returned results are local. */ public void clearAllFlags() { value = Node.NO_SIDE_EFFECTS | Node.FLAG_LOCAL_RESULTS; } public boolean areAllFlagsSet() { return value == Node.SIDE_EFFECTS_ALL; } /** * Preserve the return result flag, but clear the others: * no global state change, no throws, no this change, no arguments change */ public void clearSideEffectFlags() { value |= Node.NO_SIDE_EFFECTS; } public void setMutatesGlobalState() { // Modify global means everything must be assumed to be modified. removeFlag(Node.FLAG_GLOBAL_STATE_UNMODIFIED); removeFlag(Node.FLAG_ARGUMENTS_UNMODIFIED); removeFlag(Node.FLAG_THIS_UNMODIFIED); } public void setThrows() { removeFlag(Node.FLAG_NO_THROWS); } public void setMutatesThis() { removeFlag(Node.FLAG_THIS_UNMODIFIED); } public void setMutatesArguments() { removeFlag(Node.FLAG_ARGUMENTS_UNMODIFIED); } public void setReturnsTainted() { removeFlag(Node.FLAG_LOCAL_RESULTS); } private void removeFlag(int flag) { value &= ~flag; } } /** * @return Whether the only side-effect is "modifies this" */ public boolean isOnlyModifiesThisCall() { return areBitFlagsSet( getSideEffectFlags() & Node.NO_SIDE_EFFECTS, Node.FLAG_GLOBAL_STATE_UNMODIFIED | Node.FLAG_ARGUMENTS_UNMODIFIED | Node.FLAG_NO_THROWS); } /** * Returns true if this node is a function or constructor call that * has no side effects. */ public boolean isNoSideEffectsCall() { return areBitFlagsSet(getSideEffectFlags(), NO_SIDE_EFFECTS); } /** * Returns true if this node is a function or constructor call that * returns a primitive or a local object (an object that has no other * references). */ public boolean isLocalResultCall() { return areBitFlagsSet(getSideEffectFlags(), FLAG_LOCAL_RESULTS); } /** * returns true if all the flags are set in value. */ private boolean areBitFlagsSet(int value, int flags) { return (value & flags) == flags; } /** * This should only be called for STRING nodes children of OBJECTLIT. */ public boolean isQuotedString() { return false; } /** * This should only be called for STRING nodes children of OBJECTLIT. */ public void setQuotedString() { Kit.codeBug(); } static class NodeMismatch { final Node nodeA; final Node nodeB; NodeMismatch(Node nodeA, Node nodeB) { this.nodeA = nodeA; this.nodeB = nodeB; } @Override public boolean equals(Object object) { if (object instanceof NodeMismatch) { NodeMismatch that = (NodeMismatch) object; return that.nodeA.equals(this.nodeA) && that.nodeB.equals(this.nodeB); } return false; } @Override public int hashCode() { return Objects.hashCode(nodeA, nodeB); } } }
nuxleus/closure-compiler
src/com/google/javascript/rhino/Node.java
Java
apache-2.0
70,611
package com.luyh.mytest; import android.support.v4.app.Fragment; /** * Created by luyh on 2016/4/5. */ public class BaseFragment extends Fragment { //Fragment延迟加载解决方案 @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if(getUserVisibleHint()){ onVisible(); } else { onInvisible(); } } protected void onVisible(){ } protected void onInvisible(){ } }
710224800/myTest
app/src/main/java/com/luyh/mytest/BaseFragment.java
Java
apache-2.0
523
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.simplesystemsmanagement.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.simplesystemsmanagement.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * DescribeInventoryDeletionsRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DescribeInventoryDeletionsRequestProtocolMarshaller implements Marshaller<Request<DescribeInventoryDeletionsRequest>, DescribeInventoryDeletionsRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("AmazonSSM.DescribeInventoryDeletions").serviceName("AWSSimpleSystemsManagement").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public DescribeInventoryDeletionsRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<DescribeInventoryDeletionsRequest> marshall(DescribeInventoryDeletionsRequest describeInventoryDeletionsRequest) { if (describeInventoryDeletionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<DescribeInventoryDeletionsRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, describeInventoryDeletionsRequest); protocolMarshaller.startMarshalling(); DescribeInventoryDeletionsRequestMarshaller.getInstance().marshall(describeInventoryDeletionsRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/DescribeInventoryDeletionsRequestProtocolMarshaller.java
Java
apache-2.0
2,897
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ioteventsdata.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Information used to update the detector (instance). * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/UpdateDetectorRequest" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateDetectorRequest implements Serializable, Cloneable, StructuredPojo { /** * <p> * The ID to assign to the detector update <code>"message"</code>. Each <code>"messageId"</code> must be unique * within each batch sent. * </p> */ private String messageId; /** * <p> * The name of the detector model that created the detectors (instances). * </p> */ private String detectorModelName; /** * <p> * The value of the input key attribute (identifying the device or system) that caused the creation of this detector * (instance). * </p> */ private String keyValue; /** * <p> * The new state, variable values, and timer settings of the detector (instance). * </p> */ private DetectorStateDefinition state; /** * <p> * The ID to assign to the detector update <code>"message"</code>. Each <code>"messageId"</code> must be unique * within each batch sent. * </p> * * @param messageId * The ID to assign to the detector update <code>"message"</code>. Each <code>"messageId"</code> must be * unique within each batch sent. */ public void setMessageId(String messageId) { this.messageId = messageId; } /** * <p> * The ID to assign to the detector update <code>"message"</code>. Each <code>"messageId"</code> must be unique * within each batch sent. * </p> * * @return The ID to assign to the detector update <code>"message"</code>. Each <code>"messageId"</code> must be * unique within each batch sent. */ public String getMessageId() { return this.messageId; } /** * <p> * The ID to assign to the detector update <code>"message"</code>. Each <code>"messageId"</code> must be unique * within each batch sent. * </p> * * @param messageId * The ID to assign to the detector update <code>"message"</code>. Each <code>"messageId"</code> must be * unique within each batch sent. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateDetectorRequest withMessageId(String messageId) { setMessageId(messageId); return this; } /** * <p> * The name of the detector model that created the detectors (instances). * </p> * * @param detectorModelName * The name of the detector model that created the detectors (instances). */ public void setDetectorModelName(String detectorModelName) { this.detectorModelName = detectorModelName; } /** * <p> * The name of the detector model that created the detectors (instances). * </p> * * @return The name of the detector model that created the detectors (instances). */ public String getDetectorModelName() { return this.detectorModelName; } /** * <p> * The name of the detector model that created the detectors (instances). * </p> * * @param detectorModelName * The name of the detector model that created the detectors (instances). * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateDetectorRequest withDetectorModelName(String detectorModelName) { setDetectorModelName(detectorModelName); return this; } /** * <p> * The value of the input key attribute (identifying the device or system) that caused the creation of this detector * (instance). * </p> * * @param keyValue * The value of the input key attribute (identifying the device or system) that caused the creation of this * detector (instance). */ public void setKeyValue(String keyValue) { this.keyValue = keyValue; } /** * <p> * The value of the input key attribute (identifying the device or system) that caused the creation of this detector * (instance). * </p> * * @return The value of the input key attribute (identifying the device or system) that caused the creation of this * detector (instance). */ public String getKeyValue() { return this.keyValue; } /** * <p> * The value of the input key attribute (identifying the device or system) that caused the creation of this detector * (instance). * </p> * * @param keyValue * The value of the input key attribute (identifying the device or system) that caused the creation of this * detector (instance). * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateDetectorRequest withKeyValue(String keyValue) { setKeyValue(keyValue); return this; } /** * <p> * The new state, variable values, and timer settings of the detector (instance). * </p> * * @param state * The new state, variable values, and timer settings of the detector (instance). */ public void setState(DetectorStateDefinition state) { this.state = state; } /** * <p> * The new state, variable values, and timer settings of the detector (instance). * </p> * * @return The new state, variable values, and timer settings of the detector (instance). */ public DetectorStateDefinition getState() { return this.state; } /** * <p> * The new state, variable values, and timer settings of the detector (instance). * </p> * * @param state * The new state, variable values, and timer settings of the detector (instance). * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateDetectorRequest withState(DetectorStateDefinition state) { setState(state); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getMessageId() != null) sb.append("MessageId: ").append(getMessageId()).append(","); if (getDetectorModelName() != null) sb.append("DetectorModelName: ").append(getDetectorModelName()).append(","); if (getKeyValue() != null) sb.append("KeyValue: ").append(getKeyValue()).append(","); if (getState() != null) sb.append("State: ").append(getState()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateDetectorRequest == false) return false; UpdateDetectorRequest other = (UpdateDetectorRequest) obj; if (other.getMessageId() == null ^ this.getMessageId() == null) return false; if (other.getMessageId() != null && other.getMessageId().equals(this.getMessageId()) == false) return false; if (other.getDetectorModelName() == null ^ this.getDetectorModelName() == null) return false; if (other.getDetectorModelName() != null && other.getDetectorModelName().equals(this.getDetectorModelName()) == false) return false; if (other.getKeyValue() == null ^ this.getKeyValue() == null) return false; if (other.getKeyValue() != null && other.getKeyValue().equals(this.getKeyValue()) == false) return false; if (other.getState() == null ^ this.getState() == null) return false; if (other.getState() != null && other.getState().equals(this.getState()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMessageId() == null) ? 0 : getMessageId().hashCode()); hashCode = prime * hashCode + ((getDetectorModelName() == null) ? 0 : getDetectorModelName().hashCode()); hashCode = prime * hashCode + ((getKeyValue() == null) ? 0 : getKeyValue().hashCode()); hashCode = prime * hashCode + ((getState() == null) ? 0 : getState().hashCode()); return hashCode; } @Override public UpdateDetectorRequest clone() { try { return (UpdateDetectorRequest) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.ioteventsdata.model.transform.UpdateDetectorRequestMarshaller.getInstance().marshall(this, protocolMarshaller); } }
aws/aws-sdk-java
aws-java-sdk-ioteventsdata/src/main/java/com/amazonaws/services/ioteventsdata/model/UpdateDetectorRequest.java
Java
apache-2.0
10,485
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.mediastore.model; import javax.annotation.Generated; /** * <p> * The CORS policy that you specified in the request does not exist. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CorsPolicyNotFoundException extends com.amazonaws.services.mediastore.model.AWSMediaStoreException { private static final long serialVersionUID = 1L; /** * Constructs a new CorsPolicyNotFoundException with the specified error message. * * @param message * Describes the error encountered. */ public CorsPolicyNotFoundException(String message) { super(message); } }
aws/aws-sdk-java
aws-java-sdk-mediastore/src/main/java/com/amazonaws/services/mediastore/model/CorsPolicyNotFoundException.java
Java
apache-2.0
1,251
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.vfs2.util; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.Locale; import java.util.Properties; import java.util.ResourceBundle; /** * @since 2.0 */ public class CombinedResources extends ResourceBundle { // locale.getLanguage() // locale.getCountry() // locale.getVariant() private final String resourceName; private boolean inited; private final Properties properties = new Properties(); public CombinedResources(final String resourceName) { this.resourceName = resourceName; } protected void init() { if (inited) { return; } loadResources(getResourceName()); loadResources(Locale.getDefault()); loadResources(getLocale()); inited = true; } protected void loadResources(final Locale locale) { if (locale == null) { return; } final String[] parts = new String[] { locale.getLanguage(), locale.getCountry(), locale.getVariant() }; final StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) { sb.append(getResourceName()); for (int j = 0; j < i; j++) { sb.append('_').append(parts[j]); } if (parts[i].length() != 0) { sb.append('_').append(parts[i]); loadResources(sb.toString()); } sb.setLength(0); } } protected void loadResources(String resourceName) { ClassLoader loader = getClass().getClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } resourceName = resourceName.replace('.', '/') + ".properties"; try { final Enumeration<URL> resources = loader.getResources(resourceName); while (resources.hasMoreElements()) { final URL resource = resources.nextElement(); try { properties.load(resource.openConnection().getInputStream()); } catch (final IOException ignored) { /* Ignored. */ } } } catch (final IOException ignored) { /* Ignored. */ } } public String getResourceName() { return resourceName; } @Override public Enumeration<String> getKeys() { if (!inited) { init(); } return new Enumeration<String>() { @Override public boolean hasMoreElements() { return properties.keys().hasMoreElements(); } @Override public String nextElement() { // We know that our properties will only ever contain Strings return (String) properties.keys().nextElement(); } }; } @Override protected Object handleGetObject(final String key) { if (!inited) { init(); } return properties.get(key); } }
wso2/wso2-commons-vfs
commons-vfs2/src/main/java/org/apache/commons/vfs2/util/CombinedResources.java
Java
apache-2.0
3,885
package com.innerfunction.semo.test; import com.innerfunction.semo.Container; import com.innerfunction.semo.IOCConfigurable; public class IOCConfigurableImplementation implements IOCConfigurable{ public String value; public boolean beforeConfigureCalled = false; public boolean afterConfigureCalled = false; @Override public void beforeConfigure(Container container) { beforeConfigureCalled = (value == null); } @Override public void afterConfigure(Container container) { afterConfigureCalled = (value != null); } public void setValue(String value) { this.value = value; } }
innerfunction/semo-core-and
src/com/innerfunction/semo/test/IOCConfigurableImplementation.java
Java
apache-2.0
657
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.api.java.io.jdbc.catalog; import org.apache.flink.util.StringUtils; import java.util.Objects; import static org.apache.flink.util.Preconditions.checkArgument; /** * Table path of PostgreSQL in Flink. Can be of formats "table_name" or "schema_name.table_name". * When it's "table_name", the schema name defaults to "public". */ public class PostgresTablePath { private static final String DEFAULT_POSTGRES_SCHEMA_NAME = "public"; private final String pgSchemaName; private final String pgTableName; public PostgresTablePath(String pgSchemaName, String pgTableName) { checkArgument(!StringUtils.isNullOrWhitespaceOnly(pgSchemaName)); checkArgument(!StringUtils.isNullOrWhitespaceOnly(pgTableName)); this.pgSchemaName = pgSchemaName; this.pgTableName = pgTableName; } public static PostgresTablePath fromFlinkTableName(String flinkTableName) { if (flinkTableName.contains(".")) { String[] path = flinkTableName.split("\\."); checkArgument(path != null && path.length == 2, String.format("Table name '%s' is not valid. The parsed length is %d", flinkTableName, path.length)); return new PostgresTablePath(path[0], path[1]); } else { return new PostgresTablePath(DEFAULT_POSTGRES_SCHEMA_NAME, flinkTableName); } } public static String toFlinkTableName(String schema, String table) { return new PostgresTablePath(schema, table).getFullPath(); } public String getFullPath() { return String.format("%s.%s", pgSchemaName, pgTableName); } @Override public String toString() { return getFullPath(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PostgresTablePath that = (PostgresTablePath) o; return Objects.equals(pgSchemaName, that.pgSchemaName) && Objects.equals(pgTableName, that.pgTableName); } @Override public int hashCode() { return Objects.hash(pgSchemaName, pgTableName); } }
bowenli86/flink
flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/catalog/PostgresTablePath.java
Java
apache-2.0
2,802
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.cache.lucene.internal.cli; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang.StringUtils; import org.springframework.shell.core.annotation.CliAvailabilityIndicator; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.apache.geode.cache.execute.Execution; import org.apache.geode.cache.execute.Function; import org.apache.geode.cache.execute.ResultCollector; import org.apache.geode.cache.lucene.internal.cli.functions.LuceneCreateIndexFunction; import org.apache.geode.cache.lucene.internal.cli.functions.LuceneDescribeIndexFunction; import org.apache.geode.cache.lucene.internal.cli.functions.LuceneDestroyIndexFunction; import org.apache.geode.cache.lucene.internal.cli.functions.LuceneListIndexFunction; import org.apache.geode.cache.lucene.internal.cli.functions.LuceneSearchIndexFunction; import org.apache.geode.cache.lucene.internal.security.LucenePermission; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.execute.AbstractExecution; import org.apache.geode.management.cli.CliMetaData; import org.apache.geode.management.cli.ConverterHint; import org.apache.geode.management.cli.Result; import org.apache.geode.management.internal.cli.CliUtil; import org.apache.geode.management.internal.cli.commands.GfshCommand; import org.apache.geode.management.internal.cli.exceptions.UserErrorException; import org.apache.geode.management.internal.cli.functions.CliFunctionResult; import org.apache.geode.management.internal.cli.i18n.CliStrings; import org.apache.geode.management.internal.cli.result.CommandResult; import org.apache.geode.management.internal.cli.result.CommandResultException; import org.apache.geode.management.internal.cli.result.ResultBuilder; import org.apache.geode.management.internal.cli.result.TabularResultData; import org.apache.geode.management.internal.cli.shell.Gfsh; import org.apache.geode.management.internal.configuration.domain.XmlEntity; import org.apache.geode.security.ResourcePermission.Operation; import org.apache.geode.security.ResourcePermission.Resource; /** * The LuceneIndexCommands class encapsulates all Geode shell (Gfsh) commands related to Lucene * indexes defined in Geode. * * @see GfshCommand * @see LuceneIndexDetails * @see LuceneListIndexFunction */ @SuppressWarnings("unused") public class LuceneIndexCommands implements GfshCommand { private static final LuceneCreateIndexFunction createIndexFunction = new LuceneCreateIndexFunction(); private static final LuceneDescribeIndexFunction describeIndexFunction = new LuceneDescribeIndexFunction(); private static final LuceneSearchIndexFunction searchIndexFunction = new LuceneSearchIndexFunction(); private static final LuceneDestroyIndexFunction destroyIndexFunction = new LuceneDestroyIndexFunction(); private List<LuceneSearchResults> searchResults = null; @CliCommand(value = LuceneCliStrings.LUCENE_LIST_INDEX, help = LuceneCliStrings.LUCENE_LIST_INDEX__HELP) @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA}) public Result listIndex(@CliOption(key = LuceneCliStrings.LUCENE_LIST_INDEX__STATS, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = LuceneCliStrings.LUCENE_LIST_INDEX__STATS__HELP) final boolean stats) { getSecurityService().authorize(Resource.CLUSTER, Operation.READ, LucenePermission.TARGET); return toTabularResult(getIndexListing(), stats); } @SuppressWarnings("unchecked") protected List<LuceneIndexDetails> getIndexListing() { final Execution functionExecutor = getMembersFunctionExecutor(getAllMembers(getCache())); if (functionExecutor instanceof AbstractExecution) { ((AbstractExecution) functionExecutor).setIgnoreDepartedMembers(true); } final ResultCollector resultsCollector = functionExecutor.execute(new LuceneListIndexFunction()); final List<Set<LuceneIndexDetails>> results = (List<Set<LuceneIndexDetails>>) resultsCollector.getResult(); List<LuceneIndexDetails> sortedResults = results.stream().flatMap(Collection::stream).sorted().collect(Collectors.toList()); LinkedHashSet<LuceneIndexDetails> uniqResults = new LinkedHashSet<>(); uniqResults.addAll(sortedResults); sortedResults.clear(); sortedResults.addAll(uniqResults); return sortedResults; } protected Result toTabularResult(final List<LuceneIndexDetails> indexDetailsList, boolean stats) { if (!indexDetailsList.isEmpty()) { final TabularResultData indexData = ResultBuilder.createTabularResultData(); for (final LuceneIndexDetails indexDetails : indexDetailsList) { indexData.accumulate("Index Name", indexDetails.getIndexName()); indexData.accumulate("Region Path", indexDetails.getRegionPath()); indexData.accumulate("Server Name", indexDetails.getServerName()); indexData.accumulate("Indexed Fields", indexDetails.getSearchableFieldNamesString()); indexData.accumulate("Field Analyzer", indexDetails.getFieldAnalyzersString()); indexData.accumulate("Serializer", indexDetails.getSerializerString()); indexData.accumulate("Status", indexDetails.getInitialized() ? "Initialized" : "Defined"); if (stats) { if (!indexDetails.getInitialized()) { indexData.accumulate("Query Executions", "NA"); indexData.accumulate("Updates", "NA"); indexData.accumulate("Commits", "NA"); indexData.accumulate("Documents", "NA"); } else { indexData.accumulate("Query Executions", indexDetails.getIndexStats().get("queryExecutions")); indexData.accumulate("Updates", indexDetails.getIndexStats().get("updates")); indexData.accumulate("Commits", indexDetails.getIndexStats().get("commits")); indexData.accumulate("Documents", indexDetails.getIndexStats().get("documents")); } } } return ResultBuilder.buildResult(indexData); } else { return ResultBuilder .createInfoResult(LuceneCliStrings.LUCENE_LIST_INDEX__INDEXES_NOT_FOUND_MESSAGE); } } /** * On the server, we also verify the resource operation permissions CLUSTER:WRITE:DISK */ @CliCommand(value = LuceneCliStrings.LUCENE_CREATE_INDEX, help = LuceneCliStrings.LUCENE_CREATE_INDEX__HELP) @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA}) // TODO : Add optionContext for indexName public Result createIndex(@CliOption(key = LuceneCliStrings.LUCENE__INDEX_NAME, mandatory = true, help = LuceneCliStrings.LUCENE_CREATE_INDEX__NAME__HELP) final String indexName, @CliOption(key = LuceneCliStrings.LUCENE__REGION_PATH, mandatory = true, optionContext = ConverterHint.REGION_PATH, help = LuceneCliStrings.LUCENE_CREATE_INDEX__REGION_HELP) final String regionPath, @CliOption(key = LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, mandatory = true, help = LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD_HELP) final String[] fields, @CliOption(key = LuceneCliStrings.LUCENE_CREATE_INDEX__ANALYZER, help = LuceneCliStrings.LUCENE_CREATE_INDEX__ANALYZER_HELP) final String[] analyzers, @CliOption(key = LuceneCliStrings.LUCENE_CREATE_INDEX__SERIALIZER, help = LuceneCliStrings.LUCENE_CREATE_INDEX__SERIALIZER_HELP) final String serializer) throws CommandResultException { Result result; // Every lucene index potentially writes to disk. getSecurityService().authorize(Resource.CLUSTER, Operation.MANAGE, LucenePermission.TARGET); final InternalCache cache = getCache(); // trim fields for any leading trailing spaces. String[] trimmedFields = Arrays.stream(fields).map(String::trim).toArray(String[]::new); LuceneIndexInfo indexInfo = new LuceneIndexInfo(indexName, regionPath, trimmedFields, analyzers, serializer); final ResultCollector<?, ?> rc = this.executeFunctionOnAllMembers(createIndexFunction, indexInfo); final List<CliFunctionResult> funcResults = (List<CliFunctionResult>) rc.getResult(); final XmlEntity xmlEntity = funcResults.stream().filter(CliFunctionResult::isSuccessful) .map(CliFunctionResult::getXmlEntity).filter(Objects::nonNull).findFirst().orElse(null); final TabularResultData tabularResult = ResultBuilder.createTabularResultData(); for (final CliFunctionResult cliFunctionResult : funcResults) { tabularResult.accumulate("Member", cliFunctionResult.getMemberIdOrName()); if (cliFunctionResult.isSuccessful()) { tabularResult.accumulate("Status", "Successfully created lucene index"); } else { tabularResult.accumulate("Status", "Failed: " + cliFunctionResult.getMessage()); } } result = ResultBuilder.buildResult(tabularResult); if (xmlEntity != null) { persistClusterConfiguration(result, () -> { getSharedConfiguration().addXmlEntity(xmlEntity, null); }); } return result; } @CliCommand(value = LuceneCliStrings.LUCENE_DESCRIBE_INDEX, help = LuceneCliStrings.LUCENE_DESCRIBE_INDEX__HELP) @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA}) public Result describeIndex( @CliOption(key = LuceneCliStrings.LUCENE__INDEX_NAME, mandatory = true, help = LuceneCliStrings.LUCENE_DESCRIBE_INDEX__NAME__HELP) final String indexName, @CliOption(key = LuceneCliStrings.LUCENE__REGION_PATH, mandatory = true, optionContext = ConverterHint.REGION_PATH, help = LuceneCliStrings.LUCENE_DESCRIBE_INDEX__REGION_HELP) final String regionPath) throws Exception { getSecurityService().authorize(Resource.CLUSTER, Operation.READ, LucenePermission.TARGET); LuceneIndexInfo indexInfo = new LuceneIndexInfo(indexName, regionPath); return toTabularResult(getIndexDetails(indexInfo), true); } @SuppressWarnings("unchecked") protected List<LuceneIndexDetails> getIndexDetails(LuceneIndexInfo indexInfo) throws Exception { final ResultCollector<?, ?> rc = executeFunctionOnRegion(describeIndexFunction, indexInfo, true); final List<LuceneIndexDetails> funcResults = (List<LuceneIndexDetails>) rc.getResult(); return funcResults.stream().filter(Objects::nonNull).collect(Collectors.toList()); } /** * Internally, we verify the resource operation permissions DATA:READ:[RegionName] */ @CliCommand(value = LuceneCliStrings.LUCENE_SEARCH_INDEX, help = LuceneCliStrings.LUCENE_SEARCH_INDEX__HELP) @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA}) public Result searchIndex(@CliOption(key = LuceneCliStrings.LUCENE__INDEX_NAME, mandatory = true, help = LuceneCliStrings.LUCENE_SEARCH_INDEX__NAME__HELP) final String indexName, @CliOption(key = LuceneCliStrings.LUCENE__REGION_PATH, mandatory = true, optionContext = ConverterHint.REGION_PATH, help = LuceneCliStrings.LUCENE_SEARCH_INDEX__REGION_HELP) final String regionPath, @CliOption( key = {LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRING, LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRINGS}, mandatory = true, help = LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRING__HELP) final String queryString, @CliOption(key = LuceneCliStrings.LUCENE_SEARCH_INDEX__DEFAULT_FIELD, mandatory = true, help = LuceneCliStrings.LUCENE_SEARCH_INDEX__DEFAULT_FIELD__HELP) final String defaultField, @CliOption(key = LuceneCliStrings.LUCENE_SEARCH_INDEX__LIMIT, unspecifiedDefaultValue = "-1", help = LuceneCliStrings.LUCENE_SEARCH_INDEX__LIMIT__HELP) final int limit, @CliOption(key = LuceneCliStrings.LUCENE_SEARCH_INDEX__KEYSONLY, unspecifiedDefaultValue = "false", help = LuceneCliStrings.LUCENE_SEARCH_INDEX__KEYSONLY__HELP) boolean keysOnly) throws Exception { getSecurityService().authorize(Resource.DATA, Operation.READ, regionPath); LuceneQueryInfo queryInfo = new LuceneQueryInfo(indexName, regionPath, queryString, defaultField, limit, keysOnly); int pageSize = Integer.MAX_VALUE; searchResults = getSearchResults(queryInfo); return displayResults(pageSize, keysOnly); } @CliCommand(value = LuceneCliStrings.LUCENE_DESTROY_INDEX, help = LuceneCliStrings.LUCENE_DESTROY_INDEX__HELP) @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA}) public Result destroyIndex(@CliOption(key = LuceneCliStrings.LUCENE__INDEX_NAME, help = LuceneCliStrings.LUCENE_DESTROY_INDEX__NAME__HELP) final String indexName, @CliOption(key = LuceneCliStrings.LUCENE__REGION_PATH, mandatory = true, optionContext = ConverterHint.REGION_PATH, help = LuceneCliStrings.LUCENE_DESTROY_INDEX__REGION_HELP) final String regionPath) { if (indexName != null && StringUtils.isEmpty(indexName)) { return ResultBuilder.createInfoResult( CliStrings.format(LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__INDEX_CANNOT_BE_EMPTY)); } getSecurityService().authorize(Resource.CLUSTER, Operation.MANAGE, LucenePermission.TARGET); Result result; List<CliFunctionResult> accumulatedResults = new ArrayList<>(); final XmlEntity xmlEntity = executeDestroyIndexFunction(accumulatedResults, indexName, regionPath); result = getDestroyIndexResult(accumulatedResults, indexName, regionPath); if (xmlEntity != null) { persistClusterConfiguration(result, () -> { // Delete the xml entity to remove the index(es) in all groups getSharedConfiguration().deleteXmlEntity(xmlEntity, null); }); } return result; } private XmlEntity executeDestroyIndexFunction(List<CliFunctionResult> accumulatedResults, String indexName, String regionPath) { // Destroy has three cases: // // - no members define the region // In this case, send the request to all members to handle the case where the index has been // created, but not the region // // - all members define the region // In this case, send the request to one of the region members to destroy the index on all // member // // - some members define the region; some don't // In this case, send the request to one of the region members to destroy the index in all the // region members. Then send the function to the remaining members to handle the case where // the index has been created, but not the region XmlEntity xmlEntity = null; InternalCache cache = getCache(); Set<DistributedMember> regionMembers = findMembersForRegion(cache, regionPath); Set<DistributedMember> normalMembers = getAllNormalMembers(cache); LuceneDestroyIndexInfo indexInfo = new LuceneDestroyIndexInfo(indexName, regionPath); ResultCollector<?, ?> rc; if (regionMembers.isEmpty()) { // Attempt to destroy the proxy index on all members indexInfo.setDefinedDestroyOnly(true); rc = executeFunction(destroyIndexFunction, indexInfo, normalMembers); accumulatedResults.addAll((List<CliFunctionResult>) rc.getResult()); } else { // Attempt to destroy the index on a region member indexInfo.setDefinedDestroyOnly(false); Set<DistributedMember> singleMember = new HashSet<>(); singleMember.add(regionMembers.iterator().next()); rc = executeFunction(destroyIndexFunction, indexInfo, singleMember); List<CliFunctionResult> cliFunctionResults = (List<CliFunctionResult>) rc.getResult(); CliFunctionResult cliFunctionResult = cliFunctionResults.get(0); xmlEntity = cliFunctionResult.getXmlEntity(); for (DistributedMember regionMember : regionMembers) { accumulatedResults.add(new CliFunctionResult(regionMember.getId(), cliFunctionResult.isSuccessful(), cliFunctionResult.getMessage())); } // If that succeeds, destroy the proxy index(es) on all other members if necessary if (cliFunctionResult.isSuccessful()) { normalMembers.removeAll(regionMembers); if (!normalMembers.isEmpty()) { indexInfo.setDefinedDestroyOnly(true); rc = executeFunction(destroyIndexFunction, indexInfo, normalMembers); accumulatedResults.addAll((List<CliFunctionResult>) rc.getResult()); } } else { // @todo Should dummy results be added to the accumulatedResults for the non-region // members in the failed case } } return xmlEntity; } private Result getDestroyIndexResult(List<CliFunctionResult> cliFunctionResults, String indexName, String regionPath) { final TabularResultData tabularResult = ResultBuilder.createTabularResultData(); for (CliFunctionResult cliFunctionResult : cliFunctionResults) { tabularResult.accumulate("Member", cliFunctionResult.getMemberIdOrName()); if (cliFunctionResult.isSuccessful()) { tabularResult.accumulate("Status", indexName == null ? CliStrings.format( LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__SUCCESSFULLY_DESTROYED_INDEXES_FROM_REGION_0, new Object[] {regionPath}) : CliStrings.format( LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__SUCCESSFULLY_DESTROYED_INDEX_0_FROM_REGION_1, new Object[] {indexName, regionPath})); } else { tabularResult.accumulate("Status", cliFunctionResult.getMessage()); } } return ResultBuilder.buildResult(tabularResult); } private Result displayResults(int pageSize, boolean keysOnly) throws Exception { if (searchResults.size() == 0) { return ResultBuilder .createInfoResult(LuceneCliStrings.LUCENE_SEARCH_INDEX__NO_RESULTS_MESSAGE); } Gfsh gfsh = initGfsh(); boolean pagination = searchResults.size() > pageSize; int fromIndex = 0; int toIndex = pageSize < searchResults.size() ? pageSize : searchResults.size(); int currentPage = 1; int totalPages = (int) Math.ceil((float) searchResults.size() / pageSize); boolean skipDisplay = false; String step = null; do { if (!skipDisplay) { CommandResult commandResult = (CommandResult) getResults(fromIndex, toIndex, keysOnly); if (!pagination) { return commandResult; } Gfsh.println(); while (commandResult.hasNextLine()) { gfsh.printAsInfo(commandResult.nextLine()); } gfsh.printAsInfo("\t\tPage " + currentPage + " of " + totalPages); String message = ("Press n to move to next page, q to quit and p to previous page : "); step = gfsh.interact(message); } switch (step) { case "n": { if (currentPage == totalPages) { gfsh.printAsInfo("No more results to display."); step = gfsh.interact("Press p to move to last page and q to quit."); skipDisplay = true; continue; } if (skipDisplay) { skipDisplay = false; } else { currentPage++; int current = fromIndex; fromIndex = toIndex; toIndex = (pageSize + fromIndex >= searchResults.size()) ? searchResults.size() : pageSize + fromIndex; } break; } case "p": { if (currentPage == 1) { gfsh.printAsInfo("At the top of the search results."); step = gfsh.interact("Press n to move to the first page and q to quit."); skipDisplay = true; continue; } if (skipDisplay) { skipDisplay = false; } else { currentPage--; int current = fromIndex; toIndex = fromIndex; fromIndex = current - pageSize <= 0 ? 0 : current - pageSize; } break; } case "q": return ResultBuilder.createInfoResult("Search complete."); default: Gfsh.println("Invalid option"); break; } } while (true); } protected Gfsh initGfsh() { return Gfsh.getCurrentInstance(); } private List<LuceneSearchResults> getSearchResults(final LuceneQueryInfo queryInfo) throws Exception { final String[] groups = {}; final ResultCollector<?, ?> rc = this.executeSearch(queryInfo); final List<Set<LuceneSearchResults>> functionResults = (List<Set<LuceneSearchResults>>) rc.getResult(); return functionResults.stream().flatMap(Collection::stream).sorted() .collect(Collectors.toList()); } private Result getResults(int fromIndex, int toIndex, boolean keysonly) throws Exception { final TabularResultData data = ResultBuilder.createTabularResultData(); for (int i = fromIndex; i < toIndex; i++) { if (!searchResults.get(i).getExceptionFlag()) { data.accumulate("key", searchResults.get(i).getKey()); if (!keysonly) { data.accumulate("value", searchResults.get(i).getValue()); data.accumulate("score", searchResults.get(i).getScore()); } } else { throw new UserErrorException(searchResults.get(i).getExceptionMessage()); } } return ResultBuilder.buildResult(data); } protected ResultCollector<?, ?> executeFunctionOnAllMembers(Function function, final LuceneFunctionSerializable functionArguments) throws IllegalArgumentException, CommandResultException { Set<DistributedMember> targetMembers = CliUtil.getAllNormalMembers(getCache()); return executeFunction(function, functionArguments, targetMembers); } protected ResultCollector<?, ?> executeSearch(final LuceneQueryInfo queryInfo) throws Exception { return executeFunctionOnRegion(searchIndexFunction, queryInfo, false); } protected ResultCollector<?, ?> executeFunctionOnRegion(Function function, LuceneFunctionSerializable functionArguments, boolean returnAllMembers) { Set<DistributedMember> targetMembers = CliUtil.getRegionAssociatedMembers( functionArguments.getRegionPath(), getCache(), returnAllMembers); if (targetMembers.isEmpty()) { throw new UserErrorException(CliStrings.format( LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__COULDNOT_FIND_MEMBERS_FOR_REGION_0, new Object[] {functionArguments.getRegionPath()})); } return executeFunction(function, functionArguments, targetMembers); } @CliAvailabilityIndicator({LuceneCliStrings.LUCENE_SEARCH_INDEX, LuceneCliStrings.LUCENE_CREATE_INDEX, LuceneCliStrings.LUCENE_DESCRIBE_INDEX, LuceneCliStrings.LUCENE_LIST_INDEX, LuceneCliStrings.LUCENE_DESTROY_INDEX}) public boolean indexCommandsAvailable() { Gfsh gfsh = Gfsh.getCurrentInstance(); // command should always be available on the server if (gfsh == null) { return true; } // if in gfshVM, only when gfsh is connected and ready return gfsh.isConnectedAndReady(); } }
smanvi-pivotal/geode
geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommands.java
Java
apache-2.0
24,331
package pl.tecna.gwt.connectors.client; import com.google.gwt.user.client.ui.FocusPanel; public class Point extends FocusPanel implements Comparable<Point> { protected Integer top; protected Integer left; public Point(Integer left, Integer top) { super(); this.left = left; this.top = top; } public void showOnDiagram() { } public void initPosition(Integer left, Integer top) { this.left = left; this.top = top; } public void setLeftPosition(Integer left) { setPosition(left, top); } public void setTopPosition(Integer top) { setPosition(left, top); } public void setPosition(Integer left, Integer top) { this.left = left; this.top = top; } public Integer getTop() { return top; } public Integer getLeft() { return left; } public String toDebugString() { return "top:" + top + " left:" + left; } /** * Compares two points using their left and top values. <br> * If values are equal 0 is returned. If values are not eqal, sumary of absolute differences * between points is returned. */ public int compareTo(Point o) { int leftCompare = o.getLeft().compareTo(this.getLeft()); int topCompare = o.getTop().compareTo(this.getTop()); if (leftCompare == 0 && topCompare == 0) { return 0; } else { return Math.abs(leftCompare) + Math.abs(topCompare); } } @Override public String toString() { return "top:" + top + " left:" + left; } }
robertwaszkowski/gwt-connectors
src/main/java/pl/tecna/gwt/connectors/client/Point.java
Java
apache-2.0
1,507
/** * Copyright 2012 A24Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ssgwt.client.ui.datagrid; import org.ssgwt.client.ui.datagrid.event.ISelectAllEventHandler; import org.ssgwt.client.ui.datagrid.event.SelectAllEvent; import com.google.gwt.cell.client.AbstractCell; import com.google.gwt.cell.client.ValueUpdater; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.event.shared.HasHandlers; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.client.SafeHtmlTemplates; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Image; /** * The cell that is used to display a Header that allows filtering * * @author Michael Barnard * @since 3 July 2012 */ public class SelectAllCell extends AbstractCell<String> implements HasHandlers { /** * Instance of the template */ private static Template template; /** * Holds an instance of the default resources */ private static Resources DEFAULT_RESOURCES; /** * Flag indicating if the filter connected to the header is active */ private boolean filterActive = false; /** * Holds an instance of resources */ private Resources resources; /** * Holds the filter image that is displayed in the header */ private Image filterImage; /** * The handler manager used to handle events */ private HandlerManager handlerManager; private boolean doMouseOver = true; /** * Create an instance on the default resources object if it the * DEFAULT_RESOURCES variable is null if not it just return the object in * the DEFAULT_RESOURCES variable * * @return the default resource object */ private static Resources getDefaultResources() { if (DEFAULT_RESOURCES == null) { DEFAULT_RESOURCES = GWT.create(Resources.class); } return DEFAULT_RESOURCES; } /** * A ClientBundle that provides images for this widget. * * @author Michael Barnard * @since 03 July 2012 */ public interface Resources extends ClientBundle { @Source("images/Header_Select_All_down.png") ImageResource filterIconActive(); @Source("images/Header_Select_All_up.png") ImageResource filterIconInactive(); @Source("images/Header_Select_All_over.png") ImageResource filterIconOver(); @Source("images/Header_Select_All_down.png") ImageResource filterIconDown(); } /** * Template providing SafeHTML templates to build the widget * * @author Michael Barnard * @since 3 July 2012 */ interface Template extends SafeHtmlTemplates { @Template("<div style=\"\">") SafeHtml openContainerTag(); @Template("<img src=\"\" />") SafeHtml imageTag(); @Template("</div>") SafeHtml closeContainerTag(); } /** * Default class constructor */ public SelectAllCell() { this(getDefaultResources()); } /** * Class constructor that allows the user to use a custom resource * * @param resources - The resources object that should be used */ public SelectAllCell(Resources resources) { super("mousedown", "mouseover", "mouseout", "mouseup"); this.resources = resources; if (template == null) { template = GWT.create(Template.class); } handlerManager = new HandlerManager(this); } /** * The function that renders the content of the Cell */ @Override public void render(Context context, String value, SafeHtmlBuilder sb) { if (filterActive) { filterImage = new Image(resources.filterIconActive()); } else { filterImage = new Image(resources.filterIconInactive()); } sb.append(template.openContainerTag()); sb.appendHtmlConstant(filterImage.toString()); sb.append(template.closeContainerTag()); } /** * Handle a browser event that took place within the cell. The default * implementation returns null. * * @param context - the {@link Context} of the cell * @param parent - the parent Element * @param value - the value associated with the cell * @param event - the native browser event * @param valueUpdater - a {@link ValueUpdater}, or null if not specified */ @Override public void onBrowserEvent(Context context, Element parent, String value, NativeEvent event, ValueUpdater<String> valueUpdater) { super.onBrowserEvent(context, parent, value, event, valueUpdater); Element filterImageElement = getImageElement(parent); Element filterImageParentElement = filterImageElement.getParentElement(); if (event.getEventTarget().equals(filterImageElement)) { if ("mousedown".equals(event.getType())) { replaceImageElement(resources.filterIconDown(), filterImageElement, filterImageParentElement); } else if ("mouseover".equals(event.getType())) { if (doMouseOver && Window.Navigator.getAppName().equals("Microsoft Internet Explorer")) { doMouseOver = false; replaceImageElement(resources.filterIconOver(), filterImageElement, filterImageParentElement); } else if (!Window.Navigator.getAppName().equals("Microsoft Internet Explorer")) { replaceImageElement(resources.filterIconOver(), filterImageElement, filterImageParentElement); } } else if ("mouseout".equals(event.getType())) { if (Window.Navigator.getAppName().equals("Microsoft Internet Explorer")) { doMouseOver = true; } if (filterActive) { replaceImageElement(resources.filterIconActive(), filterImageElement, filterImageParentElement); } else { replaceImageElement(resources.filterIconInactive(), filterImageElement, filterImageParentElement); } } else if ("mouseup".equals(event.getType())) { replaceImageElement(resources.filterIconOver(), filterImageElement, filterImageParentElement); fireEvent(new SelectAllEvent()); } } } /** * This replaces the image that is displayed in the Cell * * @param newImage - The new image the should be displayed * @param elementToReplace - The image element that should be replaced * @param parentOfElementToReplace - The parent of the element that should be replaced */ public void replaceImageElement(ImageResource newImage, Element elementToReplace, Element parentOfElementToReplace) { filterImage.setResource(newImage); elementToReplace.removeFromParent(); parentOfElementToReplace.appendChild(filterImage.getElement()); } /** * Retrieves the element of the image that is being displayed in the Cell * * @param parent - The top level container of the Cell * * @return The element object that represents the image in the Cell */ protected Element getImageElement(Element parent) { return parent.getFirstChildElement().getElementsByTagName("img").getItem(0); } /** * This is used to fire an event * * @param event - The event that needs to be fired */ @Override public void fireEvent(GwtEvent<?> event) { handlerManager.fireEvent(event); } /** * Adds a handler to the handler manager * * @param handler - The handler to be added to the handle manager * @return The handle registration */ public HandlerRegistration addEventHandler( ISelectAllEventHandler handler) { return handlerManager.addHandler(SelectAllEvent.TYPE, handler); } }
A24Group/ssGWT-lib
src/org/ssgwt/client/ui/datagrid/SelectAllCell.java
Java
apache-2.0
8,900
package com.yaochen.boss.model; import com.ycsoft.beans.core.prod.CProd; public class CProdCycleDto extends CProd { private Boolean ismax;//是否最大到期日 private Integer public_balance;//公用账目余额 private Double invalid_date_num;//到期日按基准日期转换成数字 private Double tariff_rent_365;//按365天计算一天的资费 private Double exp_date_num;//失效日期转换成数字,如果exp_date为空,也设置为空 private Integer tariff_billing_cycle;//资费周期 private Double tariff_cycle_rent_365;//一个资费周期的资费 private Double invalid_cycle_num;//一个资费周期天数 private Double backup_invlaid_num;//备份周期的基准到期日 private Integer public_active_balance;//公用账目活动余额 private String public_acctitem_id;//公用账目ID private Double public_toprod_balance;//公用账目转账金额 private String public_acct_id; private String cust_no; private String cust_name; private String address; private String card_id; private String user_type; private Integer order_balance;//产品预约公用账目金额 public Double getPublic_toprod_balance() { return public_toprod_balance; } public void setPublic_toprod_balance(Double public_toprod_balance) { this.public_toprod_balance = public_toprod_balance; } public Double getTariff_cycle_rent_365() { return tariff_cycle_rent_365; } public void setTariff_cycle_rent_365(Double tariff_cycle_rent_365) { this.tariff_cycle_rent_365 = tariff_cycle_rent_365; } public Integer getTariff_billing_cycle() { return tariff_billing_cycle; } public void setTariff_billing_cycle(Integer tariff_billing_cycle) { this.tariff_billing_cycle = tariff_billing_cycle; } public Integer getPublic_balance() { return public_balance; } public void setPublic_balance(Integer public_balance) { this.public_balance = public_balance; } public Double getInvalid_date_num() { return invalid_date_num; } public void setInvalid_date_num(Double invalid_date_num) { this.invalid_date_num = invalid_date_num; } public Double getInvalid_cycle_num() { return invalid_cycle_num; } public void setInvalid_cycle_num(Double invalid_cycle_num) { this.invalid_cycle_num = invalid_cycle_num; } public Double getBackup_invlaid_num() { return backup_invlaid_num; } public void setBackup_invlaid_num(Double backup_invlaid_num) { this.backup_invlaid_num = backup_invlaid_num; } public Double getTariff_rent_365() { return tariff_rent_365; } public void setTariff_rent_365(Double tariff_rent_365) { this.tariff_rent_365 = tariff_rent_365; } public Double getExp_date_num() { return exp_date_num; } public void setExp_date_num(Double exp_date_num) { this.exp_date_num = exp_date_num; } public Boolean getIsmax() { return ismax; } public void setIsmax(Boolean ismax) { this.ismax = ismax; } public Integer getPublic_active_balance() { return public_active_balance; } public void setPublic_active_balance(Integer public_active_balance) { this.public_active_balance = public_active_balance; } public String getPublic_acctitem_id() { return public_acctitem_id; } public void setPublic_acctitem_id(String public_acctitem_id) { this.public_acctitem_id = public_acctitem_id; } public String getCust_no() { return cust_no; } public void setCust_no(String cust_no) { this.cust_no = cust_no; } public String getCust_name() { return cust_name; } public void setCust_name(String cust_name) { this.cust_name = cust_name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCard_id() { return card_id; } public void setCard_id(String card_id) { this.card_id = card_id; } public String getUser_type() { return user_type; } public void setUser_type(String user_type) { this.user_type = user_type; } public String getPublic_acct_id() { return public_acct_id; } public void setPublic_acct_id(String public_acct_id) { this.public_acct_id = public_acct_id; } public Integer getOrder_balance() { return order_balance; } public void setOrder_balance(Integer order_balance) { this.order_balance = order_balance; } }
leopardoooo/cambodia
boss-job/src/main/java/com/yaochen/boss/model/CProdCycleDto.java
Java
apache-2.0
4,399
/** * Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.pricer.cms; import static com.opengamma.strata.market.model.SabrParameterType.ALPHA; import static com.opengamma.strata.market.model.SabrParameterType.BETA; import static com.opengamma.strata.market.model.SabrParameterType.NU; import static com.opengamma.strata.market.model.SabrParameterType.RHO; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.OptionalDouble; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.strata.basics.currency.Currency; import com.opengamma.strata.basics.currency.CurrencyAmount; import com.opengamma.strata.collect.ArgChecker; import com.opengamma.strata.collect.Messages; import com.opengamma.strata.collect.array.DoubleArray; import com.opengamma.strata.market.explain.ExplainKey; import com.opengamma.strata.market.explain.ExplainMapBuilder; import com.opengamma.strata.market.sensitivity.PointSensitivityBuilder; import com.opengamma.strata.math.MathException; import com.opengamma.strata.math.impl.integration.RungeKuttaIntegrator1D; import com.opengamma.strata.pricer.impl.option.SabrExtrapolationRightFunction; import com.opengamma.strata.pricer.impl.volatility.smile.SabrFormulaData; import com.opengamma.strata.pricer.rate.RatesProvider; import com.opengamma.strata.pricer.swap.DiscountingSwapProductPricer; import com.opengamma.strata.pricer.swaption.SabrSwaptionVolatilities; import com.opengamma.strata.pricer.swaption.SwaptionSabrSensitivity; import com.opengamma.strata.pricer.swaption.SwaptionVolatilitiesName; import com.opengamma.strata.product.cms.CmsPeriod; import com.opengamma.strata.product.cms.CmsPeriodType; import com.opengamma.strata.product.common.PutCall; import com.opengamma.strata.product.swap.RatePaymentPeriod; import com.opengamma.strata.product.swap.ResolvedSwap; import com.opengamma.strata.product.swap.ResolvedSwapLeg; import com.opengamma.strata.product.swap.SwapIndex; import com.opengamma.strata.product.swap.SwapLegType; /** * Computes the price of a CMS coupon/caplet/floorlet by swaption replication on a shifted SABR formula with extrapolation. * <p> * The extrapolation is done on call prices above a certain strike. See {@link SabrExtrapolationRightFunction} for * more details on the extrapolation method. * <p> * The replication requires numerical integration. This is completed by {@link RungeKuttaIntegrator1D}. * <p> * The consistency between {@code RatesProvider} and {@code SabrParametersSwaptionVolatilities} is not checked in this * class, but validated only once in {@link SabrExtrapolationReplicationCmsLegPricer}. * <p> * Reference: Hagan, P. S. (2003). Convexity conundrums: Pricing CMS swaps, caps, and floors. * Wilmott Magazine, March, pages 38--44. * OpenGamma implementation note: Replication pricing for linear and TEC format CMS, Version 1.2, March 2011. * OpenGamma implementation note for the extrapolation: Smile extrapolation, version 1.2, May 2011. */ public class SabrExtrapolationReplicationCmsPeriodPricer { /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(SabrExtrapolationReplicationCmsPeriodPricer.class); /** * The minimal number of iterations for the numerical integration. */ private static final int NUM_ITER = 10; /** The relative tolerance for the numerical integration in PV computation. */ private static final double REL_TOL = 1.0e-10; /** The absolute tolerance for the numerical integration in PV computation. * The numerical integration stops when the difference between two steps is below the absolute tolerance * plus the relative tolerance multiplied by the value.*/ private static final double ABS_TOL = 1.0e-8; /** * The relative tolerance for the numerical integration in sensitivity computation. */ private static final double REL_TOL_STRIKE = 1e-5; /** * The relative tolerance for the numerical integration in sensitivity computation. */ private static final double REL_TOL_VEGA = 1e-3; /** * The maximum iteration count. */ private static final int MAX_COUNT = 10; /** * Shift from zero bound for floor. * To avoid numerical instability of the SABR function around 0. Shift by 0.01 bps. */ private static final double ZERO_SHIFT = 1e-6; /** * The minimal time for which the convexity adjustment is computed. The time is less than a day. * For expiry below that value, the forward rate is used for present value. */ private static final double MIN_TIME = 1e-4; /** * Pricer for the underlying swap. */ private final DiscountingSwapProductPricer swapPricer; /** * The cut-off strike. * <p> * The smile is extrapolated above that level. */ private final double cutOffStrike; /** * The tail thickness parameter. * <p> * This must be greater than 0 in order to ensure that the call price converges to 0 for infinite strike. */ private final double mu; //------------------------------------------------------------------------- /** * Obtains the pricer. * * @param swapPricer the pricer for underlying swap * @param cutOffStrike the cut-off strike value * @param mu the tail thickness * @return the pricer */ public static SabrExtrapolationReplicationCmsPeriodPricer of( DiscountingSwapProductPricer swapPricer, double cutOffStrike, double mu) { return new SabrExtrapolationReplicationCmsPeriodPricer(swapPricer, cutOffStrike, mu); } /** * Obtains the pricer with default swap pricer. * * @param cutOffStrike the cut-off strike value * @param mu the tail thickness * @return the pricer */ public static SabrExtrapolationReplicationCmsPeriodPricer of(double cutOffStrike, double mu) { return of(DiscountingSwapProductPricer.DEFAULT, cutOffStrike, mu); } private SabrExtrapolationReplicationCmsPeriodPricer( DiscountingSwapProductPricer swapPricer, double cutOffStrike, double mu) { this.swapPricer = ArgChecker.notNull(swapPricer, "swapPricer"); this.cutOffStrike = cutOffStrike; this.mu = ArgChecker.notNegativeOrZero(mu, "mu"); } //------------------------------------------------------------------------- /** * Computes the present value by replication in SABR framework with extrapolation on the right. * * @param cmsPeriod the CMS * @param provider the rates provider * @param swaptionVolatilities the swaption volatilities * @return the present value */ public CurrencyAmount presentValue( CmsPeriod cmsPeriod, RatesProvider provider, SabrSwaptionVolatilities swaptionVolatilities) { Currency ccy = cmsPeriod.getCurrency(); if (provider.getValuationDate().isAfter(cmsPeriod.getPaymentDate())) { return CurrencyAmount.zero(ccy); } SwapIndex index = cmsPeriod.getIndex(); ResolvedSwap swap = cmsPeriod.getUnderlyingSwap(); double dfPayment = provider.discountFactor(ccy, cmsPeriod.getPaymentDate()); ZonedDateTime valuationDate = swaptionVolatilities.getValuationDateTime(); LocalDate fixingDate = cmsPeriod.getFixingDate(); double expiryTime = swaptionVolatilities.relativeTime( fixingDate.atTime(index.getFixingTime()).atZone(index.getFixingZone())); double tenor = swaptionVolatilities.tenor(swap.getStartDate(), swap.getEndDate()); double shift = swaptionVolatilities.shift(expiryTime, tenor); double strikeCpn = cmsPeriod.getCmsPeriodType().equals(CmsPeriodType.COUPON) ? -shift : cmsPeriod.getStrike(); if (!fixingDate.isAfter(valuationDate.toLocalDate())) { OptionalDouble fixedRate = provider.timeSeries(cmsPeriod.getIndex()).get(fixingDate); if (fixedRate.isPresent()) { double payoff = payOff(cmsPeriod.getCmsPeriodType(), strikeCpn, fixedRate.getAsDouble()); return CurrencyAmount.of(ccy, dfPayment * payoff * cmsPeriod.getNotional() * cmsPeriod.getYearFraction()); } else if (fixingDate.isBefore(valuationDate.toLocalDate())) { throw new IllegalArgumentException(Messages.format( "Unable to get fixing for {} on date {}, no time-series supplied", cmsPeriod.getIndex(), fixingDate)); } } double forward = swapPricer.parRate(swap, provider); if (expiryTime < MIN_TIME) { double payoff = payOff(cmsPeriod.getCmsPeriodType(), strikeCpn, forward); return CurrencyAmount.of(ccy, dfPayment * payoff * cmsPeriod.getNotional() * cmsPeriod.getYearFraction()); } double eta = index.getTemplate().getConvention().getFixedLeg().getDayCount() .relativeYearFraction(cmsPeriod.getPaymentDate(), swap.getStartDate()); CmsIntegrantProvider intProv = new CmsIntegrantProvider( cmsPeriod, swap, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor, cutOffStrike, eta); double factor = dfPayment / intProv.h(forward) * intProv.g(forward); double strikePart = factor * intProv.k(strikeCpn) * intProv.bs(strikeCpn); RungeKuttaIntegrator1D integrator = new RungeKuttaIntegrator1D(ABS_TOL, REL_TOL, NUM_ITER); double integralPart = 0d; Function<Double, Double> integrant = intProv.integrant(); try { if (intProv.getPutCall().isCall()) { integralPart = dfPayment * integrateCall(integrator, integrant, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor); } else { integralPart = -dfPayment * integrator.integrate(integrant, -shift + ZERO_SHIFT, strikeCpn); } } catch (Exception e) { throw new MathException(e); } double priceCMS = (strikePart + integralPart); if (cmsPeriod.getCmsPeriodType().equals(CmsPeriodType.COUPON)) { priceCMS -= dfPayment * shift; } priceCMS *= cmsPeriod.getNotional() * cmsPeriod.getYearFraction(); return CurrencyAmount.of(ccy, priceCMS); } /** * Computes the adjusted forward rate for a CMS coupon. * <p> * The adjusted forward rate, is the number such that, multiplied by the notional, the year fraction and the payment * date discount factor, it produces the present value. In other terms, it is the number which used in the same * formula used for Ibor coupon pricing will provide the correct present value. * <p> * For period already fixed, this number will be equal to the swap index fixing. * <p> * For cap or floor the result is the adjusted forward rate for the coupon equivalent to the cap/floor, * i.e. the coupon with the same dates and index but with no cap or floor strike. * * @param cmsPeriod the CMS period, which should be of the type {@link CmsPeriodType#COUPON} * @param provider the rates provider * @param swaptionVolatilities the swaption volatilities * @return the adjusted forward rate */ public double adjustedForwardRate( CmsPeriod cmsPeriod, RatesProvider provider, SabrSwaptionVolatilities swaptionVolatilities) { CmsPeriod coupon = cmsPeriod.toCouponEquivalent(); Currency ccy = cmsPeriod.getCurrency(); double dfPayment = provider.discountFactor(ccy, coupon.getPaymentDate()); double pv = presentValue(coupon, provider, swaptionVolatilities).getAmount(); return pv / (coupon.getNotional() * coupon.getYearFraction() * dfPayment); } /** * Computes the adjustment to the forward rate for a CMS coupon. * <p> * The adjustment to the forward rate, is the quantity that need to be added to the forward rate to obtain the * adjusted forward rate. The adjusted forward rate is the number which used in the same formula used for * Ibor coupon pricing (forward * notional * accrual factor * discount factor) will provide the correct present value. * <p> * For cap or floor the result is the adjustment to the forward rate for the coupon equivalent to the cap/floor, * i.e. the coupon with the same dates and index but with no cap or floor strike. * * @param cmsPeriod the CMS period, which should be of the type {@link CmsPeriodType#COUPON} * @param provider the rates provider * @param swaptionVolatilities the swaption volatilities * @return the adjusted forward rate */ public double adjustmentToForwardRate( CmsPeriod cmsPeriod, RatesProvider provider, SabrSwaptionVolatilities swaptionVolatilities) { CmsPeriod coupon = cmsPeriod.toCouponEquivalent(); double adjustedForwardRate = adjustedForwardRate(coupon, provider, swaptionVolatilities); double forward = swapPricer.parRate(coupon.getUnderlyingSwap(), provider); return adjustedForwardRate - forward; } //------------------------------------------------------------------------- /** * Computes the present value curve sensitivity by replication in SABR framework with extrapolation on the right. * * @param cmsPeriod the CMS * @param provider the rates provider * @param swaptionVolatilities the swaption volatilities * @return the present value sensitivity */ public PointSensitivityBuilder presentValueSensitivityRates( CmsPeriod cmsPeriod, RatesProvider provider, SabrSwaptionVolatilities swaptionVolatilities) { Currency ccy = cmsPeriod.getCurrency(); if (provider.getValuationDate().isAfter(cmsPeriod.getPaymentDate())) { return PointSensitivityBuilder.none(); } SwapIndex index = cmsPeriod.getIndex(); ResolvedSwap swap = cmsPeriod.getUnderlyingSwap(); double dfPayment = provider.discountFactor(ccy, cmsPeriod.getPaymentDate()); ZonedDateTime valuationDate = swaptionVolatilities.getValuationDateTime(); LocalDate fixingDate = cmsPeriod.getFixingDate(); double expiryTime = swaptionVolatilities.relativeTime( fixingDate.atTime(index.getFixingTime()).atZone(index.getFixingZone())); double tenor = swaptionVolatilities.tenor(swap.getStartDate(), swap.getEndDate()); double shift = swaptionVolatilities.shift(expiryTime, tenor); double strikeCpn = cmsPeriod.getCmsPeriodType().equals(CmsPeriodType.COUPON) ? -shift : cmsPeriod.getStrike(); if (!fixingDate.isAfter(valuationDate.toLocalDate())) { OptionalDouble fixedRate = provider.timeSeries(cmsPeriod.getIndex()).get(fixingDate); if (fixedRate.isPresent()) { double payoff = payOff(cmsPeriod.getCmsPeriodType(), strikeCpn, fixedRate.getAsDouble()); return provider.discountFactors(ccy).zeroRatePointSensitivity( cmsPeriod.getPaymentDate()).multipliedBy(payoff * cmsPeriod.getNotional() * cmsPeriod.getYearFraction()); } else if (fixingDate.isBefore(valuationDate.toLocalDate())) { throw new IllegalArgumentException(Messages.format( "Unable to get fixing for {} on date {}, no time-series supplied", cmsPeriod.getIndex(), fixingDate)); } } double forward = swapPricer.parRate(swap, provider); double eta = index.getTemplate().getConvention().getFixedLeg().getDayCount() .relativeYearFraction(cmsPeriod.getPaymentDate(), swap.getStartDate()); CmsDeltaIntegrantProvider intProv = new CmsDeltaIntegrantProvider( cmsPeriod, swap, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor, cutOffStrike, eta); RungeKuttaIntegrator1D integrator = new RungeKuttaIntegrator1D(ABS_TOL, REL_TOL, NUM_ITER); double[] bs = intProv.bsbsp(strikeCpn); double[] n = intProv.getNnp(); double strikePartPrice = intProv.k(strikeCpn) * n[0] * bs[0]; double integralPartPrice = 0d; double integralPart = 0d; Function<Double, Double> integrant = intProv.integrant(); Function<Double, Double> integrantDelta = intProv.integrantDelta(); try { if (intProv.getPutCall().isCall()) { integralPartPrice = integrateCall(integrator, integrant, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor); integralPart = dfPayment * integrateCall(integrator, integrantDelta, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor); } else { integralPartPrice = -integrator.integrate(integrant, -shift + ZERO_SHIFT, strikeCpn); integralPart = -dfPayment * integrator.integrate(integrantDelta, -shift, strikeCpn); } } catch (Exception e) { throw new MathException(e); } double deltaPD = strikePartPrice + integralPartPrice; if (cmsPeriod.getCmsPeriodType().equals(CmsPeriodType.COUPON)) { deltaPD -= shift; } deltaPD *= cmsPeriod.getNotional() * cmsPeriod.getYearFraction(); double strikePart = dfPayment * intProv.k(strikeCpn) * (n[1] * bs[0] + n[0] * bs[1]); double deltaFwd = (strikePart + integralPart) * cmsPeriod.getNotional() * cmsPeriod.getYearFraction(); PointSensitivityBuilder sensiFwd = swapPricer.parRateSensitivity(swap, provider).multipliedBy(deltaFwd); PointSensitivityBuilder sensiDf = provider.discountFactors(ccy) .zeroRatePointSensitivity(cmsPeriod.getPaymentDate()).multipliedBy(deltaPD); return sensiFwd.combinedWith(sensiDf); } /** * Computes the present value sensitivity to SABR parameters by replication in SABR framework with extrapolation on the right. * * @param cmsPeriod the CMS * @param provider the rates provider * @param swaptionVolatilities the swaption volatilities * @return the present value sensitivity */ public PointSensitivityBuilder presentValueSensitivityModelParamsSabr( CmsPeriod cmsPeriod, RatesProvider provider, SabrSwaptionVolatilities swaptionVolatilities) { Currency ccy = cmsPeriod.getCurrency(); SwapIndex index = cmsPeriod.getIndex(); ResolvedSwap swap = cmsPeriod.getUnderlyingSwap(); double dfPayment = provider.discountFactor(ccy, cmsPeriod.getPaymentDate()); ZonedDateTime valuationDate = swaptionVolatilities.getValuationDateTime(); LocalDate fixingDate = cmsPeriod.getFixingDate(); ZonedDateTime expiryDate = fixingDate.atTime(index.getFixingTime()).atZone(index.getFixingZone()); double tenor = swaptionVolatilities.tenor(swap.getStartDate(), swap.getEndDate()); if (provider.getValuationDate().isAfter(cmsPeriod.getPaymentDate())) { return PointSensitivityBuilder.none(); } if (!fixingDate.isAfter(valuationDate.toLocalDate())) { OptionalDouble fixedRate = provider.timeSeries(cmsPeriod.getIndex()).get(fixingDate); if (fixedRate.isPresent()) { return PointSensitivityBuilder.none(); } else if (fixingDate.isBefore(valuationDate.toLocalDate())) { throw new IllegalArgumentException(Messages.format( "Unable to get fixing for {} on date {}, no time-series supplied", cmsPeriod.getIndex(), fixingDate)); } } double expiryTime = swaptionVolatilities.relativeTime(expiryDate); double shift = swaptionVolatilities.shift(expiryTime, tenor); double strikeCpn = cmsPeriod.getCmsPeriodType().equals(CmsPeriodType.COUPON) ? -shift : cmsPeriod.getStrike(); double forward = swapPricer.parRate(swap, provider); double eta = index.getTemplate().getConvention().getFixedLeg().getDayCount() .relativeYearFraction(cmsPeriod.getPaymentDate(), swap.getStartDate()); CmsIntegrantProvider intProv = new CmsIntegrantProvider( cmsPeriod, swap, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor, cutOffStrike, eta); double factor = dfPayment / intProv.h(forward) * intProv.g(forward); double factor2 = factor * intProv.k(strikeCpn); double[] strikePartPrice = intProv.getSabrExtrapolation() .priceAdjointSabr(Math.max(0d, strikeCpn + shift), intProv.getPutCall()) // handle tiny but negative number .getDerivatives().multipliedBy(factor2).toArray(); RungeKuttaIntegrator1D integrator = new RungeKuttaIntegrator1D(ABS_TOL, REL_TOL_VEGA, NUM_ITER); double[] totalSensi = new double[4]; for (int loopparameter = 0; loopparameter < 4; loopparameter++) { double integralPart = 0d; Function<Double, Double> integrant = intProv.integrantVega(loopparameter); try { if (intProv.getPutCall().isCall()) { integralPart = dfPayment * integrateCall(integrator, integrant, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor); } else { integralPart = -dfPayment * integrator.integrate(integrant, -shift + ZERO_SHIFT, strikeCpn); } } catch (Exception e) { throw new RuntimeException(e); } totalSensi[loopparameter] = (strikePartPrice[loopparameter] + integralPart) * cmsPeriod.getNotional() * cmsPeriod.getYearFraction(); } SwaptionVolatilitiesName name = swaptionVolatilities.getName(); return PointSensitivityBuilder.of( SwaptionSabrSensitivity.of(name, expiryTime, tenor, ALPHA, ccy, totalSensi[0]), SwaptionSabrSensitivity.of(name, expiryTime, tenor, BETA, ccy, totalSensi[1]), SwaptionSabrSensitivity.of(name, expiryTime, tenor, RHO, ccy, totalSensi[2]), SwaptionSabrSensitivity.of(name, expiryTime, tenor, NU, ccy, totalSensi[3])); } /** * Computes the present value sensitivity to strike by replication in SABR framework with extrapolation on the right. * * @param cmsPeriod the CMS * @param provider the rates provider * @param swaptionVolatilities the swaption volatilities * @return the present value sensitivity */ public double presentValueSensitivityStrike( CmsPeriod cmsPeriod, RatesProvider provider, SabrSwaptionVolatilities swaptionVolatilities) { ArgChecker.isFalse( cmsPeriod.getCmsPeriodType().equals(CmsPeriodType.COUPON), "presentValueSensitivityStrike is not relevant for CMS coupon"); Currency ccy = cmsPeriod.getCurrency(); SwapIndex index = cmsPeriod.getIndex(); if (provider.getValuationDate().isAfter(cmsPeriod.getPaymentDate())) { return 0d; } ResolvedSwap swap = cmsPeriod.getUnderlyingSwap(); double dfPayment = provider.discountFactor(ccy, cmsPeriod.getPaymentDate()); ZonedDateTime valuationDate = swaptionVolatilities.getValuationDateTime(); LocalDate fixingDate = cmsPeriod.getFixingDate(); double tenor = swaptionVolatilities.tenor(swap.getStartDate(), swap.getEndDate()); ZonedDateTime expiryDate = fixingDate.atTime(index.getFixingTime()).atZone(index.getFixingZone()); double expiryTime = swaptionVolatilities.relativeTime(expiryDate); double strike = cmsPeriod.getStrike(); double shift = swaptionVolatilities.shift(expiryTime, tenor); if (!fixingDate.isAfter(valuationDate.toLocalDate())) { OptionalDouble fixedRate = provider.timeSeries(cmsPeriod.getIndex()).get(fixingDate); if (fixedRate.isPresent()) { double payoff = 0d; switch (cmsPeriod.getCmsPeriodType()) { case CAPLET: payoff = fixedRate.getAsDouble() >= strike ? -1d : 0d; break; case FLOORLET: payoff = fixedRate.getAsDouble() < strike ? 1d : 0d; break; default: throw new IllegalArgumentException("unsupported CMS type"); } return payoff * cmsPeriod.getNotional() * cmsPeriod.getYearFraction() * dfPayment; } else if (fixingDate.isBefore(valuationDate.toLocalDate())) { throw new IllegalArgumentException(Messages.format( "Unable to get fixing for {} on date {}, no time-series supplied", cmsPeriod.getIndex(), fixingDate)); } } double forward = swapPricer.parRate(swap, provider); double eta = index.getTemplate().getConvention().getFixedLeg().getDayCount() .relativeYearFraction(cmsPeriod.getPaymentDate(), swap.getStartDate()); CmsIntegrantProvider intProv = new CmsIntegrantProvider( cmsPeriod, swap, swaptionVolatilities, forward, strike, expiryTime, tenor, cutOffStrike, eta); double factor = dfPayment * intProv.g(forward) / intProv.h(forward); RungeKuttaIntegrator1D integrator = new RungeKuttaIntegrator1D(ABS_TOL, REL_TOL_STRIKE, NUM_ITER); double[] kpkpp = intProv.kpkpp(strike); double firstPart; double thirdPart; Function<Double, Double> integrant = intProv.integrantDualDelta(); if (intProv.getPutCall().isCall()) { firstPart = -kpkpp[0] * intProv.bs(strike); thirdPart = integrateCall(integrator, integrant, swaptionVolatilities, forward, strike, expiryTime, tenor); } else { firstPart = -kpkpp[0] * intProv.bs(strike); thirdPart = -integrator.integrate(integrant, -shift + ZERO_SHIFT, strike); } double secondPart = intProv.k(strike) * intProv.getSabrExtrapolation().priceDerivativeStrike(strike + shift, intProv.getPutCall()); return cmsPeriod.getNotional() * cmsPeriod.getYearFraction() * factor * (firstPart + secondPart + thirdPart); } private double payOff(CmsPeriodType cmsPeriodType, double strikeCpn, Double fixedRate) { double payoff = 0d; switch (cmsPeriodType) { case CAPLET: payoff = Math.max(fixedRate - strikeCpn, 0d); break; case FLOORLET: payoff = Math.max(strikeCpn - fixedRate, 0d); break; case COUPON: payoff = fixedRate; break; default: throw new IllegalArgumentException("unsupported CMS type"); } return payoff; } private double integrateCall( RungeKuttaIntegrator1D integrator, Function<Double, Double> integrant, SabrSwaptionVolatilities swaptionVolatilities, double forward, double strike, double expiryTime, double tenor) { double res; double vol = swaptionVolatilities.volatility(expiryTime, tenor, forward, forward); double upper0 = Math.max( forward * Math.exp(6d * vol * Math.sqrt(expiryTime)), Math.max(cutOffStrike, 2d * strike)); // To ensure that the integral covers a good part of the smile double upper = Math.min(upper0, 1d); // To ensure that we don't miss the meaningful part res = integrator.integrate(integrant, strike, upper); double reminder = integrant.apply(upper) * upper; double error = reminder / res; int count = 0; while (Math.abs(error) > integrator.getRelativeTolerance() && count < MAX_COUNT) { res += integrator.integrate(integrant, upper, 2d * upper); upper *= 2d; reminder = integrant.apply(upper) * upper; error = reminder / res; ++count; if (count == MAX_COUNT) { log.info("Maximum iteration count, " + MAX_COUNT + ", has been reached. Relative error is greater than " + integrator.getRelativeTolerance()); } } return res; } //explain PV for an Cms period public void explainPresentValue( CmsPeriod period, RatesProvider ratesProvider, SabrSwaptionVolatilities swaptionVolatilities, ExplainMapBuilder builder) { String type = period.getCmsPeriodType().toString(); Currency ccy = period.getCurrency(); LocalDate paymentDate = period.getPaymentDate(); builder.put(ExplainKey.ENTRY_TYPE, "Cms" + type + "Period"); builder.put(ExplainKey.STRIKE_VALUE, period.getStrike()); builder.put(ExplainKey.NOTIONAL, CurrencyAmount.of(ccy, period.getNotional())); builder.put(ExplainKey.PAYMENT_DATE, period.getPaymentDate()); builder.put(ExplainKey.DISCOUNT_FACTOR, ratesProvider.discountFactor(ccy, paymentDate)); builder.put(ExplainKey.START_DATE, period.getStartDate()); builder.put(ExplainKey.END_DATE, period.getEndDate()); builder.put(ExplainKey.FIXING_DATE, period.getFixingDate()); builder.put(ExplainKey.ACCRUAL_YEAR_FRACTION, period.getYearFraction()); builder.put(ExplainKey.PRESENT_VALUE, presentValue(period, ratesProvider, swaptionVolatilities)); builder.put(ExplainKey.FORWARD_RATE, swapPricer.parRate(period.getUnderlyingSwap(), ratesProvider)); builder.put(ExplainKey.CONVEXITY_ADJUSTED_RATE, adjustedForwardRate(period, ratesProvider, swaptionVolatilities)); } //------------------------------------------------------------------------- /** * Inner class to implement the integration used in price replication. */ private class CmsIntegrantProvider { /* Small parameter below which a value is regarded as 0. */ protected static final double EPS = 1.0E-4; private final int nbFixedPeriod; private final int nbFixedPaymentYear; private final double tau; private final double eta; private final double strike; private final double shift; private final double factor; private final SabrExtrapolationRightFunction sabrExtrapolation; private final PutCall putCall; private final double[] g0; /** * Gets the tau field. * * @return the tau */ public double getTau() { return tau; } /** * Gets the eta field. * * @return the eta */ public double getEta() { return eta; } /** * Gets the putCall field. * * @return the putCall */ public PutCall getPutCall() { return putCall; } /** * Gets the strike field. * * @return the strike */ protected double getStrike() { return strike; } /** * Gets the shift field. * * @return the shift */ protected double getShift() { return shift; } /** * Gets the sabrExtrapolation field. * * @return the sabrExtrapolation */ public SabrExtrapolationRightFunction getSabrExtrapolation() { return sabrExtrapolation; } public CmsIntegrantProvider( CmsPeriod cmsPeriod, ResolvedSwap swap, SabrSwaptionVolatilities swaptionVolatilities, double forward, double strike, double timeToExpiry, double tenor, double cutOffStrike, double eta) { ResolvedSwapLeg fixedLeg = swap.getLegs(SwapLegType.FIXED).get(0); this.nbFixedPeriod = fixedLeg.getPaymentPeriods().size(); this.nbFixedPaymentYear = (int) Math.round(1d / ((RatePaymentPeriod) fixedLeg.getPaymentPeriods().get(0)).getAccrualPeriods().get(0).getYearFraction()); this.tau = 1d / nbFixedPaymentYear; this.eta = eta; SabrFormulaData sabrPoint = SabrFormulaData.of( swaptionVolatilities.alpha(timeToExpiry, tenor), swaptionVolatilities.beta(timeToExpiry, tenor), swaptionVolatilities.rho(timeToExpiry, tenor), swaptionVolatilities.nu(timeToExpiry, tenor)); this.shift = swaptionVolatilities.shift(timeToExpiry, tenor); this.sabrExtrapolation = SabrExtrapolationRightFunction .of(forward + shift, timeToExpiry, sabrPoint, cutOffStrike + shift, mu); this.putCall = cmsPeriod.getCmsPeriodType().equals(CmsPeriodType.FLOORLET) ? PutCall.PUT : PutCall.CALL; this.strike = strike; this.factor = g(forward) / h(forward); this.g0 = new double[4]; g0[0] = nbFixedPeriod * tau; g0[1] = -0.5 * nbFixedPeriod * (nbFixedPeriod + 1.0d) * tau * tau; g0[2] = -2.0d / 3.0d * g0[1] * (nbFixedPeriod + 2.0d) * tau; g0[3] = -3.0d / 4.0d * g0[2] * (nbFixedPeriod + 2.0d) * tau; } /** * Obtains the integrant used in price replication. * * @return the integrant */ Function<Double, Double> integrant() { return new Function<Double, Double>() { @Override public Double apply(Double x) { double[] kD = kpkpp(x); // Implementation note: kD[0] contains the first derivative of k; kD[1] the second derivative of k. return factor * (kD[1] * (x - strike) + 2d * kD[0]) * bs(x); } }; } /** * Obtains the integrant sensitivity to the i-th SABR parameter. * * @param i the index of SABR parameters * @return the vega integrant */ Function<Double, Double> integrantVega(int i) { return new Function<Double, Double>() { @Override public Double apply(Double x) { double[] kD = kpkpp(x); // Implementation note: kD[0] contains the first derivative of k; kD[1] the second derivative of k. double xShifted = Math.max(x + shift, 0d); // handle tiny but negative number DoubleArray priceDerivativeSABR = getSabrExtrapolation().priceAdjointSabr(xShifted, putCall).getDerivatives(); return priceDerivativeSABR.get(i) * (factor * (kD[1] * (x - strike) + 2d * kD[0])); } }; } /** * Obtains the integrant sensitivity to strike. * * @return the dual delta integrant */ Function<Double, Double> integrantDualDelta() { return new Function<Double, Double>() { @Override public Double apply(Double x) { double[] kD = kpkpp(x); // Implementation note: kD[0] contains the first derivative of k; kD[1] the second derivative of k. return -kD[1] * bs(x); } }; } /** * The approximation of the discount factor as function of the swap rate. * * @param x the swap rate. * @return the discount factor. */ double h(double x) { return Math.pow(1d + tau * x, eta); } /** * The cash annuity. * * @param x the swap rate. * @return the annuity. */ double g(double x) { if (Math.abs(x) >= EPS) { double periodFactor = 1d + x / nbFixedPaymentYear; double nPeriodDiscount = Math.pow(periodFactor, -nbFixedPeriod); return (1d - nPeriodDiscount) / x; } // Special case when x ~ 0: expansion of g around 0 return g0[0] + g0[1] * x + 0.5 * g0[2] * x * x + g0[3] * x * x * x / 6.0d; } /** * The cash annuity. * * @param x the swap rate. * @return the annuity. */ double[] ggpgpp(double x) { if (Math.abs(x) >= EPS) { double periodFactor = 1d + x / nbFixedPaymentYear; double nPeriodDiscount = Math.pow(periodFactor, -nbFixedPeriod); double[] ggpgpp = new double[3]; ggpgpp[0] = (1d - nPeriodDiscount) / x; ggpgpp[1] = -ggpgpp[0] / x + nbFixedPeriod * nPeriodDiscount / (x * nbFixedPaymentYear * periodFactor); ggpgpp[2] = 2d / (x * x) * ggpgpp[0] - 2d * nbFixedPeriod * nPeriodDiscount / (x * x * nbFixedPaymentYear * periodFactor) - (nbFixedPeriod + 1d) * nbFixedPeriod * nPeriodDiscount / (x * nbFixedPaymentYear * nbFixedPaymentYear * periodFactor * periodFactor); return ggpgpp; } // Special case when x ~ 0: expansion of g around 0 return new double[] {g0[0] + g0[1] * x + 0.5 * g0[2] * x * x + g0[3] * x * x * x / 6.0d, g0[1] + g0[2] * x + 0.5 * g0[3] * x * x, g0[2] + g0[3] * x}; } /** * The factor used in the strike part and in the integration of the replication. * * @param x the swap rate. * @return the factor. */ double k(double x) { double g = g(x); double h = Math.pow(1.0 + tau * x, eta); return h / g; } /** * The first and second derivative of the function k. * <p> * The first element is the first derivative and the second element is second derivative. * * @param x the swap rate. * @return the derivatives */ protected double[] kpkpp(double x) { double periodFactor = 1d + x / nbFixedPaymentYear; /** * The value of the annuity and its first and second derivative. */ double[] ggpgpp = ggpgpp(x); double h = Math.pow(1d + tau * x, eta); double hp = eta * tau * h / periodFactor; double hpp = (eta - 1d) * tau * hp / periodFactor; double kp = hp / ggpgpp[0] - h * ggpgpp[1] / (ggpgpp[0] * ggpgpp[0]); double kpp = hpp / ggpgpp[0] - 2d * hp * ggpgpp[1] / (ggpgpp[0] * ggpgpp[0]) - h * (ggpgpp[2] / (ggpgpp[0] * ggpgpp[0]) - 2d * (ggpgpp[1] * ggpgpp[1]) / (ggpgpp[0] * ggpgpp[0] * ggpgpp[0])); return new double[] {kp, kpp}; } /** * The Black price with numeraire 1 as function of the strike. * * @param strike the strike. * @return the Black prcie. */ double bs(double strike) { double strikeShifted = Math.max(strike + getShift(), 0d); // handle tiny but negative number return sabrExtrapolation.price(strikeShifted, putCall); } } /** * Inner class to implement the integration used for delta calculation. */ private class CmsDeltaIntegrantProvider extends CmsIntegrantProvider { private final double[] nnp; public CmsDeltaIntegrantProvider( CmsPeriod cmsPeriod, ResolvedSwap swap, SabrSwaptionVolatilities swaptionVolatilities, double forward, double strike, double timeToExpiry, double tenor, double cutOffStrike, double eta) { super(cmsPeriod, swap, swaptionVolatilities, forward, strike, timeToExpiry, tenor, cutOffStrike, eta); this.nnp = nnp(forward); } /** * Gets the nnp field. * * @return the nnp */ public double[] getNnp() { return nnp; } /** * Obtains the integrant sensitivity to forward. * * @return the delta integrant */ Function<Double, Double> integrantDelta() { return new Function<Double, Double>() { @Override public Double apply(Double x) { double[] kD = kpkpp(x); // Implementation note: kD[0] contains the first derivative of k; kD[1] the second derivative of k. double[] bs = bsbsp(x); return (kD[1] * (x - getStrike()) + 2d * kD[0]) * (nnp[1] * bs[0] + nnp[0] * bs[1]); } }; } /** * The Black price and its derivative with respect to the forward. * * @param strike the strike. * @return the Black price and its derivative. */ private double[] bsbsp(double strike) { double[] result = new double[2]; double strikeShifted = Math.max(strike + getShift(), 0d); // handle tiny but negative number result[0] = getSabrExtrapolation().price(strikeShifted, getPutCall()); result[1] = getSabrExtrapolation().priceDerivativeForward(strikeShifted, getPutCall()); return result; } private double[] nnp(double x) { double[] result = new double[2]; double[] ggpgpp = ggpgpp(x); double[] hhp = hhp(x); result[0] = ggpgpp[0] / hhp[0]; result[1] = ggpgpp[1] / hhp[0] - ggpgpp[0] * hhp[1] / (hhp[0] * hhp[0]); return result; } private double[] hhp(double x) { double[] result = new double[2]; result[0] = Math.pow(1d + getTau() * x, getEta()); result[1] = getEta() * getTau() * result[0] / (1d + x * getTau()); return result; } } }
jmptrader/Strata
modules/pricer/src/main/java/com/opengamma/strata/pricer/cms/SabrExtrapolationReplicationCmsPeriodPricer.java
Java
apache-2.0
38,833
/* * Licensed to the University Corporation for Advanced Internet Development, * Inc. (UCAID) under one or more contributor license agreements. See the * NOTICE file distributed with this work for additional information regarding * copyright ownership. The UCAID licenses this file to You under the Apache * License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.internet2.middleware.shibboleth.common.config.resource; import edu.internet2.middleware.shibboleth.common.config.BaseSpringNamespaceHandler; /** Namespace handler for resources. */ public class ResourceNamespaceHandler extends BaseSpringNamespaceHandler { /** Namespace URI. */ public static final String NAMESPACE = "urn:mace:shibboleth:2.0:resource"; /** {@inheritDoc} */ public void init() { registerBeanDefinitionParser(ClasspathResourceBeanDefinitionParser.SCHEMA_TYPE, new ClasspathResourceBeanDefinitionParser()); registerBeanDefinitionParser(FilesystemResourceBeanDefinitionParser.SCHEMA_TYPE, new FilesystemResourceBeanDefinitionParser()); registerBeanDefinitionParser(HttpResourceBeanDefinitionParser.SCHEMA_TYPE, new HttpResourceBeanDefinitionParser()); registerBeanDefinitionParser(FileBackedHttpResourceBeanDefinitionParser.SCHEMA_TYPE, new FileBackedHttpResourceBeanDefinitionParser()); registerBeanDefinitionParser(SVNResourceBeanDefinitionParser.SCHEMA_TYPE, new SVNResourceBeanDefinitionParser()); registerBeanDefinitionParser(PropertyReplacementResourceFilterBeanDefinitionParser.SCHEMA_TYPE, new PropertyReplacementResourceFilterBeanDefinitionParser()); registerBeanDefinitionParser(ChainingResourceFilterBeanDefinitionParser.SCHEMA_TYPE, new ChainingResourceFilterBeanDefinitionParser()); } }
brainysmith/shibboleth-common
src/main/java/edu/internet2/middleware/shibboleth/common/config/resource/ResourceNamespaceHandler.java
Java
apache-2.0
2,371
package cumt.tj.learn.offer; import java.util.HashMap; /** * Created by sky on 17-8-4. * 题目描述 * 输入两个链表,找出它们的第一个公共结点。 * * 思路: * 1. 利用hashMap存储Node法: * 遍历list1 * 利用一个hash表,存储已经出现的node * 遍历list2 * 查找hash表中是否有node,有则返回 * 2. 利用单链表特点,利用栈辅助法: * 对于单链表,只要有一个节点相同,那么后面的结点肯定都相同了 * 所以需要从后往前找,第一个不相同的结点的下一个节点就是第一个公共结点 * 而对于单链表来说,没有指向前一个结点的指针,所以不能从后向前找 * 所以第一次遍历利用2个栈分别存2个列表的结点 * 第二次从2个栈顶分别取结点进行比较,就是各自的尾结点,直到不相同的时候,调用.next就是结果 * 这样会用到2个栈,空间为O(n+m),时间也是O(n+m) * 3. 不需要辅助栈法 * 第一次遍历,计算2个链表的长度,得到长度差interval * 对于相对较长的链表,先遍历interval * 然后2个链表一起遍历,一个相同的就是结果 * */ public class FindFirstCommonNode { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { return simpleFind(pHead1,pHead2); } public ListNode simpleFind(ListNode pHead1,ListNode pHead2){ // * 第一次遍历,计算2个链表的长度,得到长度差interval int length1=0; int length2=0; ListNode current1=pHead1; ListNode current2=pHead2; while (current1!=null){ length1++; current1=current1.next; } while (current2!=null){ length2++; current2=current2.next; } // * 对于相对较长的链表,先遍历interval int interval=length2-length1; if(interval<0){ //第一个更长 for (int i=interval;i<0;i++){ pHead1=pHead1.next; } }else if(interval>0){ //第二个更长 for(int i=0;i<interval;i++){ pHead2=pHead2.next; } } // * 然后2个链表一起遍历,第一个相同的就是结果 while (pHead1!=pHead2){ pHead1=pHead1.next; pHead2=pHead2.next; } return pHead1; } public ListNode findByHashMap(ListNode pHead1,ListNode pHead2){ HashMap<ListNode,Boolean> nodeMap=new HashMap<ListNode, Boolean>(); while (pHead1!=null){ nodeMap.put(pHead1,true); pHead1=pHead1.next; } while ((pHead2!=null)){ if(nodeMap.get(pHead2)!=null) return pHead2; pHead2=pHead2.next; } return null; } }
codeboytj/data-structures-algorithms
src/main/java/cumt/tj/learn/offer/FindFirstCommonNode.java
Java
apache-2.0
2,864
/** Automatically generated file. DO NOT MODIFY */ package org.crazyit.appProject4_3_1; public final class BuildConfig { public final static boolean DEBUG = true; }
00wendi00/MyProject
W_eclipse1_1/Project4_3_1/gen/org/crazyit/appProject4_3_1/BuildConfig.java
Java
apache-2.0
169
/* * Copyright 2013 Aven Solutions Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.avensolutions.baconbits; import java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema; /** * Extension of LinkedIn DataFu BagConcat class, to bypass errors * Unions all input bags to produce a single bag containing all tuples. * <p> * This UDF accepts two forms of input: * <ol> * <li>a tuple of 2 or more elements where each element is a bag with the same schema</li> * <li>a single bag where each element of that bag is a bag and all of these bags have the same schema</li> * </ol> * <p> * Example 1: * <pre> * {@code * define BagConcatEx datafu.pig.bags.BagConcatEx(); * -- This example illustrates the use on a tuple of bags * * -- input: * -- ({(1),(2),(3)},{(3),(4),(5)}) * -- ({(20),(25)},{(40),(50)}) * input = LOAD 'input' AS (A: bag{T: tuple(v:INT)}, B: bag{T: tuple(v:INT)}); * * -- output: * -- ({(1),(2),(3),(3),(4),(5)}) * -- ({(20),(25),(40),(50)}) * output = FOREACH input GENERATE BagConcatEx(A,B); * } * </pre> * <p> * Example 2: * <pre> * {@code * define BagConcatEx datafu.pig.bags.BagConcatEx(); * -- This example illustrates the use on a bag of bags * * -- input: * -- ({({(1),(2),(3)}),({(3),(4),(5)})}) * -- ({({(20),(25)}),({(40),(50)})}) * input = LOAD 'input' AS (A: bag{T: tuple(bag{T2: tuple(v:INT)})}); * * -- output: * -- ({(1),(2),(3),(3),(4),(5)}) * -- ({(20),(25),(40),(50)}) * output = FOREACH input GENERATE BagConcatEx(A); * } * </pre> * * @author wvaughan * */ public class BagConcatEx extends EvalFunc<DataBag> { @Override public DataBag exec(Tuple input) throws IOException { DataBag output = BagFactory.getInstance().newDefaultBag(); if (input.size() > 1) { // tuple of bags for (int i=0; i < input.size(); i++) { Object o = input.get(i); if (!(o instanceof DataBag)) { //throw new RuntimeException("Expected a TUPLE of BAGs as input"); System.err.println("Expected a TUPLE of BAGs as input"); break; } DataBag inputBag = (DataBag) o; for (Tuple elem : inputBag) { output.add(elem); } } } else { // bag of bags DataBag outerBag = (DataBag)input.get(0); for (Tuple outerTuple : outerBag) { DataBag innerBag = (DataBag)outerTuple.get(0); for (Tuple innerTuple : innerBag) { output.add(innerTuple); } } } return output; } @Override public Schema outputSchema(Schema input) { try { Schema outputBagTupleSchema = null; if (input.size() == 0) { throw new RuntimeException("Expected input tuple to contain fields. Got none."); } // determine whether the input is a tuple of bags or a bag of bags if (input.size() != 1) { // tuple of bags // verify that each element in the input is a bag for (FieldSchema fieldSchema : input.getFields()) { if (fieldSchema.type != DataType.BAG) { throwBadTypeError("Expected a TUPLE of BAGs as input. Got instead: %s in schema: %s", fieldSchema.type, input); } if (fieldSchema.schema == null) { throwBadSchemaError(fieldSchema.alias, input); } } outputBagTupleSchema = input.getField(0).schema; } else { // bag of bags // should only be a single element in the input and it should be a bag FieldSchema fieldSchema = input.getField(0); if (fieldSchema.type != DataType.BAG) { throwBadTypeError("Expected a BAG of BAGs as input. Got instead: %s in schema: %s", fieldSchema.type, input); } // take the tuple schema from this outer bag Schema outerBagTuple = input.getField(0).schema; // verify that this tuple contains only a bag for each element Schema outerBagSchema = outerBagTuple.getField(0).schema; if (outerBagSchema.size() != 1) { throw new RuntimeException(String.format("Expected outer bag to have only a single field. Got instead: %s", outerBagSchema.prettyPrint())); } FieldSchema outerBagFieldSchema = outerBagSchema.getField(0); if (outerBagFieldSchema.type != DataType.BAG) { throwBadTypeError("Expected a BAG of BAGs as input. Got instead: %s", outerBagFieldSchema.type, outerBagTuple); } // take the schema of the inner tuple as the schema for the tuple in the output bag FieldSchema innerTupleSchema = outerBagSchema.getField(0); if (innerTupleSchema.schema == null) { throwBadSchemaError(innerTupleSchema.alias, outerBagSchema); } outputBagTupleSchema = innerTupleSchema.schema; } // return the correct schema return new Schema(new Schema.FieldSchema(getSchemaName(this.getClass().getName().toLowerCase(), input), outputBagTupleSchema, DataType.BAG)); } catch (Exception e) { throw new RuntimeException(e); } } private void throwBadSchemaError(String alias, Schema schema) throws FrontendException { throw new FrontendException(String.format("Expected non-null schema for all bags. Got null on field %s, in: %s", alias, schema.prettyPrint())); } private void throwBadTypeError(String expectedMessage, byte actualType, Schema schema) throws FrontendException { throw new FrontendException(String.format(expectedMessage, DataType.findTypeName(actualType), schema.prettyPrint())); } }
avensolutions/baconbits
src/java/BagConcatEx.java
Java
apache-2.0
6,493
package com.bagri.server.hazelcast.impl; import static com.bagri.core.Constants.*; import static com.bagri.core.test.TestUtils.getBasicDataFormats; import static com.bagri.core.test.TestUtils.loadProperties; import static org.junit.Assert.assertEquals; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.xml.xquery.XQItemAccessor; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.bagri.core.api.ResultCursor; import com.bagri.core.system.Collection; import com.bagri.core.system.Library; import com.bagri.core.system.Module; import com.bagri.core.system.Parameter; import com.bagri.core.system.Schema; import com.bagri.core.test.BagriManagementTest; import com.bagri.support.util.FileUtils; import com.bagri.support.util.JMXUtils; @Ignore public class QueryModuleTest extends BagriManagementTest { private static ClassPathXmlApplicationContext context; @BeforeClass public static void setUpBeforeClass() throws Exception { sampleRoot = "../../etc/samples/mp/"; System.setProperty(pn_log_level, "trace"); System.setProperty(pn_node_instance, "0"); System.setProperty("logback.configurationFile", "hz-logging.xml"); System.setProperty(pn_config_properties_file, "json.properties"); System.setProperty(pn_config_path, "src/test/resources"); context = new ClassPathXmlApplicationContext("spring/cache-test-context.xml"); } @AfterClass public static void tearDownAfterClass() throws Exception { context.close(); } @Before public void setUp() throws Exception { xRepo = context.getBean(SchemaRepositoryImpl.class); SchemaRepositoryImpl xdmRepo = (SchemaRepositoryImpl) xRepo; Schema schema = xdmRepo.getSchema(); if (schema == null) { Properties props = loadProperties("src/test/resources/json.properties"); props.setProperty(pn_xqj_baseURI, "file:/../../etc/samples/mp/"); schema = new Schema(1, new java.util.Date(), "test", "test", "test schema", true, props); //schema.setProperty(pn_schema_format_default, "JSON"); Collection collection = new Collection(1, new Date(), JMXUtils.getCurrentUser(), 1, "CLN_Product_Inventory", "/", null, "inventories", true); schema.addCollection(collection); xdmRepo.setSchema(schema); xdmRepo.setDataFormats(getBasicDataFormats()); xdmRepo.setLibraries(new ArrayList<Library>()); String fName = sampleRoot + "/inventory_service.xq"; String mBody = FileUtils.readTextFile(fName); //do I need to read it from file? Module module = new Module(1, new Date(), JMXUtils.getCurrentUser(), "in_svc", fName, "inv module", "inv", "http://mpoffice.ru/inv", mBody, true); List<Module> modules = new ArrayList<>(); modules.add(module); xdmRepo.setModules(modules); ((ClientManagementImpl) xdmRepo.getClientManagement()).addClient(client_id, user_name); xdmRepo.setClientId(client_id); long txId = xRepo.getTxManagement().beginTransaction(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("../../etc/samples/mp/mp2/"), "*.json")) { for (Path path: stream) { createDocumentTest(path.toFile().getAbsolutePath()); } } xRepo.getTxManagement().commitTransaction(txId); } } @After public void tearDown() throws Exception { xRepo.close(); } @Test public void queryProductsByCategoryTest() throws Exception { String query = "import module namespace inv=\"http://mpoffice.ru/inv\" at \"inventory_service.xq\";\n" + "declare variable $pcat external;\n" + "declare variable $rid external;\n" + "declare variable $psize external;\n" + "declare variable $pnum external;\n" + "\n" + "inv:get-products-by-category($pcat, $rid, $psize, $pnum)\n"; Map<String, Object> params = new HashMap<>(); params.put("pcat", "091210"); params.put("rid", null); //12345); params.put("psize", 100); params.put("pnum", 1); Properties props = new Properties(); props.setProperty(pn_query_customQuery, "1=(/inventory/product-category starts-with pcat) and (((/inventory/virtual-stores/region-id = rid) or (rid = null)) and (/inventory/virtual-stores/status = literal_103_39))"); try (ResultCursor<XQItemAccessor> results = query(query, params, props)) { int cnt = 0; for (XQItemAccessor item: results) { cnt++; } assertEquals(2, cnt); } } @Test public void queryProductByIdTest() throws Exception { String query = "import module namespace inv=\"http://mpoffice.ru/inv\" at \"inventory_service.xq\";\n" + "declare variable $pid external;\n" + "declare variable $rid external;\n" + "\n" + "inv:get-product-by-id($pid, $rid)\n"; Map<String, Object> params = new HashMap<>(); params.put("pid", 7525L); params.put("rid", null); //235 Properties props = new Properties(); props.setProperty(pn_query_customQuery, "1=(/inventory/product-id = pid) and ((/inventory/virtual-stores/status = literal_80_40) and ((/inventory/virtual-stores/region-id = rid) or (rid = null)))"); try (ResultCursor<XQItemAccessor> results = query(query, params, props)) { int cnt = 0; for (XQItemAccessor item: results) { cnt++; } assertEquals(4, cnt); } } @Test public void queryProductsByIdsTest() throws Exception { String query = "import module namespace inv=\"http://mpoffice.ru/inv\" at \"inventory_service.xq\";\n" + "declare variable $pids external;\n" + "\n" + "inv:get-products-by-ids($pids)\n"; Map<String, Object> params = new HashMap<>(); //List<Integer> pids = new ArrayList<>(); List<String> pids = new ArrayList<>(); pids.add("5977"); pids.add("7525"); pids.add("11386"); params.put("pids", pids); //params.put("var2", "active"); Properties props = new Properties(); props.setProperty(pn_query_customPaths, "3=/inventory/virtual-stores/status"); try (ResultCursor<XQItemAccessor> results = query(query, params, props)) { int cnt = 0; for (XQItemAccessor item: results) { cnt++; } assertEquals(9, cnt); } } @Test public void queryProductsByIdsAndRegionTest() throws Exception { String query = "import module namespace inv=\"http://mpoffice.ru/inv\" at \"inventory_service.xq\";\n" + "declare variable $pids external;\n" + "declare variable $rid external;\n" + "\n" + "inv:get-products-by-ids-and-region($pids, $rid)\n"; Map<String, Object> params = new HashMap<>(); //List<Integer> pids = new ArrayList<>(); List<String> pids = new ArrayList<>(); pids.add("5977"); pids.add("7525"); pids.add("11386"); params.put("pids", pids); //params.put("var2", "active"); params.put("rid", 235); Properties props = new Properties(); props.setProperty(pn_query_customPaths, "3=/inventory/virtual-stores/region-id;5=/inventory/virtual-stores/status"); try (ResultCursor<XQItemAccessor> results = query(query, params, props)) { int cnt = 0; for (XQItemAccessor item: results) { cnt++; } assertEquals(3, cnt); } } @Test public void checkProductsCacheTest() throws Exception { String query = "import module namespace inv=\"http://mpoffice.ru/inv\" at \"inventory_service.xq\";\n" + "declare variable $pids external;\n" + "\n" + "inv:get-products-by-ids($pids)\n"; Map<String, Object> params = new HashMap<>(); //List<Integer> pids = new ArrayList<>(); List<String> pids = new ArrayList<>(); pids.add("11386"); params.put("pids", pids); //params.put("rid", null); //235 Properties props = new Properties(); props.setProperty(pn_query_customPaths, "1=/inventory/product-id EQ pids"); try (ResultCursor<XQItemAccessor> results = query(query, params, props)) { int cnt = 0; for (XQItemAccessor item: results) { cnt++; } assertEquals(3, cnt); } } }
dsukhoroslov/bagri
bagri-server/bagri-server-hazelcast/src/test/java/com/bagri/server/hazelcast/impl/QueryModuleTest.java
Java
apache-2.0
8,495
/* * Copyright 2015 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencb.cellbase.lib.db; import org.junit.Ignore; import org.junit.Test; import org.opencb.cellbase.core.config.CellBaseConfiguration; import org.opencb.cellbase.core.db.DBAdaptorFactory; import org.opencb.cellbase.core.db.api.variation.ClinicalDBAdaptor; import org.opencb.cellbase.lib.GenericMongoDBAdaptorTest; import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.commons.datastore.core.QueryResult; import java.io.IOException; import java.util.List; public class ClinicalMongoDBAdaptorTest extends GenericMongoDBAdaptorTest { // TODO: to be finished - properly implemented @Ignore @Test public void testGetAllByRegionList() throws Exception { CellBaseConfiguration cellBaseConfiguration = new CellBaseConfiguration(); DBAdaptorFactory dbAdaptorFactory = new MongoDBAdaptorFactory(cellBaseConfiguration); ClinicalDBAdaptor clinicalDBAdaptor = dbAdaptorFactory.getClinicalDBAdaptor("hsapiens", "GRCh37"); QueryOptions queryOptions = new QueryOptions("include", "clinvarList"); } // TODO: to be finished - properly implemented @Ignore @Test public void testGetAll() { CellBaseConfiguration cellBaseConfiguration = new CellBaseConfiguration(); try { cellBaseConfiguration = CellBaseConfiguration .load(CellBaseConfiguration.class.getClassLoader().getResourceAsStream("configuration.json")); } catch (IOException e) { e.printStackTrace(); } DBAdaptorFactory dbAdaptorFactory = new MongoDBAdaptorFactory(cellBaseConfiguration); ClinicalDBAdaptor clinicalDBAdaptor = dbAdaptorFactory.getClinicalDBAdaptor("hsapiens", "GRCh37"); QueryOptions queryOptions = new QueryOptions(); // queryOptions.add("source", "gwas"); // queryOptions.add("phenotype", "ALZHEIMER DISEASE 2, DUE TO APOE4 ISOFORM"); // queryOptions.addToListOption("phenotype", "ALZHEIMER"); queryOptions.addToListOption("phenotype", "alzheimer"); // queryOptions.addToListOption("phenotype", "retinitis"); // queryOptions.addToListOption("phenotype", "diabetes"); // queryOptions.addToListOption("region", new Region("3", 550000, 1166666)); // queryOptions.add("region", "5:13759611-13799611"); // queryOptions.addToListOption("region", new Region("1", 550000, 1166666)); // queryOptions.addToListOption("gene", "APOE"); // queryOptions.addToListOption("significance", "Likely_pathogenic"); // queryOptions.addToListOption("review", "REVIEWED_BY_PROFESSIONAL_SOCIETY"); // queryOptions.addToListOption("type", "Indel"); // queryOptions.addToListOption("so", "missense_variant"); // queryOptions.addToListOption("rs", "rs429358"); // queryOptions.addToListOption("rcv", "RCV000019455"); queryOptions.add("limit", 30); QueryResult queryResult = clinicalDBAdaptor.getAll(queryOptions); } // TODO: to be finished - properly implemented @Ignore @Test public void testGetPhenotypeGeneRelations() throws Exception { CellBaseConfiguration cellBaseConfiguration = new CellBaseConfiguration(); try { cellBaseConfiguration = CellBaseConfiguration .load(CellBaseConfiguration.class.getClassLoader().getResourceAsStream("configuration.json")); } catch (IOException e) { e.printStackTrace(); } DBAdaptorFactory dbAdaptorFactory = new MongoDBAdaptorFactory(cellBaseConfiguration); ClinicalDBAdaptor clinicalDBAdaptor = dbAdaptorFactory.getClinicalDBAdaptor("hsapiens", "GRCh37"); QueryOptions queryOptions = new QueryOptions(); // queryOptions.addToListOption("include", "clinvar"); // queryOptions.addToListOption("include", "gwas"); List<QueryResult> queryResultList = clinicalDBAdaptor.getPhenotypeGeneRelations(queryOptions); } }
dapregi/cellbase
cellbase-lib/src/test/java/org/opencb/cellbase/lib/db/ClinicalMongoDBAdaptorTest.java
Java
apache-2.0
4,565
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.versions; import com.facebook.buck.log.Logger; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.Flavor; import com.facebook.buck.model.InternalFlavor; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.rules.TargetGraphAndBuildTargets; import com.facebook.buck.rules.TargetNode; import com.facebook.buck.util.MoreCollectors; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Throwables; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveAction; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.StreamSupport; /** * Takes a regular {@link TargetGraph}, resolves any versioned nodes, and returns a new graph with * the versioned nodes removed. */ public class VersionedTargetGraphBuilder { private static final Logger LOG = Logger.get(VersionedTargetGraphBuilder.class); private final ForkJoinPool pool; private final VersionSelector versionSelector; private final TargetGraphAndBuildTargets unversionedTargetGraphAndBuildTargets; /** * The resolved version graph being built. */ private final VersionedTargetGraph.Builder targetGraphBuilder = VersionedTargetGraph.builder(); /** * Map of the build targets to nodes in the resolved graph. */ private final ConcurrentHashMap<BuildTarget, TargetNode<?, ?>> index; /** * Fork-join actions for each root node. */ private final ConcurrentHashMap<BuildTarget, RootAction> rootActions; /** * Intermediate version info for each node. */ private final ConcurrentHashMap<BuildTarget, VersionInfo> versionInfo; /** * Count of root nodes. */ private final AtomicInteger roots = new AtomicInteger(); VersionedTargetGraphBuilder( ForkJoinPool pool, VersionSelector versionSelector, TargetGraphAndBuildTargets unversionedTargetGraphAndBuildTargets) { Preconditions.checkArgument( unversionedTargetGraphAndBuildTargets.getTargetGraph().getGroups().isEmpty(), "graph versioning does not currently support target groups"); this.pool = pool; this.versionSelector = versionSelector; this.unversionedTargetGraphAndBuildTargets = unversionedTargetGraphAndBuildTargets; this.index = new ConcurrentHashMap<>( unversionedTargetGraphAndBuildTargets.getTargetGraph().getNodes().size() * 4, 0.75f, pool.getParallelism()); this.rootActions = new ConcurrentHashMap<>( unversionedTargetGraphAndBuildTargets.getTargetGraph().getNodes().size() / 2, 0.75f, pool.getParallelism()); this.versionInfo = new ConcurrentHashMap<>( 2 * unversionedTargetGraphAndBuildTargets.getTargetGraph().getNodes().size(), 0.75f, pool.getParallelism()); } private TargetNode<?, ?> getNode(BuildTarget target) { return unversionedTargetGraphAndBuildTargets.getTargetGraph().get(target); } private Optional<TargetNode<?, ?>> getNodeOptional(BuildTarget target) { return unversionedTargetGraphAndBuildTargets.getTargetGraph().getOptional(target); } private TargetNode<?, ?> indexPutIfAbsent(TargetNode<?, ?> node) { return index.putIfAbsent(node.getBuildTarget(), node); } /** * Get/cache the transitive version info for this node. */ private VersionInfo getVersionInfo(TargetNode<?, ?> node) { VersionInfo info = this.versionInfo.get(node.getBuildTarget()); if (info != null) { return info; } Map<BuildTarget, ImmutableSet<Version>> versionDomain = new HashMap<>(); Optional<TargetNode<VersionedAliasDescription.Arg, ?>> versionedNode = TargetGraphVersionTransformations.getVersionedNode(node); if (versionedNode.isPresent()) { ImmutableMap<Version, BuildTarget> versions = versionedNode.get().getConstructorArg().versions; // Merge in the versioned deps and the version domain. versionDomain.put(node.getBuildTarget(), versions.keySet()); // If this version has only one possible choice, there's no need to wrap the constraints from // it's transitive deps in an implication constraint. if (versions.size() == 1) { Map.Entry<Version, BuildTarget> ent = versions.entrySet().iterator().next(); VersionInfo depInfo = getVersionInfo(getNode(ent.getValue())); versionDomain.putAll(depInfo.getVersionDomain()); } else { // For each version choice, inherit the transitive constraints by wrapping them in an // implication dependent on the specific version that pulls them in. for (Map.Entry<Version, BuildTarget> ent : versions.entrySet()) { VersionInfo depInfo = getVersionInfo(getNode(ent.getValue())); versionDomain.putAll(depInfo.getVersionDomain()); } } } else { // Merge in the constraints and version domain/deps from transitive deps. for (BuildTarget depTarget : TargetGraphVersionTransformations.getDeps(node)) { TargetNode<?, ?> dep = getNode(depTarget); if (TargetGraphVersionTransformations.isVersionPropagator(dep) || TargetGraphVersionTransformations.getVersionedNode(dep).isPresent()) { VersionInfo depInfo = getVersionInfo(dep); versionDomain.putAll(depInfo.getVersionDomain()); } } } info = VersionInfo.of(versionDomain); this.versionInfo.put(node.getBuildTarget(), info); return info; } /** * @return a flavor to which summarizes the given version selections. */ static Flavor getVersionedFlavor(SortedMap<BuildTarget, Version> versions) { Preconditions.checkArgument(!versions.isEmpty()); Hasher hasher = Hashing.md5().newHasher(); for (Map.Entry<BuildTarget, Version> ent : versions.entrySet()) { hasher.putString(ent.getKey().toString(), Charsets.UTF_8); hasher.putString(ent.getValue().getName(), Charsets.UTF_8); } return InternalFlavor.of("v" + hasher.hash().toString().substring(0, 7)); } private TargetNode<?, ?> resolveVersions( TargetNode<?, ?> node, ImmutableMap<BuildTarget, Version> selectedVersions) { Optional<TargetNode<VersionedAliasDescription.Arg, ?>> versionedNode = node.castArg(VersionedAliasDescription.Arg.class); if (versionedNode.isPresent()) { node = getNode( Preconditions.checkNotNull( versionedNode.get().getConstructorArg().versions.get( selectedVersions.get(node.getBuildTarget())))); } return node; } /** * @return the {@link BuildTarget} to use in the resolved target graph, formed by adding a * flavor generated from the given version selections. */ private Optional<BuildTarget> getTranslateBuildTarget( TargetNode<?, ?> node, ImmutableMap<BuildTarget, Version> selectedVersions) { BuildTarget originalTarget = node.getBuildTarget(); node = resolveVersions(node, selectedVersions); BuildTarget newTarget = node.getBuildTarget(); if (TargetGraphVersionTransformations.isVersionPropagator(node)) { VersionInfo info = getVersionInfo(node); Collection<BuildTarget> versionedDeps = info.getVersionDomain().keySet(); TreeMap<BuildTarget, Version> versions = new TreeMap<>(); for (BuildTarget depTarget : versionedDeps) { versions.put(depTarget, selectedVersions.get(depTarget)); } if (!versions.isEmpty()) { Flavor versionedFlavor = getVersionedFlavor(versions); newTarget = node.getBuildTarget().withAppendedFlavors(versionedFlavor); } } return newTarget.equals(originalTarget) ? Optional.empty() : Optional.of(newTarget); } public TargetGraph build() throws VersionException, InterruptedException { LOG.debug( "Starting version target graph transformation (nodes %d)", unversionedTargetGraphAndBuildTargets.getTargetGraph().getNodes().size()); long start = System.currentTimeMillis(); // Walk through explicit built targets, separating them into root and non-root nodes. ImmutableList<RootAction> actions = unversionedTargetGraphAndBuildTargets.getBuildTargets().stream() .map(this::getNode) .map(RootAction::new) .collect(MoreCollectors.toImmutableList()); // Add actions to the `rootActions` member for bookkeeping. actions.forEach(a -> rootActions.put(a.getRoot().getBuildTarget(), a)); // Kick off the jobs to process the root nodes. actions.forEach(pool::submit); // Wait for actions to complete. for (RootAction action : actions) { action.getChecked(); } long end = System.currentTimeMillis(); LOG.debug( "Finished version target graph transformation in %.2f (nodes %d, roots: %d)", (end - start) / 1000.0, index.size(), roots.get()); return targetGraphBuilder.build(); } public static TargetGraphAndBuildTargets transform( VersionSelector versionSelector, TargetGraphAndBuildTargets unversionedTargetGraphAndBuildTargets, ForkJoinPool pool) throws VersionException, InterruptedException { return unversionedTargetGraphAndBuildTargets.withTargetGraph( new VersionedTargetGraphBuilder( pool, versionSelector, unversionedTargetGraphAndBuildTargets) .build()); } /** * Transform a version sub-graph at the given root node. */ private class RootAction extends RecursiveAction { private final TargetNode<?, ?> node; RootAction(TargetNode<?, ?> node) { this.node = node; } private final Predicate<BuildTarget> isVersionPropagator = target -> TargetGraphVersionTransformations.isVersionPropagator(getNode(target)); private final Predicate<BuildTarget> isVersioned = target -> TargetGraphVersionTransformations.getVersionedNode(getNode(target)).isPresent(); /** * Process a non-root node in the graph. */ private TargetNode<?, ?> processNode(TargetNode<?, ?> node) throws VersionException { // If we've already processed this node, exit now. TargetNode<?, ?> processed = index.get(node.getBuildTarget()); if (processed != null) { return processed; } // Add the node to the graph and recurse on its deps. TargetNode<?, ?> oldNode = indexPutIfAbsent(node); if (oldNode != null) { node = oldNode; } else { targetGraphBuilder.addNode(node.getBuildTarget().withFlavors(), node); for (TargetNode<?, ?> dep : process(node.getDeps())) { targetGraphBuilder.addEdge(node, dep); } } return node; } /** * Dispatch new jobs to transform the given nodes in parallel and wait for their results. */ private Iterable<TargetNode<?, ?>> process(Iterable<BuildTarget> targets) throws VersionException { int size = Iterables.size(targets); List<RootAction> newActions = new ArrayList<>(size); List<RootAction> oldActions = new ArrayList<>(size); List<TargetNode<?, ?>> nonRootNodes = new ArrayList<>(size); for (BuildTarget target : targets) { TargetNode<?, ?> node = getNode(target); // If we see a root node, create an action to process it using the pool, since it's // potentially heavy-weight. if (TargetGraphVersionTransformations.isVersionRoot(node)) { RootAction oldAction = rootActions.get(target); if (oldAction != null) { oldActions.add(oldAction); } else { RootAction newAction = new RootAction(getNode(target)); oldAction = rootActions.putIfAbsent(target, newAction); if (oldAction == null) { newActions.add(newAction); } else { oldActions.add(oldAction); } } } else { nonRootNodes.add(node); } } // Kick off all new rootActions in parallel. invokeAll(newActions); // For non-root nodes, just process them in-place, as they are inexpensive. for (TargetNode<?, ?> node : nonRootNodes) { processNode(node); } // Wait for any existing rootActions to finish. for (RootAction action : oldActions) { action.join(); } // Now that everything is ready, return all the results. return StreamSupport.stream(targets.spliterator(), false) .map(index::get) .collect(MoreCollectors.toImmutableList()); } public Void getChecked() throws VersionException, InterruptedException { try { return get(); } catch (ExecutionException e) { Throwable rootCause = Throwables.getRootCause(e); Throwables.throwIfInstanceOf(rootCause, VersionException.class); Throwables.throwIfInstanceOf(rootCause, RuntimeException.class); throw new IllegalStateException( String.format("Unexpected exception: %s: %s", e.getClass(), e.getMessage()), e); } } @SuppressWarnings("unchecked") private TargetNode<?, ?> processVersionSubGraphNode( TargetNode<?, ?> node, ImmutableMap<BuildTarget, Version> selectedVersions, TargetNodeTranslator targetTranslator) throws VersionException { Optional<BuildTarget> newTarget = targetTranslator.translateBuildTarget(node.getBuildTarget()); TargetNode<?, ?> processed = index.get(newTarget.orElse(node.getBuildTarget())); if (processed != null) { return processed; } // Create the new target node, with the new target and deps. TargetNode<?, ?> newNode = ((Optional<TargetNode<?, ?>>) (Optional<?>) targetTranslator.translateNode(node)) .orElse(node); LOG.verbose( "%s: new node declared deps %s, extra deps %s, arg %s", newNode.getBuildTarget(), newNode.getDeclaredDeps(), newNode.getExtraDeps(), newNode.getConstructorArg()); // Add the new node, and it's dep edges, to the new graph. TargetNode<?, ?> oldNode = indexPutIfAbsent(newNode); if (oldNode != null) { newNode = oldNode; } else { // Insert the node into the graph, indexing it by a base target containing only the version // flavor, if one exists. targetGraphBuilder.addNode( node.getBuildTarget().withFlavors( Sets.difference( newNode.getBuildTarget().getFlavors(), node.getBuildTarget().getFlavors())), newNode); for (BuildTarget depTarget : FluentIterable.from(node.getDeps()) .filter(Predicates.or(isVersionPropagator, isVersioned))) { targetGraphBuilder.addEdge( newNode, processVersionSubGraphNode( resolveVersions(getNode(depTarget), selectedVersions), selectedVersions, targetTranslator)); } for (TargetNode<?, ?> dep : process( FluentIterable.from(node.getDeps()) .filter(Predicates.not(Predicates.or(isVersionPropagator, isVersioned))))) { targetGraphBuilder.addEdge(newNode, dep); } } return newNode; } // Transform a root node and its version sub-graph. private TargetNode<?, ?> processRoot(TargetNode<?, ?> root) throws VersionException { // If we've already processed this root, exit now. final TargetNode<?, ?> processedRoot = index.get(root.getBuildTarget()); if (processedRoot != null) { return processedRoot; } // For stats collection. roots.incrementAndGet(); VersionInfo versionInfo = getVersionInfo(root); // Select the versions to use for this sub-graph. final ImmutableMap<BuildTarget, Version> selectedVersions = versionSelector.resolve( root.getBuildTarget(), versionInfo.getVersionDomain()); // Build a target translator object to translate build targets. ImmutableList<TargetTranslator<?>> translators = ImmutableList.of( new QueryTargetTranslator()); TargetNodeTranslator targetTranslator = new TargetNodeTranslator(translators) { private final LoadingCache<BuildTarget, Optional<BuildTarget>> cache = CacheBuilder.newBuilder() .build( CacheLoader.from( target -> { // If we're handling the root node, there's nothing to translate. if (root.getBuildTarget().equals(target)) { return Optional.empty(); } // If this target isn't in the target graph, which can be the case // of build targets in the `tests` parameter, don't do any // translation. Optional<TargetNode<?, ?>> node = getNodeOptional(target); if (!node.isPresent()) { return Optional.empty(); } return getTranslateBuildTarget(getNode(target), selectedVersions); })); @Override public Optional<BuildTarget> translateBuildTarget(BuildTarget target) { return cache.getUnchecked(target); } @Override public Optional<ImmutableMap<BuildTarget, Version>> getSelectedVersions( BuildTarget target) { ImmutableMap.Builder<BuildTarget, Version> builder = ImmutableMap.builder(); for (BuildTarget dep : getVersionInfo(getNode(target)).getVersionDomain().keySet()) { builder.put(dep, selectedVersions.get(dep)); } return Optional.of(builder.build()); } }; return processVersionSubGraphNode(root, selectedVersions, targetTranslator); } @Override protected void compute() { try { processRoot(node); } catch (VersionException e) { completeExceptionally(e); } } public TargetNode<?, ?> getRoot() { return node; } } }
grumpyjames/buck
src/com/facebook/buck/versions/VersionedTargetGraphBuilder.java
Java
apache-2.0
20,103
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.gs.obevo.util.vfs; import java.nio.charset.Charset; /** * Interface to determine how the Charset is determined for the given input types. * * The common implementation either goes w/ a standard charset or derives it based on the bytes. * * Instances to this class should be accessed via {@link CharsetStrategyFactory}. */ public interface CharsetStrategy { Charset determineCharset(byte[] bytes); }
shantstepanian/obevo
obevo-core/src/main/java/com/gs/obevo/util/vfs/CharsetStrategy.java
Java
apache-2.0
1,019