Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
195
Analyzer analyzer = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName, Reader reader) { Tokenizer t = new WhitespaceTokenizer(Lucene.VERSION, reader); return new TokenStreamComponents(t, new TruncateTokenFilter(t, 3)); } };
0true
src_test_java_org_apache_lucene_analysis_miscellaneous_TruncateTokenFilterTests.java
941
Runnable lockRunnable = new Runnable() { public void run() { lock.lock(); } };
0true
hazelcast_src_test_java_com_hazelcast_concurrent_lock_LockTest.java
132
public class ReadPastEndException extends Exception { public ReadPastEndException() { super(); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_ReadPastEndException.java
85
public class ConvertGetterToMethodProposal extends CorrectionProposal { public static void addConvertGetterToMethodProposal(Collection<ICompletionProposal> proposals, CeylonEditor editor, IFile file, Node node) { Value getter = null; Tree.Type type = null; if (node instanceof Tree.AttributeGetterDefinition) { getter = ((Tree.AttributeGetterDefinition) node).getDeclarationModel(); type = ((Tree.AttributeGetterDefinition) node).getType(); } else if (node instanceof Tree.AttributeDeclaration && ((Tree.AttributeDeclaration) node).getSpecifierOrInitializerExpression() instanceof Tree.LazySpecifierExpression) { getter = ((Tree.AttributeDeclaration) node).getDeclarationModel(); type = ((Tree.AttributeDeclaration) node).getType(); } if (getter != null) { addConvertGetterToMethodProposal(proposals, editor, file, getter, type); } } private static void addConvertGetterToMethodProposal(Collection<ICompletionProposal> proposals, CeylonEditor editor, IFile file, Value getter, Tree.Type type) { try { RenameRefactoring refactoring = new RenameRefactoring(editor) { @Override public String getName() { return "Convert Getter to Method"; }; }; refactoring.setNewName(getter.getName() + "()"); if (refactoring.getDeclaration() == null || !refactoring.getDeclaration().equals(getter) || !refactoring.isEnabled() || !refactoring.checkAllConditions(new NullProgressMonitor()).isOK()) { return; } CompositeChange change = refactoring.createChange(new NullProgressMonitor()); if (change.getChildren().length == 0) { return; } if (type instanceof Tree.ValueModifier) { TextFileChange tfc = new TextFileChange("Convert Getter to Method", file); tfc.setEdit(new ReplaceEdit(type.getStartIndex(), type.getStopIndex() - type.getStartIndex() + 1, "function")); change.add(tfc); } ConvertGetterToMethodProposal proposal = new ConvertGetterToMethodProposal(change, getter); if (!proposals.contains(proposal)) { proposals.add(proposal); } } catch (OperationCanceledException e) { // noop } catch (CoreException e) { throw new RuntimeException(e); } } private ConvertGetterToMethodProposal(Change change, Value getter) { super("Convert getter '" + getter.getName() + "' to method", change, null, CHANGE); } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertGetterToMethodProposal.java
1,377
public class IndexMetaData { public interface Custom { String type(); interface Factory<T extends Custom> { String type(); T readFrom(StreamInput in) throws IOException; void writeTo(T customIndexMetaData, StreamOutput out) throws IOException; T fromMap(Map<String, Object> map) throws IOException; T fromXContent(XContentParser parser) throws IOException; void toXContent(T customIndexMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException; /** * Merges from first to second, with first being more important, i.e., if something exists in first and second, * first will prevail. */ T merge(T first, T second); } } public static Map<String, Custom.Factory> customFactories = new HashMap<String, Custom.Factory>(); static { // register non plugin custom metadata registerFactory(IndexWarmersMetaData.TYPE, IndexWarmersMetaData.FACTORY); } /** * Register a custom index meta data factory. Make sure to call it from a static block. */ public static void registerFactory(String type, Custom.Factory factory) { customFactories.put(type, factory); } @Nullable public static <T extends Custom> Custom.Factory<T> lookupFactory(String type) { return customFactories.get(type); } public static <T extends Custom> Custom.Factory<T> lookupFactorySafe(String type) throws ElasticsearchIllegalArgumentException { Custom.Factory<T> factory = customFactories.get(type); if (factory == null) { throw new ElasticsearchIllegalArgumentException("No custom index metadata factoy registered for type [" + type + "]"); } return factory; } public static final ClusterBlock INDEX_READ_ONLY_BLOCK = new ClusterBlock(5, "index read-only (api)", false, false, RestStatus.FORBIDDEN, ClusterBlockLevel.WRITE, ClusterBlockLevel.METADATA); public static final ClusterBlock INDEX_READ_BLOCK = new ClusterBlock(7, "index read (api)", false, false, RestStatus.FORBIDDEN, ClusterBlockLevel.READ); public static final ClusterBlock INDEX_WRITE_BLOCK = new ClusterBlock(8, "index write (api)", false, false, RestStatus.FORBIDDEN, ClusterBlockLevel.WRITE); public static final ClusterBlock INDEX_METADATA_BLOCK = new ClusterBlock(9, "index metadata (api)", false, false, RestStatus.FORBIDDEN, ClusterBlockLevel.METADATA); public static enum State { OPEN((byte) 0), CLOSE((byte) 1); private final byte id; State(byte id) { this.id = id; } public byte id() { return this.id; } public static State fromId(byte id) { if (id == 0) { return OPEN; } else if (id == 1) { return CLOSE; } throw new ElasticsearchIllegalStateException("No state match for id [" + id + "]"); } public static State fromString(String state) { if ("open".equals(state)) { return OPEN; } else if ("close".equals(state)) { return CLOSE; } throw new ElasticsearchIllegalStateException("No state match for [" + state + "]"); } } public static final String SETTING_NUMBER_OF_SHARDS = "index.number_of_shards"; public static final String SETTING_NUMBER_OF_REPLICAS = "index.number_of_replicas"; public static final String SETTING_AUTO_EXPAND_REPLICAS = "index.auto_expand_replicas"; public static final String SETTING_READ_ONLY = "index.blocks.read_only"; public static final String SETTING_BLOCKS_READ = "index.blocks.read"; public static final String SETTING_BLOCKS_WRITE = "index.blocks.write"; public static final String SETTING_BLOCKS_METADATA = "index.blocks.metadata"; public static final String SETTING_VERSION_CREATED = "index.version.created"; public static final String SETTING_UUID = "index.uuid"; public static final String INDEX_UUID_NA_VALUE = "_na_"; private final String index; private final long version; private final State state; private final ImmutableOpenMap<String, AliasMetaData> aliases; private final Settings settings; private final ImmutableOpenMap<String, MappingMetaData> mappings; private final ImmutableOpenMap<String, Custom> customs; private transient final int totalNumberOfShards; private final DiscoveryNodeFilters requireFilters; private final DiscoveryNodeFilters includeFilters; private final DiscoveryNodeFilters excludeFilters; private IndexMetaData(String index, long version, State state, Settings settings, ImmutableOpenMap<String, MappingMetaData> mappings, ImmutableOpenMap<String, AliasMetaData> aliases, ImmutableOpenMap<String, Custom> customs) { Preconditions.checkArgument(settings.getAsInt(SETTING_NUMBER_OF_SHARDS, -1) != -1, "must specify numberOfShards for index [" + index + "]"); Preconditions.checkArgument(settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, -1) != -1, "must specify numberOfReplicas for index [" + index + "]"); this.index = index; this.version = version; this.state = state; this.settings = settings; this.mappings = mappings; this.customs = customs; this.totalNumberOfShards = numberOfShards() * (numberOfReplicas() + 1); this.aliases = aliases; ImmutableMap<String, String> requireMap = settings.getByPrefix("index.routing.allocation.require.").getAsMap(); if (requireMap.isEmpty()) { requireFilters = null; } else { requireFilters = DiscoveryNodeFilters.buildFromKeyValue(AND, requireMap); } ImmutableMap<String, String> includeMap = settings.getByPrefix("index.routing.allocation.include.").getAsMap(); if (includeMap.isEmpty()) { includeFilters = null; } else { includeFilters = DiscoveryNodeFilters.buildFromKeyValue(OR, includeMap); } ImmutableMap<String, String> excludeMap = settings.getByPrefix("index.routing.allocation.exclude.").getAsMap(); if (excludeMap.isEmpty()) { excludeFilters = null; } else { excludeFilters = DiscoveryNodeFilters.buildFromKeyValue(OR, excludeMap); } } public String index() { return index; } public String getIndex() { return index(); } public String uuid() { return settings.get(SETTING_UUID, INDEX_UUID_NA_VALUE); } public String getUUID() { return uuid(); } /** * Test whether the current index UUID is the same as the given one. Returns true if either are _na_ */ public boolean isSameUUID(String otherUUID) { assert otherUUID != null; assert uuid() != null; if (INDEX_UUID_NA_VALUE.equals(otherUUID) || INDEX_UUID_NA_VALUE.equals(uuid())) { return true; } return otherUUID.equals(getUUID()); } public long version() { return this.version; } public long getVersion() { return this.version; } public State state() { return this.state; } public State getState() { return state(); } public int numberOfShards() { return settings.getAsInt(SETTING_NUMBER_OF_SHARDS, -1); } public int getNumberOfShards() { return numberOfShards(); } public int numberOfReplicas() { return settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, -1); } public int getNumberOfReplicas() { return numberOfReplicas(); } public int totalNumberOfShards() { return totalNumberOfShards; } public int getTotalNumberOfShards() { return totalNumberOfShards(); } public Settings settings() { return settings; } public Settings getSettings() { return settings(); } public ImmutableOpenMap<String, AliasMetaData> aliases() { return this.aliases; } public ImmutableOpenMap<String, AliasMetaData> getAliases() { return aliases(); } public ImmutableOpenMap<String, MappingMetaData> mappings() { return mappings; } public ImmutableOpenMap<String, MappingMetaData> getMappings() { return mappings(); } @Nullable public MappingMetaData mapping(String mappingType) { return mappings.get(mappingType); } /** * Sometimes, the default mapping exists and an actual mapping is not created yet (introduced), * in this case, we want to return the default mapping in case it has some default mapping definitions. * <p/> * Note, once the mapping type is introduced, the default mapping is applied on the actual typed MappingMetaData, * setting its routing, timestamp, and so on if needed. */ @Nullable public MappingMetaData mappingOrDefault(String mappingType) { MappingMetaData mapping = mappings.get(mappingType); if (mapping != null) { return mapping; } return mappings.get(MapperService.DEFAULT_MAPPING); } public ImmutableOpenMap<String, Custom> customs() { return this.customs; } public ImmutableOpenMap<String, Custom> getCustoms() { return this.customs; } public <T extends Custom> T custom(String type) { return (T) customs.get(type); } @Nullable public DiscoveryNodeFilters requireFilters() { return requireFilters; } @Nullable public DiscoveryNodeFilters includeFilters() { return includeFilters; } @Nullable public DiscoveryNodeFilters excludeFilters() { return excludeFilters; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexMetaData that = (IndexMetaData) o; if (!aliases.equals(that.aliases)) { return false; } if (!index.equals(that.index)) { return false; } if (!mappings.equals(that.mappings)) { return false; } if (!settings.equals(that.settings)) { return false; } if (state != that.state) { return false; } return true; } @Override public int hashCode() { int result = index.hashCode(); result = 31 * result + state.hashCode(); result = 31 * result + aliases.hashCode(); result = 31 * result + settings.hashCode(); result = 31 * result + mappings.hashCode(); return result; } public static Builder builder(String index) { return new Builder(index); } public static Builder builder(IndexMetaData indexMetaData) { return new Builder(indexMetaData); } public static class Builder { private String index; private State state = State.OPEN; private long version = 1; private Settings settings = ImmutableSettings.Builder.EMPTY_SETTINGS; private final ImmutableOpenMap.Builder<String, MappingMetaData> mappings; private final ImmutableOpenMap.Builder<String, AliasMetaData> aliases; private final ImmutableOpenMap.Builder<String, Custom> customs; public Builder(String index) { this.index = index; this.mappings = ImmutableOpenMap.builder(); this.aliases = ImmutableOpenMap.builder(); this.customs = ImmutableOpenMap.builder(); } public Builder(IndexMetaData indexMetaData) { this.index = indexMetaData.index(); this.state = indexMetaData.state; this.version = indexMetaData.version; this.settings = indexMetaData.settings(); this.mappings = ImmutableOpenMap.builder(indexMetaData.mappings); this.aliases = ImmutableOpenMap.builder(indexMetaData.aliases); this.customs = ImmutableOpenMap.builder(indexMetaData.customs); } public String index() { return index; } public Builder index(String index) { this.index = index; return this; } public Builder numberOfShards(int numberOfShards) { settings = settingsBuilder().put(settings).put(SETTING_NUMBER_OF_SHARDS, numberOfShards).build(); return this; } public int numberOfShards() { return settings.getAsInt(SETTING_NUMBER_OF_SHARDS, -1); } public Builder numberOfReplicas(int numberOfReplicas) { settings = settingsBuilder().put(settings).put(SETTING_NUMBER_OF_REPLICAS, numberOfReplicas).build(); return this; } public int numberOfReplicas() { return settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, -1); } public Builder settings(Settings.Builder settings) { this.settings = settings.build(); return this; } public Builder settings(Settings settings) { this.settings = settings; return this; } public MappingMetaData mapping(String type) { return mappings.get(type); } public Builder removeMapping(String mappingType) { mappings.remove(mappingType); return this; } public Builder putMapping(String type, String source) throws IOException { XContentParser parser = XContentFactory.xContent(source).createParser(source); try { putMapping(new MappingMetaData(type, parser.mapOrdered())); } finally { parser.close(); } return this; } public Builder putMapping(MappingMetaData mappingMd) { mappings.put(mappingMd.type(), mappingMd); return this; } public Builder state(State state) { this.state = state; return this; } public Builder putAlias(AliasMetaData aliasMetaData) { aliases.put(aliasMetaData.alias(), aliasMetaData); return this; } public Builder putAlias(AliasMetaData.Builder aliasMetaData) { aliases.put(aliasMetaData.alias(), aliasMetaData.build()); return this; } public Builder removerAlias(String alias) { aliases.remove(alias); return this; } public Builder putCustom(String type, Custom customIndexMetaData) { this.customs.put(type, customIndexMetaData); return this; } public Builder removeCustom(String type) { this.customs.remove(type); return this; } public Custom getCustom(String type) { return this.customs.get(type); } public long version() { return this.version; } public Builder version(long version) { this.version = version; return this; } public IndexMetaData build() { ImmutableOpenMap.Builder<String, AliasMetaData> tmpAliases = aliases; Settings tmpSettings = settings; // For backward compatibility String[] legacyAliases = settings.getAsArray("index.aliases"); if (legacyAliases.length > 0) { tmpAliases = ImmutableOpenMap.builder(); for (String alias : legacyAliases) { AliasMetaData aliasMd = AliasMetaData.newAliasMetaDataBuilder(alias).build(); tmpAliases.put(alias, aliasMd); } tmpAliases.putAll(aliases); // Remove index.aliases from settings once they are migrated to the new data structure tmpSettings = ImmutableSettings.settingsBuilder().put(settings).putArray("index.aliases").build(); } // update default mapping on the MappingMetaData if (mappings.containsKey(MapperService.DEFAULT_MAPPING)) { MappingMetaData defaultMapping = mappings.get(MapperService.DEFAULT_MAPPING); for (ObjectCursor<MappingMetaData> cursor : mappings.values()) { cursor.value.updateDefaultMapping(defaultMapping); } } return new IndexMetaData(index, version, state, tmpSettings, mappings.build(), tmpAliases.build(), customs.build()); } public static void toXContent(IndexMetaData indexMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(indexMetaData.index(), XContentBuilder.FieldCaseConversion.NONE); builder.field("version", indexMetaData.version()); builder.field("state", indexMetaData.state().toString().toLowerCase(Locale.ENGLISH)); boolean binary = params.paramAsBoolean("binary", false); builder.startObject("settings"); for (Map.Entry<String, String> entry : indexMetaData.settings().getAsMap().entrySet()) { builder.field(entry.getKey(), entry.getValue()); } builder.endObject(); builder.startArray("mappings"); for (ObjectObjectCursor<String, MappingMetaData> cursor : indexMetaData.mappings()) { if (binary) { builder.value(cursor.value.source().compressed()); } else { byte[] data = cursor.value.source().uncompressed(); XContentParser parser = XContentFactory.xContent(data).createParser(data); Map<String, Object> mapping = parser.mapOrdered(); parser.close(); builder.map(mapping); } } builder.endArray(); for (ObjectObjectCursor<String, Custom> cursor : indexMetaData.customs()) { builder.startObject(cursor.key, XContentBuilder.FieldCaseConversion.NONE); lookupFactorySafe(cursor.key).toXContent(cursor.value, builder, params); builder.endObject(); } builder.startObject("aliases"); for (ObjectCursor<AliasMetaData> cursor : indexMetaData.aliases().values()) { AliasMetaData.Builder.toXContent(cursor.value, builder, params); } builder.endObject(); builder.endObject(); } public static IndexMetaData fromXContent(XContentParser parser) throws IOException { if (parser.currentToken() == XContentParser.Token.START_OBJECT) { parser.nextToken(); } Builder builder = new Builder(parser.currentName()); String currentFieldName = null; XContentParser.Token token = parser.nextToken(); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { if ("settings".equals(currentFieldName)) { builder.settings(ImmutableSettings.settingsBuilder().put(SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered()))); } else if ("mappings".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { String mappingType = currentFieldName; Map<String, Object> mappingSource = MapBuilder.<String, Object>newMapBuilder().put(mappingType, parser.mapOrdered()).map(); builder.putMapping(new MappingMetaData(mappingType, mappingSource)); } } } else if ("aliases".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { builder.putAlias(AliasMetaData.Builder.fromXContent(parser)); } } else { // check if its a custom index metadata Custom.Factory<Custom> factory = lookupFactory(currentFieldName); if (factory == null) { //TODO warn parser.skipChildren(); } else { builder.putCustom(factory.type(), factory.fromXContent(parser)); } } } else if (token == XContentParser.Token.START_ARRAY) { if ("mappings".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) { builder.putMapping(new MappingMetaData(new CompressedString(parser.binaryValue()))); } else { Map<String, Object> mapping = parser.mapOrdered(); if (mapping.size() == 1) { String mappingType = mapping.keySet().iterator().next(); builder.putMapping(new MappingMetaData(mappingType, mapping)); } } } } } else if (token.isValue()) { if ("state".equals(currentFieldName)) { builder.state(State.fromString(parser.text())); } else if ("version".equals(currentFieldName)) { builder.version(parser.longValue()); } } } return builder.build(); } public static IndexMetaData readFrom(StreamInput in) throws IOException { Builder builder = new Builder(in.readString()); builder.version(in.readLong()); builder.state(State.fromId(in.readByte())); builder.settings(readSettingsFromStream(in)); int mappingsSize = in.readVInt(); for (int i = 0; i < mappingsSize; i++) { MappingMetaData mappingMd = MappingMetaData.readFrom(in); builder.putMapping(mappingMd); } int aliasesSize = in.readVInt(); for (int i = 0; i < aliasesSize; i++) { AliasMetaData aliasMd = AliasMetaData.Builder.readFrom(in); builder.putAlias(aliasMd); } int customSize = in.readVInt(); for (int i = 0; i < customSize; i++) { String type = in.readString(); Custom customIndexMetaData = lookupFactorySafe(type).readFrom(in); builder.putCustom(type, customIndexMetaData); } return builder.build(); } public static void writeTo(IndexMetaData indexMetaData, StreamOutput out) throws IOException { out.writeString(indexMetaData.index()); out.writeLong(indexMetaData.version()); out.writeByte(indexMetaData.state().id()); writeSettingsToStream(indexMetaData.settings(), out); out.writeVInt(indexMetaData.mappings().size()); for (ObjectCursor<MappingMetaData> cursor : indexMetaData.mappings().values()) { MappingMetaData.writeTo(cursor.value, out); } out.writeVInt(indexMetaData.aliases().size()); for (ObjectCursor<AliasMetaData> cursor : indexMetaData.aliases().values()) { AliasMetaData.Builder.writeTo(cursor.value, out); } out.writeVInt(indexMetaData.customs().size()); for (ObjectObjectCursor<String, Custom> cursor : indexMetaData.customs()) { out.writeString(cursor.key); lookupFactorySafe(cursor.key).writeTo(cursor.value, out); } } } }
1no label
src_main_java_org_elasticsearch_cluster_metadata_IndexMetaData.java
241
private static class CommandFactory extends XaCommandFactory { private final NeoStore neoStore; private final IndexingService indexingService; CommandFactory( NeoStore neoStore, IndexingService indexingService ) { this.neoStore = neoStore; this.indexingService = indexingService; } @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { return Command.readCommand( neoStore, indexingService, byteChannel, buffer ); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreXaDataSource.java
1,620
threadPool.generic().execute(new Runnable() { @Override public void run() { for (DiscoveryNode node : nodesDelta.removedNodes()) { transportService.disconnectFromNode(node); } } });
0true
src_main_java_org_elasticsearch_cluster_service_InternalClusterService.java
923
registerLockStoreConstructor(SERVICE_NAME, new ConstructorFunction<ObjectNamespace, LockStoreInfo>() { public LockStoreInfo createNew(ObjectNamespace key) { return new LockStoreInfo() { @Override public int getBackupCount() { return 1; } @Override public int getAsyncBackupCount() { return 0; } }; } });
0true
hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockServiceImpl.java
3,211
constructors[REPL_CLEAR_MESSAGE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new VectorClock(); } };
1no label
hazelcast_src_main_java_com_hazelcast_replicatedmap_operation_ReplicatedMapDataSerializerHook.java
1,865
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() { public Boolean execute(TransactionalTaskContext context) throws TransactionException { final TransactionalMap<Object, Object> txMap = context.getMap("default"); txMap.put("3", "3"); map2.put("4", "4"); assertEquals("1", txMap.remove("1")); assertEquals("2", map2.remove("2")); assertEquals("1", map2.get("1")); assertEquals(null, txMap.get("1")); assertEquals(null, txMap.remove("2")); assertEquals(2, txMap.size()); return true; } });
0true
hazelcast_src_test_java_com_hazelcast_map_MapTransactionTest.java
3,072
public class CloseEngineException extends EngineException { public CloseEngineException(ShardId shardId, String msg) { super(shardId, msg); } public CloseEngineException(ShardId shardId, String msg, Throwable cause) { super(shardId, msg, cause); } }
0true
src_main_java_org_elasticsearch_index_engine_CloseEngineException.java
218
private static final ThreadLocal<ThreadLocalManager> THREAD_LOCAL_MANAGER = new ThreadLocal<ThreadLocalManager>() { @Override protected ThreadLocalManager initialValue() { return new ThreadLocalManager(); } };
0true
common_src_main_java_org_broadleafcommerce_common_classloader_release_ThreadLocalManager.java
1,961
@Repository("blRoleDao") public class RoleDaoImpl implements RoleDao { @PersistenceContext(unitName = "blPU") protected EntityManager em; @Resource(name = "blEntityConfiguration") protected EntityConfiguration entityConfiguration; public Address readAddressById(Long id) { return (Address) em.find(AddressImpl.class, id); } @SuppressWarnings("unchecked") public List<CustomerRole> readCustomerRolesByCustomerId(Long customerId) { Query query = em.createNamedQuery("BC_READ_CUSTOMER_ROLES_BY_CUSTOMER_ID"); query.setParameter("customerId", customerId); return query.getResultList(); } public Role readRoleByName(String name) { Query query = em.createNamedQuery("BC_READ_ROLE_BY_NAME"); query.setParameter("name", name); return (Role) query.getSingleResult(); } public void addRoleToCustomer(CustomerRole customerRole) { em.persist(customerRole); } }
1no label
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_dao_RoleDaoImpl.java
160
private final class MultiTargetCallback { final Collection<Address> targets; final ConcurrentMap<Address, Object> results; private MultiTargetCallback(Collection<Address> targets) { this.targets = synchronizedSet(new HashSet<Address>(targets)); this.results = new ConcurrentHashMap<Address, Object>(targets.size()); } public void notify(Address target, Object result) { if (targets.remove(target)) { results.put(target, result); } else { if (results.containsKey(target)) { throw new IllegalArgumentException("Duplicate response from -> " + target); } throw new IllegalArgumentException("Unknown target! -> " + target); } if (targets.isEmpty()) { Object response = reduce(results); endpoint.sendResponse(response, getCallId()); } } }
0true
hazelcast_src_main_java_com_hazelcast_client_MultiTargetClientRequest.java
150
public final class LifecycleServiceImpl implements LifecycleService { private final HazelcastClient client; private final ConcurrentMap<String, LifecycleListener> lifecycleListeners = new ConcurrentHashMap<String, LifecycleListener>(); private final AtomicBoolean active = new AtomicBoolean(false); private final BuildInfo buildInfo; public LifecycleServiceImpl(HazelcastClient client) { this.client = client; final List<ListenerConfig> listenerConfigs = client.getClientConfig().getListenerConfigs(); if (listenerConfigs != null && !listenerConfigs.isEmpty()) { for (ListenerConfig listenerConfig : listenerConfigs) { if (listenerConfig.getImplementation() instanceof LifecycleListener) { addLifecycleListener((LifecycleListener) listenerConfig.getImplementation()); } } } buildInfo = BuildInfoProvider.getBuildInfo(); fireLifecycleEvent(STARTING); } private ILogger getLogger() { return Logger.getLogger(LifecycleService.class); } public String addLifecycleListener(LifecycleListener lifecycleListener) { final String id = UuidUtil.buildRandomUuidString(); lifecycleListeners.put(id, lifecycleListener); return id; } public boolean removeLifecycleListener(String registrationId) { return lifecycleListeners.remove(registrationId) != null; } public void fireLifecycleEvent(LifecycleEvent.LifecycleState lifecycleState) { final LifecycleEvent lifecycleEvent = new LifecycleEvent(lifecycleState); getLogger().info("HazelcastClient[" + client.getName() + "]" + "[" + buildInfo.getVersion() + "] is " + lifecycleEvent.getState()); for (LifecycleListener lifecycleListener : lifecycleListeners.values()) { lifecycleListener.stateChanged(lifecycleEvent); } } void setStarted() { active.set(true); fireLifecycleEvent(STARTED); } public boolean isRunning() { return active.get(); } public void shutdown() { if (!active.compareAndSet(true, false)) { return; } fireLifecycleEvent(SHUTTING_DOWN); client.doShutdown(); fireLifecycleEvent(SHUTDOWN); } public void terminate() { shutdown(); } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_LifecycleServiceImpl.java
430
public interface IndexRetriever { /** * Returns the {@link KeyInformation} for a particular key in a given store. * * @param store * @param key * @return */ public KeyInformation get(String store, String key); /** * Returns a {@link StoreRetriever} for the given store on this IndexRetriever * @param store * @return */ public StoreRetriever get(String store); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_KeyInformation.java
1,011
public static class Order { }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_FulfillmentOptionImpl.java
1,808
private static class ChangeStateEntryProcessor implements EntryProcessor, EntryBackupProcessor { ChangeStateEntryProcessor() { } public Object process(Map.Entry entry) { SampleObjects.Employee value = (SampleObjects.Employee) entry.getValue(); value.setState(SampleObjects.State.STATE2); entry.setValue(value); return value; } public EntryBackupProcessor getBackupProcessor() { return ChangeStateEntryProcessor.this; } public void processBackup(Map.Entry entry) { SampleObjects.Employee value = (SampleObjects.Employee) entry.getValue(); value.setState(SampleObjects.State.STATE2); entry.setValue(value); } }
0true
hazelcast_src_test_java_com_hazelcast_map_MapClientRequestTest.java
4,890
public class RestNodesAction extends AbstractCatAction { @Inject public RestNodesAction(Settings settings, Client client, RestController controller) { super(settings, client); controller.registerHandler(GET, "/_cat/nodes", this); } @Override void documentation(StringBuilder sb) { sb.append("/_cat/nodes\n"); } @Override public void doRequest(final RestRequest request, final RestChannel channel) { final ClusterStateRequest clusterStateRequest = new ClusterStateRequest(); clusterStateRequest.clear().nodes(true); clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local())); clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout())); client.admin().cluster().state(clusterStateRequest, new ActionListener<ClusterStateResponse>() { @Override public void onResponse(final ClusterStateResponse clusterStateResponse) { NodesInfoRequest nodesInfoRequest = new NodesInfoRequest(); nodesInfoRequest.clear().jvm(true).os(true).process(true); client.admin().cluster().nodesInfo(nodesInfoRequest, new ActionListener<NodesInfoResponse>() { @Override public void onResponse(final NodesInfoResponse nodesInfoResponse) { NodesStatsRequest nodesStatsRequest = new NodesStatsRequest(); nodesStatsRequest.clear().jvm(true).os(true).fs(true).indices(true); client.admin().cluster().nodesStats(nodesStatsRequest, new ActionListener<NodesStatsResponse>() { @Override public void onResponse(NodesStatsResponse nodesStatsResponse) { try { channel.sendResponse(RestTable.buildResponse(buildTable(request, clusterStateResponse, nodesInfoResponse, nodesStatsResponse), request, channel)); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); } @Override Table getTableWithHeader(final RestRequest request) { Table table = new Table(); table.startHeaders(); table.addCell("id", "default:false;alias:id,nodeId;desc:unique node id"); table.addCell("pid", "default:false;alias:p;desc:process id"); table.addCell("host", "alias:h;desc:host name"); table.addCell("ip", "alias:i;desc:ip address"); table.addCell("port", "default:false;alias:po;desc:bound transport port"); table.addCell("version", "default:false;alias:v;desc:es version"); table.addCell("build", "default:false;alias:b;desc:es build hash"); table.addCell("jdk", "default:false;alias:j;desc:jdk version"); table.addCell("disk.avail", "default:false;alias:d,disk,diskAvail;text-align:right;desc:available disk space"); table.addCell("heap.percent", "alias:hp,heapPercent;text-align:right;desc:used heap ratio"); table.addCell("heap.max", "default:false;alias:hm,heapMax;text-align:right;desc:max configured heap"); table.addCell("ram.percent", "alias:rp,ramPercent;text-align:right;desc:used machine memory ratio"); table.addCell("ram.max", "default:false;alias:rm,ramMax;text-align:right;desc:total machine memory"); table.addCell("load", "alias:l;text-align:right;desc:most recent load avg"); table.addCell("uptime", "default:false;alias:u;text-align:right;desc:node uptime"); table.addCell("node.role", "alias:r,role,dc,nodeRole;desc:d:data node, c:client node"); table.addCell("master", "alias:m;desc:m:master-eligible, *:current master"); table.addCell("name", "alias:n;desc:node name"); table.addCell("completion.size", "alias:cs,completionSize;default:false;text-align:right;desc:size of completion"); table.addCell("fielddata.memory_size", "alias:fm,fielddataMemory;default:false;text-align:right;desc:used fielddata cache"); table.addCell("fielddata.evictions", "alias:fe,fielddataEvictions;default:false;text-align:right;desc:fielddata evictions"); table.addCell("filter_cache.memory_size", "alias:fcm,filterCacheMemory;default:false;text-align:right;desc:used filter cache"); table.addCell("filter_cache.evictions", "alias:fce,filterCacheEvictions;default:false;text-align:right;desc:filter cache evictions"); table.addCell("flush.total", "alias:ft,flushTotal;default:false;text-align:right;desc:number of flushes"); table.addCell("flush.total_time", "alias:ftt,flushTotalTime;default:false;text-align:right;desc:time spent in flush"); table.addCell("get.current", "alias:gc,getCurrent;default:false;text-align:right;desc:number of current get ops"); table.addCell("get.time", "alias:gti,getTime;default:false;text-align:right;desc:time spent in get"); table.addCell("get.total", "alias:gto,getTotal;default:false;text-align:right;desc:number of get ops"); table.addCell("get.exists_time", "alias:geti,getExistsTime;default:false;text-align:right;desc:time spent in successful gets"); table.addCell("get.exists_total", "alias:geto,getExistsTotal;default:false;text-align:right;desc:number of successful gets"); table.addCell("get.missing_time", "alias:gmti,getMissingTime;default:false;text-align:right;desc:time spent in failed gets"); table.addCell("get.missing_total", "alias:gmto,getMissingTotal;default:false;text-align:right;desc:number of failed gets"); table.addCell("id_cache.memory_size", "alias:im,idCacheMemory;default:false;text-align:right;desc:used id cache"); table.addCell("indexing.delete_current", "alias:idc,indexingDeleteCurrent;default:false;text-align:right;desc:number of current deletions"); table.addCell("indexing.delete_time", "alias:idti,indexingDeleteTime;default:false;text-align:right;desc:time spent in deletions"); table.addCell("indexing.delete_total", "alias:idto,indexingDeleteTotal;default:false;text-align:right;desc:number of delete ops"); table.addCell("indexing.index_current", "alias:iic,indexingIndexCurrent;default:false;text-align:right;desc:number of current indexing ops"); table.addCell("indexing.index_time", "alias:iiti,indexingIndexTime;default:false;text-align:right;desc:time spent in indexing"); table.addCell("indexing.index_total", "alias:iito,indexingIndexTotal;default:false;text-align:right;desc:number of indexing ops"); table.addCell("merges.current", "alias:mc,mergesCurrent;default:false;text-align:right;desc:number of current merges"); table.addCell("merges.current_docs", "alias:mcd,mergesCurrentDocs;default:false;text-align:right;desc:number of current merging docs"); table.addCell("merges.current_size", "alias:mcs,mergesCurrentSize;default:false;text-align:right;desc:size of current merges"); table.addCell("merges.total", "alias:mt,mergesTotal;default:false;text-align:right;desc:number of completed merge ops"); table.addCell("merges.total_docs", "alias:mtd,mergesTotalDocs;default:false;text-align:right;desc:docs merged"); table.addCell("merges.total_size", "alias:mts,mergesTotalSize;default:false;text-align:right;desc:size merged"); table.addCell("merges.total_time", "alias:mtt,mergesTotalTime;default:false;text-align:right;desc:time spent in merges"); table.addCell("percolate.current", "alias:pc,percolateCurrent;default:false;text-align:right;desc:number of current percolations"); table.addCell("percolate.memory_size", "alias:pm,percolateMemory;default:false;text-align:right;desc:memory used by percolations"); table.addCell("percolate.queries", "alias:pq,percolateQueries;default:false;text-align:right;desc:number of registered percolation queries"); table.addCell("percolate.time", "alias:pti,percolateTime;default:false;text-align:right;desc:time spent percolating"); table.addCell("percolate.total", "alias:pto,percolateTotal;default:false;text-align:right;desc:total percolations"); table.addCell("refresh.total", "alias:rto,refreshTotal;default:false;text-align:right;desc:total refreshes"); table.addCell("refresh.time", "alias:rti,refreshTime;default:false;text-align:right;desc:time spent in refreshes"); table.addCell("search.fetch_current", "alias:sfc,searchFetchCurrent;default:false;text-align:right;desc:current fetch phase ops"); table.addCell("search.fetch_time", "alias:sfti,searchFetchTime;default:false;text-align:right;desc:time spent in fetch phase"); table.addCell("search.fetch_total", "alias:sfto,searchFetchTotal;default:false;text-align:right;desc:total fetch ops"); table.addCell("search.open_contexts", "alias:so,searchOpenContexts;default:false;text-align:right;desc:open search contexts"); table.addCell("search.query_current", "alias:sqc,searchQueryCurrent;default:false;text-align:right;desc:current query phase ops"); table.addCell("search.query_time", "alias:sqti,searchQueryTime;default:false;text-align:right;desc:time spent in query phase"); table.addCell("search.query_total", "alias:sqto,searchQueryTotal;default:false;text-align:right;desc:total query phase ops"); table.addCell("segments.count", "alias:sc,segmentsCount;default:false;text-align:right;desc:number of segments"); table.addCell("segments.memory", "alias:sm,segmentsMemory;default:false;text-align:right;desc:memory used by segments"); table.endHeaders(); return table; } private Table buildTable(RestRequest req, ClusterStateResponse state, NodesInfoResponse nodesInfo, NodesStatsResponse nodesStats) { boolean fullId = req.paramAsBoolean("full_id", false); DiscoveryNodes nodes = state.getState().nodes(); String masterId = nodes.masterNodeId(); Table table = getTableWithHeader(req); for (DiscoveryNode node : nodes) { NodeInfo info = nodesInfo.getNodesMap().get(node.id()); NodeStats stats = nodesStats.getNodesMap().get(node.id()); table.startRow(); table.addCell(fullId ? node.id() : Strings.substring(node.getId(), 0, 4)); table.addCell(info == null ? null : info.getProcess().id()); table.addCell(node.getHostName()); table.addCell(node.getHostAddress()); if (node.address() instanceof InetSocketTransportAddress) { table.addCell(((InetSocketTransportAddress) node.address()).address().getPort()); } else { table.addCell("-"); } table.addCell(info == null ? null : info.getVersion().number()); table.addCell(info == null ? null : info.getBuild().hashShort()); table.addCell(info == null ? null : info.getJvm().version()); table.addCell(stats == null ? null : stats.getFs() == null ? null : stats.getFs().total().getAvailable()); table.addCell(stats == null ? null : stats.getJvm().getMem().getHeapUsedPrecent()); table.addCell(info == null ? null : info.getJvm().getMem().getHeapMax()); table.addCell(stats == null ? null : stats.getOs().mem() == null ? null : stats.getOs().mem().usedPercent()); table.addCell(info == null ? null : info.getOs().mem() == null ? null : info.getOs().mem().total()); // sigar fails to load in IntelliJ table.addCell(stats == null ? null : stats.getOs() == null ? null : stats.getOs().getLoadAverage().length < 1 ? null : String.format(Locale.ROOT, "%.2f", stats.getOs().getLoadAverage()[0])); table.addCell(stats == null ? null : stats.getJvm().uptime()); table.addCell(node.clientNode() ? "c" : node.dataNode() ? "d" : "-"); table.addCell(masterId.equals(node.id()) ? "*" : node.masterNode() ? "m" : "-"); table.addCell(node.name()); table.addCell(stats == null ? null : stats.getIndices().getCompletion().getSize()); table.addCell(stats == null ? null : stats.getIndices().getFieldData().getMemorySize()); table.addCell(stats == null ? null : stats.getIndices().getFieldData().getEvictions()); table.addCell(stats == null ? null : stats.getIndices().getFilterCache().getMemorySize()); table.addCell(stats == null ? null : stats.getIndices().getFilterCache().getEvictions()); table.addCell(stats == null ? null : stats.getIndices().getFlush().getTotal()); table.addCell(stats == null ? null : stats.getIndices().getFlush().getTotalTime()); table.addCell(stats == null ? null : stats.getIndices().getGet().current()); table.addCell(stats == null ? null : stats.getIndices().getGet().getTime()); table.addCell(stats == null ? null : stats.getIndices().getGet().getCount()); table.addCell(stats == null ? null : stats.getIndices().getGet().getExistsTime()); table.addCell(stats == null ? null : stats.getIndices().getGet().getExistsCount()); table.addCell(stats == null ? null : stats.getIndices().getGet().getMissingTime()); table.addCell(stats == null ? null : stats.getIndices().getGet().getMissingCount()); table.addCell(stats == null ? null : stats.getIndices().getIdCache().getMemorySize()); table.addCell(stats == null ? null : stats.getIndices().getIndexing().getTotal().getDeleteCurrent()); table.addCell(stats == null ? null : stats.getIndices().getIndexing().getTotal().getDeleteTime()); table.addCell(stats == null ? null : stats.getIndices().getIndexing().getTotal().getDeleteCount()); table.addCell(stats == null ? null : stats.getIndices().getIndexing().getTotal().getIndexCurrent()); table.addCell(stats == null ? null : stats.getIndices().getIndexing().getTotal().getIndexTime()); table.addCell(stats == null ? null : stats.getIndices().getIndexing().getTotal().getIndexCount()); table.addCell(stats == null ? null : stats.getIndices().getMerge().getCurrent()); table.addCell(stats == null ? null : stats.getIndices().getMerge().getCurrentNumDocs()); table.addCell(stats == null ? null : stats.getIndices().getMerge().getCurrentSize()); table.addCell(stats == null ? null : stats.getIndices().getMerge().getTotal()); table.addCell(stats == null ? null : stats.getIndices().getMerge().getTotalNumDocs()); table.addCell(stats == null ? null : stats.getIndices().getMerge().getTotalSize()); table.addCell(stats == null ? null : stats.getIndices().getMerge().getTotalTime()); table.addCell(stats == null ? null : stats.getIndices().getPercolate().getCurrent()); table.addCell(stats == null ? null : stats.getIndices().getPercolate().getMemorySize()); table.addCell(stats == null ? null : stats.getIndices().getPercolate().getNumQueries()); table.addCell(stats == null ? null : stats.getIndices().getPercolate().getTime()); table.addCell(stats == null ? null : stats.getIndices().getPercolate().getCount()); table.addCell(stats == null ? null : stats.getIndices().getRefresh().getTotal()); table.addCell(stats == null ? null : stats.getIndices().getRefresh().getTotalTime()); table.addCell(stats == null ? null : stats.getIndices().getSearch().getTotal().getFetchCurrent()); table.addCell(stats == null ? null : stats.getIndices().getSearch().getTotal().getFetchTime()); table.addCell(stats == null ? null : stats.getIndices().getSearch().getTotal().getFetchCount()); table.addCell(stats == null ? null : stats.getIndices().getSearch().getOpenContexts()); table.addCell(stats == null ? null : stats.getIndices().getSearch().getTotal().getQueryCurrent()); table.addCell(stats == null ? null : stats.getIndices().getSearch().getTotal().getQueryTime()); table.addCell(stats == null ? null : stats.getIndices().getSearch().getTotal().getQueryCount()); table.addCell(stats == null ? null : stats.getIndices().getSegments().getCount()); table.addCell(stats == null ? null : stats.getIndices().getSegments().getMemory()); table.endRow(); } return table; } }
1no label
src_main_java_org_elasticsearch_rest_action_cat_RestNodesAction.java
288
public class CassandraDaemonWrapper { private static final Logger log = LoggerFactory.getLogger(CassandraDaemonWrapper.class); private static String activeConfig; private static boolean started; public static synchronized void start(String config) { if (started) { if (null != config && !config.equals(activeConfig)) { log.warn("Can't start in-process Cassandra instance " + "with yaml path {} because an instance was " + "previously started with yaml path {}", config, activeConfig); } return; } started = true; log.debug("Current working directory: {}", System.getProperty("user.dir")); System.setProperty("cassandra.config", config); // Prevent Cassandra from closing stdout/stderr streams System.setProperty("cassandra-foreground", "yes"); // Prevent Cassandra from overwriting Log4J configuration System.setProperty("log4j.defaultInitOverride", "false"); log.info("Starting cassandra with {}", config); /* * This main method doesn't block for any substantial length of time. It * creates and starts threads and returns in relatively short order. */ CassandraDaemon.main(new String[0]); activeConfig = config; } public static synchronized boolean isStarted() { return started; } public static void stop() { // Do nothing } }
0true
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_utils_CassandraDaemonWrapper.java
2,842
public class ChineseAnalyzerProvider extends AbstractIndexAnalyzerProvider<ChineseAnalyzer> { private final ChineseAnalyzer analyzer; @Inject public ChineseAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); analyzer = new ChineseAnalyzer(); } @Override public ChineseAnalyzer get() { return this.analyzer; } }
0true
src_main_java_org_elasticsearch_index_analysis_ChineseAnalyzerProvider.java
2,096
static class Entry { final HandlesStreamInput handles; Entry(HandlesStreamInput handles) { this.handles = handles; } }
0true
src_main_java_org_elasticsearch_common_io_stream_CachedStreamInput.java
3,749
public class TTLMappingTests extends ElasticsearchTestCase { @Test public void testSimpleDisabled() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").endObject().string(); DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping); BytesReference source = XContentFactory.jsonBuilder() .startObject() .field("field", "value") .endObject() .bytes(); ParsedDocument doc = docMapper.parse(SourceToParse.source(source).type("type").id("1").ttl(Long.MAX_VALUE)); assertThat(doc.rootDoc().getField("_ttl"), equalTo(null)); } @Test public void testEnabled() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("_ttl").field("enabled", "yes").endObject() .endObject().endObject().string(); DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping); BytesReference source = XContentFactory.jsonBuilder() .startObject() .field("field", "value") .endObject() .bytes(); ParsedDocument doc = docMapper.parse(SourceToParse.source(source).type("type").id("1").ttl(Long.MAX_VALUE)); assertThat(doc.rootDoc().getField("_ttl").fieldType().stored(), equalTo(true)); assertThat(doc.rootDoc().getField("_ttl").fieldType().indexed(), equalTo(true)); assertThat(doc.rootDoc().getField("_ttl").tokenStream(docMapper.indexAnalyzer()), notNullValue()); } @Test public void testDefaultValues() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").endObject().string(); DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping); assertThat(docMapper.TTLFieldMapper().enabled(), equalTo(TTLFieldMapper.Defaults.ENABLED_STATE.enabled)); assertThat(docMapper.TTLFieldMapper().fieldType().stored(), equalTo(TTLFieldMapper.Defaults.TTL_FIELD_TYPE.stored())); assertThat(docMapper.TTLFieldMapper().fieldType().indexed(), equalTo(TTLFieldMapper.Defaults.TTL_FIELD_TYPE.indexed())); } @Test public void testSetValues() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("_ttl") .field("enabled", "yes").field("store", "no").field("index", "no") .endObject() .endObject().endObject().string(); DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping); assertThat(docMapper.TTLFieldMapper().enabled(), equalTo(true)); assertThat(docMapper.TTLFieldMapper().fieldType().stored(), equalTo(false)); assertThat(docMapper.TTLFieldMapper().fieldType().indexed(), equalTo(false)); } @Test public void testThatEnablingTTLFieldOnMergeWorks() throws Exception { String mappingWithoutTtl = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").field("field").startObject().field("type", "string").endObject().endObject() .endObject().endObject().string(); String mappingWithTtl = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("_ttl") .field("enabled", "yes").field("store", "no").field("index", "no") .endObject() .startObject("properties").field("field").startObject().field("type", "string").endObject().endObject() .endObject().endObject().string(); DocumentMapper mapperWithoutTtl = MapperTestUtils.newParser().parse(mappingWithoutTtl); DocumentMapper mapperWithTtl = MapperTestUtils.newParser().parse(mappingWithTtl); DocumentMapper.MergeFlags mergeFlags = DocumentMapper.MergeFlags.mergeFlags().simulate(false); DocumentMapper.MergeResult mergeResult = mapperWithoutTtl.merge(mapperWithTtl, mergeFlags); assertThat(mergeResult.hasConflicts(), equalTo(false)); assertThat(mapperWithoutTtl.TTLFieldMapper().enabled(), equalTo(true)); } @Test public void testThatChangingTTLKeepsMapperEnabled() throws Exception { String mappingWithTtl = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("_ttl") .field("enabled", "yes") .endObject() .startObject("properties").field("field").startObject().field("type", "string").endObject().endObject() .endObject().endObject().string(); String updatedMapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("_ttl") .field("default", "1w") .endObject() .startObject("properties").field("field").startObject().field("type", "string").endObject().endObject() .endObject().endObject().string(); DocumentMapper initialMapper = MapperTestUtils.newParser().parse(mappingWithTtl); DocumentMapper updatedMapper = MapperTestUtils.newParser().parse(updatedMapping); DocumentMapper.MergeFlags mergeFlags = DocumentMapper.MergeFlags.mergeFlags().simulate(false); DocumentMapper.MergeResult mergeResult = initialMapper.merge(updatedMapper, mergeFlags); assertThat(mergeResult.hasConflicts(), equalTo(false)); assertThat(initialMapper.TTLFieldMapper().enabled(), equalTo(true)); } }
0true
src_test_java_org_elasticsearch_index_mapper_ttl_TTLMappingTests.java
1,576
public class DiskThresholdDecider extends AllocationDecider { private volatile Double freeDiskThresholdLow; private volatile Double freeDiskThresholdHigh; private volatile ByteSizeValue freeBytesThresholdLow; private volatile ByteSizeValue freeBytesThresholdHigh; private volatile boolean enabled; public static final String CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED = "cluster.routing.allocation.disk.threshold_enabled"; public static final String CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK = "cluster.routing.allocation.disk.watermark.low"; public static final String CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK = "cluster.routing.allocation.disk.watermark.high"; class ApplySettings implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { String newLowWatermark = settings.get(CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, null); String newHighWatermark = settings.get(CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, null); Boolean newEnableSetting = settings.getAsBoolean(CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, null); if (newEnableSetting != null) { logger.info("updating [{}] from [{}] to [{}]", CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, DiskThresholdDecider.this.enabled, newEnableSetting); DiskThresholdDecider.this.enabled = newEnableSetting; } if (newLowWatermark != null) { if (!validWatermarkSetting(newLowWatermark)) { throw new ElasticsearchParseException("Unable to parse low watermark: [" + newLowWatermark + "]"); } logger.info("updating [{}] to [{}]", CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, newLowWatermark); DiskThresholdDecider.this.freeDiskThresholdLow = 100.0 - thresholdPercentageFromWatermark(newLowWatermark); DiskThresholdDecider.this.freeBytesThresholdLow = thresholdBytesFromWatermark(newLowWatermark); } if (newHighWatermark != null) { if (!validWatermarkSetting(newHighWatermark)) { throw new ElasticsearchParseException("Unable to parse high watermark: [" + newHighWatermark + "]"); } logger.info("updating [{}] to [{}]", CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, newHighWatermark); DiskThresholdDecider.this.freeDiskThresholdHigh = 100.0 - thresholdPercentageFromWatermark(newHighWatermark); DiskThresholdDecider.this.freeBytesThresholdHigh = thresholdBytesFromWatermark(newHighWatermark); } } } public DiskThresholdDecider(Settings settings) { this(settings, new NodeSettingsService(settings)); } @Inject public DiskThresholdDecider(Settings settings, NodeSettingsService nodeSettingsService) { super(settings); String lowWatermark = settings.get(CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, "0.7"); String highWatermark = settings.get(CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, "0.85"); if (!validWatermarkSetting(lowWatermark)) { throw new ElasticsearchParseException("Unable to parse low watermark: [" + lowWatermark + "]"); } if (!validWatermarkSetting(highWatermark)) { throw new ElasticsearchParseException("Unable to parse high watermark: [" + highWatermark + "]"); } // Watermark is expressed in terms of used data, but we need "free" data watermark this.freeDiskThresholdLow = 100.0 - thresholdPercentageFromWatermark(lowWatermark); this.freeDiskThresholdHigh = 100.0 - thresholdPercentageFromWatermark(highWatermark); this.freeBytesThresholdLow = thresholdBytesFromWatermark(lowWatermark); this.freeBytesThresholdHigh = thresholdBytesFromWatermark(highWatermark); this.enabled = settings.getAsBoolean(CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, false); nodeSettingsService.addListener(new ApplySettings()); } public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { if (!enabled) { return allocation.decision(Decision.YES, "disk threshold decider disabled"); } // Allow allocation regardless if only a single node is available if (allocation.nodes().size() <= 1) { return allocation.decision(Decision.YES, "only a single node is present"); } ClusterInfo clusterInfo = allocation.clusterInfo(); if (clusterInfo == null) { if (logger.isTraceEnabled()) { logger.trace("Cluster info unavailable for disk threshold decider, allowing allocation."); } return allocation.decision(Decision.YES, "cluster info unavailable"); } Map<String, DiskUsage> usages = clusterInfo.getNodeDiskUsages(); Map<String, Long> shardSizes = clusterInfo.getShardSizes(); if (usages.isEmpty()) { if (logger.isTraceEnabled()) { logger.trace("Unable to determine disk usages for disk-aware allocation, allowing allocation"); } return allocation.decision(Decision.YES, "disk usages unavailable"); } DiskUsage usage = usages.get(node.nodeId()); if (usage == null) { // If there is no usage, and we have other nodes in the cluster, // use the average usage for all nodes as the usage for this node usage = averageUsage(node, usages); if (logger.isDebugEnabled()) { logger.debug("Unable to determine disk usage for [{}], defaulting to average across nodes [{} total] [{} free] [{}% free]", node.nodeId(), usage.getTotalBytes(), usage.getFreeBytes(), usage.getFreeDiskAsPercentage()); } } // First, check that the node currently over the low watermark double freeDiskPercentage = usage.getFreeDiskAsPercentage(); long freeBytes = usage.getFreeBytes(); if (logger.isDebugEnabled()) { logger.debug("Node [{}] has {}% free disk", node.nodeId(), freeDiskPercentage); } if (freeBytes < freeBytesThresholdLow.bytes()) { if (logger.isDebugEnabled()) { logger.debug("Less than the required {} free bytes threshold ({} bytes free) on node {}, preventing allocation", freeBytesThresholdLow, freeBytes, node.nodeId()); } return allocation.decision(Decision.NO, "less than required [%s] free on node, free: [%s]", freeBytesThresholdLow, new ByteSizeValue(freeBytes)); } if (freeDiskPercentage < freeDiskThresholdLow) { if (logger.isDebugEnabled()) { logger.debug("Less than the required {}% free disk threshold ({}% free) on node [{}], preventing allocation", freeDiskThresholdLow, freeDiskPercentage, node.nodeId()); } return allocation.decision(Decision.NO, "less than required [%d%%] free disk on node, free: [%d%%]", freeDiskThresholdLow, freeDiskThresholdLow); } // Secondly, check that allocating the shard to this node doesn't put it above the high watermark Long shardSize = shardSizes.get(shardIdentifierFromRouting(shardRouting)); shardSize = shardSize == null ? 0 : shardSize; double freeSpaceAfterShard = this.freeDiskPercentageAfterShardAssigned(usage, shardSize); long freeBytesAfterShard = freeBytes - shardSize; if (freeBytesAfterShard < freeBytesThresholdHigh.bytes()) { logger.warn("After allocating, node [{}] would have less than the required {} free bytes threshold ({} bytes free), preventing allocation", node.nodeId(), freeBytesThresholdHigh, freeBytesAfterShard); return allocation.decision(Decision.NO, "after allocation less than required [%s] free on node, free: [%s]", freeBytesThresholdLow, new ByteSizeValue(freeBytesAfterShard)); } if (freeSpaceAfterShard < freeDiskThresholdHigh) { logger.warn("After allocating, node [{}] would have less than the required {}% free disk threshold ({}% free), preventing allocation", node.nodeId(), freeDiskThresholdHigh, freeSpaceAfterShard); return allocation.decision(Decision.NO, "after allocation less than required [%d%%] free disk on node, free: [%d%%]", freeDiskThresholdLow, freeSpaceAfterShard); } return allocation.decision(Decision.YES, "enough disk for shard on node, free: [%s]", new ByteSizeValue(freeBytes)); } public Decision canRemain(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { if (!enabled) { return allocation.decision(Decision.YES, "disk threshold decider disabled"); } // Allow allocation regardless if only a single node is available if (allocation.nodes().size() <= 1) { return allocation.decision(Decision.YES, "only a single node is present"); } ClusterInfo clusterInfo = allocation.clusterInfo(); if (clusterInfo == null) { if (logger.isTraceEnabled()) { logger.trace("Cluster info unavailable for disk threshold decider, allowing allocation."); } return allocation.decision(Decision.YES, "cluster info unavailable"); } Map<String, DiskUsage> usages = clusterInfo.getNodeDiskUsages(); if (usages.isEmpty()) { if (logger.isTraceEnabled()) { logger.trace("Unable to determine disk usages for disk-aware allocation, allowing allocation"); } return allocation.decision(Decision.YES, "disk usages unavailable"); } DiskUsage usage = usages.get(node.nodeId()); if (usage == null) { // If there is no usage, and we have other nodes in the cluster, // use the average usage for all nodes as the usage for this node usage = averageUsage(node, usages); if (logger.isDebugEnabled()) { logger.debug("Unable to determine disk usage for {}, defaulting to average across nodes [{} total] [{} free] [{}% free]", node.nodeId(), usage.getTotalBytes(), usage.getFreeBytes(), usage.getFreeDiskAsPercentage()); } } // If this node is already above the high threshold, the shard cannot remain (get it off!) double freeDiskPercentage = usage.getFreeDiskAsPercentage(); long freeBytes = usage.getFreeBytes(); if (logger.isDebugEnabled()) { logger.debug("Node [{}] has {}% free disk ({} bytes)", node.nodeId(), freeDiskPercentage, freeBytes); } if (freeBytes < freeBytesThresholdHigh.bytes()) { if (logger.isDebugEnabled()) { logger.debug("Less than the required {} free bytes threshold ({} bytes free) on node {}, shard cannot remain", freeBytesThresholdHigh, freeBytes, node.nodeId()); } return allocation.decision(Decision.NO, "after allocation less than required [%s] free on node, free: [%s]", freeBytesThresholdHigh, new ByteSizeValue(freeBytes)); } if (freeDiskPercentage < freeDiskThresholdHigh) { if (logger.isDebugEnabled()) { logger.debug("Less than the required {}% free disk threshold ({}% free) on node {}, shard cannot remain", freeDiskThresholdHigh, freeDiskPercentage, node.nodeId()); } return allocation.decision(Decision.NO, "after allocation less than required [%d%%] free disk on node, free: [%d%%]", freeDiskThresholdHigh, freeDiskPercentage); } return allocation.decision(Decision.YES, "enough disk for shard to remain on node, free: [%s]", new ByteSizeValue(freeBytes)); } /** * Returns a {@link DiskUsage} for the {@link RoutingNode} using the * average usage of other nodes in the disk usage map. * @param node Node to return an averaged DiskUsage object for * @param usages Map of nodeId to DiskUsage for all known nodes * @return DiskUsage representing given node using the average disk usage */ public DiskUsage averageUsage(RoutingNode node, Map<String, DiskUsage> usages) { long totalBytes = 0; long freeBytes = 0; for (DiskUsage du : usages.values()) { totalBytes += du.getTotalBytes(); freeBytes += du.getFreeBytes(); } return new DiskUsage(node.nodeId(), totalBytes / usages.size(), freeBytes / usages.size()); } /** * Given the DiskUsage for a node and the size of the shard, return the * percentage of free disk if the shard were to be allocated to the node. * @param usage A DiskUsage for the node to have space computed for * @param shardSize Size in bytes of the shard * @return Percentage of free space after the shard is assigned to the node */ public double freeDiskPercentageAfterShardAssigned(DiskUsage usage, Long shardSize) { shardSize = (shardSize == null) ? 0 : shardSize; return 100.0 - (((double)(usage.getUsedBytes() + shardSize) / usage.getTotalBytes()) * 100.0); } /** * Attempts to parse the watermark into a percentage, returning 100.0% if * it cannot be parsed. */ public double thresholdPercentageFromWatermark(String watermark) { try { return 100.0 * Double.parseDouble(watermark); } catch (NumberFormatException ex) { return 100.0; } } /** * Attempts to parse the watermark into a {@link ByteSizeValue}, returning * a ByteSizeValue of 0 bytes if the value cannot be parsed. */ public ByteSizeValue thresholdBytesFromWatermark(String watermark) { try { return ByteSizeValue.parseBytesSizeValue(watermark); } catch (ElasticsearchParseException ex) { return ByteSizeValue.parseBytesSizeValue("0b"); } } /** * Checks if a watermark string is a valid percentage or byte size value, * returning true if valid, false if invalid. */ public boolean validWatermarkSetting(String watermark) { try { double w = Double.parseDouble(watermark); if (w < 0 || w > 1.0) { return false; } return true; } catch (NumberFormatException e) { try { ByteSizeValue.parseBytesSizeValue(watermark); return true; } catch (ElasticsearchParseException ex) { return false; } } } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_decider_DiskThresholdDecider.java
527
public class DependencyLicenseCopy extends Copy { protected File licenseDir = null; protected Vector<ResourceCollection> rcs = new Vector<ResourceCollection>(); @SuppressWarnings("unchecked") public void execute() throws BuildException { super.execute(); try { for (int i = 0; i < rcs.size(); i++) { ResourceCollection rc = (ResourceCollection) rcs.elementAt(i); Iterator<Resource> resources = rc.iterator(); while (resources.hasNext()) { Resource r = (Resource) resources.next(); if (!r.isExists()) { continue; } if (r instanceof FileResource) { FileResource fr = (FileResource) r; String baseDir = fr.getBaseDir().getAbsolutePath(); String file = fr.getFile().getAbsolutePath(); file = file.substring(baseDir.length(), file.length()); String[] parts = file.split("/"); if (parts.length<=1) { parts = file.split("\\\\"); } if (parts.length <= 1) { throw new BuildException("Unable to recognize the path separator for src file: " + file); } String[] specificParts = new String[parts.length-1]; System.arraycopy(parts, 0, specificParts, 0, specificParts.length); String specificFilePart = StringUtils.join(specificParts, '/') + "/license.txt"; File specificFile = new File(licenseDir, specificFilePart); File specificDestinationFile = new File(destDir, specificFilePart); if (specificFile.exists()) { fileUtils.copyFile(specificFile, specificDestinationFile); continue; } String[] generalParts = new String[3]; System.arraycopy(parts, 0, generalParts, 0, 3); String generalFilePart = StringUtils.join(generalParts, '/') + "/license.txt"; File generalFile = new File(licenseDir, generalFilePart); if (generalFile.exists()) { fileUtils.copyFile(generalFile, specificDestinationFile); continue; } String[] moreGeneralParts = new String[2]; System.arraycopy(parts, 0, moreGeneralParts, 0, 2); String moreGeneralFilePart = StringUtils.join(moreGeneralParts, '/') + "/license.txt"; File moreGeneralFile = new File(licenseDir, moreGeneralFilePart); if (moreGeneralFile.exists()) { fileUtils.copyFile(moreGeneralFile, specificDestinationFile); } } } } } catch (IOException e) { throw new BuildException(e); } } public void add(ResourceCollection res) { super.add(res); rcs.add(res); } public File getLicenseDir() { return licenseDir; } public void setLicenseDir(File licenseDir) { this.licenseDir = licenseDir; } }
0true
common_src_main_java_org_broadleafcommerce_common_util_DependencyLicenseCopy.java
233
public interface SystemProperty extends Serializable { public Long getId(); public void setId(Long id); public String getName(); public void setName(String name); public String getValue(); public void setValue(String value); }
0true
common_src_main_java_org_broadleafcommerce_common_config_domain_SystemProperty.java
193
@Embeddable public class Auditable implements Serializable { private static final long serialVersionUID = 1L; @Column(name = "DATE_CREATED", updatable = false) @Temporal(TemporalType.TIMESTAMP) @AdminPresentation(friendlyName = "Auditable_Date_Created", order = 1000, tab = Presentation.Tab.Name.Audit, tabOrder = Presentation.Tab.Order.Audit, group = "Auditable_Audit", groupOrder = 1000, readOnly = true) protected Date dateCreated; @Column(name = "CREATED_BY", updatable = false) @AdminPresentation(friendlyName = "Auditable_Created_By", order = 2000, tab = Presentation.Tab.Name.Audit, tabOrder = Presentation.Tab.Order.Audit, group = "Auditable_Audit", readOnly = true) protected Long createdBy; @Column(name = "DATE_UPDATED") @Temporal(TemporalType.TIMESTAMP) @AdminPresentation(friendlyName = "Auditable_Date_Updated", order = 3000, tab = Presentation.Tab.Name.Audit, tabOrder = Presentation.Tab.Order.Audit, group = "Auditable_Audit", readOnly = true) protected Date dateUpdated; @Column(name = "UPDATED_BY") @AdminPresentation(friendlyName = "Auditable_Updated_By", order = 4000, tab = Presentation.Tab.Name.Audit, tabOrder = Presentation.Tab.Order.Audit, group = "Auditable_Audit", readOnly = true) protected Long updatedBy; public Date getDateCreated() { return dateCreated; } public Long getCreatedBy() { return createdBy; } public Date getDateUpdated() { return dateUpdated; } public Long getUpdatedBy() { return updatedBy; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public void setCreatedBy(Long createdBy) { this.createdBy = createdBy; } public void setDateUpdated(Date dateUpdated) { this.dateUpdated = dateUpdated; } public void setUpdatedBy(Long updatedBy) { this.updatedBy = updatedBy; } public static class Presentation { public static class Tab { public static class Name { public static final String Audit = "Auditable_Tab"; } public static class Order { public static final int Audit = 99000; } } public static class Group { public static class Name { public static final String Audit = "Auditable_Audit"; } public static class Order { public static final int Audit = 1000; } } } }
1no label
common_src_main_java_org_broadleafcommerce_common_audit_Auditable.java
352
NODE { @Override public Connection connect(Configuration config) throws IOException { log.debug("Configuring Node Client"); ImmutableSettings.Builder settingsBuilder = settingsBuilder(config); if (config.has(ElasticSearchIndex.TTL_INTERVAL)) { String k = "indices.ttl.interval"; settingsBuilder.put(k, config.get(ElasticSearchIndex.TTL_INTERVAL)); log.debug("Set {}: {}", k, config.get(ElasticSearchIndex.TTL_INTERVAL)); } makeLocalDirsIfNecessary(settingsBuilder, config); NodeBuilder nodeBuilder = NodeBuilder.nodeBuilder().settings(settingsBuilder.build()); // Apply explicit Titan properties file overrides (otherwise conf-file or ES defaults apply) if (config.has(ElasticSearchIndex.CLIENT_ONLY)) { boolean clientOnly = config.get(ElasticSearchIndex.CLIENT_ONLY); nodeBuilder.client(clientOnly).data(!clientOnly); } if (config.has(ElasticSearchIndex.LOCAL_MODE)) nodeBuilder.local(config.get(ElasticSearchIndex.LOCAL_MODE)); if (config.has(ElasticSearchIndex.LOAD_DEFAULT_NODE_SETTINGS)) nodeBuilder.loadConfigSettings(config.get(ElasticSearchIndex.LOAD_DEFAULT_NODE_SETTINGS)); Node node = nodeBuilder.node(); Client client = node.client(); return new Connection(node, client); } };
0true
titan-es_src_main_java_com_thinkaurelius_titan_diskstorage_es_ElasticSearchSetup.java
780
public class CollectionTxnRemoveBackupOperation extends CollectionOperation implements BackupOperation { private long itemId; public CollectionTxnRemoveBackupOperation() { } public CollectionTxnRemoveBackupOperation(String name, long itemId) { super(name); this.itemId = itemId; } @Override public int getId() { return CollectionDataSerializerHook.COLLECTION_TXN_REMOVE_BACKUP; } @Override public void beforeRun() throws Exception { } @Override public void run() throws Exception { getOrCreateContainer().commitRemoveBackup(itemId); } @Override public void afterRun() throws Exception { } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeLong(itemId); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); itemId = in.readLong(); } }
0true
hazelcast_src_main_java_com_hazelcast_collection_txn_CollectionTxnRemoveBackupOperation.java
207
private class ClientPacketProcessor implements Runnable { final ClientPacket packet; ClientPacketProcessor(ClientPacket packet) { this.packet = packet; } @Override public void run() { final ClientConnection conn = (ClientConnection) packet.getConn(); final ClientResponse clientResponse = getSerializationService().toObject(packet.getData()); final int callId = clientResponse.getCallId(); final Data response = clientResponse.getResponse(); if (clientResponse.isEvent()) { handleEvent(response, callId, conn); } else { handlePacket(response, clientResponse.isError(), callId, conn); } conn.decrementPacketCount(); } private void handlePacket(Object response, boolean isError, int callId, ClientConnection conn) { final ClientCallFuture future = conn.deRegisterCallId(callId); if (future == null) { LOGGER.warning("No call for callId: " + callId + ", response: " + response); return; } if (isError) { response = getSerializationService().toObject(response); } future.notify(response); } private void handleEvent(Data event, int callId, ClientConnection conn) { final EventHandler eventHandler = conn.getEventHandler(callId); final Object eventObject = getSerializationService().toObject(event); if (eventHandler == null) { LOGGER.warning("No eventHandler for callId: " + callId + ", event: " + eventObject + ", conn: " + conn); return; } eventHandler.handle(eventObject); } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientConnectionManagerImpl.java
1,226
public static enum Type { SOFT_THREAD_LOCAL { @Override <T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors) { return threadLocal(softFactory(dequeFactory(c, limit / estimatedThreadPoolSize))); } }, THREAD_LOCAL { @Override <T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors) { return threadLocal(dequeFactory(c, limit / estimatedThreadPoolSize)); } }, QUEUE { @Override <T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors) { return concurrentDeque(c, limit); } }, SOFT_CONCURRENT { @Override <T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors) { return concurrent(softFactory(dequeFactory(c, limit / availableProcessors)), availableProcessors); } }, CONCURRENT { @Override <T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors) { return concurrent(dequeFactory(c, limit / availableProcessors), availableProcessors); } }, NONE { @Override <T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors) { return none(c); } }; public static Type parse(String type) { if (Strings.isNullOrEmpty(type)) { return SOFT_CONCURRENT; } try { return Type.valueOf(type.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { throw new ElasticsearchIllegalArgumentException("no type support [" + type + "]"); } } abstract <T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors); }
0true
src_main_java_org_elasticsearch_cache_recycler_PageCacheRecycler.java
3,043
public static final class BloomFilteredTerms extends FilterAtomicReader.FilterTerms { private BloomFilter filter; public BloomFilteredTerms(Terms terms, BloomFilter filter) { super(terms); this.filter = filter; } public BloomFilter getFilter() { return filter; } @Override public TermsEnum iterator(TermsEnum reuse) throws IOException { TermsEnum result; if ((reuse != null) && (reuse instanceof BloomFilteredTermsEnum)) { // recycle the existing BloomFilteredTermsEnum by asking the delegate // to recycle its contained TermsEnum BloomFilteredTermsEnum bfte = (BloomFilteredTermsEnum) reuse; if (bfte.filter == filter) { bfte.reset(this.in); return bfte; } reuse = bfte.reuse; } // We have been handed something we cannot reuse (either null, wrong // class or wrong filter) so allocate a new object result = new BloomFilteredTermsEnum(this.in, reuse, filter); return result; } }
0true
src_main_java_org_elasticsearch_index_codec_postingsformat_BloomFilterPostingsFormat.java
787
return new DataSerializableFactory() { @Override public IdentifiedDataSerializable create(int typeId) { switch (typeId) { case ADD_BACKUP: return new AddBackupOperation(); case ADD_AND_GET: return new AddAndGetOperation(); case ALTER: return new AlterOperation(); case ALTER_AND_GET: return new AlterAndGetOperation(); case APPLY: return new ApplyOperation(); case COMPARE_AND_SET: return new CompareAndSetOperation(); case GET: return new GetOperation(); case GET_AND_SET: return new GetAndSetOperation(); case GET_AND_ALTER: return new GetAndAlterOperation(); case GET_AND_ADD: return new GetAndAddOperation(); case SET_OPERATION: return new SetOperation(); case SET_BACKUP: return new SetBackupOperation(); case REPLICATION: return new AtomicLongReplicationOperation(); default: return null; } } };
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_AtomicLongDataSerializerHook.java
1,726
@edu.umd.cs.findbugs.annotations.SuppressWarnings("SE_BAD_FIELD") public class DataAwareEntryEvent extends EntryEvent { private final static long serialVersionUID = 1; protected final Data dataKey; protected final Data dataNewValue; protected final Data dataOldValue; private final transient SerializationService serializationService; public DataAwareEntryEvent(Member from, int eventType, String source, Data dataKey, Data dataNewValue, Data dataOldValue, SerializationService serializationService) { super(source, from, eventType, null, null); this.dataKey = dataKey; this.dataNewValue = dataNewValue; this.dataOldValue = dataOldValue; this.serializationService = serializationService; } public Data getKeyData() { return dataKey; } public Data getNewValueData() { return dataNewValue; } public Data getOldValueData() { return dataOldValue; } public Object getKey() { if (key == null && dataKey != null) { key = serializationService.toObject(dataKey); } return key; } public Object getOldValue() { if (oldValue == null && dataOldValue != null) { oldValue = serializationService.toObject(dataOldValue); } return oldValue; } public Object getValue() { if (value == null && dataNewValue != null) { value = serializationService.toObject(dataNewValue); } return value; } public String getLongName() { return name; } }
1no label
hazelcast_src_main_java_com_hazelcast_map_DataAwareEntryEvent.java
1,192
public class PaymentContextImpl implements PaymentContext { protected Money originalPaymentAmount; protected Money remainingPaymentAmount; protected Money transactionAmount; protected Money remainingTransactionAmount; protected PaymentInfo paymentInfo; protected Referenced referencedPaymentInfo; protected String transactionId; protected String userName; public PaymentContextImpl(Money transactionAmount, Money remainingTransactionAmount, PaymentInfo paymentInfo, Referenced referencedPaymentInfo, String userName) { this.transactionAmount = transactionAmount; this.remainingTransactionAmount = remainingTransactionAmount; this.paymentInfo = paymentInfo; this.referencedPaymentInfo = referencedPaymentInfo; this.userName = userName; } @Deprecated public Money getOriginalPaymentAmount() { return originalPaymentAmount; } @Deprecated public Money getRemainingPaymentAmount() { return remainingPaymentAmount; } @Override public Money getTransactionAmount() { return transactionAmount; } @Override public void setTransactionAmount(Money transactionAmount) { this.transactionAmount = transactionAmount; } @Override public Money getRemainingTransactionAmount() { return remainingTransactionAmount; } @Override public void setRemainingTransactionAmount(Money remainingTransactionAmount) { this.remainingTransactionAmount = remainingTransactionAmount; } public PaymentInfo getPaymentInfo() { return paymentInfo; } public Referenced getReferencedPaymentInfo() { return referencedPaymentInfo; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public String getUserName() { return userName; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_PaymentContextImpl.java
873
public class FulfillmentGroupOfferPotential { protected Offer offer; protected Money totalSavings = new Money(BankersRounding.zeroAmount()); protected int priority; public Offer getOffer() { return offer; } public void setOffer(Offer offer) { this.offer = offer; } public Money getTotalSavings() { return totalSavings; } public void setTotalSavings(Money totalSavings) { this.totalSavings = totalSavings; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((offer == null) ? 0 : offer.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; } FulfillmentGroupOfferPotential other = (FulfillmentGroupOfferPotential) obj; if (offer == null) { if (other.offer != null) { return false; } } else if (!offer.equals(other.offer)) { return false; } return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_FulfillmentGroupOfferPotential.java
1,922
Module assistedModule = new AbstractModule() { @SuppressWarnings("unchecked") // raw keys are necessary for the args array and return value protected void configure() { Binder binder = binder().withSource(method); int p = 0; for (Key<?> paramKey : paramTypes.get(method)) { // Wrap in a Provider to cover null, and to prevent Guice from injecting the parameter binder.bind((Key) paramKey).toProvider(Providers.of(args[p++])); } if (producedType != null && !returnType.equals(producedType)) { binder.bind(returnType).to((Key) producedType); } else { binder.bind(returnType); } } };
0true
src_main_java_org_elasticsearch_common_inject_assistedinject_FactoryProvider2.java
1,246
public class NodeClusterAdminClient extends AbstractClusterAdminClient implements InternalClusterAdminClient { private final ThreadPool threadPool; private final ImmutableMap<ClusterAction, TransportAction> actions; @Inject public NodeClusterAdminClient(Settings settings, ThreadPool threadPool, Map<GenericAction, TransportAction> actions) { this.threadPool = threadPool; MapBuilder<ClusterAction, TransportAction> actionsBuilder = new MapBuilder<ClusterAction, TransportAction>(); for (Map.Entry<GenericAction, TransportAction> entry : actions.entrySet()) { if (entry.getKey() instanceof ClusterAction) { actionsBuilder.put((ClusterAction) entry.getKey(), entry.getValue()); } } this.actions = actionsBuilder.immutableMap(); } @Override public ThreadPool threadPool() { return this.threadPool; } @SuppressWarnings("unchecked") @Override public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute(ClusterAction<Request, Response, RequestBuilder> action, Request request) { TransportAction<Request, Response> transportAction = actions.get(action); return transportAction.execute(request); } @SuppressWarnings("unchecked") @Override public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute(ClusterAction<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) { TransportAction<Request, Response> transportAction = actions.get(action); transportAction.execute(request, listener); } }
0true
src_main_java_org_elasticsearch_client_node_NodeClusterAdminClient.java
621
static final class Fields { static final XContentBuilderString INDICES = new XContentBuilderString("indices"); static final XContentBuilderString SHARDS = new XContentBuilderString("shards"); }
0true
src_main_java_org_elasticsearch_action_admin_indices_stats_IndicesStatsResponse.java
3,228
public abstract class ScriptDocValues { public static final ScriptDocValues EMPTY = new Empty(); public static final Strings EMPTY_STRINGS = new Strings(BytesValues.EMPTY); protected int docId; protected boolean listLoaded = false; public void setNextDocId(int docId) { this.docId = docId; this.listLoaded = false; } public abstract boolean isEmpty(); public abstract List<?> getValues(); public static class Empty extends ScriptDocValues { @Override public void setNextDocId(int docId) { } @Override public boolean isEmpty() { return true; } @Override public List<?> getValues() { return Collections.emptyList(); } } public final static class Strings extends ScriptDocValues { private final BytesValues values; private final CharsRef spare = new CharsRef(); private SlicedObjectList<String> list; public Strings(BytesValues values) { this.values = values; list = new SlicedObjectList<String>(values.isMultiValued() ? new String[10] : new String[1]) { @Override public void grow(int newLength) { assert offset == 0; // NOTE: senseless if offset != 0 if (values.length >= newLength) { return; } final String[] current = values; values = new String[ArrayUtil.oversize(newLength, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; System.arraycopy(current, 0, values, 0, current.length); } }; } @Override public boolean isEmpty() { return values.setDocument(docId) == 0; } public BytesValues getInternalValues() { return this.values; } public BytesRef getBytesValue() { int numValues = values.setDocument(docId); if (numValues == 0) { return null; } return values.nextValue(); } public String getValue() { String value = null; if (values.setDocument(docId) > 0) { UnicodeUtil.UTF8toUTF16(values.nextValue(), spare); value = spare.toString(); } return value; } public List<String> getValues() { if (!listLoaded) { final int numValues = values.setDocument(docId); list.offset = 0; list.grow(numValues); list.length = numValues; for (int i = 0; i < numValues; i++) { BytesRef next = values.nextValue(); UnicodeUtil.UTF8toUTF16(next, spare); list.values[i] = spare.toString(); } listLoaded = true; } return list; } } public static class Longs extends ScriptDocValues { private final LongValues values; private final MutableDateTime date = new MutableDateTime(0, DateTimeZone.UTC); private final SlicedLongList list; public Longs(LongValues values) { this.values = values; this.list = new SlicedLongList(values.isMultiValued() ? 10 : 1); } public LongValues getInternalValues() { return this.values; } @Override public boolean isEmpty() { return values.setDocument(docId) == 0; } public long getValue() { int numValues = values.setDocument(docId); if (numValues == 0) { return 0l; } return values.nextValue(); } public List<Long> getValues() { if (!listLoaded) { final int numValues = values.setDocument(docId); list.offset = 0; list.grow(numValues); list.length = numValues; for (int i = 0; i < numValues; i++) { list.values[i] = values.nextValue(); } listLoaded = true; } return list; } public MutableDateTime getDate() { date.setMillis(getValue()); return date; } } public static class Doubles extends ScriptDocValues { private final DoubleValues values; private final SlicedDoubleList list; public Doubles(DoubleValues values) { this.values = values; this.list = new SlicedDoubleList(values.isMultiValued() ? 10 : 1); } public DoubleValues getInternalValues() { return this.values; } @Override public boolean isEmpty() { return values.setDocument(docId) == 0; } public double getValue() { int numValues = values.setDocument(docId); if (numValues == 0) { return 0d; } return values.nextValue(); } public List<Double> getValues() { if (!listLoaded) { int numValues = values.setDocument(docId); list.offset = 0; list.grow(numValues); list.length = numValues; for (int i = 0; i < numValues; i++) { list.values[i] = values.nextValue(); } listLoaded = true; } return list; } } public static class GeoPoints extends ScriptDocValues { private final GeoPointValues values; private final SlicedObjectList<GeoPoint> list; public GeoPoints(GeoPointValues values) { this.values = values; list = new SlicedObjectList<GeoPoint>(values.isMultiValued() ? new GeoPoint[10] : new GeoPoint[1]) { @Override public void grow(int newLength) { assert offset == 0; // NOTE: senseless if offset != 0 if (values.length >= newLength) { return; } final GeoPoint[] current = values; values = new GeoPoint[ArrayUtil.oversize(newLength, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; System.arraycopy(current, 0, values, 0, current.length); } }; } @Override public boolean isEmpty() { return values.setDocument(docId) == 0; } public GeoPoint getValue() { int numValues = values.setDocument(docId); if (numValues == 0) { return null; } return values.nextValue(); } public double getLat() { return getValue().lat(); } public double[] getLats() { List<GeoPoint> points = getValues(); double[] lats = new double[points.size()]; for (int i = 0; i < points.size(); i++) { lats[i] = points.get(i).lat(); } return lats; } public double[] getLons() { List<GeoPoint> points = getValues(); double[] lons = new double[points.size()]; for (int i = 0; i < points.size(); i++) { lons[i] = points.get(i).lon(); } return lons; } public double getLon() { return getValue().lon(); } public List<GeoPoint> getValues() { if (!listLoaded) { int numValues = values.setDocument(docId); list.offset = 0; list.grow(numValues); list.length = numValues; for (int i = 0; i < numValues; i++) { GeoPoint next = values.nextValue(); GeoPoint point = list.values[i]; if (point == null) { point = list.values[i] = new GeoPoint(); } point.reset(next.lat(), next.lon()); list.values[i] = point; } listLoaded = true; } return list; } public double factorDistance(double lat, double lon) { GeoPoint point = getValue(); return GeoDistance.FACTOR.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT); } public double factorDistanceWithDefault(double lat, double lon, double defaultValue) { if (isEmpty()) { return defaultValue; } GeoPoint point = getValue(); return GeoDistance.FACTOR.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT); } public double factorDistance02(double lat, double lon) { GeoPoint point = getValue(); return GeoDistance.FACTOR.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT) + 1; } public double factorDistance13(double lat, double lon) { GeoPoint point = getValue(); return GeoDistance.FACTOR.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT) + 2; } public double arcDistance(double lat, double lon) { GeoPoint point = getValue(); return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT); } public double arcDistanceWithDefault(double lat, double lon, double defaultValue) { if (isEmpty()) { return defaultValue; } GeoPoint point = getValue(); return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT); } public double arcDistanceInKm(double lat, double lon) { GeoPoint point = getValue(); return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.KILOMETERS); } public double arcDistanceInKmWithDefault(double lat, double lon, double defaultValue) { if (isEmpty()) { return defaultValue; } GeoPoint point = getValue(); return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.KILOMETERS); } public double arcDistanceInMiles(double lat, double lon) { GeoPoint point = getValue(); return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.MILES); } public double arcDistanceInMilesWithDefault(double lat, double lon, double defaultValue) { if (isEmpty()) { return defaultValue; } GeoPoint point = getValue(); return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.MILES); } public double distance(double lat, double lon) { GeoPoint point = getValue(); return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT); } public double distanceWithDefault(double lat, double lon, double defaultValue) { if (isEmpty()) { return defaultValue; } GeoPoint point = getValue(); return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT); } public double distanceInKm(double lat, double lon) { GeoPoint point = getValue(); return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.KILOMETERS); } public double distanceInKmWithDefault(double lat, double lon, double defaultValue) { if (isEmpty()) { return defaultValue; } GeoPoint point = getValue(); return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.KILOMETERS); } public double distanceInMiles(double lat, double lon) { GeoPoint point = getValue(); return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.MILES); } public double distanceInMilesWithDefault(double lat, double lon, double defaultValue) { if (isEmpty()) { return defaultValue; } GeoPoint point = getValue(); return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.MILES); } } }
1no label
src_main_java_org_elasticsearch_index_fielddata_ScriptDocValues.java
1,153
public class StandardTransactionBuilder implements TransactionConfiguration, TransactionBuilder { private boolean isReadOnly = false; private boolean hasEnabledBatchLoading = false; private boolean assignIDsImmediately = false; private DefaultSchemaMaker defaultSchemaMaker; private boolean verifyExternalVertexExistence = true; private boolean verifyInternalVertexExistence = false; private boolean verifyUniqueness = true; private boolean acquireLocks = true; private boolean propertyPrefetching = true; private boolean singleThreaded = false; private boolean threadBound = false; private int vertexCacheSize; private int dirtyVertexSize; private long indexCacheWeight; private String logIdentifier; private int[] restrictedPartitions = new int[0]; private Timepoint userCommitTime = null; private String groupName; private final boolean forceIndexUsage; private final ModifiableConfiguration writableCustomOptions; private final Configuration customOptions; private final StandardTitanGraph graph; /** * Constructs a new TitanTransaction configuration with default configuration parameters. */ public StandardTransactionBuilder(GraphDatabaseConfiguration graphConfig, StandardTitanGraph graph) { Preconditions.checkNotNull(graphConfig); Preconditions.checkNotNull(graph); if (graphConfig.isReadOnly()) readOnly(); if (graphConfig.isBatchLoading()) enableBatchLoading(); this.graph = graph; this.defaultSchemaMaker = graphConfig.getDefaultSchemaMaker(); this.assignIDsImmediately = graphConfig.hasFlushIDs(); this.forceIndexUsage = graphConfig.hasForceIndexUsage(); this.groupName = graphConfig.getMetricsPrefix(); this.logIdentifier = null; this.propertyPrefetching = graphConfig.hasPropertyPrefetching(); this.writableCustomOptions = GraphDatabaseConfiguration.buildConfiguration(); this.customOptions = new MergedConfiguration(writableCustomOptions, graphConfig.getConfiguration()); setVertexCacheSize(graphConfig.getTxVertexCacheSize()); setDirtyVertexSize(graphConfig.getTxDirtyVertexSize()); } public StandardTransactionBuilder threadBound() { this.threadBound = true; this.singleThreaded = true; return this; } @Override public StandardTransactionBuilder readOnly() { this.isReadOnly = true; return this; } @Override public StandardTransactionBuilder enableBatchLoading() { hasEnabledBatchLoading = true; checkExternalVertexExistence(false); consistencyChecks(false); return this; } @Override public StandardTransactionBuilder disableBatchLoading() { hasEnabledBatchLoading = false; checkExternalVertexExistence(true); consistencyChecks(true); return this; } @Override public StandardTransactionBuilder setVertexCacheSize(int size) { Preconditions.checkArgument(size >= 0); this.vertexCacheSize = size; this.indexCacheWeight = size / 2; return this; } @Override public TransactionBuilder setDirtyVertexSize(int size) { this.dirtyVertexSize = size; return this; } @Override public StandardTransactionBuilder checkInternalVertexExistence(boolean enabled) { this.verifyInternalVertexExistence = enabled; return this; } @Override public StandardTransactionBuilder checkExternalVertexExistence(boolean enabled) { this.verifyExternalVertexExistence = enabled; return this; } @Override public TransactionBuilder consistencyChecks(boolean enabled) { this.verifyUniqueness = enabled; this.acquireLocks = enabled; return this; } @Override public StandardTransactionBuilder setCommitTime(long timestampSinceEpoch, TimeUnit unit) { this.userCommitTime = getTimestampProvider().getTime(timestampSinceEpoch,unit); return this; } @Override public void setCommitTime(Timepoint time) { throw new UnsupportedOperationException("Use setCommitTime(lnog,TimeUnit)"); } @Override public StandardTransactionBuilder setGroupName(String p) { this.groupName = p; return this; } @Override public StandardTransactionBuilder setLogIdentifier(String logName) { this.logIdentifier = logName; return this; } @Override public TransactionBuilder setRestrictedPartitions(int[] partitions) { Preconditions.checkNotNull(partitions); this.restrictedPartitions=partitions; return this; } @Override public TransactionBuilder setCustomOption(String k, Object v) { writableCustomOptions.set((ConfigOption<Object>)ConfigElement.parse(ROOT_NS, k).element, v); return this; } @Override public TitanTransaction start() { TransactionConfiguration immutable = new ImmutableTxCfg(isReadOnly, hasEnabledBatchLoading, assignIDsImmediately, forceIndexUsage, verifyExternalVertexExistence, verifyInternalVertexExistence, acquireLocks, verifyUniqueness, propertyPrefetching, singleThreaded, threadBound, getTimestampProvider(), userCommitTime, indexCacheWeight, getVertexCacheSize(), getDirtyVertexSize(), logIdentifier, restrictedPartitions, groupName, defaultSchemaMaker, customOptions); return graph.newTransaction(immutable); } /* ############################################## TransactionConfig ############################################## */ @Override public final boolean isReadOnly() { return isReadOnly; } @Override public final boolean hasAssignIDsImmediately() { return assignIDsImmediately; } @Override public final boolean hasForceIndexUsage() { return forceIndexUsage; } @Override public boolean hasEnabledBatchLoading() { return hasEnabledBatchLoading; } @Override public final boolean hasVerifyExternalVertexExistence() { return verifyExternalVertexExistence; } @Override public final boolean hasVerifyInternalVertexExistence() { return verifyInternalVertexExistence; } @Override public final boolean hasAcquireLocks() { return acquireLocks; } @Override public final DefaultSchemaMaker getAutoSchemaMaker() { return defaultSchemaMaker; } @Override public final boolean hasVerifyUniqueness() { return verifyUniqueness; } public boolean hasPropertyPrefetching() { return propertyPrefetching; } @Override public final boolean isSingleThreaded() { return singleThreaded; } @Override public final boolean isThreadBound() { return threadBound; } @Override public final int getVertexCacheSize() { return vertexCacheSize; } @Override public final int getDirtyVertexSize() { return dirtyVertexSize; } @Override public final long getIndexCacheWeight() { return indexCacheWeight; } @Override public String getLogIdentifier() { return logIdentifier; } @Override public int[] getRestrictedPartitions() { return restrictedPartitions; } @Override public boolean hasRestrictedPartitions() { return restrictedPartitions.length>0; } @Override public String getGroupName() { return groupName; } @Override public boolean hasGroupName() { return null != groupName; } @Override public Timepoint getCommitTime() { return userCommitTime; } @Override public boolean hasCommitTime() { return userCommitTime!=null; } @Override public <V> V getCustomOption(ConfigOption<V> opt) { return getCustomOptions().get(opt); } @Override public Configuration getCustomOptions() { return customOptions; } @Override public TimestampProvider getTimestampProvider() { return graph.getConfiguration().getTimestampProvider(); } private static class ImmutableTxCfg implements TransactionConfiguration { private final boolean isReadOnly; private final boolean hasEnabledBatchLoading; private final boolean hasAssignIDsImmediately; private final boolean hasForceIndexUsage; private final boolean hasVerifyExternalVertexExistence; private final boolean hasVerifyInternalVertexExistence; private final boolean hasAcquireLocks; private final boolean hasVerifyUniqueness; private final boolean hasPropertyPrefetching; private final boolean isSingleThreaded; private final boolean isThreadBound; private final long indexCacheWeight; private final int vertexCacheSize; private final int dirtyVertexSize; private final String logIdentifier; private final int[] restrictedPartitions; private final DefaultSchemaMaker defaultSchemaMaker; private final BaseTransactionConfig handleConfig; public ImmutableTxCfg(boolean isReadOnly, boolean hasEnabledBatchLoading, boolean hasAssignIDsImmediately, boolean hasForceIndexUsage, boolean hasVerifyExternalVertexExistence, boolean hasVerifyInternalVertexExistence, boolean hasAcquireLocks, boolean hasVerifyUniqueness, boolean hasPropertyPrefetching, boolean isSingleThreaded, boolean isThreadBound, TimestampProvider times, Timepoint commitTime, long indexCacheWeight, int vertexCacheSize, int dirtyVertexSize, String logIdentifier, int[] restrictedPartitions, String groupName, DefaultSchemaMaker defaultSchemaMaker, Configuration customOptions) { this.isReadOnly = isReadOnly; this.hasEnabledBatchLoading = hasEnabledBatchLoading; this.hasAssignIDsImmediately = hasAssignIDsImmediately; this.hasForceIndexUsage = hasForceIndexUsage; this.hasVerifyExternalVertexExistence = hasVerifyExternalVertexExistence; this.hasVerifyInternalVertexExistence = hasVerifyInternalVertexExistence; this.hasAcquireLocks = hasAcquireLocks; this.hasVerifyUniqueness = hasVerifyUniqueness; this.hasPropertyPrefetching = hasPropertyPrefetching; this.isSingleThreaded = isSingleThreaded; this.isThreadBound = isThreadBound; this.indexCacheWeight = indexCacheWeight; this.vertexCacheSize = vertexCacheSize; this.dirtyVertexSize = dirtyVertexSize; this.logIdentifier = logIdentifier; this.restrictedPartitions=restrictedPartitions; this.defaultSchemaMaker = defaultSchemaMaker; this.handleConfig = new StandardBaseTransactionConfig.Builder() .commitTime(commitTime) .timestampProvider(times) .groupName(groupName) .customOptions(customOptions).build(); } @Override public boolean hasEnabledBatchLoading() { return hasEnabledBatchLoading; } @Override public boolean isReadOnly() { return isReadOnly; } @Override public boolean hasAssignIDsImmediately() { return hasAssignIDsImmediately; } @Override public final boolean hasForceIndexUsage() { return hasForceIndexUsage; } @Override public boolean hasVerifyExternalVertexExistence() { return hasVerifyExternalVertexExistence; } @Override public boolean hasVerifyInternalVertexExistence() { return hasVerifyInternalVertexExistence; } @Override public boolean hasAcquireLocks() { return hasAcquireLocks; } @Override public DefaultSchemaMaker getAutoSchemaMaker() { return defaultSchemaMaker; } @Override public boolean hasVerifyUniqueness() { return hasVerifyUniqueness; } @Override public boolean hasPropertyPrefetching() { return hasPropertyPrefetching; } @Override public boolean isSingleThreaded() { return isSingleThreaded; } @Override public boolean isThreadBound() { return isThreadBound; } @Override public int getVertexCacheSize() { return vertexCacheSize; } @Override public int getDirtyVertexSize() { return dirtyVertexSize; } @Override public long getIndexCacheWeight() { return indexCacheWeight; } @Override public String getLogIdentifier() { return logIdentifier; } @Override public int[] getRestrictedPartitions() { return restrictedPartitions; } @Override public boolean hasRestrictedPartitions() { return restrictedPartitions.length>0; } @Override public Timepoint getCommitTime() { return handleConfig.getCommitTime(); } @Override public void setCommitTime(Timepoint time) { handleConfig.setCommitTime(time); } @Override public boolean hasCommitTime() { return handleConfig.hasCommitTime(); } @Override public String getGroupName() { return handleConfig.getGroupName(); } @Override public boolean hasGroupName() { return handleConfig.hasGroupName(); } @Override public <V> V getCustomOption(ConfigOption<V> opt) { return handleConfig.getCustomOption(opt); } @Override public Configuration getCustomOptions() { return handleConfig.getCustomOptions(); } @Override public TimestampProvider getTimestampProvider() { return handleConfig.getTimestampProvider(); } } }
1no label
titan-core_src_main_java_com_thinkaurelius_titan_graphdb_transaction_StandardTransactionBuilder.java
322
public class JavaElementImageProvider { /** * Flags for the JavaImageLabelProvider: * Generate images with overlays. */ public final static int OVERLAY_ICONS= 0x1; /** * Generate small sized images. */ public final static int SMALL_ICONS= 0x2; /** * Use the 'light' style for rendering types. */ public final static int LIGHT_TYPE_ICONS= 0x4; public static final Point SMALL_SIZE= new Point(16, 16); public static final Point BIG_SIZE= new Point(22, 16); private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED; private static ImageDescriptor DESC_OBJ_PROJECT; { ISharedImages images= JavaPlugin.getDefault().getWorkbench().getSharedImages(); DESC_OBJ_PROJECT_CLOSED= images.getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED); DESC_OBJ_PROJECT= images.getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT); } private ImageDescriptorRegistry fRegistry; public JavaElementImageProvider() { fRegistry= null; // lazy initialization } /** * Returns the icon for a given element. The icon depends on the element type * and element properties. If configured, overlay icons are constructed for * <code>ISourceReference</code>s. * @param element the element * @param flags Flags as defined by the JavaImageLabelProvider * @return return the image or <code>null</code> */ public Image getImageLabel(Object element, int flags) { return getImageLabel(computeDescriptor(element, flags)); } private Image getImageLabel(ImageDescriptor descriptor){ if (descriptor == null) return null; return getRegistry().get(descriptor); } private ImageDescriptorRegistry getRegistry() { if (fRegistry == null) { fRegistry= JavaPlugin.getImageDescriptorRegistry(); } return fRegistry; } private ImageDescriptor computeDescriptor(Object element, int flags){ if (element instanceof IJavaElement) { return getJavaImageDescriptor((IJavaElement) element, flags); } else if (element instanceof IFile) { IFile file= (IFile) element; if (JavaCore.isJavaLikeFileName(file.getName())) { return getCUResourceImageDescriptor(file, flags); // image for a CU not on the build path } if (CeylonBuilder.isCeylon(file)) { return CeylonPlugin.getInstance().getImageRegistry() .getDescriptor(getImageKeyForFile(file)); } return getWorkbenchImageDescriptor(file, flags); } else if (element instanceof IAdaptable) { return getWorkbenchImageDescriptor((IAdaptable) element, flags); } return null; } private static boolean showOverlayIcons(int flags) { return (flags & OVERLAY_ICONS) != 0; } private static boolean useSmallSize(int flags) { return (flags & SMALL_ICONS) != 0; } private static boolean useLightIcons(int flags) { return (flags & LIGHT_TYPE_ICONS) != 0; } /** * Returns an image descriptor for a compilation unit not on the class path. * The descriptor includes overlays, if specified. * @param file the cu resource file * @param flags the image flags * @return returns the image descriptor */ public ImageDescriptor getCUResourceImageDescriptor(IFile file, int flags) { Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; return new JavaElementImageDescriptor(JavaPluginImages.DESC_OBJS_CUNIT_RESOURCE, 0, size); } /** * Returns an image descriptor for a java element. The descriptor includes overlays, if specified. * @param element the Java element * @param flags the image flags * @return returns the image descriptor */ public ImageDescriptor getJavaImageDescriptor(IJavaElement element, int flags) { Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; ImageDescriptor baseDesc= getBaseImageDescriptor(element, flags); if (baseDesc != null) { int adornmentFlags= computeJavaAdornmentFlags(element, flags); return new JavaElementImageDescriptor(baseDesc, adornmentFlags, size); } return new JavaElementImageDescriptor(JavaPluginImages.DESC_OBJS_GHOST, 0, size); } /** * Returns an image descriptor for a IAdaptable. The descriptor includes overlays, if specified (only error ticks apply). * Returns <code>null</code> if no image could be found. * @param adaptable the adaptable * @param flags the image flags * @return returns the image descriptor */ public ImageDescriptor getWorkbenchImageDescriptor(IAdaptable adaptable, int flags) { IWorkbenchAdapter wbAdapter= (IWorkbenchAdapter) adaptable.getAdapter(IWorkbenchAdapter.class); if (wbAdapter == null) { return null; } ImageDescriptor descriptor= wbAdapter.getImageDescriptor(adaptable); if (descriptor == null) { return null; } Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; return new JavaElementImageDescriptor(descriptor, 0, size); } // ---- Computation of base image key ------------------------------------------------- /** * Returns an image descriptor for a java element. This is the base image, no overlays. * @param element the element * @param renderFlags the image flags * @return returns the image descriptor */ public ImageDescriptor getBaseImageDescriptor(IJavaElement element, int renderFlags) { try { switch (element.getElementType()) { case IJavaElement.INITIALIZER: return JavaPluginImages.DESC_MISC_PRIVATE; // 23479 case IJavaElement.METHOD: { IMethod method= (IMethod) element; IType declType= method.getDeclaringType(); int flags= method.getFlags(); if (declType.isEnum() && isDefaultFlag(flags) && method.isConstructor()) return JavaPluginImages.DESC_MISC_PRIVATE; return getMethodImageDescriptor(JavaModelUtil.isInterfaceOrAnnotation(declType), flags); } case IJavaElement.FIELD: { IMember member= (IMember) element; IType declType= member.getDeclaringType(); return getFieldImageDescriptor(JavaModelUtil.isInterfaceOrAnnotation(declType), member.getFlags()); } case IJavaElement.LOCAL_VARIABLE: return JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE; case IJavaElement.PACKAGE_DECLARATION: return JavaPluginImages.DESC_OBJS_PACKDECL; case IJavaElement.IMPORT_DECLARATION: return JavaPluginImages.DESC_OBJS_IMPDECL; case IJavaElement.IMPORT_CONTAINER: return JavaPluginImages.DESC_OBJS_IMPCONT; case IJavaElement.TYPE: { IType type= (IType) element; IType declType= type.getDeclaringType(); boolean isInner= declType != null; boolean isInInterfaceOrAnnotation= isInner && JavaModelUtil.isInterfaceOrAnnotation(declType); return getTypeImageDescriptor(isInner, isInInterfaceOrAnnotation, type.getFlags(), useLightIcons(renderFlags)); } case IJavaElement.PACKAGE_FRAGMENT_ROOT: { IPackageFragmentRoot root= (IPackageFragmentRoot) element; IPath attach= root.getSourceAttachmentPath(); if (root.getKind() == IPackageFragmentRoot.K_BINARY) { if (root.isArchive()) { if (root.isExternal()) { if (attach == null) { return JavaPluginImages.DESC_OBJS_EXTJAR; } else { return JavaPluginImages.DESC_OBJS_EXTJAR_WSRC; } } else { if (attach == null) { return JavaPluginImages.DESC_OBJS_JAR; } else { return JavaPluginImages.DESC_OBJS_JAR_WSRC; } } } else { if (attach == null) { return JavaPluginImages.DESC_OBJS_CLASSFOLDER; } else { return JavaPluginImages.DESC_OBJS_CLASSFOLDER_WSRC; } } } else { return JavaPluginImages.DESC_OBJS_PACKFRAG_ROOT; } } case IJavaElement.PACKAGE_FRAGMENT: return getPackageFragmentIcon(element); case IJavaElement.COMPILATION_UNIT: return JavaPluginImages.DESC_OBJS_CUNIT; case IJavaElement.CLASS_FILE: /* this is too expensive for large packages try { IClassFile cfile= (IClassFile)element; if (cfile.isClass()) return JavaPluginImages.IMG_OBJS_CFILECLASS; return JavaPluginImages.IMG_OBJS_CFILEINT; } catch(JavaModelException e) { // fall through; }*/ return JavaPluginImages.DESC_OBJS_CFILE; case IJavaElement.JAVA_PROJECT: IJavaProject jp= (IJavaProject)element; if (jp.getProject().isOpen()) { IProject project= jp.getProject(); IWorkbenchAdapter adapter= (IWorkbenchAdapter)project.getAdapter(IWorkbenchAdapter.class); if (adapter != null) { ImageDescriptor result= adapter.getImageDescriptor(project); if (result != null) return result; } return DESC_OBJ_PROJECT; } return DESC_OBJ_PROJECT_CLOSED; case IJavaElement.JAVA_MODEL: return JavaPluginImages.DESC_OBJS_JAVA_MODEL; case IJavaElement.TYPE_PARAMETER: return JavaPluginImages.DESC_OBJS_TYPEVARIABLE; case IJavaElement.ANNOTATION: return JavaPluginImages.DESC_OBJS_ANNOTATION; default: // ignore. Must be a new, yet unknown Java element // give an advanced IWorkbenchAdapter the chance IWorkbenchAdapter wbAdapter= (IWorkbenchAdapter) element.getAdapter(IWorkbenchAdapter.class); if (wbAdapter != null && !(wbAdapter instanceof JavaWorkbenchAdapter)) { // avoid recursion ImageDescriptor imageDescriptor= wbAdapter.getImageDescriptor(element); if (imageDescriptor != null) { return imageDescriptor; } } return JavaPluginImages.DESC_OBJS_GHOST; } } catch (JavaModelException e) { if (e.isDoesNotExist()) return JavaPluginImages.DESC_OBJS_UNKNOWN; JavaPlugin.log(e); return JavaPluginImages.DESC_OBJS_GHOST; } } private static boolean isDefaultFlag(int flags) { return !Flags.isPublic(flags) && !Flags.isProtected(flags) && !Flags.isPrivate(flags); } private ImageDescriptor getPackageFragmentIcon(IJavaElement element) throws JavaModelException { IPackageFragment fragment= (IPackageFragment)element; boolean containsJavaElements= false; try { containsJavaElements= fragment.hasChildren(); for (Object o: fragment.getNonJavaResources()) { if (o instanceof IFile) { IFile file = (IFile) o; String ext = file.getFileExtension(); if (ext!=null && ext.equals("ceylon")) { containsJavaElements=true; if (file.getName().equals("module.ceylon")) { return CeylonPlugin.getInstance().getImageRegistry() .getDescriptor(CEYLON_MODULE); } } } } } catch(JavaModelException e) { // assuming no children; } if(!containsJavaElements && (fragment.getNonJavaResources().length > 0)) return JavaPluginImages.DESC_OBJS_EMPTY_PACKAGE_RESOURCES; else if (!containsJavaElements) return JavaPluginImages.DESC_OBJS_EMPTY_PACKAGE; return JavaPluginImages.DESC_OBJS_PACKAGE; } public void dispose() { } // ---- Methods to compute the adornments flags --------------------------------- private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) { int flags= 0; if (showOverlayIcons(renderFlags)) { try { if (element instanceof IMember) { IMember member= (IMember)element; int modifiers= member.getFlags(); if (Flags.isAbstract(modifiers) && confirmAbstract(member)) flags|= JavaElementImageDescriptor.ABSTRACT; if (Flags.isFinal(modifiers) || isInterfaceOrAnnotationField(member) || isEnumConstant(member, modifiers)) flags|= JavaElementImageDescriptor.FINAL; if (Flags.isStatic(modifiers) || isInterfaceOrAnnotationFieldOrType(member) || isEnumConstant(member, modifiers)) flags|= JavaElementImageDescriptor.STATIC; if (Flags.isDeprecated(modifiers)) flags|= JavaElementImageDescriptor.DEPRECATED; int elementType= element.getElementType(); if (elementType == IJavaElement.METHOD) { if (((IMethod)element).isConstructor()) flags|= JavaElementImageDescriptor.CONSTRUCTOR; if (Flags.isSynchronized(modifiers)) // collides with 'super' flag flags|= JavaElementImageDescriptor.SYNCHRONIZED; if (Flags.isNative(modifiers)) flags|= JavaElementImageDescriptor.NATIVE; } if (member.getElementType() == IJavaElement.TYPE) { if (JavaModelUtil.hasMainMethod((IType)member)) { flags|= JavaElementImageDescriptor.RUNNABLE; } } if (member.getElementType() == IJavaElement.FIELD) { if (Flags.isVolatile(modifiers)) flags|= JavaElementImageDescriptor.VOLATILE; if (Flags.isTransient(modifiers)) flags|= JavaElementImageDescriptor.TRANSIENT; } } else if (element instanceof ILocalVariable && Flags.isFinal(((ILocalVariable)element).getFlags())) { flags|= JavaElementImageDescriptor.FINAL; } } catch (JavaModelException e) { // do nothing. Can't compute runnable adornment or get flags } } return flags; } private static boolean confirmAbstract(IMember element) throws JavaModelException { // never show the abstract symbol on interfaces or members in interfaces if (element.getElementType() == IJavaElement.TYPE) { return ! JavaModelUtil.isInterfaceOrAnnotation((IType) element); } return ! JavaModelUtil.isInterfaceOrAnnotation(element.getDeclaringType()); } private static boolean isInterfaceOrAnnotationField(IMember element) throws JavaModelException { // always show the final symbol on interface fields if (element.getElementType() == IJavaElement.FIELD) { return JavaModelUtil.isInterfaceOrAnnotation(element.getDeclaringType()); } return false; } private static boolean isInterfaceOrAnnotationFieldOrType(IMember element) throws JavaModelException { // always show the static symbol on interface fields and types if (element.getElementType() == IJavaElement.FIELD) { return JavaModelUtil.isInterfaceOrAnnotation(element.getDeclaringType()); } else if (element.getElementType() == IJavaElement.TYPE && element.getDeclaringType() != null) { return JavaModelUtil.isInterfaceOrAnnotation(element.getDeclaringType()); } return false; } private static boolean isEnumConstant(IMember element, int modifiers) { if (element.getElementType() == IJavaElement.FIELD) { return Flags.isEnum(modifiers); } return false; } public static ImageDescriptor getMethodImageDescriptor(boolean isInInterfaceOrAnnotation, int flags) { if (Flags.isPublic(flags) || isInInterfaceOrAnnotation) return JavaPluginImages.DESC_MISC_PUBLIC; if (Flags.isProtected(flags)) return JavaPluginImages.DESC_MISC_PROTECTED; if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_MISC_PRIVATE; return JavaPluginImages.DESC_MISC_DEFAULT; } public static ImageDescriptor getFieldImageDescriptor(boolean isInInterfaceOrAnnotation, int flags) { if (Flags.isPublic(flags) || isInInterfaceOrAnnotation || Flags.isEnum(flags)) return JavaPluginImages.DESC_FIELD_PUBLIC; if (Flags.isProtected(flags)) return JavaPluginImages.DESC_FIELD_PROTECTED; if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_FIELD_PRIVATE; return JavaPluginImages.DESC_FIELD_DEFAULT; } public static ImageDescriptor getTypeImageDescriptor(boolean isInner, boolean isInInterfaceOrAnnotation, int flags, boolean useLightIcons) { if (Flags.isEnum(flags)) { if (useLightIcons) { return JavaPluginImages.DESC_OBJS_ENUM_ALT; } if (isInner) { return getInnerEnumImageDescriptor(isInInterfaceOrAnnotation, flags); } return getEnumImageDescriptor(flags); } else if (Flags.isAnnotation(flags)) { if (useLightIcons) { return JavaPluginImages.DESC_OBJS_ANNOTATION_ALT; } if (isInner) { return getInnerAnnotationImageDescriptor(isInInterfaceOrAnnotation, flags); } return getAnnotationImageDescriptor(flags); } else if (Flags.isInterface(flags)) { if (useLightIcons) { return JavaPluginImages.DESC_OBJS_INTERFACEALT; } if (isInner) { return getInnerInterfaceImageDescriptor(isInInterfaceOrAnnotation, flags); } return getInterfaceImageDescriptor(flags); } else { if (useLightIcons) { return JavaPluginImages.DESC_OBJS_CLASSALT; } if (isInner) { return getInnerClassImageDescriptor(isInInterfaceOrAnnotation, flags); } return getClassImageDescriptor(flags); } } public static Image getDecoratedImage(ImageDescriptor baseImage, int adornments, Point size) { return JavaPlugin.getImageDescriptorRegistry().get(new JavaElementImageDescriptor(baseImage, adornments, size)); } private static ImageDescriptor getClassImageDescriptor(int flags) { if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_CLASS; else return JavaPluginImages.DESC_OBJS_CLASS_DEFAULT; } private static ImageDescriptor getInnerClassImageDescriptor(boolean isInInterfaceOrAnnotation, int flags) { if (Flags.isPublic(flags) || isInInterfaceOrAnnotation) return JavaPluginImages.DESC_OBJS_INNER_CLASS_PUBLIC; else if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_INNER_CLASS_PRIVATE; else if (Flags.isProtected(flags)) return JavaPluginImages.DESC_OBJS_INNER_CLASS_PROTECTED; else return JavaPluginImages.DESC_OBJS_INNER_CLASS_DEFAULT; } private static ImageDescriptor getEnumImageDescriptor(int flags) { if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_ENUM; else return JavaPluginImages.DESC_OBJS_ENUM_DEFAULT; } private static ImageDescriptor getInnerEnumImageDescriptor(boolean isInInterfaceOrAnnotation, int flags) { if (Flags.isPublic(flags) || isInInterfaceOrAnnotation) return JavaPluginImages.DESC_OBJS_ENUM; else if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_ENUM_PRIVATE; else if (Flags.isProtected(flags)) return JavaPluginImages.DESC_OBJS_ENUM_PROTECTED; else return JavaPluginImages.DESC_OBJS_ENUM_DEFAULT; } private static ImageDescriptor getAnnotationImageDescriptor(int flags) { if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_ANNOTATION; else return JavaPluginImages.DESC_OBJS_ANNOTATION_DEFAULT; } private static ImageDescriptor getInnerAnnotationImageDescriptor(boolean isInInterfaceOrAnnotation, int flags) { if (Flags.isPublic(flags) || isInInterfaceOrAnnotation) return JavaPluginImages.DESC_OBJS_ANNOTATION; else if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_ANNOTATION_PRIVATE; else if (Flags.isProtected(flags)) return JavaPluginImages.DESC_OBJS_ANNOTATION_PROTECTED; else return JavaPluginImages.DESC_OBJS_ANNOTATION_DEFAULT; } private static ImageDescriptor getInterfaceImageDescriptor(int flags) { if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_INTERFACE; else return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT; } private static ImageDescriptor getInnerInterfaceImageDescriptor(boolean isInInterfaceOrAnnotation, int flags) { if (Flags.isPublic(flags) || isInInterfaceOrAnnotation) return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PUBLIC; else if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PRIVATE; else if (Flags.isProtected(flags)) return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PROTECTED; else return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT; } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_JavaElementImageProvider.java
379
public interface Locale extends Serializable { String getLocaleCode(); void setLocaleCode(String localeCode); public String getFriendlyName(); public void setFriendlyName(String friendlyName); public void setDefaultFlag(Boolean defaultFlag); public Boolean getDefaultFlag(); public BroadleafCurrency getDefaultCurrency(); public void setDefaultCurrency(BroadleafCurrency currency); public Boolean getUseInSearchIndex(); public void setUseInSearchIndex(Boolean useInSearchIndex); }
0true
common_src_main_java_org_broadleafcommerce_common_locale_domain_Locale.java
1,358
new ClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { List<ShardRoutingEntry> shardRoutingEntries = new ArrayList<ShardRoutingEntry>(); startedShardsQueue.drainTo(shardRoutingEntries); // nothing to process (a previous event has processed it already) if (shardRoutingEntries.isEmpty()) { return currentState; } RoutingTable routingTable = currentState.routingTable(); MetaData metaData = currentState.getMetaData(); List<ShardRouting> shardRoutingToBeApplied = new ArrayList<ShardRouting>(shardRoutingEntries.size()); for (int i = 0; i < shardRoutingEntries.size(); i++) { ShardRoutingEntry shardRoutingEntry = shardRoutingEntries.get(i); ShardRouting shardRouting = shardRoutingEntry.shardRouting; try { IndexMetaData indexMetaData = metaData.index(shardRouting.index()); IndexRoutingTable indexRoutingTable = routingTable.index(shardRouting.index()); // if there is no metadata, no routing table or the current index is not of the right uuid, the index has been deleted while it was being allocated // which is fine, we should just ignore this if (indexMetaData == null) { continue; } if (indexRoutingTable == null) { continue; } if (!indexMetaData.isSameUUID(shardRoutingEntry.indexUUID)) { logger.debug("{} ignoring shard started, different index uuid, current {}, got {}", shardRouting.shardId(), indexMetaData.getUUID(), shardRoutingEntry); continue; } // find the one that maps to us, if its already started, no need to do anything... // the shard might already be started since the nodes that is starting the shards might get cluster events // with the shard still initializing, and it will try and start it again (until the verification comes) IndexShardRoutingTable indexShardRoutingTable = indexRoutingTable.shard(shardRouting.id()); boolean applyShardEvent = true; for (ShardRouting entry : indexShardRoutingTable) { if (shardRouting.currentNodeId().equals(entry.currentNodeId())) { // we found the same shard that exists on the same node id if (!entry.initializing()) { // shard is in initialized state, skipping event (probable already started) logger.debug("{} ignoring shard started event for {}, current state: {}", shardRouting.shardId(), shardRoutingEntry, entry.state()); applyShardEvent = false; } } } if (applyShardEvent) { shardRoutingToBeApplied.add(shardRouting); logger.debug("{} will apply shard started {}", shardRouting.shardId(), shardRoutingEntry); } } catch (Throwable t) { logger.error("{} unexpected failure while processing shard started [{}]", t, shardRouting.shardId(), shardRouting); } } if (shardRoutingToBeApplied.isEmpty()) { return currentState; } RoutingAllocation.Result routingResult = allocationService.applyStartedShards(currentState, shardRoutingToBeApplied, true); if (!routingResult.changed()) { return currentState; } return ClusterState.builder(currentState).routingResult(routingResult).build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } });
0true
src_main_java_org_elasticsearch_cluster_action_shard_ShardStateAction.java
1,773
public static class Ring<P extends ShapeBuilder> extends BaseLineStringBuilder<Ring<P>> { private final P parent; protected Ring(P parent) { this(parent, new ArrayList<Coordinate>()); } protected Ring(P parent, ArrayList<Coordinate> points) { super(points); this.parent = parent; } public P close() { Coordinate start = points.get(0); Coordinate end = points.get(points.size()-1); if(start.x != end.x || start.y != end.y) { points.add(start); } return parent; } @Override public GeoShapeType type() { return null; } }
0true
src_main_java_org_elasticsearch_common_geo_builders_BasePolygonBuilder.java
1,586
public class EnableAllocationTests extends ElasticsearchAllocationTestCase { private final ESLogger logger = Loggers.getLogger(EnableAllocationTests.class); @Test public void testClusterEnableNone() { AllocationService strategy = createAllocationService(settingsBuilder() .put(CLUSTER_ROUTING_ALLOCATION_ENABLE, Allocation.NONE.name()) .build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(1).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("--> adding two nodes and do rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() .put(newNode("node1")) .put(newNode("node2")) ).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(clusterState.routingNodes().shardsWithState(INITIALIZING).size(), equalTo(0)); } @Test public void testClusterEnableOnlyPrimaries() { AllocationService strategy = createAllocationService(settingsBuilder() .put(CLUSTER_ROUTING_ALLOCATION_ENABLE, Allocation.PRIMARIES.name()) .build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(1).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("--> adding two nodes do rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() .put(newNode("node1")) .put(newNode("node2")) ).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(clusterState.routingNodes().shardsWithState(INITIALIZING).size(), equalTo(1)); logger.info("--> start the shards (primaries)"); routingTable = strategy.applyStartedShards(clusterState, clusterState.routingNodes().shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(clusterState.routingNodes().shardsWithState(INITIALIZING).size(), equalTo(0)); } @Test public void testIndexEnableNone() { AllocationService strategy = createAllocationService(settingsBuilder() .build()); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("disabled").settings(ImmutableSettings.builder() .put(INDEX_ROUTING_ALLOCATION_ENABLE, Allocation.NONE.name())) .numberOfShards(1).numberOfReplicas(1)) .put(IndexMetaData.builder("enabled").numberOfShards(1).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("disabled")) .addAsNew(metaData.index("enabled")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("--> adding two nodes and do rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() .put(newNode("node1")) .put(newNode("node2")) ).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(clusterState.routingNodes().shardsWithState(INITIALIZING).size(), equalTo(1)); logger.info("--> start the shards (primaries)"); routingTable = strategy.applyStartedShards(clusterState, clusterState.routingNodes().shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("--> start the shards (replicas)"); routingTable = strategy.applyStartedShards(clusterState, clusterState.routingNodes().shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("--> verify only enabled index has been routed"); assertThat(clusterState.readOnlyRoutingNodes().shardsWithState("enabled", STARTED).size(), equalTo(2)); assertThat(clusterState.readOnlyRoutingNodes().shardsWithState("disabled", STARTED).size(), equalTo(0)); } }
0true
src_test_java_org_elasticsearch_cluster_routing_allocation_decider_EnableAllocationTests.java
2,577
transportService.sendRequest(newState.nodes().masterNode(), RejoinClusterRequestHandler.ACTION, new RejoinClusterRequest(currentState.nodes().localNodeId()), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleException(TransportException exp) { logger.warn("failed to send rejoin request to [{}]", exp, newState.nodes().masterNode()); } });
0true
src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java
1,414
private static final SoftLock LOCK_FAILURE = new SoftLock() {};
0true
hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_distributed_IMapRegionCache.java
3,584
public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { FloatFieldMapper.Builder builder = floatField(name); parseNumberField(builder, name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("null_value")) { builder.nullValue(nodeFloatValue(propNode)); } } return builder; } }
0true
src_main_java_org_elasticsearch_index_mapper_core_FloatFieldMapper.java
1,472
public class PlainShardsIterator implements ShardsIterator { private final List<ShardRouting> shards; private final int size; private final int index; private final int limit; private volatile int counter; public PlainShardsIterator(List<ShardRouting> shards) { this(shards, 0); } public PlainShardsIterator(List<ShardRouting> shards, int index) { this.shards = shards; this.size = shards.size(); if (size == 0) { this.index = 0; } else { this.index = Math.abs(index % size); } this.counter = this.index; this.limit = this.index + size; } @Override public void reset() { this.counter = this.index; } @Override public int remaining() { return limit - counter; } @Override public ShardRouting firstOrNull() { if (size == 0) { return null; } return shards.get(index); } @Override public ShardRouting nextOrNull() { if (size == 0) { return null; } int counter = (this.counter); if (counter >= size) { if (counter >= limit) { return null; } this.counter = counter + 1; return shards.get(counter - size); } else { this.counter = counter + 1; return shards.get(counter); } } @Override public int size() { return size; } @Override public int sizeActive() { int count = 0; for (int i = 0; i < size; i++) { if (shards.get(i).active()) { count++; } } return count; } @Override public int assignedReplicasIncludingRelocating() { int count = 0; for (int i = 0; i < size; i++) { ShardRouting shard = shards.get(i); if (shard.unassigned()) { continue; } // if the shard is primary and relocating, add one to the counter since we perform it on the replica as well // (and we already did it on the primary) if (shard.primary()) { if (shard.relocating()) { count++; } } else { count++; // if we are relocating the replica, we want to perform the index operation on both the relocating // shard and the target shard. This means that we won't loose index operations between end of recovery // and reassignment of the shard by the master node if (shard.relocating()) { count++; } } } return count; } @Override public Iterable<ShardRouting> asUnordered() { return shards; } }
1no label
src_main_java_org_elasticsearch_cluster_routing_PlainShardsIterator.java
145
final class HazelcastClientManagedContext implements ManagedContext { private final HazelcastInstance instance; private final ManagedContext externalContext; private final boolean hasExternalContext; public HazelcastClientManagedContext(final HazelcastInstance instance, final ManagedContext externalContext) { this.instance = instance; this.externalContext = externalContext; this.hasExternalContext = externalContext != null; } @Override public Object initialize(Object obj) { if (obj instanceof HazelcastInstanceAware) { ((HazelcastInstanceAware) obj).setHazelcastInstance(instance); } if (hasExternalContext) { obj = externalContext.initialize(obj); } return obj; } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_HazelcastClientManagedContext.java
207
public static final Factory<StaticBuffer> STATIC_FACTORY = new Factory<StaticBuffer>() { @Override public StaticBuffer get(byte[] array, int offset, int limit) { return new StaticArrayBuffer(array, offset, limit); } };
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_StaticBuffer.java
496
public class CloseIndexRequest extends AcknowledgedRequest<CloseIndexRequest> { private String[] indices; private IndicesOptions indicesOptions = IndicesOptions.fromOptions(false, false, true, false); CloseIndexRequest() { } /** * Constructs a new close index request for the specified index. */ public CloseIndexRequest(String... indices) { this.indices = indices; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (indices == null || indices.length == 0) { validationException = addValidationError("index is missing", validationException); } return validationException; } /** * The indices to be closed * @return the indices to be closed */ String[] indices() { return indices; } /** * Sets the indices to be closed * @param indices the indices to be closed * @return the request itself */ public CloseIndexRequest indices(String... indices) { this.indices = indices; return this; } /** * Specifies what type of requested indices to ignore and how to deal with wildcard expressions. * For example indices that don't exist. * * @return the desired behaviour regarding indices to ignore and wildcard indices expressions */ public IndicesOptions indicesOptions() { return indicesOptions; } /** * Specifies what type of requested indices to ignore and how to deal wild wildcard expressions. * For example indices that don't exist. * * @param indicesOptions the desired behaviour regarding indices to ignore and wildcard indices expressions * @return the request itself */ public CloseIndexRequest indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); indices = in.readStringArray(); readTimeout(in); indicesOptions = IndicesOptions.readIndicesOptions(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArray(indices); writeTimeout(out); indicesOptions.writeIndicesOptions(out); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_close_CloseIndexRequest.java
1,381
public interface OTxListener { public enum EVENT { BEFORE_COMMIT, AFTER_COMMIT, BEFORE_ROLLBACK, AFTER_ROLLBACK } public void onEvent(ORecordOperation iTxEntry, EVENT iEvent); }
0true
core_src_main_java_com_orientechnologies_orient_core_tx_OTxListener.java
1,320
public class FieldType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, FieldType> TYPES = new LinkedHashMap<String, FieldType>(); public static final FieldType ID = new FieldType("id", "ID"); public static final FieldType CATEGORY = new FieldType("category", "Category"); public static final FieldType INT = new FieldType("i", "Integer"); public static final FieldType INTS = new FieldType("is", "Integer (Multi)"); public static final FieldType STRING = new FieldType("s", "String"); public static final FieldType STRINGS = new FieldType("ss", "String (Multi)"); public static final FieldType LONG = new FieldType("l", "Long"); public static final FieldType LONGS = new FieldType("ls", "Long (Multi)"); public static final FieldType TEXT = new FieldType("t", "Text"); public static final FieldType TEXTS = new FieldType("txt", "Text (Multi)"); public static final FieldType BOOLEAN = new FieldType("b", "Boolean"); public static final FieldType BOOLEANS = new FieldType("bs", "Boolean (Multi)"); public static final FieldType DOUBLE = new FieldType("d", "Double"); public static final FieldType DOUBLES = new FieldType("ds", "Double (Multi)"); public static final FieldType PRICE = new FieldType("p", "Price"); public static final FieldType DATE = new FieldType("dt", "Date"); public static final FieldType DATES = new FieldType("dts", "Date (Multi)"); public static final FieldType TRIEINT = new FieldType("ti", "Trie Integer"); public static final FieldType TRIELONG = new FieldType("tl", "Trie Long"); public static final FieldType TRIEDOUBLE = new FieldType("td", "Trie Double"); public static final FieldType TRIEDATE = new FieldType("tdt", "Trie Date"); public static FieldType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public FieldType() { //do nothing } public FieldType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } @Override public String getType() { return type; } @Override public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.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; FieldType other = (FieldType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_domain_solr_FieldType.java
627
public abstract class AbstractModelVariableModifierProcessor extends AbstractElementProcessor { public AbstractModelVariableModifierProcessor(String elementName) { super(elementName); } /** * This method will handle calling the modifyModelAttributes abstract method and return * an "OK" processor result */ @Override protected ProcessorResult processElement(final Arguments arguments, final Element element) { modifyModelAttributes(arguments, element); // Remove the tag from the DOM final NestableNode parent = element.getParent(); parent.removeChild(element); return ProcessorResult.OK; } /** * Helper method to add a value to the expression evaluation root (model) Map * @param key the key to add to the model * @param value the value represented by the key */ @SuppressWarnings("unchecked") protected void addToModel(Arguments arguments, String key, Object value) { ((Map<String, Object>) arguments.getExpressionEvaluationRoot()).put(key, value); } /** * This method must be overriding by a processor that wishes to modify the model. It will * be called by this abstract processor in the correct precendence in the evaluation chain. * @param arguments * @param element */ protected abstract void modifyModelAttributes(Arguments arguments, Element element); }
0true
common_src_main_java_org_broadleafcommerce_common_web_dialect_AbstractModelVariableModifierProcessor.java
388
new Thread(){ public void run() { try { if(mm.tryLock(key, 10, TimeUnit.SECONDS)){ tryLockReturnsTrue.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_multimap_ClientMultiMapLockTest.java
556
public class GetMappingsResponse extends ActionResponse { private ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> mappings = ImmutableOpenMap.of(); GetMappingsResponse(ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> mappings) { this.mappings = mappings; } GetMappingsResponse() { } public ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> mappings() { return mappings; } public ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> getMappings() { return mappings(); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); int size = in.readVInt(); ImmutableOpenMap.Builder<String, ImmutableOpenMap<String, MappingMetaData>> indexMapBuilder = ImmutableOpenMap.builder(); for (int i = 0; i < size; i++) { String key = in.readString(); int valueSize = in.readVInt(); ImmutableOpenMap.Builder<String, MappingMetaData> typeMapBuilder = ImmutableOpenMap.builder(); for (int j = 0; j < valueSize; j++) { typeMapBuilder.put(in.readString(), MappingMetaData.readFrom(in)); } indexMapBuilder.put(key, typeMapBuilder.build()); } mappings = indexMapBuilder.build(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(mappings.size()); for (ObjectObjectCursor<String, ImmutableOpenMap<String, MappingMetaData>> indexEntry : mappings) { out.writeString(indexEntry.key); out.writeVInt(indexEntry.value.size()); for (ObjectObjectCursor<String, MappingMetaData> typeEntry : indexEntry.value) { out.writeString(typeEntry.key); MappingMetaData.writeTo(typeEntry.value, out); } } } }
0true
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_GetMappingsResponse.java
1,002
public class ReduceRequest extends SemaphoreRequest { public ReduceRequest() { } public ReduceRequest(String name, int permitCount) { super(name, permitCount); } @Override protected Operation prepareOperation() { return new ReduceOperation(name, permitCount); } @Override public int getClassId() { return SemaphorePortableHook.REDUCE; } @Override public Permission getRequiredPermission() { return new SemaphorePermission(name, ActionConstants.ACTION_ACQUIRE); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_semaphore_client_ReduceRequest.java
1,083
public class MyServiceConfigParser extends AbstractXmlConfigHelper implements ServiceConfigurationParser<MyServiceConfig> { public MyServiceConfig parse(Element element) { MyServiceConfig config = new MyServiceConfig(); for (org.w3c.dom.Node configNode : new AbstractXmlConfigHelper.IterableNodeList(element.getChildNodes())) { if ("my-service".equals(cleanNodeName(configNode))) { for (org.w3c.dom.Node node : new AbstractXmlConfigHelper.IterableNodeList(configNode.getChildNodes())) { final String name = cleanNodeName(node.getNodeName()); if ("string-prop".equals(name)) { config.stringProp = getTextContent(node); } else if ("int-prop".equals(name)) { String value = getTextContent(node); config.intProp = Integer.parseInt(value); } else if ("bool-prop".equals(name)) { config.boolProp = Boolean.parseBoolean(getTextContent(node)); } } } } return config; } }
0true
hazelcast_src_test_java_com_hazelcast_config_MyServiceConfigParser.java
233
public class NioNeoDbPersistenceSource extends LifecycleAdapter implements PersistenceSource, EntityIdGenerator { private final String dataSourceName = null; private final XaDataSourceManager xaDataSourceManager; public NioNeoDbPersistenceSource(XaDataSourceManager xaDataSourceManager) { assert(xaDataSourceManager != null); this.xaDataSourceManager = xaDataSourceManager; } @Override public NeoStoreTransaction createTransaction( XaConnection connection ) { return ((NeoStoreXaConnection) connection).createTransaction(); } @Override public String toString() { return "A persistence source to [" + dataSourceName + "]"; } @Override public long nextId( Class<?> clazz ) { return xaDataSourceManager.getNeoStoreDataSource().nextId( clazz ); } @Override public long getHighestPossibleIdInUse( Class<?> clazz ) { return xaDataSourceManager.getNeoStoreDataSource().getHighestPossibleIdInUse( clazz ); } @Override public long getNumberOfIdsInUse( Class<?> clazz ) { return xaDataSourceManager.getNeoStoreDataSource().getNumberOfIdsInUse( clazz ); } @Override public XaDataSource getXaDataSource() { return xaDataSourceManager.getNeoStoreDataSource(); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NioNeoDbPersistenceSource.java
2,179
static class NotDeletedDocIdSet extends DocIdSet { private final DocIdSet innerSet; private final Bits liveDocs; NotDeletedDocIdSet(DocIdSet innerSet, Bits liveDocs) { this.innerSet = innerSet; this.liveDocs = liveDocs; } @Override public boolean isCacheable() { return innerSet.isCacheable(); } @Override public Bits bits() throws IOException { Bits bits = innerSet.bits(); if (bits == null) { return null; } return new NotDeleteBits(bits, liveDocs); } @Override public DocIdSetIterator iterator() throws IOException { if (!DocIdSets.isFastIterator(innerSet) && liveDocs instanceof FixedBitSet) { // might as well iterate over the live docs..., since the iterator is not fast enough // but we can only do that if we have Bits..., in short, we reverse the order... Bits bits = innerSet.bits(); if (bits != null) { return new NotDeletedDocIdSetIterator(((FixedBitSet) liveDocs).iterator(), bits); } } DocIdSetIterator iterator = innerSet.iterator(); if (iterator == null) { return null; } return new NotDeletedDocIdSetIterator(iterator, liveDocs); } }
0true
src_main_java_org_elasticsearch_common_lucene_search_ApplyAcceptedDocsFilter.java
1,166
public interface PaymentInfo extends Serializable { public Long getId(); public void setId(Long id); public Order getOrder(); public void setOrder(Order order); public Address getAddress(); public void setAddress(Address address); public Phone getPhone(); public void setPhone(Phone phone); public Money getAmount(); public void setAmount(Money amount); public String getReferenceNumber(); public void setReferenceNumber(String referenceNumber); public PaymentInfoType getType(); public void setType(PaymentInfoType type); public void setAmountItems(List<AmountItem> amountItems); public List<AmountItem> getAmountItems(); public String getCustomerIpAddress(); public void setCustomerIpAddress(String customerIpAddress); public Map<String, String> getAdditionalFields(); public void setAdditionalFields(Map<String, String> additionalFields); public Map<String, String[]> getRequestParameterMap(); public void setRequestParameterMap(Map<String, String[]> requestParameterMap); public Referenced createEmptyReferenced(); public List<PaymentInfoDetail> getPaymentInfoDetails(); public void setPaymentInfoDetails(List<PaymentInfoDetail> details); public Money getPaymentCapturedAmount(); public Money getPaymentCreditedAmount(); public Money getReverseAuthAmount(); public BroadleafCurrency getCurrency(); public CustomerPayment getCustomerPayment(); public void setCustomerPayment(CustomerPayment customerPayment); public List<PaymentResponseItem> getPaymentResponseItems(); public void setPaymentResponseItems(List<PaymentResponseItem> paymentResponseItems); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_domain_PaymentInfo.java
1,909
new TypeConverter() { @SuppressWarnings("unchecked") public Object convert(String value, TypeLiteral<?> toType) { try { return Class.forName(value); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage()); } } @Override public String toString() { return "TypeConverter<Class<?>>"; } }
0true
src_main_java_org_elasticsearch_common_inject_TypeConverterBindingProcessor.java
1,455
public class ShippingInfoForm implements Serializable { private static final long serialVersionUID = -7895489234675056031L; protected Address address = new AddressImpl(); protected String addressName; protected FulfillmentOption fulfillmentOption; protected Long fulfillmentOptionId; protected PersonalMessage personalMessage = new PersonalMessageImpl(); protected String deliveryMessage; public ShippingInfoForm() { address.setPhonePrimary(new PhoneImpl()); } public Long getFulfillmentOptionId() { return fulfillmentOptionId; } public void setFulfillmentOptionId(Long fulfillmentOptionId) { this.fulfillmentOptionId = fulfillmentOptionId; } public FulfillmentOption getFulfillmentOption() { return fulfillmentOption; } public void setFulfillmentOption(FulfillmentOption fulfillmentOption) { this.fulfillmentOption = fulfillmentOption; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String getAddressName() { return addressName; } public void setAddressName(String addressName) { this.addressName = addressName; } public String getDeliveryMessage() { return deliveryMessage; } public void setDeliveryMessage(String deliveryMessage) { this.deliveryMessage = deliveryMessage; } public void setPersonalMessage(PersonalMessage personalMessage) { this.personalMessage = personalMessage; } public PersonalMessage getPersonalMessage() { return personalMessage; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_checkout_model_ShippingInfoForm.java
3,163
private final static class Empty extends BytesValues { Empty() { super(false); } @Override public int setDocument(int docId) { return 0; } @Override public BytesRef nextValue() { throw new ElasticsearchIllegalStateException("Empty BytesValues has no next value"); } @Override public int currentValueHash() { throw new ElasticsearchIllegalStateException("Empty BytesValues has no hash for the current Value"); } }
0true
src_main_java_org_elasticsearch_index_fielddata_BytesValues.java
3,700
public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { TypeFieldMapper.Builder builder = type(); parseField(builder, builder.name, node, parserContext); return builder; } }
0true
src_main_java_org_elasticsearch_index_mapper_internal_TypeFieldMapper.java
679
public class PutWarmerAction extends IndicesAction<PutWarmerRequest, PutWarmerResponse, PutWarmerRequestBuilder> { public static final PutWarmerAction INSTANCE = new PutWarmerAction(); public static final String NAME = "indices/warmer/put"; private PutWarmerAction() { super(NAME); } @Override public PutWarmerResponse newResponse() { return new PutWarmerResponse(); } @Override public PutWarmerRequestBuilder newRequestBuilder(IndicesAdminClient client) { return new PutWarmerRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_warmer_put_PutWarmerAction.java
1,181
public interface OQueryOperatorFactory { /** * @return set of operators */ Set<OQueryOperator> getOperators(); }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorFactory.java
495
return scheduledExecutor.schedule(new Runnable() { public void run() { executeInternal(command); } }, delay, unit);
1no label
hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientExecutionServiceImpl.java
1,435
public class CategoryLinkTag extends AbstractCatalogTag { private static final long serialVersionUID = 1L; private Category category; @Override public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); if (category != null) out.println(getUrl(category)); super.doTag(); } public Category getCategory() { return this.category; } public void setCategory(Category category) { this.category = category; } protected String getUrl(Category category) { PageContext pageContext = (PageContext)getJspContext(); HttpServletRequest request = (HttpServletRequest)pageContext.getRequest(); StringBuffer sb = new StringBuffer(); sb.append("<a href=\""); sb.append(request.getContextPath()); sb.append("/"); sb.append(category.getGeneratedUrl()); sb.append("\">"); sb.append(category.getName()); sb.append("</a>"); return sb.toString(); } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_catalog_taglib_CategoryLinkTag.java
2,831
@edu.umd.cs.findbugs.annotations.SuppressWarnings("EI_EXPOSE_REP") public final class MigrationOperation extends BaseMigrationOperation { private static final ResponseHandler ERROR_RESPONSE_HANDLER = new ResponseHandler() { @Override public void sendResponse(Object obj) { throw new HazelcastException("Migration operations can not send response!"); } @Override public boolean isLocal() { return true; } }; private long[] replicaVersions; private Collection<Operation> tasks; private byte[] taskData; private boolean compressed; public MigrationOperation() { } public MigrationOperation(MigrationInfo migrationInfo, long[] replicaVersions, byte[] taskData, boolean compressed) { super(migrationInfo); this.replicaVersions = replicaVersions; this.taskData = taskData; this.compressed = compressed; } @Override public Object getResponse() { return success; } @Override public void run() throws Exception { assertMigrationInitiatorIsMaster(); try { doRun(); } catch (Throwable t) { logMigrationFailure(t); } } private void doRun() throws Exception { if (startMigration()) { try { migrate(); } finally { afterMigrate(); } } else { logMigrationCancelled(); } } private void assertMigrationInitiatorIsMaster() { Address masterAddress = getNodeEngine().getMasterAddress(); if (!masterAddress.equals(migrationInfo.getMaster())) { throw new RetryableHazelcastException("Migration initiator is not master node! => " + toString()); } } private boolean startMigration() { return migrationInfo.startProcessing(); } private void logMigrationCancelled() { getLogger().warning("Migration is cancelled -> " + migrationInfo); } private void afterMigrate() { if (success) { InternalPartitionServiceImpl partitionService = getService(); partitionService.setPartitionReplicaVersions(migrationInfo.getPartitionId(), replicaVersions); } migrationInfo.doneProcessing(); } private void logMigrationFailure(Throwable e) { Level level = Level.WARNING; if (e instanceof IllegalStateException) { level = Level.FINEST; } ILogger logger = getLogger(); if (logger.isLoggable(level)) { logger.log(level, e.getMessage(), e); } } private void migrate() throws Exception { buildMigrationTasks(); addActiveMigration(); for (Operation op : tasks) { try { runMigrationTask(op); } catch (Throwable e) { getLogger().severe("An exception occurred while executing migration operation " + op, e); return; } } success = true; } private void addActiveMigration() { InternalPartitionServiceImpl partitionService = getService(); partitionService.addActiveMigration(migrationInfo); } private void buildMigrationTasks() throws IOException { SerializationService serializationService = getNodeEngine().getSerializationService(); BufferObjectDataInput in = serializationService.createObjectDataInput(toData()); try { int size = in.readInt(); tasks = new ArrayList<Operation>(size); for (int i = 0; i < size; i++) { Operation task = (Operation) serializationService.readObject(in); tasks.add(task); } } finally { closeResource(in); } } private byte[] toData() throws IOException { if (compressed) { return decompress(taskData); } else { return taskData; } } private void runMigrationTask(Operation op) throws Exception { op.setNodeEngine(getNodeEngine()) .setPartitionId(getPartitionId()) .setReplicaIndex(getReplicaIndex()); op.setResponseHandler(ERROR_RESPONSE_HANDLER); OperationAccessor.setCallerAddress(op, migrationInfo.getSource()); MigrationAwareService service = op.getService(); PartitionMigrationEvent event = new PartitionMigrationEvent(MigrationEndpoint.DESTINATION, migrationInfo.getPartitionId()); service.beforeMigration(event); op.beforeRun(); op.run(); op.afterRun(); } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeBoolean(compressed); out.writeInt(taskData.length); out.write(taskData); out.writeLongArray(replicaVersions); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); compressed = in.readBoolean(); int size = in.readInt(); taskData = new byte[size]; in.readFully(taskData); replicaVersions = in.readLongArray(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getName()); sb.append("{partitionId=").append(getPartitionId()); sb.append(", migration=").append(migrationInfo); sb.append(", compressed=").append(compressed); sb.append('}'); return sb.toString(); } }
1no label
hazelcast_src_main_java_com_hazelcast_partition_impl_MigrationOperation.java
85
static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; volatile V val; volatile Node<K,V> next; Node(int hash, K key, V val, Node<K,V> next) { this.hash = hash; this.key = key; this.val = val; this.next = next; } public final K getKey() { return key; } public final V getValue() { return val; } public final int hashCode() { return key.hashCode() ^ val.hashCode(); } public final String toString(){ return key + "=" + val; } public final V setValue(V value) { throw new UnsupportedOperationException(); } public final boolean equals(Object o) { Object k, v, u; Map.Entry<?,?> e; return ((o instanceof Map.Entry) && (k = (e = (Map.Entry<?,?>)o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == (u = val) || v.equals(u))); } /** * Virtualized support for map.get(); overridden in subclasses. */ Node<K,V> find(int h, Object k) { Node<K,V> e = this; if (k != null) { do { K ek; if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek)))) return e; } while ((e = e.next) != null); } return null; } }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
3,001
public static final class IdCacheSettings { public static final String ID_CACHE_TYPE = "index.cache.id.type"; }
0true
src_main_java_org_elasticsearch_index_cache_id_IdCacheModule.java
1,957
public final class Join { private Join() { } /** * Returns a string containing the {@code tokens}, converted to strings if * necessary, separated by {@code delimiter}. If {@code tokens} is empty, it * returns an empty string. * <p/> * <p>Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return a string consisting of the joined elements */ public static String join(String delimiter, Iterable<?> tokens) { return join(delimiter, tokens.iterator()); } /** * Returns a string containing the {@code tokens}, converted to strings if * necessary, separated by {@code delimiter}. If {@code tokens} is empty, it * returns an empty string. * <p/> * <p>Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return a string consisting of the joined elements */ public static String join(String delimiter, Object[] tokens) { return join(delimiter, Arrays.asList(tokens)); } /** * Returns a string containing the {@code tokens}, converted to strings if * necessary, separated by {@code delimiter}. * <p/> * <p>Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param delimiter a string to append between every element, but not at the * beginning or end * @param firstToken the first object to append * @param otherTokens subsequent objects to append * @return a string consisting of the joined elements */ public static String join( String delimiter, @Nullable Object firstToken, Object... otherTokens) { checkNotNull(otherTokens); return join(delimiter, Lists.newArrayList(firstToken, otherTokens)); } /** * Returns a string containing the {@code tokens}, converted to strings if * necessary, separated by {@code delimiter}. If {@code tokens} is empty, it * returns an empty string. * <p/> * <p>Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return a string consisting of the joined elements */ public static String join(String delimiter, Iterator<?> tokens) { StringBuilder sb = new StringBuilder(); join(sb, delimiter, tokens); return sb.toString(); } /** * Returns a string containing the contents of {@code map}, with entries * separated by {@code entryDelimiter}, and keys and values separated with * {@code keyValueSeparator}. * <p/> * <p>Each key and value will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param keyValueSeparator a string to append between every key and its * associated value * @param entryDelimiter a string to append between every entry, but not at * the beginning or end * @param map the map containing the data to join * @return a string consisting of the joined entries of the map; empty if the * map is empty */ public static String join( String keyValueSeparator, String entryDelimiter, Map<?, ?> map) { return join(new StringBuilder(), keyValueSeparator, entryDelimiter, map) .toString(); } /** * Appends each of the {@code tokens} to {@code appendable}, separated by * {@code delimiter}. * <p/> * <p>Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param appendable the object to append the results to * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return the same {@code Appendable} instance that was passed in * @throws JoinException if an {@link IOException} occurs */ public static <T extends Appendable> T join( T appendable, String delimiter, Iterable<?> tokens) { return join(appendable, delimiter, tokens.iterator()); } /** * Appends each of the {@code tokens} to {@code appendable}, separated by * {@code delimiter}. * <p/> * <p>Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param appendable the object to append the results to * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return the same {@code Appendable} instance that was passed in * @throws JoinException if an {@link IOException} occurs */ public static <T extends Appendable> T join( T appendable, String delimiter, Object[] tokens) { return join(appendable, delimiter, Arrays.asList(tokens)); } /** * Appends each of the {@code tokens} to {@code appendable}, separated by * {@code delimiter}. * <p/> * <p>Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param appendable the object to append the results to * @param delimiter a string to append between every element, but not at the * beginning or end * @param firstToken the first object to append * @param otherTokens subsequent objects to append * @return the same {@code Appendable} instance that was passed in * @throws JoinException if an {@link IOException} occurs */ public static <T extends Appendable> T join(T appendable, String delimiter, @Nullable Object firstToken, Object... otherTokens) { checkNotNull(otherTokens); return join(appendable, delimiter, Lists.newArrayList(firstToken, otherTokens)); } /** * Appends each of the {@code tokens} to {@code appendable}, separated by * {@code delimiter}. * <p/> * <p>Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param appendable the object to append the results to * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return the same {@code Appendable} instance that was passed in * @throws JoinException if an {@link IOException} occurs */ public static <T extends Appendable> T join( T appendable, String delimiter, Iterator<?> tokens) { /* This method is the workhorse of the class */ checkNotNull(appendable); checkNotNull(delimiter); if (tokens.hasNext()) { try { appendOneToken(appendable, tokens.next()); while (tokens.hasNext()) { appendable.append(delimiter); appendOneToken(appendable, tokens.next()); } } catch (IOException e) { throw new JoinException(e); } } return appendable; } /** * Appends the contents of {@code map} to {@code appendable}, with entries * separated by {@code entryDelimiter}, and keys and values separated with * {@code keyValueSeparator}. * <p/> * <p>Each key and value will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param appendable the object to append the results to * @param keyValueSeparator a string to append between every key and its * associated value * @param entryDelimiter a string to append between every entry, but not at * the beginning or end * @param map the map containing the data to join * @return the same {@code Appendable} instance that was passed in */ public static <T extends Appendable> T join(T appendable, String keyValueSeparator, String entryDelimiter, Map<?, ?> map) { checkNotNull(appendable); checkNotNull(keyValueSeparator); checkNotNull(entryDelimiter); Iterator<? extends Map.Entry<?, ?>> entries = map.entrySet().iterator(); if (entries.hasNext()) { try { appendOneEntry(appendable, keyValueSeparator, entries.next()); while (entries.hasNext()) { appendable.append(entryDelimiter); appendOneEntry(appendable, keyValueSeparator, entries.next()); } } catch (IOException e) { throw new JoinException(e); } } return appendable; } private static void appendOneEntry( Appendable appendable, String keyValueSeparator, Map.Entry<?, ?> entry) throws IOException { appendOneToken(appendable, entry.getKey()); appendable.append(keyValueSeparator); appendOneToken(appendable, entry.getValue()); } private static void appendOneToken(Appendable appendable, Object token) throws IOException { appendable.append(toCharSequence(token)); } private static CharSequence toCharSequence(Object token) { return (token instanceof CharSequence) ? (CharSequence) token : String.valueOf(token); } /** * Exception thrown in response to an {@link IOException} from the supplied * {@link Appendable}. This is used because most callers won't want to * worry about catching an IOException. */ public static class JoinException extends RuntimeException { private JoinException(IOException cause) { super(cause); } private static final long serialVersionUID = 1L; } }
0true
src_main_java_org_elasticsearch_common_inject_internal_Join.java
1,454
public class OServerCommandGetGephi extends OServerCommandAuthenticatedDbAbstract { private static final String[] NAMES = { "GET|gephi/*" }; public OServerCommandGetGephi() { } public OServerCommandGetGephi(final OServerCommandConfiguration iConfig) { } @Override public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception { String[] urlParts = checkSyntax( iRequest.url, 4, "Syntax error: gephi/<database>/<language>/<query-text>[/<limit>][/<fetchPlan>].<br/>Limit is optional and is setted to 20 by default. Set expressely to 0 to have no limits."); final String language = urlParts[2]; final String text = urlParts[3]; final int limit = urlParts.length > 4 ? Integer.parseInt(urlParts[4]) : 20; final String fetchPlan = urlParts.length > 5 ? urlParts[5] : null; iRequest.data.commandInfo = "Gephi"; iRequest.data.commandDetail = text; final ODatabaseDocumentTx db = getProfiledDatabaseInstance(iRequest); final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph(); try { final Iterable<OrientVertex> vertices; if (language.equals("sql")) vertices = graph.command(new OSQLSynchQuery<OrientVertex>(text, limit).setFetchPlan(fetchPlan)).execute(); else if (language.equals("gremlin")) { List<Object> result = new ArrayList<Object>(); OGremlinHelper.execute(graph, text, null, null, result, null, null); vertices = new ArrayList<OrientVertex>(result.size()); for (Object o : result) { ((ArrayList<OrientVertex>) vertices).add(graph.getVertex((OIdentifiable) o)); } } else throw new IllegalArgumentException("Language '" + language + "' is not supported. Use 'sql' or 'gremlin'"); sendRecordsContent(iRequest, iResponse, vertices, fetchPlan); } finally { if (graph != null) graph.shutdown(); if (db != null) db.close(); } return false; } protected void sendRecordsContent(final OHttpRequest iRequest, final OHttpResponse iResponse, Iterable<OrientVertex> iRecords, String iFetchPlan) throws IOException { final StringWriter buffer = new StringWriter(); final OJSONWriter json = new OJSONWriter(buffer, OHttpResponse.JSON_FORMAT); json.setPrettyPrint(true); generateGraphDbOutput(iRecords, json); iResponse.send(OHttpUtils.STATUS_OK_CODE, OHttpUtils.STATUS_OK_DESCRIPTION, OHttpUtils.CONTENT_JSON, buffer.toString(), null); } protected void generateGraphDbOutput(final Iterable<OrientVertex> iVertices, final OJSONWriter json) throws IOException { if (iVertices == null) return; // CREATE A SET TO SPEED UP SEARCHES ON VERTICES final Set<OrientVertex> vertexes = new HashSet<OrientVertex>(); for (OrientVertex id : iVertices) vertexes.add(id); final Set<OrientEdge> edges = new HashSet<OrientEdge>(); for (OrientVertex vertex : vertexes) { json.resetAttributes(); json.beginObject(0, false, null); json.beginObject(1, false, "an"); json.beginObject(2, false, vertex.getIdentity()); // ADD ALL THE EDGES for (Edge e : vertex.getEdges(Direction.BOTH)) edges.add((OrientEdge) e); // ADD ALL THE PROPERTIES for (String field : vertex.getPropertyKeys()) { final Object v = vertex.getProperty(field); if (v != null) json.writeAttribute(3, false, field, v); } json.endObject(2, false); json.endObject(1, false); json.endObject(0, false); json.newline(); } for (OrientEdge edge : edges) { json.resetAttributes(); json.beginObject(); json.beginObject(1, false, "ae"); json.beginObject(2, false, edge.getId()); json.writeAttribute(3, false, "directed", false); json.writeAttribute(3, false, "source", edge.getVertex(Direction.IN).getId()); json.writeAttribute(3, false, "target", edge.getVertex(Direction.OUT).getId()); for (String field : edge.getPropertyKeys()) { final Object v = edge.getProperty(field); if (v != null) json.writeAttribute(3, false, field, v); } json.endObject(2, false); json.endObject(1, false); json.endObject(0, false); json.newline(); } } @Override public String[] getNames() { return NAMES; } }
1no label
graphdb_src_main_java_com_orientechnologies_orient_graph_server_command_OServerCommandGetGephi.java
3,693
public class TimestampFieldMapper extends DateFieldMapper implements InternalMapper, RootMapper { public static final String NAME = "_timestamp"; public static final String CONTENT_TYPE = "_timestamp"; public static final String DEFAULT_DATE_TIME_FORMAT = "dateOptionalTime"; public static class Defaults extends DateFieldMapper.Defaults { public static final String NAME = "_timestamp"; public static final FieldType FIELD_TYPE = new FieldType(DateFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.setStored(false); FIELD_TYPE.setIndexed(true); FIELD_TYPE.setTokenized(false); FIELD_TYPE.freeze(); } public static final EnabledAttributeMapper ENABLED = EnabledAttributeMapper.DISABLED; public static final String PATH = null; public static final FormatDateTimeFormatter DATE_TIME_FORMATTER = Joda.forPattern(DEFAULT_DATE_TIME_FORMAT); } public static class Builder extends NumberFieldMapper.Builder<Builder, TimestampFieldMapper> { private EnabledAttributeMapper enabledState = EnabledAttributeMapper.UNSET_DISABLED; private String path = Defaults.PATH; private FormatDateTimeFormatter dateTimeFormatter = Defaults.DATE_TIME_FORMATTER; public Builder() { super(Defaults.NAME, new FieldType(Defaults.FIELD_TYPE)); } public Builder enabled(EnabledAttributeMapper enabledState) { this.enabledState = enabledState; return builder; } public Builder path(String path) { this.path = path; return builder; } public Builder dateTimeFormatter(FormatDateTimeFormatter dateTimeFormatter) { this.dateTimeFormatter = dateTimeFormatter; return builder; } @Override public TimestampFieldMapper build(BuilderContext context) { boolean roundCeil = Defaults.ROUND_CEIL; if (context.indexSettings() != null) { Settings settings = context.indexSettings(); roundCeil = settings.getAsBoolean("index.mapping.date.round_ceil", settings.getAsBoolean("index.mapping.date.parse_upper_inclusive", Defaults.ROUND_CEIL)); } return new TimestampFieldMapper(fieldType, docValues, enabledState, path, dateTimeFormatter, roundCeil, ignoreMalformed(context), coerce(context), postingsProvider, docValuesProvider, normsLoading, fieldDataSettings, context.indexSettings()); } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { TimestampFieldMapper.Builder builder = timestamp(); parseField(builder, builder.name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("enabled")) { EnabledAttributeMapper enabledState = nodeBooleanValue(fieldNode) ? EnabledAttributeMapper.ENABLED : EnabledAttributeMapper.DISABLED; builder.enabled(enabledState); } else if (fieldName.equals("path")) { builder.path(fieldNode.toString()); } else if (fieldName.equals("format")) { builder.dateTimeFormatter(parseDateTimeFormatter(builder.name(), fieldNode.toString())); } } return builder; } } private EnabledAttributeMapper enabledState; private final String path; public TimestampFieldMapper() { this(new FieldType(Defaults.FIELD_TYPE), null, Defaults.ENABLED, Defaults.PATH, Defaults.DATE_TIME_FORMATTER, Defaults.ROUND_CEIL, Defaults.IGNORE_MALFORMED, Defaults.COERCE, null, null, null, null, ImmutableSettings.EMPTY); } protected TimestampFieldMapper(FieldType fieldType, Boolean docValues, EnabledAttributeMapper enabledState, String path, FormatDateTimeFormatter dateTimeFormatter, boolean roundCeil, Explicit<Boolean> ignoreMalformed,Explicit<Boolean> coerce, PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider, Loading normsLoading, @Nullable Settings fieldDataSettings, Settings indexSettings) { super(new Names(Defaults.NAME, Defaults.NAME, Defaults.NAME, Defaults.NAME), dateTimeFormatter, Defaults.PRECISION_STEP, Defaults.BOOST, fieldType, docValues, Defaults.NULL_VALUE, TimeUnit.MILLISECONDS /*always milliseconds*/, roundCeil, ignoreMalformed, coerce, postingsProvider, docValuesProvider, null, normsLoading, fieldDataSettings, indexSettings, MultiFields.empty(), null); this.enabledState = enabledState; this.path = path; } @Override public FieldType defaultFieldType() { return Defaults.FIELD_TYPE; } public boolean enabled() { return this.enabledState.enabled; } public String path() { return this.path; } public FormatDateTimeFormatter dateTimeFormatter() { return this.dateTimeFormatter; } /** * Override the default behavior to return a timestamp */ @Override public Object valueForSearch(Object value) { return value(value); } @Override public void validate(ParseContext context) throws MapperParsingException { } @Override public void preParse(ParseContext context) throws IOException { super.parse(context); } @Override public void postParse(ParseContext context) throws IOException { } @Override public void parse(ParseContext context) throws IOException { // nothing to do here, we call the parent in preParse } @Override public boolean includeInObject() { return true; } @Override protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException { if (enabledState.enabled) { long timestamp = context.sourceToParse().timestamp(); if (!fieldType.indexed() && !fieldType.stored() && !hasDocValues()) { context.ignoredValue(names.indexName(), String.valueOf(timestamp)); } if (fieldType.indexed() || fieldType.stored()) { fields.add(new LongFieldMapper.CustomLongNumericField(this, timestamp, fieldType)); } if (hasDocValues()) { fields.add(new NumericDocValuesField(names.indexName(), timestamp)); } } } @Override protected String contentType() { return CONTENT_TYPE; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { boolean includeDefaults = params.paramAsBoolean("include_defaults", false); // if all are defaults, no sense to write it at all if (!includeDefaults && fieldType.indexed() == Defaults.FIELD_TYPE.indexed() && customFieldDataSettings == null && fieldType.stored() == Defaults.FIELD_TYPE.stored() && enabledState == Defaults.ENABLED && path == Defaults.PATH && dateTimeFormatter.format().equals(Defaults.DATE_TIME_FORMATTER.format())) { return builder; } builder.startObject(CONTENT_TYPE); if (includeDefaults || enabledState != Defaults.ENABLED) { builder.field("enabled", enabledState.enabled); } if (enabledState.enabled) { if (includeDefaults || fieldType.indexed() != Defaults.FIELD_TYPE.indexed()) { builder.field("index", indexTokenizeOptionToString(fieldType.indexed(), fieldType.tokenized())); } if (includeDefaults || fieldType.stored() != Defaults.FIELD_TYPE.stored()) { builder.field("store", fieldType.stored()); } if (includeDefaults || path != Defaults.PATH) { builder.field("path", path); } if (includeDefaults || !dateTimeFormatter.format().equals(Defaults.DATE_TIME_FORMATTER.format())) { builder.field("format", dateTimeFormatter.format()); } if (customFieldDataSettings != null) { builder.field("fielddata", (Map) customFieldDataSettings.getAsMap()); } else if (includeDefaults) { builder.field("fielddata", (Map) fieldDataType.getSettings().getAsMap()); } } builder.endObject(); return builder; } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { TimestampFieldMapper timestampFieldMapperMergeWith = (TimestampFieldMapper) mergeWith; if (!mergeContext.mergeFlags().simulate()) { if (timestampFieldMapperMergeWith.enabledState != enabledState && !timestampFieldMapperMergeWith.enabledState.unset()) { this.enabledState = timestampFieldMapperMergeWith.enabledState; } } } }
1no label
src_main_java_org_elasticsearch_index_mapper_internal_TimestampFieldMapper.java
2,097
public class QueryPartitionOperation extends AbstractMapOperation implements PartitionAwareOperation { private Predicate predicate; private QueryResult result; public QueryPartitionOperation(String mapName, Predicate predicate) { super(mapName); this.predicate = predicate; } public QueryPartitionOperation() { } public void run() { result = mapService.queryOnPartition(name, predicate, getPartitionId()); } @Override public Object getResponse() { return result; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeObject(predicate); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); predicate = in.readObject(); } }
1no label
hazelcast_src_main_java_com_hazelcast_map_operation_QueryPartitionOperation.java
629
public class PlotView implements PlotAbstraction { private final static Logger logger = LoggerFactory.getLogger(PlotView.class); private static final Timer timer = new Timer(); // Manifestation holding this plot private PlotViewManifestation plotUser; // Used in time synchronization line mode. private SynchronizationControl synControl; private Class <? extends AbstractPlottingPackage> plotPackage; private String plotName; // Initial Settings. private AxisOrientationSetting axisOrientation; private XAxisMaximumLocationSetting xAxisMaximumLocationSetting; private YAxisMaximumLocationSetting yAxisMaximumLocationSetting; private boolean useOrdinalPositionForSubplots; // Subsequent settings private TimeAxisSubsequentBoundsSetting timeAxisSubsequentSetting; private NonTimeAxisSubsequentBoundsSetting nonTimeAxisMinSubsequentSetting; private NonTimeAxisSubsequentBoundsSetting nonTimeAxisMaxSubsequentSetting; /* Appearance Constants */ // - Fonts private Font timeAxisFont; // Thickness of the plotted lines. private int plotLineThickness; private Color plotBackgroundFrameColor; private Color plotAreaBackgroundColor; // - Axis // -- x-axis // Point where x-axis intercepts y axis private int timeAxisIntercept; //color for drawing x-axis private Color timeAxisColor; // x-axis labels private Color timeAxisLabelColor; private Color timeAxisLabelTextColor; // format of the date when shown on the x-axis private String timeAxisDataFormat; // -- y-axis private Color nonTimeAxisColor; // - Gridlines private Color gridLineColor; /* Scrolling and scaling behaviors */ // Number of sample to accumulate before autoscaling the y-axis. This // prevents rapid changing of the y axis. private int minSamplesForAutoScale; private double scrollRescaleTimeMargin; private double scrollRescaleNonTimeMinMargin; private double scrollRescaleNonTimeMaxMargin; private double depdendentVaribleAxisMinValue; private double depdendentVaribleAxisMaxValue; private long timeVariableAxisMinValue; private long timeVariableAxisMaxValue; private boolean compressionEnabled; private boolean localControlsEnabled; private int numberOfSubPlots; // Plot line settings private PlotLineDrawingFlags plotLineDraw; private PlotLineConnectionType plotLineConnectionType; /** The list of sub plots. */ public List<AbstractPlottingPackage> subPlots; /** The plot panel. */ JPanel plotPanel; /** Map for containing the data set name to sub-group. */ public Map<String, Set<AbstractPlottingPackage>> dataSetNameToSubGroupMap = new HashMap<String, Set<AbstractPlottingPackage>>(); /** Map for containing the data set name to display map. */ public Map<String, String> dataSetNameToDisplayMap = new HashMap<String, String>(); private AbbreviatingPlotLabelingAlgorithm plotLabelingAlgorithm = new AbbreviatingPlotLabelingAlgorithm();; /** List of plot subjects. */ List<PlotSubject> subPlotsToIgnoreNextUpdateFrom = new ArrayList<PlotSubject>(); /** Time axis at start of update cycle. */ GregorianCalendar timeAxisMaxAtStartOfDataUpdateCycle = new GregorianCalendar(); /** Lock updates flag. */ boolean lockUpdates = false; private PinSupport pinSupport = new PinSupport() { protected void informPinned(boolean pinned) { if(pinned) { pause(); } else { unpause(); } } }; private Pinnable timeSyncLinePin = createPin(); private Axis timeAxis = new Axis(); /** This listens to key events for the plot view and all sub-components so it can forward modifier key presses and releases to the local controls managers. */ private KeyListener keyListener = new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_CONTROL) { for(AbstractPlottingPackage p : subPlots) { ((PlotterPlot) p).localControlsManager.informCtlKeyState(false); } } else if(e.getKeyCode() == KeyEvent.VK_ALT) { for(AbstractPlottingPackage p : subPlots) { ((PlotterPlot) p).localControlsManager.informAltKeyState(false); } } else if(e.getKeyCode() == KeyEvent.VK_SHIFT) { for(AbstractPlottingPackage p : subPlots) { ((PlotterPlot) p).localControlsManager.informShiftKeyState(false); } } } @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_CONTROL) { for(AbstractPlottingPackage p : subPlots) { ((PlotterPlot) p).localControlsManager.informCtlKeyState(true); } } else if(e.getKeyCode() == KeyEvent.VK_ALT) { for(AbstractPlottingPackage p : subPlots) { ((PlotterPlot) p).localControlsManager.informAltKeyState(true); } } else if(e.getKeyCode() == KeyEvent.VK_SHIFT) { for(AbstractPlottingPackage p : subPlots) { ((PlotterPlot) p).localControlsManager.informShiftKeyState(true); } } } }; private Pinnable timeAxisUserPin = timeAxis.createPin(); private ContainerListener containerListener = new ContainerListener() { @Override public void componentAdded(ContainerEvent e) { addRecursiveListeners(e.getChild()); } @Override public void componentRemoved(ContainerEvent e) { removeRecursiveListeners(e.getChild()); } }; private TimerTask updateTimeBoundsTask; private TimeXYAxis plotTimeAxis; /** * Sets the plot view manifestation. * @param theManifestation - the plot view manifestation. */ public void setManifestation(PlotViewManifestation theManifestation) { if (theManifestation == null ) { throw new IllegalArgumentException("Plot must not have a null user"); } plotUser = theManifestation; for (AbstractPlottingPackage p: subPlots) { p.setPlotView(this); } } @Override public JPanel getPlotPanel() { return plotPanel; } @Override public void addDataSet(String dataSetName) { addDataSet(dataSetName.toLowerCase(), getNextColor(subPlots.size()-1)); } @Override public void addDataSet(String dataSetName, Color plottingColor) { throwIllegalArgumentExcpetionIfWeHaveNoPlots(); getLastPlot().addDataSet(dataSetName.toLowerCase(), plottingColor); String name = dataSetName.toLowerCase(); Set<AbstractPlottingPackage> set = dataSetNameToSubGroupMap.get(name); if(set == null) { set = new HashSet<AbstractPlottingPackage>(); dataSetNameToSubGroupMap.put(name, set); } set.add(getLastPlot()); dataSetNameToDisplayMap.put(dataSetName.toLowerCase(), dataSetName); } @Override public void addDataSet(String dataSetName, String displayName) { throwIllegalArgumentExcpetionIfWeHaveNoPlots(); getLastPlot().addDataSet(dataSetName.toLowerCase(), getNextColor(subPlots.size()-1), displayName); String name = dataSetName.toLowerCase(); Set<AbstractPlottingPackage> set = dataSetNameToSubGroupMap.get(name); if(set == null) { set = new HashSet<AbstractPlottingPackage>(); dataSetNameToSubGroupMap.put(name, set); } set.add(getLastPlot()); dataSetNameToDisplayMap.put(dataSetName.toLowerCase(), displayName); } /** * Adds the data set per subgroup index, data set name and display name. * @param subGroupIndex - the subgroup index. * @param dataSetName - data set name. * @param displayName - base display name. */ public void addDataSet(int subGroupIndex, String dataSetName, String displayName) { throwIllegalArgumentExcpetionIfIndexIsNotInSubPlots(subGroupIndex); String lowerCaseDataSetName = dataSetName.toLowerCase(); int actualIndex = subGroupIndex; subPlots.get(actualIndex).addDataSet(lowerCaseDataSetName, getNextColor(actualIndex), displayName); Set<AbstractPlottingPackage> set = dataSetNameToSubGroupMap.get(lowerCaseDataSetName); if(set == null) { set = new HashSet<AbstractPlottingPackage>(); dataSetNameToSubGroupMap.put(lowerCaseDataSetName, set); } set.add(subPlots.get(actualIndex)); dataSetNameToDisplayMap.put(lowerCaseDataSetName, displayName); } /** * Adds the popup menus to plot legend entry. */ public void addPopupMenus() { LegendEntryPopupMenuFactory popupManager = new LegendEntryPopupMenuFactory(plotUser); for (int index = 0; index < subPlots.size(); index++) { PlotterPlot plot = (PlotterPlot) subPlots.get(index); for (String dataSetName : plot.plotDataManager.dataSeries.keySet()) { plot.plotDataManager.dataSeries.get(dataSetName).legendEntry.setPopup( popupManager ); } } } /** * Get per-line settings currently in use for this stack of plots. * Each element of the returned list corresponds, * in order, to the sub-plots displayed, and maps subscription ID to a * LineSettings object describing how its plot line should be drawn. * @return a list of subscription->setting mappings for this plot */ public List<Map<String, LineSettings>> getLineSettings() { List<Map<String,LineSettings>> settingsAssignments = new ArrayList<Map<String,LineSettings>>(); for (int subPlotIndex = 0; subPlotIndex < subPlots.size(); subPlotIndex++) { Map<String, LineSettings> settingsMap = new HashMap<String, LineSettings>(); settingsAssignments.add(settingsMap); PlotterPlot plot = (PlotterPlot) subPlots.get(subPlotIndex); for (Entry<String, PlotDataSeries> entry : plot.plotDataManager.dataSeries.entrySet()) { settingsMap.put(entry.getKey(), entry.getValue().legendEntry.getLineSettings()); } } return settingsAssignments; } /** * Set line settings for use in this stack of plots. * Each element corresponds, in order, to the sub-plots displayed, and maps * subscription ID to the line settings described by a LineSettings object * @param lineSettings a list of subscription->line setting mappings for this plot */ public void setLineSettings( List<Map<String, LineSettings>> lineSettings) { if (lineSettings != null) { for (int subPlotIndex = 0; subPlotIndex < lineSettings.size() && subPlotIndex < subPlots.size(); subPlotIndex++) { PlotterPlot plot = (PlotterPlot) subPlots.get(subPlotIndex); for (Entry<String, LineSettings> entry : lineSettings.get(subPlotIndex).entrySet()) { if (plot.plotDataManager.dataSeries.containsKey(entry.getKey())) { plot.plotDataManager.dataSeries.get(entry.getKey()).legendEntry.setLineSettings(entry.getValue()) ;//.setForeground(PlotLineColorPalette.getColor(entry.getValue())); } } } } } @Override public boolean isKnownDataSet(String setName) { assert setName != null : "data set is null"; return dataSetNameToSubGroupMap.containsKey(setName.toLowerCase()); } @Override public void refreshDisplay() { for (AbstractPlottingPackage p: subPlots) { p.refreshDisplay(); } } @Override public void updateLegend(String dataSetName, FeedProvider.RenderingInfo info) { String dataSetNameLower = dataSetName.toLowerCase(); for(AbstractPlottingPackage plot : dataSetNameToSubGroupMap.get(dataSetNameLower)) { plot.updateLegend(dataSetNameLower, info); } } @Override public LimitAlarmState getNonTimeMaxAlarmState(int subGroupIndex) { throwIllegalArgumentExcpetionIfIndexIsNotInSubPlots(subGroupIndex); return subPlots.get(subGroupIndex).getNonTimeMaxAlarmState(); } @Override public LimitAlarmState getNonTimeMinAlarmState(int subGroupIndex) { throwIllegalArgumentExcpetionIfIndexIsNotInSubPlots(subGroupIndex); return subPlots.get(subGroupIndex).getNonTimeMinAlarmState(); } @Override public GregorianCalendar getMinTime() { return getLastPlot().getCurrentTimeAxisMin(); } @Override public GregorianCalendar getMaxTime() { return getLastPlot().getCurrentTimeAxisMax(); } @Override public AxisOrientationSetting getAxisOrientationSetting() { return getLastPlot().getAxisOrientationSetting(); } @Override public NonTimeAxisSubsequentBoundsSetting getNonTimeAxisSubsequentMaxSetting() { return getLastPlot().getNonTimeAxisSubsequentMaxSetting(); } @Override public NonTimeAxisSubsequentBoundsSetting getNonTimeAxisSubsequentMinSetting() { return getLastPlot().getNonTimeAxisSubsequentMinSetting(); } @Override public double getNonTimeMax() { return getLastPlot().getInitialNonTimeMaxSetting(); } @Override public double getNonTimeMaxPadding() { return getLastPlot().getNonTimeMaxPadding(); } @Override public double getNonTimeMin() { return getLastPlot().getInitialNonTimeMinSetting(); } @Override public double getNonTimeMinPadding() { return getLastPlot().getNonTimeMinPadding(); } @Override public boolean useOrdinalPositionForSubplots() { return getLastPlot().getOrdinalPositionInStackedPlot(); } @Override public TimeAxisSubsequentBoundsSetting getTimeAxisSubsequentSetting() { return getLastPlot().getTimeAxisSubsequentSetting(); } @Override public long getTimeMax() { return getLastPlot().getInitialTimeMaxSetting(); } @Override public long getTimeMin() { return getLastPlot().getInitialTimeMinSetting(); } @Override public double getTimePadding() { return getLastPlot().getTimePadding(); } @Override public XAxisMaximumLocationSetting getXAxisMaximumLocation() { return getLastPlot().getXAxisMaximumLocation(); } @Override public YAxisMaximumLocationSetting getYAxisMaximumLocation() { return getLastPlot().getYAxisMaximumLocation(); } @Override public void showTimeSyncLine(GregorianCalendar time) { assert time != null; timeSyncLinePin.setPinned(true); for (AbstractPlottingPackage p: subPlots) { p.showTimeSyncLine(time); } } @Override public void removeTimeSyncLine() { timeSyncLinePin.setPinned(false); for (AbstractPlottingPackage p: subPlots) { p.removeTimeSyncLine(); } } @Override public boolean isTimeSyncLineVisible() { return getLastPlot().isTimeSyncLineVisible(); } @Override public void initiateGlobalTimeSync(GregorianCalendar time) { synControl = plotUser.synchronizeTime(time.getTimeInMillis()); } @Override public void updateGlobalTimeSync(GregorianCalendar time) { if(synControl == null) { synControl = plotUser.synchronizeTime(time.getTimeInMillis()); } else { synControl.update(time.getTimeInMillis()); } } @Override public void notifyGlobalTimeSyncFinished() { if (synControl!=null) { synControl.synchronizationDone(); } removeTimeSyncLine(); } @Override public boolean inTimeSyncMode() { return getLastPlot().inTimeSyncMode(); } private Color getNextColor(int subGroupIndex) { throwIllegalArgumentExcpetionIfIndexIsNotInSubPlots(subGroupIndex); if (subPlots.get(subGroupIndex).getDataSetSize() < PlotLineColorPalette.getColorCount()) { return PlotLineColorPalette.getColor(subPlots.get(subGroupIndex).getDataSetSize()); } else { // Exceeded the number of colors in the pallet. return PlotConstants.ROLL_OVER_PLOT_LINE_COLOR; } } @Override public double getNonTimeMaxCurrentlyDisplayed() { return getLastPlot().getNonTimeMaxDataValueCurrentlyDisplayed(); } @Override public double getNonTimeMinCurrentlyDisplayed() { return getLastPlot().getNonTimeMinDataValueCurrentlyDisplayed(); } @Override public String toString() { assert plotPackage != null : "Plot package not initalized"; return "Plot: + " + plotName + "\n" + plotPackage.toString(); } /** * Construct plots using the builder pattern. * */ public static class Builder { // Required parameters private Class<? extends AbstractPlottingPackage> plotPackage; //Optional parameters // default values give a "traditional" chart with time on the x-axis etc. private String plotName = "Plot Name Undefined"; private AxisOrientationSetting axisOrientation = AxisOrientationSetting.X_AXIS_AS_TIME; private XAxisMaximumLocationSetting xAxisMaximumLocatoinSetting = XAxisMaximumLocationSetting.MAXIMUM_AT_RIGHT; private YAxisMaximumLocationSetting yAxisMaximumLocationSetting = YAxisMaximumLocationSetting.MAXIMUM_AT_TOP; private TimeAxisSubsequentBoundsSetting timeAxisSubsequentSetting = TimeAxisSubsequentBoundsSetting.JUMP; private NonTimeAxisSubsequentBoundsSetting nonTimeAxisMinSubsequentSetting = PlotConstants.DEFAULT_NON_TIME_AXIS_MIN_SUBSEQUENT_SETTING; private NonTimeAxisSubsequentBoundsSetting nonTimeAxisMaxSubsequentSetting = PlotConstants.DEFAULT_NON_TIME_AXIS_MAX_SUBSEQUENT_SETTING; private PlotLineDrawingFlags plotLineDraw = new PlotLineDrawingFlags(true, false); // TODO: Move to PlotConstants? private PlotLineConnectionType plotLineConnectionType = PlotLineGlobalConfiguration.getDefaultConnectionType(); // initial settings private Font timeAxisFont = PlotConstants.DEFAULT_TIME_AXIS_FONT; private int plotLineThickness = PlotConstants.DEFAULT_PLOTLINE_THICKNESS ; private Color plotBackgroundFrameColor = PlotConstants.DEFAULT_PLOT_FRAME_BACKGROUND_COLOR; private Color plotAreaBackgroundColor = PlotConstants.DEFAULT_PLOT_AREA_BACKGROUND_COLOR; private int timeAxisIntercept = PlotConstants.DEFAULT_TIME_AXIS_INTERCEPT; private Color timeAxisColor = PlotConstants.DEFAULT_TIME_AXIS_COLOR; private Color timeAxisLabelColor = PlotConstants.DEFAULT_TIME_AXIS_LABEL_COLOR; private String timeAxisDateFormat = PlotConstants.DEFAULT_TIME_AXIS_DATA_FORMAT; private Color nonTimeAxisColor = PlotConstants.DEFAULT_NON_TIME_AXIS_COLOR; private Color gridLineColor = PlotConstants.DEFAULT_GRID_LINE_COLOR; private int minSamplesForAutoScale = PlotConstants.DEFAULT_MIN_SAMPLES_FOR_AUTO_SCALE; private double scrollRescaleMarginTimeAxis = PlotConstants.DEFAULT_TIME_AXIS_PADDING; private double scrollRescaleMarginNonTimeMinAxis = PlotConstants.DEFAULT_NON_TIME_AXIS_PADDING_MIN; private double scrollRescaleMarginNonTimeMaxAxis = PlotConstants.DEFAULT_NON_TIME_AXIS_PADDING_MAX; private double depdendentVaribleAxisMinValue = PlotConstants.DEFAULT_NON_TIME_AXIS_MIN_VALUE; private double dependentVaribleAxisMaxValue = PlotConstants.DEFAULT_NON_TIME_AXIS_MAX_VALUE; private long timeVariableAxisMinValue = new GregorianCalendar().getTimeInMillis(); private long timeVariableAxisMaxValue = timeVariableAxisMinValue + PlotConstants.DEFAUlT_PLOT_SPAN; private boolean compressionEnabled = PlotConstants.COMPRESSION_ENABLED_BY_DEFAULT; private int numberOfSubPlots = PlotConstants.DEFAULT_NUMBER_OF_SUBPLOTS; private boolean localControlsEnabled = PlotConstants.LOCAL_CONTROLS_ENABLED_BY_DEFAULT; private boolean useOrdinalPositionForSubplotSetting = true; private boolean pinTimeAxisSetting = false; private AbbreviatingPlotLabelingAlgorithm plotLabelingAlgorithm = new AbbreviatingPlotLabelingAlgorithm(); /** * Specifies the required parameters for constructing a plot. * @param selectedPlotPackage plotting package to render the plot */ public Builder(Class<? extends AbstractPlottingPackage>selectedPlotPackage) { this.plotPackage = selectedPlotPackage; } /** * Specify the plot's user readable name. * @param initPlotName the initial plot name. * @return builder the plot view. */ public Builder plotName(String initPlotName) { plotName = initPlotName; return this; } /** * Specify if the time axis should be oriented on the x- or y-axis. * @param theAxisOrentation the axis orientation setting. * @return builder the plot view. */ public Builder axisOrientation(PlotConstants.AxisOrientationSetting theAxisOrentation) { axisOrientation = theAxisOrentation; return this; } /** * Specify if the x-axis maximum value should be on the left or right of the plot. * @param theXAxisSetting the X-Axis setting. * @return builder the plot view. */ public Builder xAxisMaximumLocation(PlotConstants.XAxisMaximumLocationSetting theXAxisSetting) { xAxisMaximumLocatoinSetting = theXAxisSetting; return this; } /** * Specify if the y-axis maximum value should be on the bottom or top of the plot. * @param theYAxisSetting the Y-Axis setting. * @return the builder the plot view. */ public Builder yAxisMaximumLocation(PlotConstants.YAxisMaximumLocationSetting theYAxisSetting) { yAxisMaximumLocationSetting = theYAxisSetting; return this; } /** * Specify how the bounds of the time axis will behave as plotting commences. * @param theTimeAxisSubsequentSetting the time axis subsequent bounds settings. * @return the builder the plot view. */ public Builder timeAxisBoundsSubsequentSetting(PlotConstants.TimeAxisSubsequentBoundsSetting theTimeAxisSubsequentSetting) { timeAxisSubsequentSetting = theTimeAxisSubsequentSetting; return this; } /** * Specify how the bounds of the non time axis will behave as plotting commences. * @param theNonTimeAxisMinSubsequentSetting the non-time axis minimal subsequent setting. * @return the builder the plot view. */ public Builder nonTimeAxisMinSubsequentSetting(PlotConstants.NonTimeAxisSubsequentBoundsSetting theNonTimeAxisMinSubsequentSetting) { nonTimeAxisMinSubsequentSetting = theNonTimeAxisMinSubsequentSetting; return this; } /** * Specify whether the ordinal position should be used to construct subplots. * @param useOrdinalPositionForSubplots whether ordinal position for subplots should be used. * @return the builder the plot view. */ public Builder useOrdinalPositionForSubplots(boolean useOrdinalPositionForSubplots) { useOrdinalPositionForSubplotSetting = useOrdinalPositionForSubplots; return this; } /** * Specify whether the initial time axis should be pinned. * @param pin whether time axis should initially be pinned. * @return the builder the plot view. */ public Builder pinTimeAxis(boolean pin) { pinTimeAxisSetting = pin; return this; } /** * Specify how the bounds of the non time axis will behave as plotting commences. * @param theNonTimeAxisMaxSubsequentSetting the non-time axis minimal subsequent setting. * @return the builder the plot view. */ public Builder nonTimeAxisMaxSubsequentSetting(PlotConstants.NonTimeAxisSubsequentBoundsSetting theNonTimeAxisMaxSubsequentSetting) { nonTimeAxisMaxSubsequentSetting = theNonTimeAxisMaxSubsequentSetting; return this; } /** * Specify the size of the font of the labels on the time axis. * @param theTimeAxisFontSize font size. * @return the builder the plot view. */ public Builder timeAxisFontSize(int theTimeAxisFontSize) { timeAxisFont = new Font(timeAxisFont.getFontName(), Font.PLAIN, theTimeAxisFontSize); return this; } /** * Specify the font that will be used to draw the labels on the axis axis. * This parameter overrides the time axis font size parameter when specified. * @param theTimeAxisFont the font size. * @return the builder the plot view. */ public Builder timeAxisFont(Font theTimeAxisFont) { timeAxisFont = theTimeAxisFont; return this; } /** * Specify the thickness of the line used to plot data on the plot. * @param theThickness the thickness. * @return the builder the plot view. */ public Builder plotLineThickness(int theThickness) { plotLineThickness = theThickness; return this; } /** * Specify the color of the frame surrounding the plot area. * @param theBackgroundColor the color. * @return the builder the plot view. */ public Builder plotBackgroundFrameColor(Color theBackgroundColor) { plotBackgroundFrameColor = theBackgroundColor; return this; } /** * Specify the background color of the plot area. * @param thePlotAreaColor the color. * @return the builder the plot view. */ public Builder plotAreaBackgroundColor (Color thePlotAreaColor) { plotAreaBackgroundColor = thePlotAreaColor; return this; } /** * Specify the point at which the time axis intercepts the non time axis. * @param theIntercept the intercept point. * @return the builder the plot view. */ public Builder timeAxisIntercept(int theIntercept) { timeAxisIntercept = theIntercept; return this; } /** * Specify the color of the time axis. * @param theTimeAxisColor the color. * @return the builder the plot view. */ public Builder timeAxisColor(Color theTimeAxisColor) { timeAxisColor = theTimeAxisColor; return this; } /** * Specify color of text on the time axis. * @param theTimeAxisTextColor the color. * @return the builder the plot view. */ public Builder timeAxisTextColor(Color theTimeAxisTextColor) { timeAxisLabelColor = theTimeAxisTextColor; return this; } /** * Set the format of how time information is printed on time axis labels. * @param theTimeAxisDateFormat the format. * @return the builder the plot view. */ public Builder timeAxisDateFormat(String theTimeAxisDateFormat) { timeAxisDateFormat = theTimeAxisDateFormat; return this; } /** * Set the color of the non time axis. * @param theNonTimeAxisColor the color. * @return the builder the plot view. */ public Builder nonTimeAxisColor(Color theNonTimeAxisColor) { nonTimeAxisColor = theNonTimeAxisColor; return this; } /** * Set the color of the plot gridlines. * @param theGridLineColor the color. * @return the builder the plot view. */ public Builder gridLineColor(Color theGridLineColor) { gridLineColor = theGridLineColor; return this; } /** * The minimum number of samples to accumulate out of range before an autoscale occurs. This * prevents rapid autoscaling on every plot action. * @param theMinSamplesForAutoScale the number of samples. * @return the plot view. */ public Builder minSamplesForAutoScale(int theMinSamplesForAutoScale) { minSamplesForAutoScale = theMinSamplesForAutoScale; return this; } /** * Percentage of padding to use when rescalling the time axis. * @param theScrollRescaleMargin the margin. * @return the builder the plot view. */ public Builder scrollRescaleMarginTimeAxis(double theScrollRescaleMargin) { assert theScrollRescaleMargin <= 1 && theScrollRescaleMargin >=0 : "Attempting to set a scroll rescale margin (time padding) outside of 0 .. 1"; scrollRescaleMarginTimeAxis = theScrollRescaleMargin; return this; } /** Percentage of padding to use when rescalling the non time axis min end. * @param theScrollRescaleMargin the margin. * @return the builder the plot view. */ public Builder scrollRescaleMarginNonTimeMinAxis(double theScrollRescaleMargin) { assert theScrollRescaleMargin <= 1 && theScrollRescaleMargin >=0 : "Attempting to set a scroll rescale margin (non time padding) outside of 0 .. 1"; scrollRescaleMarginNonTimeMinAxis = theScrollRescaleMargin; return this; } /** Percentage of padding to use when rescalling the non time axis max end. * @param theScrollRescaleMargin the margin. * @return the builder the plot view. */ public Builder scrollRescaleMarginNonTimeMaxAxis(double theScrollRescaleMargin) { assert theScrollRescaleMargin <= 1 && theScrollRescaleMargin >=0 : "Attempting to set a scroll rescale margin (non time padding) outside of 0 .. 1"; scrollRescaleMarginNonTimeMaxAxis = theScrollRescaleMargin; return this; } /** * Specify the maximum extent of the dependent variable axis. * @param theNonTimeVaribleAxisMaxValue the non-time variable axis max value. * @return the plot view. */ public Builder nonTimeVaribleAxisMaxValue(double theNonTimeVaribleAxisMaxValue) { dependentVaribleAxisMaxValue = theNonTimeVaribleAxisMaxValue; return this; } /** * Specify the minimum value of the dependent variable axis. * @param theNonTimeVaribleAxisMinValue the non-time axis minimal value. * @return the builder the plot view. */ public Builder nonTimeVaribleAxisMinValue(double theNonTimeVaribleAxisMinValue) { depdendentVaribleAxisMinValue = theNonTimeVaribleAxisMinValue; return this; } /** * Specify the initial minimum value of the time axis. * @param theTimeVariableAxisMinValue the time variable axis minimal value. * @return the builder the plot view. */ public Builder timeVariableAxisMinValue(long theTimeVariableAxisMinValue) { timeVariableAxisMinValue = theTimeVariableAxisMinValue; return this; } /** * specify the initial maximum value of the time axis. * @param theTimeVariableAxisMaxValue the time variable axis maximum value. * @return the builder the plot view. */ public Builder timeVariableAxisMaxValue(long theTimeVariableAxisMaxValue) { timeVariableAxisMaxValue = theTimeVariableAxisMaxValue; return this; } /** * Specify if the plot is to compress its data to match the screen resolution. * @param state true to compress, false otherwise. * @return the builder the plot view. */ public Builder isCompressionEnabled(boolean state) { compressionEnabled = state; return this; } /** * Specify the number of subplots in this plotview. * @param theNumberOfSubPlots the number of sub-plots. * @return the builder the plot view. */ public Builder numberOfSubPlots(int theNumberOfSubPlots) { numberOfSubPlots = theNumberOfSubPlots; return this; } /** * Turn the plot local controls on and off. * @param theIsEnabled true enabled; otherwise false. * @return builder the plot view. */ public Builder localControlsEnabled(boolean theIsEnabled) { localControlsEnabled = theIsEnabled; return this; } /** * Specify the plot abbreviation labeling algorithm. * @param thePlotLabelingAlgorithm the plot labeling algorithm. * @return builder the plot view. */ public Builder plotLabelingAlgorithm(AbbreviatingPlotLabelingAlgorithm thePlotLabelingAlgorithm) { plotLabelingAlgorithm = thePlotLabelingAlgorithm; assert plotLabelingAlgorithm != null : "Plot labeling algorithm should NOT be NULL at this point."; return this; } /** * Specify whether to draw lines, markers, or both. * @param plotLineDraw the plotting type * @return the plot view. */ public Builder plotLineDraw(PlotLineDrawingFlags plotLineDraw) { this.plotLineDraw = plotLineDraw; return this; } /** * * @param plotLineConnectionType * @return */ public Builder plotLineConnectionType(PlotLineConnectionType plotLineConnectionType) { this.plotLineConnectionType = plotLineConnectionType; return this; } /** * Build a new plot instance and return it. * @return the new plot instance. */ public PlotView build() { return new PlotView(this); } } // Private constructor. Construct using builder pattern. private PlotView(Builder builder) { plotPackage = builder.plotPackage; plotName = builder.plotName; axisOrientation = builder.axisOrientation; xAxisMaximumLocationSetting = builder.xAxisMaximumLocatoinSetting; yAxisMaximumLocationSetting = builder.yAxisMaximumLocationSetting; timeAxisSubsequentSetting = builder.timeAxisSubsequentSetting; nonTimeAxisMinSubsequentSetting = builder.nonTimeAxisMinSubsequentSetting; nonTimeAxisMaxSubsequentSetting = builder.nonTimeAxisMaxSubsequentSetting; useOrdinalPositionForSubplots = builder.useOrdinalPositionForSubplotSetting; timeAxisFont = builder.timeAxisFont; plotLineThickness = builder.plotLineThickness; plotBackgroundFrameColor = builder.plotBackgroundFrameColor; plotAreaBackgroundColor = builder.plotAreaBackgroundColor; timeAxisIntercept = builder.timeAxisIntercept; timeAxisColor = builder.timeAxisColor; timeAxisLabelTextColor = builder.timeAxisLabelColor; timeAxisDataFormat = builder.timeAxisDateFormat; nonTimeAxisColor = builder.nonTimeAxisColor; gridLineColor = builder.gridLineColor; minSamplesForAutoScale = builder.minSamplesForAutoScale; scrollRescaleTimeMargin = builder.scrollRescaleMarginTimeAxis; scrollRescaleNonTimeMinMargin = builder.scrollRescaleMarginNonTimeMinAxis; scrollRescaleNonTimeMaxMargin = builder.scrollRescaleMarginNonTimeMaxAxis; depdendentVaribleAxisMinValue = builder.depdendentVaribleAxisMinValue; depdendentVaribleAxisMaxValue = builder.dependentVaribleAxisMaxValue; timeVariableAxisMaxValue = builder.timeVariableAxisMaxValue; timeVariableAxisMinValue = builder.timeVariableAxisMinValue; compressionEnabled = builder.compressionEnabled; numberOfSubPlots = builder.numberOfSubPlots; localControlsEnabled = builder.localControlsEnabled; plotLabelingAlgorithm = builder.plotLabelingAlgorithm; setPlotLineDraw(builder.plotLineDraw); setPlotLineConnectionType(builder.plotLineConnectionType); plotPanel = new JPanel(); plotPanel.addAncestorListener(new AncestorListener() { @Override public synchronized void ancestorRemoved(AncestorEvent event) { if(updateTimeBoundsTask != null) { updateTimeBoundsTask.cancel(); updateTimeBoundsTask = null; } } @Override public void ancestorMoved(AncestorEvent event) { } @Override public synchronized void ancestorAdded(AncestorEvent event) { for(AbstractPlottingPackage p : subPlots) { p.updateCompressionRatio(); } updateTimeBoundsTask = new TimerTask() { @Override public void run() { try { timeReachedEnd(); } catch(Exception e) { // We need to catch exceptions because they can kill the timer. logger.error(e.toString(), e); } } }; timer.schedule(updateTimeBoundsTask, 0, 1000); } }); GridBagLayout layout = new StackPlotLayout(this); plotPanel.setLayout(layout); subPlots = new ArrayList<AbstractPlottingPackage>(numberOfSubPlots); // create the specified number of subplots for (int i=0; i< numberOfSubPlots; i++) { AbstractPlottingPackage newPlot; try { newPlot = plotPackage.newInstance(); boolean isTimeLabelEnabled = i == (numberOfSubPlots -1); newPlot.createChart(axisOrientation, xAxisMaximumLocationSetting, yAxisMaximumLocationSetting, timeAxisSubsequentSetting, nonTimeAxisMinSubsequentSetting, nonTimeAxisMaxSubsequentSetting, timeAxisFont, plotLineThickness, plotBackgroundFrameColor, plotAreaBackgroundColor, timeAxisIntercept, timeAxisColor, timeAxisLabelColor, timeAxisLabelTextColor, timeAxisDataFormat, nonTimeAxisColor, gridLineColor, minSamplesForAutoScale, scrollRescaleTimeMargin, scrollRescaleNonTimeMinMargin, scrollRescaleNonTimeMaxMargin, depdendentVaribleAxisMinValue, depdendentVaribleAxisMaxValue, timeVariableAxisMinValue, timeVariableAxisMaxValue, compressionEnabled, isTimeLabelEnabled, localControlsEnabled, useOrdinalPositionForSubplots, getPlotLineDraw(), getPlotLineConnectionType(), this, plotLabelingAlgorithm); newPlot.setPlotLabelingAlgorithm(plotLabelingAlgorithm); subPlots.add(newPlot); newPlot.registerObservor(this); logger.debug("plotLabelingAlgorithm.getPanelContextTitleList().size()=" + plotLabelingAlgorithm.getPanelContextTitleList().size() + ", plotLabelingAlgorithm.getCanvasContextTitleList().size()=" + plotLabelingAlgorithm.getCanvasContextTitleList().size()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } if (axisOrientation == AxisOrientationSetting.Y_AXIS_AS_TIME) { Collections.reverse(subPlots); } for (AbstractPlottingPackage subPlot: subPlots) { JComponent subPanel = subPlot.getPlotPanel(); plotPanel.add(subPanel); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1; c.weighty = 1; if(axisOrientation == AxisOrientationSetting.X_AXIS_AS_TIME) { c.gridwidth = GridBagConstraints.REMAINDER; } layout.setConstraints(subPanel, c); } // Note that using InputMap does not work for our situation. // See http://stackoverflow.com/questions/4880704/listening-to-key-events-for-a-component-hierarchy addRecursiveListeners(plotPanel); if (builder.pinTimeAxisSetting) { timeAxisUserPin.setPinned(true); // update the corner reset buttons after the plot is visible SwingUtilities.invokeLater(new Runnable() { public void run() { for(AbstractPlottingPackage subPlot : subPlots) { PlotterPlot plot = (PlotterPlot) subPlot; plot.updateResetButtons(); } } }); } } /** * Gets the pinnable time axis by user. * @return pinnable time axis. */ public Pinnable getTimeAxisUserPin() { return timeAxisUserPin; } private void addRecursiveListeners(Component c) { c.addKeyListener(keyListener); if(c instanceof Container) { Container cont = (Container) c; cont.addContainerListener(containerListener); for(Component child : cont.getComponents()) { addRecursiveListeners(child); } } } private void removeRecursiveListeners(Component c) { c.removeKeyListener(keyListener); if(c instanceof Container) { Container cont = (Container) c; cont.removeContainerListener(containerListener); for(Component child : cont.getComponents()) { removeRecursiveListeners(child); } } } /** * Gets the plot labeling algorithm. * @return abbreviating plot labeling algorithm. */ public AbbreviatingPlotLabelingAlgorithm getPlotLabelingAlgorithm() { return plotLabelingAlgorithm; } /** * Sets the plot labeling algorithm. * @param thePlotLabelingAlgorithm the plot labeling algorithm. */ public void setPlotLabelingAlgorithm(AbbreviatingPlotLabelingAlgorithm thePlotLabelingAlgorithm) { plotLabelingAlgorithm = thePlotLabelingAlgorithm; } @Override public AbstractPlottingPackage returnPlottingPackage() { return getLastPlot(); } @Override public void setCompressionEnabled(boolean compression) { for (AbstractPlottingPackage p: subPlots) { p.setCompressionEnabled(compression); } } @Override public boolean isCompresionEnabled() { return getLastPlot().isCompresionEnabled(); } @Override public void requestPlotData(GregorianCalendar startTime, GregorianCalendar endTime) { plotUser.requestDataRefresh(startTime, endTime); } private void requestPredictivePlotData(GregorianCalendar startTime, GregorianCalendar endTime) { plotUser.requestPredictiveData(startTime, endTime); } @Override public void informUpdateDataEventStarted() { timeAxisMaxAtStartOfDataUpdateCycle.setTimeInMillis(this.getLastPlot().getCurrentTimeAxisMax().getTimeInMillis()); for (AbstractPlottingPackage p: subPlots) { p.informUpdateCachedDataStreamStarted(); } } @Override public void informUpdateFromFeedEventStarted() { timeAxisMaxAtStartOfDataUpdateCycle.setTimeInMillis(this.getLastPlot().getCurrentTimeAxisMax().getTimeInMillis()); for (AbstractPlottingPackage p: subPlots) { p.informUpdateFromLiveDataStreamStarted(); } } @Override public void informUpdateDataEventCompleted() { for (AbstractPlottingPackage p: subPlots) { p.informUpdateCacheDataStreamCompleted(); } syncTimeAxisAcrossPlots(); } @Override public void informUpdateFromFeedEventCompleted() { for (AbstractPlottingPackage p: subPlots) { p.informUpdateFromLiveDataStreamCompleted(); } syncTimeAxisAcrossPlots(); } /** * Synchronizes the time axis across all plots. */ void syncTimeAxisAcrossPlots() { long maxAtStart = timeAxisMaxAtStartOfDataUpdateCycle.getTimeInMillis(); long currentMaxTime = maxAtStart; long currentMinTime = maxAtStart; for (AbstractPlottingPackage p: subPlots) { long max = p.getCurrentTimeAxisMaxAsLong(); if (max > currentMaxTime) { currentMaxTime = max; currentMinTime = p.getCurrentTimeAxisMinAsLong(); } } if (currentMaxTime > maxAtStart) { boolean inverted; if(axisOrientation == AxisOrientationSetting.X_AXIS_AS_TIME) { inverted = xAxisMaximumLocationSetting == XAxisMaximumLocationSetting.MAXIMUM_AT_LEFT; } else { inverted = yAxisMaximumLocationSetting == YAxisMaximumLocationSetting.MAXIMUM_AT_BOTTOM; } long start; long end; if(inverted) { start = currentMaxTime; end = currentMinTime; } else { start = currentMinTime; end = currentMaxTime; } for (AbstractPlottingPackage p: subPlots) { p.setTimeAxisStartAndStop(start, end); } } } @Override public long getCurrentMCTTime() { return plotUser.getCurrentMCTTime(); } /** * Gets the plot user view manifestation. * @return plotUser the plot user view manifestation. */ public PlotViewManifestation getPlotUser() { return plotUser; } /** * Gets the last plot. * @return abstract plotting package. */ AbstractPlottingPackage getLastPlot() { throwIllegalArgumentExcpetionIfWeHaveNoPlots(); return subPlots.get(subPlots.size() - 1); } private void throwIllegalArgumentExcpetionIfWeHaveNoPlots() { if (subPlots.size() < 1) { throw new IllegalArgumentException("Plot contains no sub plots"); } } private void throwIllegalArgumentExcpetionIfIndexIsNotInSubPlots(int subGroupIndex) { if ((subPlots.size() -1) < subGroupIndex) { throw new IllegalArgumentException("subgroup is out of range" + subGroupIndex + " > " + (subPlots.size() -1)); } } @Override public boolean plotMatchesSetting(PlotSettings settings) { if (getAxisOrientationSetting() != settings.timeAxisSetting) { return false; } if (getXAxisMaximumLocation() != settings.xAxisMaximumLocation) { return false; } if (getYAxisMaximumLocation() != settings.yAxisMaximumLocation) { return false; } if (getTimeAxisSubsequentSetting() != settings.timeAxisSubsequent) { return false; } if (getNonTimeAxisSubsequentMinSetting() != settings.nonTimeAxisSubsequentMinSetting) { return false; } if (getNonTimeAxisSubsequentMaxSetting() != settings.nonTimeAxisSubsequentMaxSetting) { return false; } if (getTimeMax() != settings.maxTime) { return false; } if (getTimeMin() != settings.minTime) { return false; } if (getNonTimeMin() != settings.minNonTime) { return false; } if (getNonTimeMax() != settings.maxNonTime) { return false; } if (getTimePadding() != settings.timePadding) { return false; } if (getNonTimeMaxPadding() != settings.nonTimeMaxPadding) { return false; } if (getNonTimeMinPadding() != settings.nonTimeMinPadding) { return false; } if (useOrdinalPositionForSubplots() != settings.ordinalPositionForStackedPlots) { return false; } return true; } @Override public void updateTimeAxis(PlotSubject subject, long startTime, long endTime) { for (AbstractPlottingPackage plot: subPlots) { if (plot!= subject) { plot.setTimeAxisStartAndStop(startTime, endTime); } } } @Override public void updateResetButtons() { for(AbstractPlottingPackage p : subPlots) { p.updateResetButtons(); } } @Override public void clearAllDataFromPlot() { for (AbstractPlottingPackage plot: subPlots) { plot.clearAllDataFromPlot(); } } @Override public Pinnable createPin() { return pinSupport.createPin(); } private void pause() { for(AbstractPlottingPackage plot : subPlots) { plot.pause(true); } } private void unpause() { // Request data from buffer to fill in what was missed while paused. plotUser.updateFromFeed(null); for(AbstractPlottingPackage plot : subPlots) { plot.pause(false); } } @Override public boolean isPinned() { return pinSupport.isPinned(); } @Override public List<AbstractPlottingPackage> getSubPlots() { return Collections.unmodifiableList(subPlots); } @Override public Axis getTimeAxis() { return timeAxis; } /** * Adds data set per map. * @param dataForPlot data map. */ public void addData(Map<String, SortedMap<Long, Double>> dataForPlot) { for(Entry<String, SortedMap<Long, Double>> feedData : dataForPlot.entrySet()) { String feedID = feedData.getKey(); String dataSetNameLower = feedID.toLowerCase(); if (!isKnownDataSet(dataSetNameLower)) { throw new IllegalArgumentException("Attempting to set value for an unknown data set " + feedID); } Set<AbstractPlottingPackage> feedPlots = dataSetNameToSubGroupMap.get(dataSetNameLower); SortedMap<Long, Double> points = feedData.getValue(); for(AbstractPlottingPackage plot : feedPlots) { plot.addData(dataSetNameLower, points); } } } /** * Adds data set per feed Id, timestamp, and telemetry value. * @param feedID the feed Id. * @param time timestamp in millisecs. * @param value telemetry value in double. */ public void addData(String feedID, long time, double value) { SortedMap<Long, Double> points = new TreeMap<Long, Double>(); points.put(time, value); addData(Collections.singletonMap(feedID, points)); } /** * Sets the plot X-Y time axis. * @param axis the X-Y time axis. */ public void setPlotTimeAxis(TimeXYAxis axis) { this.plotTimeAxis = axis; } /** * Gets the plot X-Y time axis. * @return X-Y time axis. */ public TimeXYAxis getPlotTimeAxis() { return plotTimeAxis; } private void timeReachedEnd() { long maxTime = getCurrentMCTTime(); double plotMax = Math.max(plotTimeAxis.getStart(), plotTimeAxis.getEnd()); double lag = maxTime - plotMax; double scrollRescaleTimeMargin = this.scrollRescaleTimeMargin; if (scrollRescaleTimeMargin == 0) { scrollRescaleTimeMargin = (maxTime - plotMax) / Math.abs(plotTimeAxis.getEnd() - plotTimeAxis.getStart()); } if(lag > 0 && !timeAxis.isPinned()) { if(timeAxisSubsequentSetting == TimeAxisSubsequentBoundsSetting.JUMP) { double increment = Math.abs(scrollRescaleTimeMargin * (plotTimeAxis.getEnd() - plotTimeAxis.getStart())); plotTimeAxis.shift(Math.ceil(lag / increment) * increment); for(AbstractPlottingPackage subPlot : subPlots) { subPlot.setTimeAxisStartAndStop(plotTimeAxis.getStartAsLong(), plotTimeAxis.getEndAsLong()); } } else if(timeAxisSubsequentSetting == TimeAxisSubsequentBoundsSetting.SCRUNCH) { double max = plotTimeAxis.getEnd(); double min = plotTimeAxis.getStart(); double diff = max - min; assert diff != 0 : "min = max = " + min; double scrunchFactor = 1 + scrollRescaleTimeMargin; if((max < min)) { min = max + (maxTime - max)*(scrunchFactor); } else { max = min + (maxTime - min)*(scrunchFactor); } plotTimeAxis.setStart(min); plotTimeAxis.setEnd(max); for(AbstractPlottingPackage subPlot : subPlots) { subPlot.setTimeAxisStartAndStop(plotTimeAxis.getStartAsLong(), plotTimeAxis.getEndAsLong()); subPlot.updateCompressionRatio(); } } else { assert false : "Unrecognized timeAxisSubsequentSetting: " + timeAxisSubsequentSetting; } double newPlotMax = Math.max(plotTimeAxis.getStart(), plotTimeAxis.getEnd()); if(newPlotMax != plotMax) { GregorianCalendar start = new GregorianCalendar(); GregorianCalendar end = new GregorianCalendar(); start.setTimeInMillis((long) plotMax); end.setTimeInMillis((long) newPlotMax); requestPredictivePlotData(start, end); } } } @Override public PlotLineDrawingFlags getPlotLineDraw() { return plotLineDraw; } @Override public PlotLineConnectionType getPlotLineConnectionType() { return plotLineConnectionType; } @Override public void setPlotLineDraw(PlotLineDrawingFlags draw) { plotLineDraw = draw; } @Override public void setPlotLineConnectionType(PlotLineConnectionType type) { plotLineConnectionType = type; } }
1no label
fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_bridge_PlotView.java
621
public class PrepareMergeOperation extends AbstractClusterOperation { private Address newTargetAddress; public PrepareMergeOperation() { } public PrepareMergeOperation(Address newTargetAddress) { this.newTargetAddress = newTargetAddress; } @Override public void run() { final Address caller = getCallerAddress(); final NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine(); final Node node = nodeEngine.getNode(); final Address masterAddress = node.getMasterAddress(); final ILogger logger = node.loggingService.getLogger(this.getClass().getName()); boolean local = caller == null; if (!local && !caller.equals(masterAddress)) { logger.warning("Prepare-merge instruction sent from non-master endpoint: " + caller); return; } logger.warning("Preparing to merge... Waiting for merge instruction..."); node.getClusterService().prepareToMerge(newTargetAddress); } @Override public boolean returnsResponse() { return true; } @Override public Object getResponse() { return Boolean.TRUE; } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); newTargetAddress = new Address(); newTargetAddress.readData(in); } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); newTargetAddress.writeData(out); } }
0true
hazelcast_src_main_java_com_hazelcast_cluster_PrepareMergeOperation.java
851
public class GetAndSetRequest extends ModifyRequest { public GetAndSetRequest() { } public GetAndSetRequest(String name, Data update) { super(name, update); } @Override protected Operation prepareOperation() { return new GetAndSetOperation(name, update); } @Override public int getClassId() { return AtomicReferencePortableHook.GET_AND_SET; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_GetAndSetRequest.java
1,538
public static class Map extends Mapper<NullWritable, FaunusVertex, WritableComparable, Text> { private String key; private boolean isVertex; private WritableHandler handler; private String elementKey; private SafeMapperOutputs outputs; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class); this.key = context.getConfiguration().get(KEY); this.handler = new WritableHandler(context.getConfiguration().getClass(TYPE, Text.class, WritableComparable.class)); this.elementKey = context.getConfiguration().get(ELEMENT_KEY); this.outputs = new SafeMapperOutputs(context); } private Text text = new Text(); private WritableComparable writable; @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, WritableComparable, Text>.Context context) throws IOException, InterruptedException { if (this.isVertex) { if (value.hasPaths()) { this.text.set(ElementPicker.getPropertyAsString(value, this.elementKey)); final Object temp = ElementPicker.getProperty(value, this.key); if (this.key.equals(Tokens._COUNT)) { this.writable = this.handler.set(temp); context.write(this.writable, this.text); } else if (temp instanceof Number) { this.writable = this.handler.set(multiplyPathCount((Number) temp, value.pathCount())); context.write(this.writable, this.text); } else { this.writable = this.handler.set(temp); for (int i = 0; i < value.pathCount(); i++) { context.write(this.writable, this.text); } } DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L); } } else { long edgesProcessed = 0; for (final Edge e : value.getEdges(Direction.OUT)) { final StandardFaunusEdge edge = (StandardFaunusEdge) e; if (edge.hasPaths()) { this.text.set(ElementPicker.getPropertyAsString(edge, this.elementKey)); final Object temp = ElementPicker.getProperty(edge, this.key); if (this.key.equals(Tokens._COUNT)) { this.writable = this.handler.set(temp); context.write(this.writable, this.text); } else if (temp instanceof Number) { this.writable = this.handler.set(multiplyPathCount((Number) temp, edge.pathCount())); context.write(this.writable, this.text); } else { this.writable = this.handler.set(temp); for (int i = 0; i < edge.pathCount(); i++) { context.write(this.writable, this.text); } } edgesProcessed++; } } DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_PROCESSED, edgesProcessed); } this.outputs.write(Tokens.GRAPH, NullWritable.get(), value); } @Override public void cleanup(final Mapper<NullWritable, FaunusVertex, WritableComparable, Text>.Context context) throws IOException, InterruptedException { this.outputs.close(); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_transform_OrderMapReduce.java
1,131
public interface Client extends Endpoint { /** * Returns unique uuid for this client * * @return unique uuid for this client */ String getUuid(); /** * Returns socket address of this client * * @return socket address of this client */ InetSocketAddress getSocketAddress(); /** * Returns type of this client * * @return type of this client */ ClientType getClientType(); }
0true
hazelcast_src_main_java_com_hazelcast_core_Client.java
1,548
public interface GatewayAllocator { /** * Apply all shards * @param allocation */ void applyStartedShards(StartedRerouteAllocation allocation); void applyFailedShards(FailedRerouteAllocation allocation); boolean allocateUnassigned(RoutingAllocation allocation); }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_allocator_GatewayAllocator.java
176
public strictfp class MersenneTwister extends java.util.Random implements Serializable, Cloneable { // Serialization private static final long serialVersionUID = -4035832775130174188L; // locked as of Version 15 // Period parameters private static final int N = 624; private static final int M = 397; private static final int MATRIX_A = 0x9908b0df; // private static final * constant vector a private static final int UPPER_MASK = 0x80000000; // most significant w-r bits private static final int LOWER_MASK = 0x7fffffff; // least significant r bits // Tempering parameters private static final int TEMPERING_MASK_B = 0x9d2c5680; private static final int TEMPERING_MASK_C = 0xefc60000; private int mt[]; // the array for the state vector private int mti; // mti==N+1 means mt[N] is not initialized private int mag01[]; // a good initial seed (of int size, though stored in a long) //private static final long GOOD_SEED = 4357; /* implemented here because there's a bug in Random's implementation of the Gaussian code (divide by zero, and log(0), ugh!), yet its gaussian variables are private so we can't access them here. :-( */ private double __nextNextGaussian; private boolean __haveNextNextGaussian; /* We're overriding all internal data, to my knowledge, so this should be okay */ public Object clone() { try { MersenneTwister f = (MersenneTwister)(super.clone()); f.mt = (int[])(mt.clone()); f.mag01 = (int[])(mag01.clone()); return f; } catch (CloneNotSupportedException e) { throw new InternalError(); } // should never happen } public boolean stateEquals(Object o) { if (o==this) return true; if (o == null || !(o instanceof MersenneTwister)) return false; MersenneTwister other = (MersenneTwister) o; if (mti != other.mti) return false; for(int x=0;x<mag01.length;x++) if (mag01[x] != other.mag01[x]) return false; for(int x=0;x<mt.length;x++) if (mt[x] != other.mt[x]) return false; return true; } /** Reads the entire state of the MersenneTwister RNG from the stream */ public void readState(DataInputStream stream) throws IOException { int len = mt.length; for(int x=0;x<len;x++) mt[x] = stream.readInt(); len = mag01.length; for(int x=0;x<len;x++) mag01[x] = stream.readInt(); mti = stream.readInt(); __nextNextGaussian = stream.readDouble(); __haveNextNextGaussian = stream.readBoolean(); } /** Writes the entire state of the MersenneTwister RNG to the stream */ public void writeState(DataOutputStream stream) throws IOException { int len = mt.length; for(int x=0;x<len;x++) stream.writeInt(mt[x]); len = mag01.length; for(int x=0;x<len;x++) stream.writeInt(mag01[x]); stream.writeInt(mti); stream.writeDouble(__nextNextGaussian); stream.writeBoolean(__haveNextNextGaussian); } /** * Constructor using the default seed. */ public MersenneTwister() { this(System.currentTimeMillis()); } /** * Constructor using a given seed. Though you pass this seed in * as a long, it's best to make sure it's actually an integer. */ public MersenneTwister(final long seed) { super(seed); /* just in case */ setSeed(seed); } /** * Constructor using an array of integers as seed. * Your array must have a non-zero length. Only the first 624 integers * in the array are used; if the array is shorter than this then * integers are repeatedly used in a wrap-around fashion. */ public MersenneTwister(final int[] array) { super(System.currentTimeMillis()); /* pick something at random just in case */ setSeed(array); } /** * Initalize the pseudo random number generator. Don't * pass in a long that's bigger than an int (Mersenne Twister * only uses the first 32 bits for its seed). */ synchronized public void setSeed(final long seed) { // it's always good style to call super super.setSeed(seed); // Due to a bug in java.util.Random clear up to 1.2, we're // doing our own Gaussian variable. __haveNextNextGaussian = false; mt = new int[N]; mag01 = new int[2]; mag01[0] = 0x0; mag01[1] = MATRIX_A; mt[0]= (int)(seed & 0xffffffff); for (mti=1; mti<N; mti++) { mt[mti] = (1812433253 * (mt[mti-1] ^ (mt[mti-1] >>> 30)) + mti); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ mt[mti] &= 0xffffffff; /* for >32 bit machines */ } } /** * Sets the seed of the MersenneTwister using an array of integers. * Your array must have a non-zero length. Only the first 624 integers * in the array are used; if the array is shorter than this then * integers are repeatedly used in a wrap-around fashion. */ synchronized public void setSeed(final int[] array) { if (array.length == 0) throw new IllegalArgumentException("Array length must be greater than zero"); int i, j, k; setSeed(19650218); i=1; j=0; k = (N>array.length ? N : array.length); for (; k!=0; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * 1664525)) + array[j] + j; /* non linear */ mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ i++; j++; if (i>=N) { mt[0] = mt[N-1]; i=1; } if (j>=array.length) j=0; } for (k=N-1; k!=0; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * 1566083941)) - i; /* non linear */ mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ i++; if (i>=N) { mt[0] = mt[N-1]; i=1; } } mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ } /** * Returns an integer with <i>bits</i> bits filled with a random number. */ synchronized protected int next(final int bits) { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return y >>> (32 - bits); // hope that's right! } /* If you've got a truly old version of Java, you can omit these two next methods. */ private synchronized void writeObject(final ObjectOutputStream out) throws IOException { // just so we're synchronized. out.defaultWriteObject(); } private synchronized void readObject (final ObjectInputStream in) throws IOException, ClassNotFoundException { // just so we're synchronized. in.defaultReadObject(); } /** This method is missing from jdk 1.0.x and below. JDK 1.1 includes this for us, but what the heck.*/ public boolean nextBoolean() {return next(1) != 0;} /** This generates a coin flip with a probability <tt>probability</tt> of returning true, else returning false. <tt>probability</tt> must be between 0.0 and 1.0, inclusive. Not as precise a random real event as nextBoolean(double), but twice as fast. To explicitly use this, remember you may need to cast to float first. */ public boolean nextBoolean (final float probability) { if (probability < 0.0f || probability > 1.0f) throw new IllegalArgumentException ("probability must be between 0.0 and 1.0 inclusive."); if (probability==0.0f) return false; // fix half-open issues else if (probability==1.0f) return true; // fix half-open issues return nextFloat() < probability; } /** This generates a coin flip with a probability <tt>probability</tt> of returning true, else returning false. <tt>probability</tt> must be between 0.0 and 1.0, inclusive. */ public boolean nextBoolean (final double probability) { if (probability < 0.0 || probability > 1.0) throw new IllegalArgumentException ("probability must be between 0.0 and 1.0 inclusive."); if (probability==0.0) return false; // fix half-open issues else if (probability==1.0) return true; // fix half-open issues return nextDouble() < probability; } /** This method is missing from JDK 1.1 and below. JDK 1.2 includes this for us, but what the heck. */ public int nextInt(final int n) { if (n<=0) throw new IllegalArgumentException("n must be positive, got: " + n); if ((n & -n) == n) return (int)((n * (long)next(31)) >> 31); int bits, val; do { bits = next(31); val = bits % n; } while(bits - val + (n-1) < 0); return val; } /** This method is for completness' sake. Returns a long drawn uniformly from 0 to n-1. Suffice it to say, n must be > 0, or an IllegalArgumentException is raised. */ public long nextLong(final long n) { if (n<=0) throw new IllegalArgumentException("n must be positive, got: " + n); long bits, val; do { bits = (nextLong() >>> 1); val = bits % n; } while(bits - val + (n-1) < 0); return val; } /** A bug fix for versions of JDK 1.1 and below. JDK 1.2 fixes this for us, but what the heck. */ public double nextDouble() { return (((long)next(26) << 27) + next(27)) / (double)(1L << 53); } /** Returns a double in the range from 0.0 to 1.0, possibly inclusive of 0.0 and 1.0 themselves. Thus: <p><table border=0> <th><td>Expression<td>Interval <tr><td>nextDouble(false, false)<td>(0.0, 1.0) <tr><td>nextDouble(true, false)<td>[0.0, 1.0) <tr><td>nextDouble(false, true)<td>(0.0, 1.0] <tr><td>nextDouble(true, true)<td>[0.0, 1.0] </table> <p>This version preserves all possible random values in the double range. */ public double nextDouble(boolean includeZero, boolean includeOne) { double d = 0.0; do { d = nextDouble(); // grab a value, initially from half-open [0.0, 1.0) if (includeOne && nextBoolean()) d += 1.0; // if includeOne, with 1/2 probability, push to [1.0, 2.0) } while ( (d > 1.0) || // everything above 1.0 is always invalid (!includeZero && d == 0.0)); // if we're not including zero, 0.0 is invalid return d; } /** A bug fix for versions of JDK 1.1 and below. JDK 1.2 fixes this for us, but what the heck. */ public float nextFloat() { return next(24) / ((float)(1 << 24)); } /** Returns a float in the range from 0.0f to 1.0f, possibly inclusive of 0.0f and 1.0f themselves. Thus: <p><table border=0> <th><td>Expression<td>Interval <tr><td>nextFloat(false, false)<td>(0.0f, 1.0f) <tr><td>nextFloat(true, false)<td>[0.0f, 1.0f) <tr><td>nextFloat(false, true)<td>(0.0f, 1.0f] <tr><td>nextFloat(true, true)<td>[0.0f, 1.0f] </table> <p>This version preserves all possible random values in the float range. */ public double nextFloat(boolean includeZero, boolean includeOne) { float d = 0.0f; do { d = nextFloat(); // grab a value, initially from half-open [0.0f, 1.0f) if (includeOne && nextBoolean()) d += 1.0f; // if includeOne, with 1/2 probability, push to [1.0f, 2.0f) } while ( (d > 1.0f) || // everything above 1.0f is always invalid (!includeZero && d == 0.0f)); // if we're not including zero, 0.0f is invalid return d; } /** A bug fix for all versions of the JDK. The JDK appears to use all four bytes in an integer as independent byte values! Totally wrong. I've submitted a bug report. */ public void nextBytes(final byte[] bytes) { for (int x=0;x<bytes.length;x++) bytes[x] = (byte)next(8); } /** For completeness' sake, though it's not in java.util.Random. */ public char nextChar() { // chars are 16-bit UniCode values return (char)(next(16)); } /** For completeness' sake, though it's not in java.util.Random. */ public short nextShort() { return (short)(next(16)); } /** For completeness' sake, though it's not in java.util.Random. */ public byte nextByte() { return (byte)(next(8)); } /** A bug fix for all JDK code including 1.2. nextGaussian can theoretically ask for the log of 0 and divide it by 0! See Java bug <a href="http://developer.java.sun.com/developer/bugParade/bugs/4254501.html"> http://developer.java.sun.com/developer/bugParade/bugs/4254501.html</a> */ synchronized public double nextGaussian() { if (__haveNextNextGaussian) { __haveNextNextGaussian = false; return __nextNextGaussian; } else { double v1, v2, s; do { v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0 v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0 s = v1 * v1 + v2 * v2; } while (s >= 1 || s==0 ); double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); __nextNextGaussian = v2 * multiplier; __haveNextNextGaussian = true; return v1 * multiplier; } } /** * Tests the code. */ public static void main(String args[]) { int j; MersenneTwister r; // CORRECTNESS TEST // COMPARE WITH http://www.math.keio.ac.jp/matumoto/CODES/MT2002/mt19937ar.out r = new MersenneTwister(new int[]{0x123, 0x234, 0x345, 0x456}); System.out.println("Output of MersenneTwister with new (2002/1/26) seeding mechanism"); for (j=0;j<1000;j++) { // first, convert the int from signed to "unsigned" long l = (long)r.nextInt(); if (l < 0 ) l += 4294967296L; // max int value String s = String.valueOf(l); while(s.length() < 10) s = " " + s; // buffer System.out.print(s + " "); if (j%5==4) System.out.println(); } // SPEED TEST final long SEED = 4357; int xx; long ms; System.out.println("\nTime to test grabbing 100000000 ints"); r = new MersenneTwister(SEED); ms = System.currentTimeMillis(); xx=0; for (j = 0; j < 100000000; j++) xx += r.nextInt(); System.out.println("Mersenne Twister: " + (System.currentTimeMillis()-ms) + " Ignore this: " + xx); System.out.println("To compare this with java.util.Random, run this same test on MersenneTwisterFast."); System.out.println("The comparison with Random is removed from MersenneTwister because it is a proper"); System.out.println("subclass of Random and this unfairly makes some of Random's methods un-inlinable,"); System.out.println("so it would make Random look worse than it is."); // TEST TO COMPARE TYPE CONVERSION BETWEEN // MersenneTwisterFast.java AND MersenneTwister.java System.out.println("\nGrab the first 1000 booleans"); r = new MersenneTwister(SEED); for (j = 0; j < 1000; j++) { System.out.print(r.nextBoolean() + " "); if (j%8==7) System.out.println(); } if (!(j%8==7)) System.out.println(); System.out.println("\nGrab 1000 booleans of increasing probability using nextBoolean(double)"); r = new MersenneTwister(SEED); for (j = 0; j < 1000; j++) { System.out.print(r.nextBoolean((double)(j/999.0)) + " "); if (j%8==7) System.out.println(); } if (!(j%8==7)) System.out.println(); System.out.println("\nGrab 1000 booleans of increasing probability using nextBoolean(float)"); r = new MersenneTwister(SEED); for (j = 0; j < 1000; j++) { System.out.print(r.nextBoolean((float)(j/999.0f)) + " "); if (j%8==7) System.out.println(); } if (!(j%8==7)) System.out.println(); byte[] bytes = new byte[1000]; System.out.println("\nGrab the first 1000 bytes using nextBytes"); r = new MersenneTwister(SEED); r.nextBytes(bytes); for (j = 0; j < 1000; j++) { System.out.print(bytes[j] + " "); if (j%16==15) System.out.println(); } if (!(j%16==15)) System.out.println(); byte b; System.out.println("\nGrab the first 1000 bytes -- must be same as nextBytes"); r = new MersenneTwister(SEED); for (j = 0; j < 1000; j++) { System.out.print((b = r.nextByte()) + " "); if (b!=bytes[j]) System.out.print("BAD "); if (j%16==15) System.out.println(); } if (!(j%16==15)) System.out.println(); System.out.println("\nGrab the first 1000 shorts"); r = new MersenneTwister(SEED); for (j = 0; j < 1000; j++) { System.out.print(r.nextShort() + " "); if (j%8==7) System.out.println(); } if (!(j%8==7)) System.out.println(); System.out.println("\nGrab the first 1000 ints"); r = new MersenneTwister(SEED); for (j = 0; j < 1000; j++) { System.out.print(r.nextInt() + " "); if (j%4==3) System.out.println(); } if (!(j%4==3)) System.out.println(); System.out.println("\nGrab the first 1000 ints of different sizes"); r = new MersenneTwister(SEED); int max = 1; for (j = 0; j < 1000; j++) { System.out.print(r.nextInt(max) + " "); max *= 2; if (max <= 0) max = 1; if (j%4==3) System.out.println(); } if (!(j%4==3)) System.out.println(); System.out.println("\nGrab the first 1000 longs"); r = new MersenneTwister(SEED); for (j = 0; j < 1000; j++) { System.out.print(r.nextLong() + " "); if (j%3==2) System.out.println(); } if (!(j%3==2)) System.out.println(); System.out.println("\nGrab the first 1000 longs of different sizes"); r = new MersenneTwister(SEED); long max2 = 1; for (j = 0; j < 1000; j++) { System.out.print(r.nextLong(max2) + " "); max2 *= 2; if (max2 <= 0) max2 = 1; if (j%4==3) System.out.println(); } if (!(j%4==3)) System.out.println(); System.out.println("\nGrab the first 1000 floats"); r = new MersenneTwister(SEED); for (j = 0; j < 1000; j++) { System.out.print(r.nextFloat() + " "); if (j%4==3) System.out.println(); } if (!(j%4==3)) System.out.println(); System.out.println("\nGrab the first 1000 doubles"); r = new MersenneTwister(SEED); for (j = 0; j < 1000; j++) { System.out.print(r.nextDouble() + " "); if (j%3==2) System.out.println(); } if (!(j%3==2)) System.out.println(); System.out.println("\nGrab the first 1000 gaussian doubles"); r = new MersenneTwister(SEED); for (j = 0; j < 1000; j++) { System.out.print(r.nextGaussian() + " "); if (j%3==2) System.out.println(); } if (!(j%3==2)) System.out.println(); } }
0true
commons_src_main_java_com_orientechnologies_common_util_MersenneTwister.java
110
private class TxHook implements javax.transaction.Synchronization { boolean gotBefore = false; boolean gotAfter = false; int statusBefore = -1; int statusAfter = -1; Transaction txBefore = null; Transaction txAfter = null; public void beforeCompletion() { try { statusBefore = tm.getStatus(); txBefore = tm.getTransaction(); gotBefore = true; } catch ( Exception e ) { throw new RuntimeException( "" + e ); } } public void afterCompletion( int status ) { try { statusAfter = status; txAfter = tm.getTransaction(); assertTrue( status == tm.getStatus() ); gotAfter = true; } catch ( Exception e ) { throw new RuntimeException( "" + e ); } } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestJtaCompliance.java
113
{ @Override public Object doWork( Void state ) { try { tm.begin(); tm.getTransaction().registerSynchronization( hook ); return null; } catch ( Exception e ) { throw new RuntimeException( e ); } } };
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestJtaCompliance.java
1,664
public interface PersistencePackageFactory { /** * Creates a persistence package for the given request. Different request types require different combinations * of attributes, which are generally self explanatory. * * @param request * @return the persistence package * * @see PersistencePackageRequest * @see PersistencePackageRequest.Type */ public PersistencePackage create(PersistencePackageRequest request); }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_factory_PersistencePackageFactory.java
1,933
public class AsynchronousComputationException extends ComputationException { public AsynchronousComputationException(Throwable cause) { super(cause); } }
0true
src_main_java_org_elasticsearch_common_inject_internal_AsynchronousComputationException.java
127
public class ForkJoinWorkerThread extends Thread { /* * ForkJoinWorkerThreads are managed by ForkJoinPools and perform * ForkJoinTasks. For explanation, see the internal documentation * of class ForkJoinPool. * * This class just maintains links to its pool and WorkQueue. The * pool field is set immediately upon construction, but the * workQueue field is not set until a call to registerWorker * completes. This leads to a visibility race, that is tolerated * by requiring that the workQueue field is only accessed by the * owning thread. */ final ForkJoinPool pool; // the pool this thread works in final ForkJoinPool.WorkQueue workQueue; // work-stealing mechanics /** * Creates a ForkJoinWorkerThread operating in the given pool. * * @param pool the pool this thread works in * @throws NullPointerException if pool is null */ protected ForkJoinWorkerThread(ForkJoinPool pool) { // Use a placeholder until a useful name can be set in registerWorker super("aForkJoinWorkerThread"); this.pool = pool; this.workQueue = pool.registerWorker(this); } /** * Returns the pool hosting this thread. * * @return the pool */ public ForkJoinPool getPool() { return pool; } /** * Returns the unique index number of this thread in its pool. * The returned value ranges from zero to the maximum number of * threads (minus one) that may exist in the pool, and does not * change during the lifetime of the thread. This method may be * useful for applications that track status or collect results * per-worker-thread rather than per-task. * * @return the index number */ public int getPoolIndex() { return workQueue.poolIndex >>> 1; // ignore odd/even tag bit } /** * Initializes internal state after construction but before * processing any tasks. If you override this method, you must * invoke {@code super.onStart()} at the beginning of the method. * Initialization requires care: Most fields must have legal * default values, to ensure that attempted accesses from other * threads work correctly even before this thread starts * processing tasks. */ protected void onStart() { } /** * Performs cleanup associated with termination of this worker * thread. If you override this method, you must invoke * {@code super.onTermination} at the end of the overridden method. * * @param exception the exception causing this thread to abort due * to an unrecoverable error, or {@code null} if completed normally */ protected void onTermination(Throwable exception) { } /** * This method is required to be public, but should never be * called explicitly. It performs the main run loop to execute * {@link ForkJoinTask}s. */ public void run() { Throwable exception = null; try { onStart(); pool.runWorker(workQueue); } catch (Throwable ex) { exception = ex; } finally { try { onTermination(exception); } catch (Throwable ex) { if (exception == null) exception = ex; } finally { pool.deregisterWorker(this, exception); } } } }
0true
src_main_java_jsr166e_ForkJoinWorkerThread.java
151
public interface LoadBalancer { /** * Initializes the LoadBalancer. * * @param cluster the Cluster this LoadBalancer uses to select members from. * @param config the ClientConfig. */ void init(Cluster cluster, ClientConfig config); /** * Returns the next member to route to. * * @return Returns the next member or null if no member is available */ Member next(); }
0true
hazelcast-client_src_main_java_com_hazelcast_client_LoadBalancer.java
170
public static interface ManagedBlocker { /** * Possibly blocks the current thread, for example waiting for * a lock or condition. * * @return {@code true} if no additional blocking is necessary * (i.e., if isReleasable would return true) * @throws InterruptedException if interrupted while waiting * (the method is not required to do so, but is allowed to) */ boolean block() throws InterruptedException; /** * Returns {@code true} if blocking is unnecessary. */ boolean isReleasable(); }
0true
src_main_java_jsr166y_ForkJoinPool.java
586
public interface FulfillmentPriceExceptionResponse extends Serializable { public boolean isErrorDetected(); public void setErrorDetected(boolean isErrorDetected); public String getErrorCode(); public void setErrorCode(String errorCode); public String getErrorText(); public void setErrorText(String errorText); }
0true
common_src_main_java_org_broadleafcommerce_common_vendor_service_message_FulfillmentPriceExceptionResponse.java
260
public interface EmailTrackingOpens extends Serializable { /** * @return the id */ public abstract Long getId(); /** * @param id the id to set */ public abstract void setId(Long id); /** * @return the dateOpened */ public abstract Date getDateOpened(); /** * @param dateOpened the dateOpened to set */ public abstract void setDateOpened(Date dateOpened); /** * @return the userAgent */ public abstract String getUserAgent(); /** * @param userAgent the userAgent to set */ public abstract void setUserAgent(String userAgent); /** * @return the emailTracking */ public abstract EmailTracking getEmailTracking(); /** * @param emailTracking the emailTracking to set */ public abstract void setEmailTracking(EmailTracking emailTracking); }
0true
common_src_main_java_org_broadleafcommerce_common_email_domain_EmailTrackingOpens.java
840
LINKSET("LinkSet", 15, new Class<?>[] { Set.class }, new Class<?>[] { Set.class }) { },
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OType.java
3,220
public abstract class LongValues { /** * An empty {@link LongValues instance} */ public static final LongValues EMPTY = new Empty(); private final boolean multiValued; protected int docId; /** * Creates a new {@link LongValues} instance * @param multiValued <code>true</code> iff this instance is multivalued. Otherwise <code>false</code>. */ protected LongValues(boolean multiValued) { this.multiValued = multiValued; } /** * Is one of the documents in this field data values is multi valued? */ public final boolean isMultiValued() { return multiValued; } /** * Sets iteration to the specified docID and returns the number of * values for this document ID, * @param docId document ID * * @see #nextValue() */ public abstract int setDocument(int docId); /** * Returns the next value for the current docID set to {@link #setDocument(int)}. * This method should only be called <tt>N</tt> times where <tt>N</tt> is the number * returned from {@link #setDocument(int)}. If called more than <tt>N</tt> times the behavior * is undefined. * <p> * If this instance returns ordered values the <tt>Nth</tt> value is strictly less than the <tt>N+1</tt> value with * respect to the {@link AtomicFieldData.Order} returned from {@link #getOrder()}. If this instance returns * <i>unordered</i> values {@link #getOrder()} must return {@link AtomicFieldData.Order#NONE} * Note: the values returned are de-duplicated, only unique values are returned. * </p> * * @return the next value for the current docID set to {@link #setDocument(int)}. */ public abstract long nextValue(); /** * Returns the order the values are returned from {@link #nextValue()}. * <p> Note: {@link LongValues} have {@link AtomicFieldData.Order#NUMERIC} by default.</p> */ public AtomicFieldData.Order getOrder() { return AtomicFieldData.Order.NUMERIC; } /** * Ordinal based {@link LongValues}. */ public static abstract class WithOrdinals extends LongValues { protected final Docs ordinals; protected WithOrdinals(Ordinals.Docs ordinals) { super(ordinals.isMultiValued()); this.ordinals = ordinals; } /** * Returns the associated ordinals instance. * @return the associated ordinals instance. */ public Docs ordinals() { return this.ordinals; } /** * Returns the value for the given ordinal. * @param ord the ordinal to lookup. * @return a long value associated with the given ordinal. */ public abstract long getValueByOrd(long ord); @Override public int setDocument(int docId) { this.docId = docId; return ordinals.setDocument(docId); } @Override public long nextValue() { return getValueByOrd(ordinals.nextOrd()); } } private static final class Empty extends LongValues { public Empty() { super(false); } @Override public int setDocument(int docId) { return 0; } @Override public long nextValue() { throw new ElasticsearchIllegalStateException("Empty LongValues has no next value"); } } /** Wrap a {@link DoubleValues} instance. */ public static LongValues asLongValues(final DoubleValues values) { return new LongValues(values.isMultiValued()) { @Override public int setDocument(int docId) { return values.setDocument(docId); } @Override public long nextValue() { return (long) values.nextValue(); } }; } }
0true
src_main_java_org_elasticsearch_index_fielddata_LongValues.java
3,115
public class RollbackFailedEngineException extends EngineException { public RollbackFailedEngineException(ShardId shardId, Throwable t) { super(shardId, "Rollback failed", t); } }
0true
src_main_java_org_elasticsearch_index_engine_RollbackFailedEngineException.java
3,023
public abstract class AbstractDocValuesFormatProvider implements DocValuesFormatProvider { private final String name; protected AbstractDocValuesFormatProvider(String name) { this.name = name; } public String name() { return name; } }
0true
src_main_java_org_elasticsearch_index_codec_docvaluesformat_AbstractDocValuesFormatProvider.java
1,304
interface Factory<T extends Custom> { String type(); T readFrom(StreamInput in) throws IOException; void writeTo(T customState, StreamOutput out) throws IOException; void toXContent(T customState, XContentBuilder builder, ToXContent.Params params); }
0true
src_main_java_org_elasticsearch_cluster_ClusterState.java
1,202
public class PaymentException extends Exception { private static final long serialVersionUID = 1L; public PaymentException() { super(); } public PaymentException(String message, Throwable cause) { super(message, cause); } public PaymentException(String message) { super(message); } public PaymentException(Throwable cause) { super(cause); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_exception_PaymentException.java