Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
327
public class NodesInfoResponse extends NodesOperationResponse<NodeInfo> implements ToXContent { private SettingsFilter settingsFilter; public NodesInfoResponse() { } public NodesInfoResponse(ClusterName clusterName, NodeInfo[] nodes) { super(clusterName, nodes); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); nodes = new NodeInfo[in.readVInt()]; for (int i = 0; i < nodes.length; i++) { nodes[i] = NodeInfo.readNodeInfo(in); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(nodes.length); for (NodeInfo node : nodes) { node.writeTo(out); } } public NodesInfoResponse settingsFilter(SettingsFilter settingsFilter) { this.settingsFilter = settingsFilter; return this; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field("cluster_name", getClusterName().value(), XContentBuilder.FieldCaseConversion.NONE); builder.startObject("nodes"); for (NodeInfo nodeInfo : this) { builder.startObject(nodeInfo.getNode().id(), XContentBuilder.FieldCaseConversion.NONE); builder.field("name", nodeInfo.getNode().name(), XContentBuilder.FieldCaseConversion.NONE); builder.field("transport_address", nodeInfo.getNode().address().toString()); builder.field("host", nodeInfo.getNode().getHostName(), XContentBuilder.FieldCaseConversion.NONE); builder.field("ip", nodeInfo.getNode().getHostAddress(), XContentBuilder.FieldCaseConversion.NONE); builder.field("version", nodeInfo.getVersion()); builder.field("build", nodeInfo.getBuild().hashShort()); if (nodeInfo.getServiceAttributes() != null) { for (Map.Entry<String, String> nodeAttribute : nodeInfo.getServiceAttributes().entrySet()) { builder.field(nodeAttribute.getKey(), nodeAttribute.getValue(), XContentBuilder.FieldCaseConversion.NONE); } } if (!nodeInfo.getNode().attributes().isEmpty()) { builder.startObject("attributes"); for (Map.Entry<String, String> attr : nodeInfo.getNode().attributes().entrySet()) { builder.field(attr.getKey(), attr.getValue(), XContentBuilder.FieldCaseConversion.NONE); } builder.endObject(); } if (nodeInfo.getSettings() != null) { builder.startObject("settings"); Settings settings = settingsFilter != null ? settingsFilter.filterSettings(nodeInfo.getSettings()) : nodeInfo.getSettings(); settings.toXContent(builder, params); builder.endObject(); } if (nodeInfo.getOs() != null) { nodeInfo.getOs().toXContent(builder, params); } if (nodeInfo.getProcess() != null) { nodeInfo.getProcess().toXContent(builder, params); } if (nodeInfo.getJvm() != null) { nodeInfo.getJvm().toXContent(builder, params); } if (nodeInfo.getThreadPool() != null) { nodeInfo.getThreadPool().toXContent(builder, params); } if (nodeInfo.getNetwork() != null) { nodeInfo.getNetwork().toXContent(builder, params); } if (nodeInfo.getTransport() != null) { nodeInfo.getTransport().toXContent(builder, params); } if (nodeInfo.getHttp() != null) { nodeInfo.getHttp().toXContent(builder, params); } if (nodeInfo.getPlugins() != null) { nodeInfo.getPlugins().toXContent(builder, params); } builder.endObject(); } builder.endObject(); return builder; } @Override public String toString() { try { XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint(); builder.startObject(); toXContent(builder, EMPTY_PARAMS); builder.endObject(); return builder.string(); } catch (IOException e) { return "{ \"error\" : \"" + e.getMessage() + "\"}"; } } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_info_NodesInfoResponse.java
1,633
public class OHazelcastCache implements OCache, OServerLifecycleListener { private boolean enabled = true; private final int limit; private final String mapName; private IMap<ORID, ORecordInternal<?>> map; private HazelcastInstance hInstance; private OServer server; public OHazelcastCache(final OServer iServer, final HazelcastInstance iInstance, final String iStorageName, final int iLimit) { mapName = iStorageName + ".level2cache"; limit = iLimit; hInstance = iInstance; server = iServer; server.registerLifecycleListener(this); } @Override public void startup() { if (map == null && hInstance != null) map = hInstance.getMap(mapName); } @Override public void shutdown() { if (map != null && hInstance.getCluster().getMembers().size() <= 1) // I'M LAST MEMBER: REMOVE ALL THE ENTRIES map.clear(); map = null; } @Override public boolean isEnabled() { return enabled; } @Override public boolean enable() { if (!enabled) { enabled = true; startup(); } return true; } @Override public boolean disable() { if (enabled) { enabled = false; shutdown(); } return true; } @Override public ORecordInternal<?> get(final ORID id) { if (map == null) return null; return map.get(id); } @Override public ORecordInternal<?> put(final ORecordInternal<?> record) { if (map == null) return null; if (limit < 0 || map.size() < limit) return map.put(record.getIdentity(), record); return null; } @Override public ORecordInternal<?> remove(final ORID id) { if (map == null) return null; return map.remove(id); } @Override public void clear() { if (enabled) map.clear(); } @Override public int size() { if (!enabled) return 0; return map.size(); } @Override public int limit() { if (!enabled) return 0; return limit; } @Override public Collection<ORID> keys() { if (!enabled) return Collections.emptyList(); return map.keySet(); } /** * Hazelcast manages locking automatically. */ @Override public void lock(ORID id) { } /** * Hazelcast manages locking automatically. */ @Override public void unlock(ORID id) { } @Override public void onBeforeActivate() { } @Override public void onAfterActivate() { startup(); } @Override public void onBeforeDeactivate() { shutdown(); } @Override public void onAfterDeactivate() { } }
0true
distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_OHazelcastCache.java
3
public class AbbreviationServiceImplTest { @Mock private ComponentContext context; AbbreviationServiceImpl abbrev; Dictionary<String, String> properties; @BeforeMethod public void init() { MockitoAnnotations.initMocks(this); abbrev = new AbbreviationServiceImpl(); properties = new Hashtable<String, String>(); properties.put("component.name", "AbbreviationService"); when(context.getProperties()).thenReturn(properties); } @Test public void testActivateGoodFile() { properties.put("abbreviations-file", "/default-abbreviations.properties"); abbrev.activate(context); Abbreviations abbreviations = abbrev.getAbbreviations("Fiber Optic MDM System"); assertEquals(abbreviations.getPhrases().size(), 3); assertEquals(abbreviations.getPhrases().get(0), "Fiber Optic"); assertEquals(abbreviations.getPhrases().get(1), "MDM"); assertEquals(abbreviations.getPhrases().get(2), "System"); } @Test public void testActivateNoFileProperty() { abbrev.activate(context); Abbreviations abbreviations = abbrev.getAbbreviations("Fiber Optic MDM System"); assertEquals(abbreviations.getPhrases().size(), 4); assertEquals(abbreviations.getPhrases().get(0), "Fiber"); assertEquals(abbreviations.getPhrases().get(1), "Optic"); assertEquals(abbreviations.getPhrases().get(2), "MDM"); assertEquals(abbreviations.getPhrases().get(3), "System"); } @Test public void testActivateNonexistentAbbreviationsFile() { properties.put("abbreviations-file", "/file-does-not-exist.properties"); abbrev.activate(context); Abbreviations abbreviations = abbrev.getAbbreviations("Fiber Optic MDM System"); assertEquals(abbreviations.getPhrases().size(), 4); assertEquals(abbreviations.getPhrases().get(0), "Fiber"); assertEquals(abbreviations.getPhrases().get(1), "Optic"); assertEquals(abbreviations.getPhrases().get(2), "MDM"); assertEquals(abbreviations.getPhrases().get(3), "System"); } @Test(dataProvider="findFileTests") public void testFindFile(String path, String fileProperty) throws IOException { InputStream in; Properties p; p = new Properties(); in = abbrev.findFile(path); assertNotNull(in); p.load(in); assertEquals(p.getProperty("file"), fileProperty); } @DataProvider(name = "findFileTests") public Object[][] getFindFileTests() { return new Object[][] { // A file path { "src/test/data/abbreviations.properties", "in file system" }, // A resource in the bundle using an absolute name { "/test-abbreviations.properties", "root of bundle" }, // A resource in the bundle using a relative name { "package-abbreviations.properties", "in bundle package" }, }; } }
0true
tableViews_src_test_java_gov_nasa_arc_mct_abbreviation_impl_AbbreviationServiceImplTest.java
2,665
final class DataSerializer implements StreamSerializer<DataSerializable> { private static final String FACTORY_ID = "com.hazelcast.DataSerializerHook"; private final Map<Integer, DataSerializableFactory> factories = new HashMap<Integer, DataSerializableFactory>(); DataSerializer(Map<Integer, ? extends DataSerializableFactory> dataSerializableFactories, ClassLoader classLoader) { try { final Iterator<DataSerializerHook> hooks = ServiceLoader.iterator(DataSerializerHook.class, FACTORY_ID, classLoader); while (hooks.hasNext()) { DataSerializerHook hook = hooks.next(); final DataSerializableFactory factory = hook.createFactory(); if (factory != null) { register(hook.getFactoryId(), factory); } } } catch (Exception e) { throw ExceptionUtil.rethrow(e); } if (dataSerializableFactories != null) { for (Map.Entry<Integer, ? extends DataSerializableFactory> entry : dataSerializableFactories.entrySet()) { register(entry.getKey(), entry.getValue()); } } } private void register(int factoryId, DataSerializableFactory factory) { final DataSerializableFactory current = factories.get(factoryId); if (current != null) { if (current.equals(factory)) { Logger.getLogger(getClass()).warning("DataSerializableFactory[" + factoryId + "] is already registered! Skipping " + factory); } else { throw new IllegalArgumentException("DataSerializableFactory[" + factoryId + "] is already registered! " + current + " -> " + factory); } } else { factories.put(factoryId, factory); } } public int getTypeId() { return CONSTANT_TYPE_DATA; } public DataSerializable read(ObjectDataInput in) throws IOException { final DataSerializable ds; final boolean identified = in.readBoolean(); int id = 0; int factoryId = 0; String className = null; try { if (identified) { factoryId = in.readInt(); final DataSerializableFactory dsf = factories.get(factoryId); if (dsf == null) { throw new HazelcastSerializationException("No DataSerializerFactory registered for namespace: " + factoryId); } id = in.readInt(); ds = dsf.create(id); if (ds == null) { throw new HazelcastSerializationException(dsf + " is not be able to create an instance for id: " + id + " on factoryId: " + factoryId); } // TODO: @mm - we can check if DS class is final. } else { className = in.readUTF(); ds = ClassLoaderUtil.newInstance(in.getClassLoader(), className); } ds.readData(in); return ds; } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } if (e instanceof HazelcastSerializationException) { throw (HazelcastSerializationException) e; } throw new HazelcastSerializationException("Problem while reading DataSerializable, namespace: " + factoryId + ", id: " + id + ", class: " + className + ", exception: " + e.getMessage(), e); } } public void write(ObjectDataOutput out, DataSerializable obj) throws IOException { final boolean identified = obj instanceof IdentifiedDataSerializable; out.writeBoolean(identified); if (identified) { final IdentifiedDataSerializable ds = (IdentifiedDataSerializable) obj; out.writeInt(ds.getFactoryId()); out.writeInt(ds.getId()); } else { out.writeUTF(obj.getClass().getName()); } obj.writeData(out); } public void destroy() { factories.clear(); } }
1no label
hazelcast_src_main_java_com_hazelcast_nio_serialization_DataSerializer.java
459
el[5] = StaticArrayEntryList.of(Iterables.transform(entries.entrySet(),new Function<Map.Entry<Integer, Long>, Entry>() { @Nullable @Override public Entry apply(@Nullable Map.Entry<Integer, Long> entry) { return StaticArrayEntry.ofByteBuffer(entry, BBEntryGetter.SCHEMA_INSTANCE); } }));
0true
titan-test_src_test_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_StaticArrayEntryTest.java
168
public interface SimpleClient { void auth() throws IOException; void send(Object o) throws IOException; Object receive() throws IOException; void close() throws IOException; SerializationService getSerializationService(); }
0true
hazelcast_src_test_java_com_hazelcast_client_SimpleClient.java
258
public class ODefaultCollateFactory implements OCollateFactory { private static final Map<String, OCollate> COLLATES = new HashMap<String, OCollate>(2); static { register(new ODefaultCollate()); register(new OCaseInsensitiveCollate()); } /** * @return Set of supported collate names of this factory */ @Override public Set<String> getNames() { return COLLATES.keySet(); } /** * Returns the requested collate * * @param name */ @Override public OCollate getCollate(final String name) { return COLLATES.get(name); } private static void register(final OCollate iCollate) { COLLATES.put(iCollate.getName(), iCollate); } }
0true
core_src_main_java_com_orientechnologies_orient_core_collate_ODefaultCollateFactory.java
1,258
addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); Iterator it = map.keySet(new SqlPredicate("name=" + random.nextInt(10000))).iterator(); while (it.hasNext()) { it.next(); } } }, 10);
0true
hazelcast_src_main_java_com_hazelcast_examples_AllTest.java
250
@PreInitializeConfigOptions public class AstyanaxStoreManager extends AbstractCassandraStoreManager { private static final Logger log = LoggerFactory.getLogger(AstyanaxStoreManager.class); //################### ASTYANAX SPECIFIC CONFIGURATION OPTIONS ###################### public static final ConfigNamespace ASTYANAX_NS = new ConfigNamespace(CASSANDRA_NS, "astyanax", "Astyanax-specific Cassandra options"); /** * Default name for the Cassandra cluster * <p/> */ public static final ConfigOption<String> CLUSTER_NAME = new ConfigOption<String>(ASTYANAX_NS, "cluster-name", "Default name for the Cassandra cluster", ConfigOption.Type.MASKABLE, "Titan Cluster"); /** * Maximum pooled connections per host. * <p/> */ public static final ConfigOption<Integer> MAX_CONNECTIONS_PER_HOST = new ConfigOption<Integer>(ASTYANAX_NS, "max-connections-per-host", "Maximum pooled connections per host", ConfigOption.Type.MASKABLE, 32); /** * Maximum open connections allowed in the pool (counting all hosts). * <p/> */ public static final ConfigOption<Integer> MAX_CONNECTIONS = new ConfigOption<Integer>(ASTYANAX_NS, "max-connections", "Maximum open connections allowed in the pool (counting all hosts)", ConfigOption.Type.MASKABLE, -1); /** * Maximum number of operations allowed per connection before the connection is closed. * <p/> */ public static final ConfigOption<Integer> MAX_OPERATIONS_PER_CONNECTION = new ConfigOption<Integer>(ASTYANAX_NS, "max-operations-per-connection", "Maximum number of operations allowed per connection before the connection is closed", ConfigOption.Type.MASKABLE, 100 * 1000); /** * Maximum pooled "cluster" connections per host. * <p/> * These connections are mostly idle and only used for DDL operations * (like creating keyspaces). Titan doesn't need many of these connections * in ordinary operation. */ public static final ConfigOption<Integer> MAX_CLUSTER_CONNECTIONS_PER_HOST = new ConfigOption<Integer>(ASTYANAX_NS, "max-cluster-connections-per-host", "Maximum pooled \"cluster\" connections per host", ConfigOption.Type.MASKABLE, 3); /** * How Astyanax discovers Cassandra cluster nodes. This must be one of the * values of the Astyanax NodeDiscoveryType enum. * <p/> */ public static final ConfigOption<String> NODE_DISCOVERY_TYPE = new ConfigOption<String>(ASTYANAX_NS, "node-discovery-type", "How Astyanax discovers Cassandra cluster nodes", ConfigOption.Type.MASKABLE, "RING_DESCRIBE"); /** * Astyanax specific host supplier useful only when discovery type set to DISCOVERY_SERVICE or TOKEN_AWARE. * Excepts fully qualified class name which extends google.common.base.Supplier<List<Host>>. */ public static final ConfigOption<String> HOST_SUPPLIER = new ConfigOption<String>(ASTYANAX_NS, "host-supplier", "Host supplier to use when discovery type is set to DISCOVERY_SERVICE or TOKEN_AWARE", ConfigOption.Type.MASKABLE, String.class); /** * Astyanax's connection pooler implementation. This must be one of the * values of the Astyanax ConnectionPoolType enum. * <p/> */ public static final ConfigOption<String> CONNECTION_POOL_TYPE = new ConfigOption<String>(ASTYANAX_NS, "connection-pool-type", "Astyanax's connection pooler implementation", ConfigOption.Type.MASKABLE, "TOKEN_AWARE"); /** * In Astyanax, RetryPolicy and RetryBackoffStrategy sound and look similar * but are used for distinct purposes. RetryPolicy is for retrying failed * operations. RetryBackoffStrategy is for retrying attempts to talk to * uncommunicative hosts. This config option controls RetryPolicy. */ public static final ConfigOption<String> RETRY_POLICY = new ConfigOption<String>(ASTYANAX_NS, "retry-policy", "Astyanax's retry policy implementation with configuration parameters", ConfigOption.Type.MASKABLE, "com.netflix.astyanax.retry.BoundedExponentialBackoff,100,25000,8"); /** * If non-null, this must be the fully-qualified classname (i.e. the * complete package name, a dot, and then the class name) of an * implementation of Astyanax's RetryBackoffStrategy interface. This string * may be followed by a sequence of integers, separated from the full * classname and from each other by commas; in this case, the integers are * cast to native Java ints and passed to the class constructor as * arguments. Here's an example setting that would instantiate an Astyanax * FixedRetryBackoffStrategy with an delay interval of 1s and suspend time * of 5s: * <p/> * <code> * com.netflix.astyanax.connectionpool.impl.FixedRetryBackoffStrategy,1000,5000 * </code> * <p/> * If null, then Astyanax uses its default strategy, which is an * ExponentialRetryBackoffStrategy instance. The instance parameters take * Astyanax's built-in default values, which can be overridden via the * following config keys: * <ul> * <li>{@link #RETRY_DELAY_SLICE}</li> * <li>{@link #RETRY_MAX_DELAY_SLICE}</li> * <li>{@link #RETRY_SUSPEND_WINDOW}</li> * </ul> * <p/> * In Astyanax, RetryPolicy and RetryBackoffStrategy sound and look similar * but are used for distinct purposes. RetryPolicy is for retrying failed * operations. RetryBackoffStrategy is for retrying attempts to talk to * uncommunicative hosts. This config option controls RetryBackoffStrategy. */ public static final ConfigOption<String> RETRY_BACKOFF_STRATEGY = new ConfigOption<String>(ASTYANAX_NS, "retry-backoff-strategy", "Astyanax's retry backoff strategy with configuration parameters", ConfigOption.Type.MASKABLE, "com.netflix.astyanax.connectionpool.impl.FixedRetryBackoffStrategy,1000,5000"); /** * Controls the retryDelaySlice parameter on Astyanax * ConnectionPoolConfigurationImpl objects, which is in turn used by * ExponentialRetryBackoffStrategy. See the code for * {@link ConnectionPoolConfigurationImpl}, * {@link ExponentialRetryBackoffStrategy}, and the javadoc for * {@link #RETRY_BACKOFF_STRATEGY} for more information. * <p/> * This parameter is not meaningful for and has no effect on * FixedRetryBackoffStrategy. */ public static final ConfigOption<Integer> RETRY_DELAY_SLICE = new ConfigOption<Integer>(ASTYANAX_NS, "retry-delay-slice", "Astyanax's connection pool \"retryDelaySlice\" parameter", ConfigOption.Type.MASKABLE, ConnectionPoolConfigurationImpl.DEFAULT_RETRY_DELAY_SLICE); /** * Controls the retryMaxDelaySlice parameter on Astyanax * ConnectionPoolConfigurationImpl objects, which is in turn used by * ExponentialRetryBackoffStrategy. See the code for * {@link ConnectionPoolConfigurationImpl}, * {@link ExponentialRetryBackoffStrategy}, and the javadoc for * {@link #RETRY_BACKOFF_STRATEGY} for more information. * <p/> * This parameter is not meaningful for and has no effect on * FixedRetryBackoffStrategy. */ public static final ConfigOption<Integer> RETRY_MAX_DELAY_SLICE = new ConfigOption<Integer>(ASTYANAX_NS, "retry-max-delay-slice", "Astyanax's connection pool \"retryMaxDelaySlice\" parameter", ConfigOption.Type.MASKABLE, ConnectionPoolConfigurationImpl.DEFAULT_RETRY_MAX_DELAY_SLICE); /** * Controls the retrySuspendWindow parameter on Astyanax * ConnectionPoolConfigurationImpl objects, which is in turn used by * ExponentialRetryBackoffStrategy. See the code for * {@link ConnectionPoolConfigurationImpl}, * {@link ExponentialRetryBackoffStrategy}, and the javadoc for * {@link #RETRY_BACKOFF_STRATEGY} for more information. * <p/> * This parameter is not meaningful for and has no effect on * FixedRetryBackoffStrategy. */ public static final ConfigOption<Integer> RETRY_SUSPEND_WINDOW = new ConfigOption<Integer>(ASTYANAX_NS, "retry-suspend-window", "Astyanax's connection pool \"retryMaxDelaySlice\" parameter", ConfigOption.Type.MASKABLE, ConnectionPoolConfigurationImpl.DEFAULT_RETRY_SUSPEND_WINDOW); private final String clusterName; private final AstyanaxContext<Keyspace> keyspaceContext; private final AstyanaxContext<Cluster> clusterContext; private final RetryPolicy retryPolicy; private final int retryDelaySlice; private final int retryMaxDelaySlice; private final int retrySuspendWindow; private final RetryBackoffStrategy retryBackoffStrategy; private final Map<String, AstyanaxKeyColumnValueStore> openStores; public AstyanaxStoreManager(Configuration config) throws BackendException { super(config); this.clusterName = config.get(CLUSTER_NAME); retryDelaySlice = config.get(RETRY_DELAY_SLICE); retryMaxDelaySlice = config.get(RETRY_MAX_DELAY_SLICE); retrySuspendWindow = config.get(RETRY_SUSPEND_WINDOW); retryBackoffStrategy = getRetryBackoffStrategy(config.get(RETRY_BACKOFF_STRATEGY)); retryPolicy = getRetryPolicy(config.get(RETRY_POLICY)); final int maxConnsPerHost = config.get(MAX_CONNECTIONS_PER_HOST); final int maxClusterConnsPerHost = config.get(MAX_CLUSTER_CONNECTIONS_PER_HOST); this.clusterContext = createCluster(getContextBuilder(config, maxClusterConnsPerHost, "Cluster")); ensureKeyspaceExists(clusterContext.getClient()); this.keyspaceContext = getContextBuilder(config, maxConnsPerHost, "Keyspace").buildKeyspace(ThriftFamilyFactory.getInstance()); this.keyspaceContext.start(); openStores = new HashMap<String, AstyanaxKeyColumnValueStore>(8); } @Override public Deployment getDeployment() { return Deployment.REMOTE; // TODO } @Override @SuppressWarnings("unchecked") public IPartitioner<? extends Token<?>> getCassandraPartitioner() throws BackendException { Cluster cl = clusterContext.getClient(); try { return FBUtilities.newPartitioner(cl.describePartitioner()); } catch (ConnectionException e) { throw new TemporaryBackendException(e); } catch (ConfigurationException e) { throw new PermanentBackendException(e); } } @Override public String toString() { return "astyanax" + super.toString(); } @Override public void close() { // Shutdown the Astyanax contexts openStores.clear(); keyspaceContext.shutdown(); clusterContext.shutdown(); } @Override public synchronized AstyanaxKeyColumnValueStore openDatabase(String name) throws BackendException { if (openStores.containsKey(name)) return openStores.get(name); else { ensureColumnFamilyExists(name); AstyanaxKeyColumnValueStore store = new AstyanaxKeyColumnValueStore(name, keyspaceContext.getClient(), this, retryPolicy); openStores.put(name, store); return store; } } @Override public void mutateMany(Map<String, Map<StaticBuffer, KCVMutation>> batch, StoreTransaction txh) throws BackendException { MutationBatch m = keyspaceContext.getClient().prepareMutationBatch().withAtomicBatch(atomicBatch) .setConsistencyLevel(getTx(txh).getWriteConsistencyLevel().getAstyanax()) .withRetryPolicy(retryPolicy.duplicate()); final MaskedTimestamp commitTime = new MaskedTimestamp(txh); for (Map.Entry<String, Map<StaticBuffer, KCVMutation>> batchentry : batch.entrySet()) { String storeName = batchentry.getKey(); Preconditions.checkArgument(openStores.containsKey(storeName), "Store cannot be found: " + storeName); ColumnFamily<ByteBuffer, ByteBuffer> columnFamily = openStores.get(storeName).getColumnFamily(); Map<StaticBuffer, KCVMutation> mutations = batchentry.getValue(); for (Map.Entry<StaticBuffer, KCVMutation> ent : mutations.entrySet()) { // The CLMs for additions and deletions are separated because // Astyanax's operation timestamp cannot be set on a per-delete // or per-addition basis. KCVMutation titanMutation = ent.getValue(); ByteBuffer key = ent.getKey().asByteBuffer(); if (titanMutation.hasDeletions()) { ColumnListMutation<ByteBuffer> dels = m.withRow(columnFamily, key); dels.setTimestamp(commitTime.getDeletionTime(times.getUnit())); for (StaticBuffer b : titanMutation.getDeletions()) dels.deleteColumn(b.as(StaticBuffer.BB_FACTORY)); } if (titanMutation.hasAdditions()) { ColumnListMutation<ByteBuffer> upds = m.withRow(columnFamily, key); upds.setTimestamp(commitTime.getAdditionTime(times.getUnit())); for (Entry e : titanMutation.getAdditions()) { Integer ttl = (Integer) e.getMetaData().get(EntryMetaData.TTL); if (null != ttl && ttl > 0) { upds.putColumn(e.getColumnAs(StaticBuffer.BB_FACTORY), e.getValueAs(StaticBuffer.BB_FACTORY), ttl); } else { upds.putColumn(e.getColumnAs(StaticBuffer.BB_FACTORY), e.getValueAs(StaticBuffer.BB_FACTORY)); } } } } } try { m.execute(); } catch (ConnectionException e) { throw new TemporaryBackendException(e); } sleepAfterWrite(txh, commitTime); } @Override public List<KeyRange> getLocalKeyPartition() throws BackendException { throw new UnsupportedOperationException(); } @Override public void clearStorage() throws BackendException { try { Cluster cluster = clusterContext.getClient(); Keyspace ks = cluster.getKeyspace(keySpaceName); // Not a big deal if Keyspace doesn't not exist (dropped manually by user or tests). // This is called on per test setup basis to make sure that previous test cleaned // everything up, so first invocation would always fail as Keyspace doesn't yet exist. if (ks == null) return; for (ColumnFamilyDefinition cf : cluster.describeKeyspace(keySpaceName).getColumnFamilyList()) { ks.truncateColumnFamily(new ColumnFamily<Object, Object>(cf.getName(), null, null)); } } catch (ConnectionException e) { throw new PermanentBackendException(e); } } private void ensureColumnFamilyExists(String name) throws BackendException { ensureColumnFamilyExists(name, "org.apache.cassandra.db.marshal.BytesType"); } private void ensureColumnFamilyExists(String name, String comparator) throws BackendException { Cluster cl = clusterContext.getClient(); try { KeyspaceDefinition ksDef = cl.describeKeyspace(keySpaceName); boolean found = false; if (null != ksDef) { for (ColumnFamilyDefinition cfDef : ksDef.getColumnFamilyList()) { found |= cfDef.getName().equals(name); } } if (!found) { ColumnFamilyDefinition cfDef = cl.makeColumnFamilyDefinition() .setName(name) .setKeyspace(keySpaceName) .setComparatorType(comparator); ImmutableMap.Builder<String, String> compressionOptions = new ImmutableMap.Builder<String, String>(); if (compressionEnabled) { compressionOptions.put("sstable_compression", compressionClass) .put("chunk_length_kb", Integer.toString(compressionChunkSizeKB)); } cl.addColumnFamily(cfDef.setCompressionOptions(compressionOptions.build())); } } catch (ConnectionException e) { throw new TemporaryBackendException(e); } } private static AstyanaxContext<Cluster> createCluster(AstyanaxContext.Builder cb) { AstyanaxContext<Cluster> clusterCtx = cb.buildCluster(ThriftFamilyFactory.getInstance()); clusterCtx.start(); return clusterCtx; } private AstyanaxContext.Builder getContextBuilder(Configuration config, int maxConnsPerHost, String usedFor) { final ConnectionPoolType poolType = ConnectionPoolType.valueOf(config.get(CONNECTION_POOL_TYPE)); final NodeDiscoveryType discType = NodeDiscoveryType.valueOf(config.get(NODE_DISCOVERY_TYPE)); final int maxConnections = config.get(MAX_CONNECTIONS); final int maxOperationsPerConnection = config.get(MAX_OPERATIONS_PER_CONNECTION); final int connectionTimeout = (int) connectionTimeoutMS.getLength(TimeUnit.MILLISECONDS); ConnectionPoolConfigurationImpl cpool = new ConnectionPoolConfigurationImpl(usedFor + "TitanConnectionPool") .setPort(port) .setMaxOperationsPerConnection(maxOperationsPerConnection) .setMaxConnsPerHost(maxConnsPerHost) .setRetryDelaySlice(retryDelaySlice) .setRetryMaxDelaySlice(retryMaxDelaySlice) .setRetrySuspendWindow(retrySuspendWindow) .setSocketTimeout(connectionTimeout) .setConnectTimeout(connectionTimeout) .setSeeds(StringUtils.join(hostnames, ",")); if (null != retryBackoffStrategy) { cpool.setRetryBackoffStrategy(retryBackoffStrategy); log.debug("Custom RetryBackoffStrategy {}", cpool.getRetryBackoffStrategy()); } else { log.debug("Default RetryBackoffStrategy {}", cpool.getRetryBackoffStrategy()); } AstyanaxConfigurationImpl aconf = new AstyanaxConfigurationImpl() .setConnectionPoolType(poolType) .setDiscoveryType(discType) .setTargetCassandraVersion("1.2"); if (0 < maxConnections) { cpool.setMaxConns(maxConnections); } if (hasAuthentication()) { cpool.setAuthenticationCredentials(new SimpleAuthenticationCredentials(username, password)); } if (config.get(SSL_ENABLED)) { cpool.setSSLConnectionContext(new SSLConnectionContext(config.get(SSL_TRUSTSTORE_LOCATION), config.get(SSL_TRUSTSTORE_PASSWORD))); } AstyanaxContext.Builder ctxBuilder = new AstyanaxContext.Builder(); // Standard context builder options ctxBuilder .forCluster(clusterName) .forKeyspace(keySpaceName) .withAstyanaxConfiguration(aconf) .withConnectionPoolConfiguration(cpool) .withConnectionPoolMonitor(new CountingConnectionPoolMonitor()); // Conditional context builder option: host supplier if (config.has(HOST_SUPPLIER)) { String hostSupplier = config.get(HOST_SUPPLIER); Supplier<List<Host>> supplier = null; if (hostSupplier != null) { try { supplier = (Supplier<List<Host>>) Class.forName(hostSupplier).newInstance(); ctxBuilder.withHostSupplier(supplier); } catch (Exception e) { log.warn("Problem with host supplier class " + hostSupplier + ", going to use default.", e); } } } return ctxBuilder; } private void ensureKeyspaceExists(Cluster cl) throws BackendException { KeyspaceDefinition ksDef; try { ksDef = cl.describeKeyspace(keySpaceName); if (null != ksDef && ksDef.getName().equals(keySpaceName)) { log.debug("Found keyspace {}", keySpaceName); return; } } catch (ConnectionException e) { log.debug("Failed to describe keyspace {}", keySpaceName); } log.debug("Creating keyspace {}...", keySpaceName); try { ksDef = cl.makeKeyspaceDefinition() .setName(keySpaceName) .setStrategyClass(storageConfig.get(REPLICATION_STRATEGY)) .setStrategyOptions(strategyOptions); cl.addKeyspace(ksDef); log.debug("Created keyspace {}", keySpaceName); } catch (ConnectionException e) { log.debug("Failed to create keyspace {}", keySpaceName); throw new TemporaryBackendException(e); } } private static RetryBackoffStrategy getRetryBackoffStrategy(String desc) throws PermanentBackendException { if (null == desc) return null; String[] tokens = desc.split(","); String policyClassName = tokens[0]; int argCount = tokens.length - 1; Integer[] args = new Integer[argCount]; for (int i = 1; i < tokens.length; i++) { args[i - 1] = Integer.valueOf(tokens[i]); } try { RetryBackoffStrategy rbs = instantiate(policyClassName, args, desc); log.debug("Instantiated RetryBackoffStrategy object {} from config string \"{}\"", rbs, desc); return rbs; } catch (Exception e) { throw new PermanentBackendException("Failed to instantiate Astyanax RetryBackoffStrategy implementation", e); } } private static RetryPolicy getRetryPolicy(String serializedRetryPolicy) throws BackendException { String[] tokens = serializedRetryPolicy.split(","); String policyClassName = tokens[0]; int argCount = tokens.length - 1; Integer[] args = new Integer[argCount]; for (int i = 1; i < tokens.length; i++) { args[i - 1] = Integer.valueOf(tokens[i]); } try { RetryPolicy rp = instantiate(policyClassName, args, serializedRetryPolicy); log.debug("Instantiated RetryPolicy object {} from config string \"{}\"", rp, serializedRetryPolicy); return rp; } catch (Exception e) { throw new PermanentBackendException("Failed to instantiate Astyanax Retry Policy class", e); } } @SuppressWarnings("unchecked") private static <V> V instantiate(String policyClassName, Integer[] args, String raw) throws Exception { for (Constructor<?> con : Class.forName(policyClassName).getConstructors()) { Class<?>[] parameterTypes = con.getParameterTypes(); // match constructor by number of arguments first if (args.length != parameterTypes.length) continue; // check if the constructor parameter types are compatible with argument types (which are integer) // note that we allow long.class arguments too because integer is cast to long by runtime. boolean intsOrLongs = true; for (Class<?> pc : parameterTypes) { if (!pc.equals(int.class) && !pc.equals(long.class)) { intsOrLongs = false; break; } } // we found a constructor with required number of parameters but times didn't match, let's carry on if (!intsOrLongs) continue; if (log.isDebugEnabled()) log.debug("About to instantiate class {} with {} arguments", con.toString(), args.length); return (V) con.newInstance(args); } throw new Exception("Failed to identify a class matching the Astyanax Retry Policy config string \"" + raw + "\""); } @Override public Map<String, String> getCompressionOptions(String cf) throws BackendException { try { Keyspace k = keyspaceContext.getClient(); KeyspaceDefinition kdef = k.describeKeyspace(); if (null == kdef) { throw new PermanentBackendException("Keyspace " + k.getKeyspaceName() + " is undefined"); } ColumnFamilyDefinition cfdef = kdef.getColumnFamily(cf); if (null == cfdef) { throw new PermanentBackendException("Column family " + cf + " is undefined"); } return cfdef.getCompressionOptions(); } catch (ConnectionException e) { throw new PermanentBackendException(e); } } }
0true
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_astyanax_AstyanaxStoreManager.java
892
public class TransportSearchScrollScanAction extends AbstractComponent { private final ThreadPool threadPool; private final ClusterService clusterService; private final SearchServiceTransportAction searchService; private final SearchPhaseController searchPhaseController; @Inject public TransportSearchScrollScanAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController) { super(settings); this.threadPool = threadPool; this.clusterService = clusterService; this.searchService = searchService; this.searchPhaseController = searchPhaseController; } public void execute(SearchScrollRequest request, ParsedScrollId scrollId, ActionListener<SearchResponse> listener) { new AsyncAction(request, scrollId, listener).start(); } private class AsyncAction { private final SearchScrollRequest request; private final ActionListener<SearchResponse> listener; private final ParsedScrollId scrollId; private final DiscoveryNodes nodes; private volatile AtomicArray<ShardSearchFailure> shardFailures; private final AtomicArray<QueryFetchSearchResult> queryFetchResults; private final AtomicInteger successfulOps; private final AtomicInteger counter; private final long startTime = System.currentTimeMillis(); private AsyncAction(SearchScrollRequest request, ParsedScrollId scrollId, ActionListener<SearchResponse> listener) { this.request = request; this.listener = listener; this.scrollId = scrollId; this.nodes = clusterService.state().nodes(); this.successfulOps = new AtomicInteger(scrollId.getContext().length); this.counter = new AtomicInteger(scrollId.getContext().length); this.queryFetchResults = new AtomicArray<QueryFetchSearchResult>(scrollId.getContext().length); } protected final ShardSearchFailure[] buildShardFailures() { if (shardFailures == null) { return ShardSearchFailure.EMPTY_ARRAY; } List<AtomicArray.Entry<ShardSearchFailure>> entries = shardFailures.asList(); ShardSearchFailure[] failures = new ShardSearchFailure[entries.size()]; for (int i = 0; i < failures.length; i++) { failures[i] = entries.get(i).value; } return failures; } // we do our best to return the shard failures, but its ok if its not fully concurrently safe // we simply try and return as much as possible protected final void addShardFailure(final int shardIndex, ShardSearchFailure failure) { if (shardFailures == null) { shardFailures = new AtomicArray<ShardSearchFailure>(scrollId.getContext().length); } shardFailures.set(shardIndex, failure); } public void start() { if (scrollId.getContext().length == 0) { final InternalSearchResponse internalResponse = new InternalSearchResponse(new InternalSearchHits(InternalSearchHits.EMPTY, Long.parseLong(this.scrollId.getAttributes().get("total_hits")), 0.0f), null, null, null, false); listener.onResponse(new SearchResponse(internalResponse, request.scrollId(), 0, 0, 0l, buildShardFailures())); return; } int localOperations = 0; Tuple<String, Long>[] context = scrollId.getContext(); for (int i = 0; i < context.length; i++) { Tuple<String, Long> target = context[i]; DiscoveryNode node = nodes.get(target.v1()); if (node != null) { if (nodes.localNodeId().equals(node.id())) { localOperations++; } else { executePhase(i, node, target.v2()); } } else { if (logger.isDebugEnabled()) { logger.debug("Node [" + target.v1() + "] not available for scroll request [" + scrollId.getSource() + "]"); } successfulOps.decrementAndGet(); if (counter.decrementAndGet() == 0) { finishHim(); } } } if (localOperations > 0) { if (request.operationThreading() == SearchOperationThreading.SINGLE_THREAD) { threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() { @Override public void run() { Tuple<String, Long>[] context1 = scrollId.getContext(); for (int i = 0; i < context1.length; i++) { Tuple<String, Long> target = context1[i]; DiscoveryNode node = nodes.get(target.v1()); if (node != null && nodes.localNodeId().equals(node.id())) { executePhase(i, node, target.v2()); } } } }); } else { boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD; Tuple<String, Long>[] context1 = scrollId.getContext(); for (int i = 0; i < context1.length; i++) { final Tuple<String, Long> target = context1[i]; final int shardIndex = i; final DiscoveryNode node = nodes.get(target.v1()); if (node != null && nodes.localNodeId().equals(node.id())) { try { if (localAsync) { threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() { @Override public void run() { executePhase(shardIndex, node, target.v2()); } }); } else { executePhase(shardIndex, node, target.v2()); } } catch (Throwable t) { onPhaseFailure(t, target.v2(), shardIndex); } } } } } for (Tuple<String, Long> target : scrollId.getContext()) { DiscoveryNode node = nodes.get(target.v1()); if (node == null) { if (logger.isDebugEnabled()) { logger.debug("Node [" + target.v1() + "] not available for scroll request [" + scrollId.getSource() + "]"); } successfulOps.decrementAndGet(); if (counter.decrementAndGet() == 0) { finishHim(); } } else { } } } void executePhase(final int shardIndex, DiscoveryNode node, final long searchId) { searchService.sendExecuteScan(node, internalScrollSearchRequest(searchId, request), new SearchServiceListener<QueryFetchSearchResult>() { @Override public void onResult(QueryFetchSearchResult result) { queryFetchResults.set(shardIndex, result); if (counter.decrementAndGet() == 0) { finishHim(); } } @Override public void onFailure(Throwable t) { onPhaseFailure(t, searchId, shardIndex); } }); } void onPhaseFailure(Throwable t, long searchId, int shardIndex) { if (logger.isDebugEnabled()) { logger.debug("[{}] Failed to execute query phase", t, searchId); } addShardFailure(shardIndex, new ShardSearchFailure(t)); successfulOps.decrementAndGet(); if (counter.decrementAndGet() == 0) { finishHim(); } } private void finishHim() { try { innerFinishHim(); } catch (Throwable e) { ReduceSearchPhaseException failure = new ReduceSearchPhaseException("fetch", "", e, buildShardFailures()); if (logger.isDebugEnabled()) { logger.debug("failed to reduce search", failure); } listener.onFailure(failure); } } private void innerFinishHim() throws IOException { int numberOfHits = 0; for (AtomicArray.Entry<QueryFetchSearchResult> entry : queryFetchResults.asList()) { numberOfHits += entry.value.queryResult().topDocs().scoreDocs.length; } ScoreDoc[] docs = new ScoreDoc[numberOfHits]; int counter = 0; for (AtomicArray.Entry<QueryFetchSearchResult> entry : queryFetchResults.asList()) { ScoreDoc[] scoreDocs = entry.value.queryResult().topDocs().scoreDocs; for (ScoreDoc scoreDoc : scoreDocs) { scoreDoc.shardIndex = entry.index; docs[counter++] = scoreDoc; } } final InternalSearchResponse internalResponse = searchPhaseController.merge(docs, queryFetchResults, queryFetchResults); ((InternalSearchHits) internalResponse.hits()).totalHits = Long.parseLong(this.scrollId.getAttributes().get("total_hits")); for (AtomicArray.Entry<QueryFetchSearchResult> entry : queryFetchResults.asList()) { if (entry.value.queryResult().topDocs().scoreDocs.length < entry.value.queryResult().size()) { // we found more than we want for this round, remove this from our scrolling queryFetchResults.set(entry.index, null); } } String scrollId = null; if (request.scroll() != null) { // we rebuild the scroll id since we remove shards that we finished scrolling on scrollId = TransportSearchHelper.buildScrollId(this.scrollId.getType(), queryFetchResults, this.scrollId.getAttributes()); // continue moving the total_hits } listener.onResponse(new SearchResponse(internalResponse, scrollId, this.scrollId.getContext().length, successfulOps.get(), System.currentTimeMillis() - startTime, buildShardFailures())); } } }
0true
src_main_java_org_elasticsearch_action_search_type_TransportSearchScrollScanAction.java
157
private static class MockedFileChannel extends StoreFileChannel { private ByteBuffer bs; public MockedFileChannel(byte [] bs) { super( (FileChannel) null ); this.bs = ByteBuffer.wrap(bs); } @Override public long position() throws IOException { return bs.position(); } @Override public int read(ByteBuffer buffer) throws IOException { int start = bs.position(); buffer.put(bs); return bs.position() - start; } @Override public void close() throws IOException { } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestXaLogicalLogFiles.java
793
public class PercolateRequest extends BroadcastOperationRequest<PercolateRequest> { public static final XContentType contentType = Requests.CONTENT_TYPE; private String documentType; private String routing; private String preference; private GetRequest getRequest; private boolean onlyCount; private BytesReference source; private boolean unsafe; private BytesReference docSource; // Used internally in order to compute tookInMillis, TransportBroadcastOperationAction itself doesn't allow // to hold it temporarily in an easy way long startTime; public PercolateRequest() { } public PercolateRequest(PercolateRequest request, BytesReference docSource) { super(request.indices()); operationThreading(request.operationThreading()); this.documentType = request.documentType(); this.routing = request.routing(); this.preference = request.preference(); this.source = request.source; this.docSource = docSource; this.onlyCount = request.onlyCount; this.startTime = request.startTime; } public String documentType() { return documentType; } public void documentType(String type) { this.documentType = type; } public String routing() { return routing; } public PercolateRequest routing(String routing) { this.routing = routing; return this; } public String preference() { return preference; } public PercolateRequest preference(String preference) { this.preference = preference; return this; } public GetRequest getRequest() { return getRequest; } public void getRequest(GetRequest getRequest) { this.getRequest = getRequest; } /** * Before we fork on a local thread, make sure we copy over the bytes if they are unsafe */ @Override public void beforeLocalFork() { if (unsafe) { source = source.copyBytesArray(); unsafe = false; } } public BytesReference source() { return source; } public PercolateRequest source(Map document) throws ElasticsearchGenerationException { return source(document, contentType); } public PercolateRequest source(Map document, XContentType contentType) throws ElasticsearchGenerationException { try { XContentBuilder builder = XContentFactory.contentBuilder(contentType); builder.map(document); return source(builder); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + document + "]", e); } } public PercolateRequest source(String document) { this.source = new BytesArray(document); this.unsafe = false; return this; } public PercolateRequest source(XContentBuilder documentBuilder) { source = documentBuilder.bytes(); unsafe = false; return this; } public PercolateRequest source(byte[] document) { return source(document, 0, document.length); } public PercolateRequest source(byte[] source, int offset, int length) { return source(source, offset, length, false); } public PercolateRequest source(byte[] source, int offset, int length, boolean unsafe) { return source(new BytesArray(source, offset, length), unsafe); } public PercolateRequest source(BytesReference source, boolean unsafe) { this.source = source; this.unsafe = unsafe; return this; } public PercolateRequest source(PercolateSourceBuilder sourceBuilder) { this.source = sourceBuilder.buildAsBytes(contentType); this.unsafe = false; return this; } public boolean onlyCount() { return onlyCount; } public void onlyCount(boolean onlyCount) { this.onlyCount = onlyCount; } BytesReference docSource() { return docSource; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); if (documentType == null) { validationException = addValidationError("type is missing", validationException); } if (source == null && getRequest == null) { validationException = addValidationError("source or get is missing", validationException); } if (getRequest != null && getRequest.fields() != null) { validationException = addValidationError("get fields option isn't supported via percolate request", validationException); } return validationException; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); startTime = in.readVLong(); documentType = in.readString(); routing = in.readOptionalString(); preference = in.readOptionalString(); unsafe = false; source = in.readBytesReference(); docSource = in.readBytesReference(); if (in.readBoolean()) { getRequest = new GetRequest(null); getRequest.readFrom(in); } onlyCount = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVLong(startTime); out.writeString(documentType); out.writeOptionalString(routing); out.writeOptionalString(preference); out.writeBytesReference(source); out.writeBytesReference(docSource); if (getRequest != null) { out.writeBoolean(true); getRequest.writeTo(out); } else { out.writeBoolean(false); } out.writeBoolean(onlyCount); } }
0true
src_main_java_org_elasticsearch_action_percolate_PercolateRequest.java
1,579
public class BatchPersistencePackage implements Serializable { protected PersistencePackage[] persistencePackages; public PersistencePackage[] getPersistencePackages() { return persistencePackages; } public void setPersistencePackages(PersistencePackage[] persistencePackages) { this.persistencePackages = persistencePackages; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof BatchPersistencePackage)) return false; BatchPersistencePackage that = (BatchPersistencePackage) o; if (!Arrays.equals(persistencePackages, that.persistencePackages)) return false; return true; } @Override public int hashCode() { return persistencePackages != null ? Arrays.hashCode(persistencePackages) : 0; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_BatchPersistencePackage.java
999
public class AvailableRequest extends SemaphoreRequest implements RetryableRequest { public AvailableRequest() { } public AvailableRequest(String name) { super(name, -1); } @Override protected Operation prepareOperation() { return new AvailableOperation(name); } @Override public int getClassId() { return SemaphorePortableHook.AVAILABLE; } @Override public Permission getRequiredPermission() { return new SemaphorePermission(name, ActionConstants.ACTION_READ); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_semaphore_client_AvailableRequest.java
89
private final class ConnectionListenerImpl implements ConnectionListener { @Override public void connectionAdded(Connection conn) { //no-op //unfortunately we can't do the endpoint creation here, because this event is only called when the //connection is bound, but we need to use the endpoint connection before that. } @Override public void connectionRemoved(Connection connection) { if (connection.isClient() && connection instanceof TcpIpConnection && nodeEngine.isActive()) { ClientEndpoint endpoint = endpoints.get(connection); if (endpoint == null) { return; } String localMemberUuid = node.getLocalMember().getUuid(); String ownerUuid = endpoint.getPrincipal().getOwnerUuid(); if (localMemberUuid.equals(ownerUuid)) { doRemoveEndpoint(connection, endpoint); } } } private void doRemoveEndpoint(Connection connection, ClientEndpoint endpoint) { removeEndpoint(connection, true); if (!endpoint.isFirstConnection()) { return; } NodeEngine nodeEngine = node.nodeEngine; Collection<MemberImpl> memberList = nodeEngine.getClusterService().getMemberList(); OperationService operationService = nodeEngine.getOperationService(); for (MemberImpl member : memberList) { ClientDisconnectionOperation op = new ClientDisconnectionOperation(endpoint.getUuid()); op.setNodeEngine(nodeEngine) .setServiceName(SERVICE_NAME) .setService(ClientEngineImpl.this) .setResponseHandler(createEmptyResponseHandler()); if (member.localMember()) { operationService.runOperationOnCallingThread(op); } else { operationService.send(op, member.getAddress()); } } } }
1no label
hazelcast_src_main_java_com_hazelcast_client_ClientEngineImpl.java
393
public class ClusterSearchShardsGroup implements Streamable, ToXContent { private String index; private int shardId; ShardRouting[] shards; ClusterSearchShardsGroup() { } public ClusterSearchShardsGroup(String index, int shardId, ShardRouting[] shards) { this.index = index; this.shardId = shardId; this.shards = shards; } public static ClusterSearchShardsGroup readSearchShardsGroupResponse(StreamInput in) throws IOException { ClusterSearchShardsGroup response = new ClusterSearchShardsGroup(); response.readFrom(in); return response; } public String getIndex() { return index; } public int getShardId() { return shardId; } public ShardRouting[] getShards() { return shards; } @Override public void readFrom(StreamInput in) throws IOException { index = in.readString(); shardId = in.readVInt(); shards = new ShardRouting[in.readVInt()]; for (int i = 0; i < shards.length; i++) { shards[i] = ImmutableShardRouting.readShardRoutingEntry(in, index, shardId); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(index); out.writeVInt(shardId); out.writeVInt(shards.length); for (ShardRouting shardRouting : shards) { shardRouting.writeToThin(out); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startArray(); for (ShardRouting shard : getShards()) { shard.toXContent(builder, params); } builder.endArray(); return builder; } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_shards_ClusterSearchShardsGroup.java
1,165
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_GIFT_CARD_PAYMENT") public class GiftCardPaymentInfoImpl implements GiftCardPaymentInfo { private static final long serialVersionUID = 1L; protected GiftCardPaymentInfoImpl() { // do not allow direct instantiation -- must at least be package private // for bytecode instrumentation // this complies with JPA specification requirements for entity // construction } @Transient protected EncryptionModule encryptionModule; @Id @GeneratedValue(generator = "GiftCardPaymentId") @GenericGenerator( name="GiftCardPaymentId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="GiftCardPaymentInfoImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.payment.domain.GiftCardPaymentInfoImpl") } ) @Column(name = "PAYMENT_ID") protected Long id; @Column(name = "REFERENCE_NUMBER", nullable = false) @Index(name="GIFTCARD_INDEX", columnNames={"REFERENCE_NUMBER"}) protected String referenceNumber; @Column(name = "PAN", nullable = false) protected String pan; @Column(name = "PIN") protected String pin; @Override public Long getId() { return id; } @Override public String getPan() { return encryptionModule.decrypt(pan); } @Override public String getPin() { return encryptionModule.decrypt(pin); } @Override public void setId(Long id) { this.id = id; } @Override public void setPan(String pan) { this.pan = encryptionModule.encrypt(pan); } @Override public void setPin(String pin) { this.pin = encryptionModule.encrypt(pin); } @Override public String getReferenceNumber() { return referenceNumber; } @Override public void setReferenceNumber(String referenceNumber) { this.referenceNumber = referenceNumber; } @Override public EncryptionModule getEncryptionModule() { return encryptionModule; } @Override public void setEncryptionModule(EncryptionModule encryptionModule) { this.encryptionModule = encryptionModule; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((pan == null) ? 0 : pan.hashCode()); result = prime * result + ((pin == null) ? 0 : pin.hashCode()); result = prime * result + ((referenceNumber == null) ? 0 : referenceNumber.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; GiftCardPaymentInfoImpl other = (GiftCardPaymentInfoImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (pan == null) { if (other.pan != null) return false; } else if (!pan.equals(other.pan)) return false; if (pin == null) { if (other.pin != null) return false; } else if (!pin.equals(other.pin)) return false; if (referenceNumber == null) { if (other.referenceNumber != null) return false; } else if (!referenceNumber.equals(other.referenceNumber)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_domain_GiftCardPaymentInfoImpl.java
2,647
public interface UnicastHostsProvider { /** * Builds the dynamic list of unicast hosts to be used for unicast discovery. */ List<DiscoveryNode> buildDynamicNodes(); }
0true
src_main_java_org_elasticsearch_discovery_zen_ping_unicast_UnicastHostsProvider.java
2,308
public abstract class Rounding implements Streamable { public abstract byte id(); /** * Given a value, compute a key that uniquely identifies the rounded value although it is not necessarily equal to the rounding value itself. */ public abstract long roundKey(long value); /** * Compute the rounded value given the key that identifies it. */ public abstract long valueForKey(long key); /** * Rounds the given value, equivalent to calling <code>roundValue(roundKey(value))</code>. * * @param value The value to round. * @return The rounded value. */ public final long round(long value) { return valueForKey(roundKey(value)); } /** * Given the rounded value (which was potentially generated by {@link #round(long)}, returns the next rounding value. For example, with * interval based rounding, if the interval is 3, {@code nextRoundValue(6) = 9 }. * * @param value The current rounding value * @return The next rounding value; */ public abstract long nextRoundingValue(long value); /** * Rounding strategy which is based on an interval * * {@code rounded = value - (value % interval) } */ public static class Interval extends Rounding { final static byte ID = 0; private long interval; public Interval() { // for serialization } /** * Creates a new interval rounding. * * @param interval The interval */ public Interval(long interval) { this.interval = interval; } @Override public byte id() { return ID; } public static long roundKey(long value, long interval) { if (value < 0) { return (value - interval + 1) / interval; } else { return value / interval; } } public static long roundValue(long key, long interval) { return key * interval; } @Override public long roundKey(long value) { return roundKey(value, interval); } @Override public long valueForKey(long key) { return key * interval; } @Override public long nextRoundingValue(long value) { assert value == round(value); return value + interval; } @Override public void readFrom(StreamInput in) throws IOException { interval = in.readVLong(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVLong(interval); } } public static class Streams { public static void write(Rounding rounding, StreamOutput out) throws IOException { out.writeByte(rounding.id()); rounding.writeTo(out); } public static Rounding read(StreamInput in) throws IOException { Rounding rounding = null; byte id = in.readByte(); switch (id) { case Interval.ID: rounding = new Interval(); break; case TimeZoneRounding.TimeTimeZoneRoundingFloor.ID: rounding = new TimeZoneRounding.TimeTimeZoneRoundingFloor(); break; case TimeZoneRounding.UTCTimeZoneRoundingFloor.ID: rounding = new TimeZoneRounding.UTCTimeZoneRoundingFloor(); break; case TimeZoneRounding.DayTimeZoneRoundingFloor.ID: rounding = new TimeZoneRounding.DayTimeZoneRoundingFloor(); break; case TimeZoneRounding.UTCIntervalTimeZoneRounding.ID: rounding = new TimeZoneRounding.UTCIntervalTimeZoneRounding(); break; case TimeZoneRounding.TimeIntervalTimeZoneRounding.ID: rounding = new TimeZoneRounding.TimeIntervalTimeZoneRounding(); break; case TimeZoneRounding.DayIntervalTimeZoneRounding.ID: rounding = new TimeZoneRounding.DayIntervalTimeZoneRounding(); break; case TimeZoneRounding.FactorTimeZoneRounding.ID: rounding = new TimeZoneRounding.FactorTimeZoneRounding(); break; case TimeZoneRounding.PrePostTimeZoneRounding.ID: rounding = new TimeZoneRounding.PrePostTimeZoneRounding(); break; default: throw new ElasticsearchException("unknown rounding id [" + id + "]"); } rounding.readFrom(in); return rounding; } } }
0true
src_main_java_org_elasticsearch_common_rounding_Rounding.java
1,144
public class ValidateRemoveRequestActivity extends BaseActivity<CartOperationContext> { @Resource(name = "blOrderItemService") protected OrderItemService orderItemService; @Override public CartOperationContext execute(CartOperationContext context) throws Exception { CartOperationRequest request = context.getSeedData(); OrderItemRequestDTO orderItemRequestDTO = request.getItemRequest(); // Throw an exception if the user did not specify an orderItemId if (orderItemRequestDTO.getOrderItemId() == null) { throw new IllegalArgumentException("OrderItemId must be specified when removing from order"); } // Throw an exception if the user did not specify an order to add the item to if (request.getOrder() == null) { throw new IllegalArgumentException("Order is required when updating item quantities"); } // Throw an exception if the user is trying to remove an order item that is part of a bundle OrderItem orderItem = orderItemService.readOrderItemById(orderItemRequestDTO.getOrderItemId()); if (orderItem != null && orderItem instanceof DiscreteOrderItem) { DiscreteOrderItem doi = (DiscreteOrderItem) orderItem; if (doi.getBundleOrderItem() != null) { throw new IllegalArgumentException("Cannot remove an item that is part of a bundle"); } } return context; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_workflow_remove_ValidateRemoveRequestActivity.java
3,308
static class Empty extends DoubleArrayAtomicFieldData { Empty(int numDocs) { super(numDocs); } @Override public LongValues getLongValues() { return LongValues.EMPTY; } @Override public DoubleValues getDoubleValues() { return DoubleValues.EMPTY; } @Override public boolean isMultiValued() { return false; } @Override public boolean isValuesOrdered() { return false; } @Override public long getNumberUniqueValues() { return 0; } @Override public long getMemorySizeInBytes() { return 0; } @Override public BytesValues getBytesValues(boolean needsHashes) { return BytesValues.EMPTY; } @Override public ScriptDocValues getScriptValues() { return ScriptDocValues.EMPTY; } }
1no label
src_main_java_org_elasticsearch_index_fielddata_plain_DoubleArrayAtomicFieldData.java
2,564
master.clusterService.submitStateUpdateTask("local-disco-update", new ClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { DiscoveryNodes newNodes = currentState.nodes().removeDeadMembers(newMembers, master.localNode.id()); DiscoveryNodes.Delta delta = newNodes.delta(currentState.nodes()); if (delta.added()) { logger.warn("No new nodes should be created when a new discovery view is accepted"); } // reroute here, so we eagerly remove dead nodes from the routing ClusterState updatedState = ClusterState.builder(currentState).nodes(newNodes).build(); RoutingAllocation.Result routingResult = master.allocationService.reroute(ClusterState.builder(updatedState).build()); return ClusterState.builder(updatedState).routingResult(routingResult).build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } });
1no label
src_main_java_org_elasticsearch_discovery_local_LocalDiscovery.java
3,075
public class DeleteFailedEngineException extends EngineException { public DeleteFailedEngineException(ShardId shardId, Engine.Delete delete, Throwable cause) { super(shardId, "Delete failed for [" + delete.uid().text() + "]", cause); } }
0true
src_main_java_org_elasticsearch_index_engine_DeleteFailedEngineException.java
259
@TestMethodProviders({ LuceneJUnit3MethodProvider.class, JUnit4MethodProvider.class }) @Listeners({ ReproduceInfoPrinter.class }) @RunWith(value = com.carrotsearch.randomizedtesting.RandomizedRunner.class) @SuppressCodecs(value = "Lucene3x") // NOTE: this class is in o.a.lucene.util since it uses some classes that are related // to the test framework that didn't make sense to copy but are package private access public abstract class AbstractRandomizedTest extends RandomizedTest { /** * Annotation for integration tests */ @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @TestGroup(enabled = true, sysProperty = SYSPROP_INTEGRATION) public @interface IntegrationTests { } // -------------------------------------------------------------------- // Test groups, system properties and other annotations modifying tests // -------------------------------------------------------------------- /** * @see #ignoreAfterMaxFailures */ public static final String SYSPROP_MAXFAILURES = "tests.maxfailures"; /** * @see #ignoreAfterMaxFailures */ public static final String SYSPROP_FAILFAST = "tests.failfast"; public static final String SYSPROP_INTEGRATION = "tests.integration"; // ----------------------------------------------------------------- // Truly immutable fields and constants, initialized once and valid // for all suites ever since. // ----------------------------------------------------------------- /** * Use this constant when creating Analyzers and any other version-dependent stuff. * <p><b>NOTE:</b> Change this when development starts for new Lucene version: */ public static final Version TEST_VERSION_CURRENT = Lucene.VERSION; /** * True if and only if tests are run in verbose mode. If this flag is false * tests are not expected to print any messages. */ public static final boolean VERBOSE = systemPropertyAsBoolean("tests.verbose", false); /** * A random multiplier which you should use when writing random tests: * multiply it by the number of iterations to scale your tests (for nightly builds). */ public static final int RANDOM_MULTIPLIER = systemPropertyAsInt("tests.multiplier", 1); /** * TODO: javadoc? */ public static final String DEFAULT_LINE_DOCS_FILE = "europarl.lines.txt.gz"; /** * the line file used by LineFileDocs */ public static final String TEST_LINE_DOCS_FILE = System.getProperty("tests.linedocsfile", DEFAULT_LINE_DOCS_FILE); /** * Create indexes in this directory, optimally use a subdir, named after the test */ public static final File TEMP_DIR; static { String s = System.getProperty("tempDir", System.getProperty("java.io.tmpdir")); if (s == null) throw new RuntimeException("To run tests, you need to define system property 'tempDir' or 'java.io.tmpdir'."); TEMP_DIR = new File(s); TEMP_DIR.mkdirs(); } /** * These property keys will be ignored in verification of altered properties. * * @see SystemPropertiesInvariantRule * @see #ruleChain * @see #classRules */ private static final String[] IGNORED_INVARIANT_PROPERTIES = { "user.timezone", "java.rmi.server.randomIDs", "sun.nio.ch.bugLevel" }; // ----------------------------------------------------------------- // Fields initialized in class or instance rules. // ----------------------------------------------------------------- // ----------------------------------------------------------------- // Class level (suite) rules. // ----------------------------------------------------------------- /** * Stores the currently class under test. */ private static final TestRuleStoreClassName classNameRule; /** * Class environment setup rule. */ static final TestRuleSetupAndRestoreClassEnv classEnvRule; /** * Suite failure marker (any error in the test or suite scope). */ public final static TestRuleMarkFailure suiteFailureMarker = new TestRuleMarkFailure(); /** * Ignore tests after hitting a designated number of initial failures. This * is truly a "static" global singleton since it needs to span the lifetime of all * test classes running inside this JVM (it cannot be part of a class rule). * <p/> * <p>This poses some problems for the test framework's tests because these sometimes * trigger intentional failures which add up to the global count. This field contains * a (possibly) changing reference to {@link TestRuleIgnoreAfterMaxFailures} and we * dispatch to its current value from the {@link #classRules} chain using {@link TestRuleDelegate}. */ private static final AtomicReference<TestRuleIgnoreAfterMaxFailures> ignoreAfterMaxFailuresDelegate; private static final TestRule ignoreAfterMaxFailures; static { int maxFailures = systemPropertyAsInt(SYSPROP_MAXFAILURES, Integer.MAX_VALUE); boolean failFast = systemPropertyAsBoolean(SYSPROP_FAILFAST, false); if (failFast) { if (maxFailures == Integer.MAX_VALUE) { maxFailures = 1; } else { Logger.getLogger(LuceneTestCase.class.getSimpleName()).warning( "Property '" + SYSPROP_MAXFAILURES + "'=" + maxFailures + ", 'failfast' is" + " ignored."); } } ignoreAfterMaxFailuresDelegate = new AtomicReference<TestRuleIgnoreAfterMaxFailures>( new TestRuleIgnoreAfterMaxFailures(maxFailures)); ignoreAfterMaxFailures = TestRuleDelegate.of(ignoreAfterMaxFailuresDelegate); } /** * Temporarily substitute the global {@link TestRuleIgnoreAfterMaxFailures}. See * {@link #ignoreAfterMaxFailuresDelegate} for some explanation why this method * is needed. */ public static TestRuleIgnoreAfterMaxFailures replaceMaxFailureRule(TestRuleIgnoreAfterMaxFailures newValue) { return ignoreAfterMaxFailuresDelegate.getAndSet(newValue); } /** * Max 10mb of static data stored in a test suite class after the suite is complete. * Prevents static data structures leaking and causing OOMs in subsequent tests. */ private final static long STATIC_LEAK_THRESHOLD = 10 * 1024 * 1024; /** * By-name list of ignored types like loggers etc. */ private final static Set<String> STATIC_LEAK_IGNORED_TYPES = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList( EnumSet.class.getName()))); private final static Set<Class<?>> TOP_LEVEL_CLASSES = Collections.unmodifiableSet(new HashSet<Class<?>>(Arrays.asList( AbstractRandomizedTest.class, LuceneTestCase.class, ElasticsearchIntegrationTest.class, ElasticsearchTestCase.class))); /** * This controls how suite-level rules are nested. It is important that _all_ rules declared * in {@link LuceneTestCase} are executed in proper order if they depend on each * other. */ @ClassRule public static TestRule classRules = RuleChain .outerRule(new TestRuleIgnoreTestSuites()) .around(ignoreAfterMaxFailures) .around(suiteFailureMarker) .around(new TestRuleAssertionsRequired()) .around(new StaticFieldsInvariantRule(STATIC_LEAK_THRESHOLD, true) { @Override protected boolean accept(java.lang.reflect.Field field) { // Don't count known classes that consume memory once. if (STATIC_LEAK_IGNORED_TYPES.contains(field.getType().getName())) { return false; } // Don't count references from ourselves, we're top-level. if (TOP_LEVEL_CLASSES.contains(field.getDeclaringClass())) { return false; } return super.accept(field); } }) .around(new NoClassHooksShadowingRule()) .around(new NoInstanceHooksOverridesRule() { @Override protected boolean verify(Method key) { String name = key.getName(); return !(name.equals("setUp") || name.equals("tearDown")); } }) .around(new SystemPropertiesInvariantRule(IGNORED_INVARIANT_PROPERTIES)) .around(classNameRule = new TestRuleStoreClassName()) .around(classEnvRule = new TestRuleSetupAndRestoreClassEnv()); // ----------------------------------------------------------------- // Test level rules. // ----------------------------------------------------------------- /** * Enforces {@link #setUp()} and {@link #tearDown()} calls are chained. */ private TestRuleSetupTeardownChained parentChainCallRule = new TestRuleSetupTeardownChained(); /** * Save test thread and name. */ private TestRuleThreadAndTestName threadAndTestNameRule = new TestRuleThreadAndTestName(); /** * Taint suite result with individual test failures. */ private TestRuleMarkFailure testFailureMarker = new TestRuleMarkFailure(suiteFailureMarker); /** * This controls how individual test rules are nested. It is important that * _all_ rules declared in {@link LuceneTestCase} are executed in proper order * if they depend on each other. */ @Rule public final TestRule ruleChain = RuleChain .outerRule(testFailureMarker) .around(ignoreAfterMaxFailures) .around(threadAndTestNameRule) .around(new SystemPropertiesInvariantRule(IGNORED_INVARIANT_PROPERTIES)) .around(new TestRuleSetupAndRestoreInstanceEnv()) .around(new TestRuleFieldCacheSanity()) .around(parentChainCallRule); // ----------------------------------------------------------------- // Suite and test case setup/ cleanup. // ----------------------------------------------------------------- /** * For subclasses to override. Overrides must call {@code super.setUp()}. */ @Before public void setUp() throws Exception { parentChainCallRule.setupCalled = true; } /** * For subclasses to override. Overrides must call {@code super.tearDown()}. */ @After public void tearDown() throws Exception { parentChainCallRule.teardownCalled = true; } // ----------------------------------------------------------------- // Test facilities and facades for subclasses. // ----------------------------------------------------------------- /** * Registers a {@link Closeable} resource that should be closed after the test * completes. * * @return <code>resource</code> (for call chaining). */ public <T extends Closeable> T closeAfterTest(T resource) { return RandomizedContext.current().closeAtEnd(resource, LifecycleScope.TEST); } /** * Registers a {@link Closeable} resource that should be closed after the suite * completes. * * @return <code>resource</code> (for call chaining). */ public static <T extends Closeable> T closeAfterSuite(T resource) { return RandomizedContext.current().closeAtEnd(resource, LifecycleScope.SUITE); } /** * Return the current class being tested. */ public static Class<?> getTestClass() { return classNameRule.getTestClass(); } /** * Return the name of the currently executing test case. */ public String getTestName() { return threadAndTestNameRule.testMethodName; } }
0true
src_test_java_org_apache_lucene_util_AbstractRandomizedTest.java
1,265
public class PricingContext implements ProcessContext { public final static long serialVersionUID = 1L; private boolean stopEntireProcess = false; private Order seedData; public void setSeedData(Object seedObject) { seedData = (Order)seedObject; } public boolean stopProcess() { this.stopEntireProcess = true; return stopEntireProcess; } public boolean isStopped() { return stopEntireProcess; } public Order getSeedData(){ return seedData; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_workflow_PricingContext.java
107
static final class ValuesView<K,V> extends CollectionView<K,V,V> implements Collection<V>, java.io.Serializable { private static final long serialVersionUID = 2249069246763182397L; ValuesView(ConcurrentHashMapV8<K,V> map) { super(map); } public final boolean contains(Object o) { return map.containsValue(o); } public final boolean remove(Object o) { if (o != null) { for (Iterator<V> it = iterator(); it.hasNext();) { if (o.equals(it.next())) { it.remove(); return true; } } } return false; } public final Iterator<V> iterator() { ConcurrentHashMapV8<K,V> m = map; Node<K,V>[] t; int f = (t = m.table) == null ? 0 : t.length; return new ValueIterator<K,V>(t, f, 0, f, m); } public final boolean add(V e) { throw new UnsupportedOperationException(); } public final boolean addAll(Collection<? extends V> c) { throw new UnsupportedOperationException(); } public ConcurrentHashMapSpliterator<V> spliteratorJSR166() { Node<K,V>[] t; ConcurrentHashMapV8<K,V> m = map; long n = m.sumCount(); int f = (t = m.table) == null ? 0 : t.length; return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n); } public void forEach(Action<? super V> action) { if (action == null) throw new NullPointerException(); Node<K,V>[] t; if ((t = map.table) != null) { Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length); for (Node<K,V> p; (p = it.advance()) != null; ) action.apply(p.val); } } }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
14
public interface FeedDataArchive { /** * This api will put data into the archive. * * @param feedID the feedID from which the data should be archived. * @param timeUnit the time unit of the time stamp of each data record that is put into the * archive. * @param entries a map from timestamp to data record. * @throws BufferFullException - Buffer full exception. */ public void putData(String feedID, TimeUnit timeUnit, Map<Long, Map<String, String>> entries) throws BufferFullException; /** * This api will put data into the archive. * @param feedID the feedID from which the data should be archived. * @param timeUnit the time unit of the time stamp of each data record that is put into the * archive. * @param time the timestamp of the data record. * @param value the data record to be saved in the archive that corresponds to the time. * @throws BufferFullException - Buffer full exception. */ public void putData(String feedID, TimeUnit timeUnit, long time, Map<String, String> value) throws BufferFullException; /** * This method accepts a set of data and will invoke the runnable once all the data has * been persisted. * @param value for the set of data, feedId is the key for the Map based on key of time * @param timeUnit the time unit of the time stamp of each data record that is put into the * archive. * @param callback to execute when the data has been committed to the repository * @throws BufferFullException - Buffer full exception. */ public void putData(Map<String,Map<Long, Map<String, String>>> value, TimeUnit timeUnit, Runnable callback) throws BufferFullException; /** * Reset the Feed Aggregator so that the content provided by the Feed Aggregator starts from the very beginning. */ public void reset(); }
0true
mctcore_src_main_java_gov_nasa_arc_mct_api_feed_FeedDataArchive.java
1,216
public class CeylonCompilationError implements Diagnostic<JavaFileObject> { private final AnalysisMessage err; private final IProject project; private final JavaFileObject jf; private final IFile file; public CeylonCompilationError(IProject proj, AnalysisMessage error) { err = error; this.project = proj; file = project.getFile(err.getTreeNode().getUnit().getFullPath()); jf = new JavaFileObject() { @Override public URI toUri() { try { return new URI(file.getFullPath().toString()); } catch (URISyntaxException e) { e.printStackTrace(); } return null; } @Override public Writer openWriter() throws IOException { return null; } @Override public Reader openReader(boolean ignoreEncodingErrors) throws IOException { return null; } @Override public OutputStream openOutputStream() throws IOException { return null; } @Override public InputStream openInputStream() throws IOException { return null; } @Override public String getName() { return file.getLocation().toOSString(); } @Override public long getLastModified() { return file.getModificationStamp(); } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return null; } @Override public boolean delete() { return false; } @Override public boolean isNameCompatible(String simpleName, Kind kind) { return false; } @Override public NestingKind getNestingKind() { return NestingKind.TOP_LEVEL; } @Override public Kind getKind() { return Kind.SOURCE; } @Override public Modifier getAccessLevel() { return Modifier.FINAL; } }; } @Override public javax.tools.Diagnostic.Kind getKind() { return Diagnostic.Kind.ERROR; } @Override public JavaFileObject getSource() { return jf; } @Override public long getPosition() { return getStartPosition(); } @Override public long getStartPosition() { int startOffset = 0; Node errorNode = Nodes.getIdentifyingNode(err.getTreeNode()); if (errorNode == null) { errorNode = err.getTreeNode(); } Token token = errorNode.getToken(); if (token!=null) { startOffset = errorNode.getStartIndex(); } return startOffset; } @Override public long getEndPosition() { int endOffset = 0; Node errorNode = Nodes.getIdentifyingNode(err.getTreeNode()); if (errorNode == null) { errorNode = err.getTreeNode(); } Token token = errorNode.getToken(); if (token!=null) { endOffset = errorNode.getStopIndex()+1; } return endOffset; } @Override public long getLineNumber() { return err.getLine(); } @Override public long getColumnNumber() { int startCol = 0; Node errorNode = Nodes.getIdentifyingNode(err.getTreeNode()); if (errorNode == null) { errorNode = err.getTreeNode(); } Token token = errorNode.getToken(); if (token!=null) { startCol = token.getCharPositionInLine(); } return startCol; } @Override public String getCode() { return String.valueOf(err.getCode()); } @Override public String getMessage(Locale locale) { return err.getMessage(); } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_builder_CeylonCompilationError.java
285
static class NodeCommand extends Command { private final NodeStore store; private final NodeRecord before; private final NodeRecord after; NodeCommand( NodeStore store, NodeRecord before, NodeRecord after ) { super( after.getId(), Mode.fromRecordState( after ) ); this.store = store; this.before = before; this.after = after; } @Override public void accept( CommandRecordVisitor visitor ) { visitor.visitNode( after ); } @Override public String toString() { return beforeAndAfterToString( before, after ); } @Override void removeFromCache( CacheAccessBackDoor cacheAccess ) { cacheAccess.removeNodeFromCache( getKey() ); } @Override public void execute() { store.updateRecord( after ); // Dynamic Label Records Collection<DynamicRecord> toUpdate = new ArrayList<>( after.getDynamicLabelRecords() ); addRemoved( toUpdate ); store.updateDynamicLabelRecords( toUpdate ); } private void addRemoved( Collection<DynamicRecord> toUpdate ) { // the dynamic label records that exist in before, but not in after should be deleted. Set<Long> idsToRemove = new HashSet<>(); for ( DynamicRecord record : before.getDynamicLabelRecords() ) { idsToRemove.add( record.getId() ); } for ( DynamicRecord record : after.getDynamicLabelRecords() ) { idsToRemove.remove( record.getId() ); } for ( long id : idsToRemove ) { toUpdate.add( new DynamicRecord( id ) ); } } @Override public void writeToFile( LogBuffer buffer ) throws IOException { buffer.put( NODE_COMMAND ); buffer.putLong( after.getId() ); writeNodeRecord( buffer, before ); writeNodeRecord( buffer, after ); } private void writeNodeRecord( LogBuffer buffer, NodeRecord record ) throws IOException { byte inUse = record.inUse() ? Record.IN_USE.byteValue() : Record.NOT_IN_USE.byteValue(); buffer.put( inUse ); if ( record.inUse() ) { buffer.putLong( record.getNextRel() ).putLong( record.getNextProp() ); // labels buffer.putLong( record.getLabelField() ); writeDynamicRecords( buffer, record.getDynamicLabelRecords() ); } } public static Command readFromFile( NeoStore neoStore, ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { if ( !readAndFlip( byteChannel, buffer, 8 ) ) { return null; } long id = buffer.getLong(); NodeRecord before = readNodeRecord( id, byteChannel, buffer ); if ( before == null ) { return null; } NodeRecord after = readNodeRecord( id, byteChannel, buffer ); if ( after == null ) { return null; } if ( !before.inUse() && after.inUse() ) { after.setCreated(); } return new NodeCommand( neoStore == null ? null : neoStore.getNodeStore(), before, after ); } private static NodeRecord readNodeRecord( long id, ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { if ( !readAndFlip( byteChannel, buffer, 1 ) ) { return null; } byte inUseFlag = buffer.get(); boolean inUse = false; if ( inUseFlag == Record.IN_USE.byteValue() ) { inUse = true; } else if ( inUseFlag != Record.NOT_IN_USE.byteValue() ) { throw new IOException( "Illegal in use flag: " + inUseFlag ); } NodeRecord record; if ( inUse ) { if ( !readAndFlip( byteChannel, buffer, 8*3 ) ) { return null; } record = new NodeRecord( id, buffer.getLong(), buffer.getLong() ); // labels long labelField = buffer.getLong(); Collection<DynamicRecord> dynamicLabelRecords = new ArrayList<>(); readDynamicRecords( byteChannel, buffer, dynamicLabelRecords, COLLECTION_DYNAMIC_RECORD_ADDER ); record.setLabelField( labelField, dynamicLabelRecords ); } else { record = new NodeRecord( id, Record.NO_NEXT_RELATIONSHIP.intValue(), Record.NO_NEXT_PROPERTY.intValue() ); } record.setInUse( inUse ); return record; } public NodeRecord getBefore() { return before; } public NodeRecord getAfter() { return after; } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_Command.java
729
private static class FindInvocationsVisitor extends Visitor { private Declaration declaration; private final Set<Tree.PositionalArgumentList> posResults = new HashSet<Tree.PositionalArgumentList>(); private final Set<Tree.NamedArgumentList> namedResults = new HashSet<Tree.NamedArgumentList>(); Set<Tree.PositionalArgumentList> getPositionalArgLists() { return posResults; } Set<Tree.NamedArgumentList> getNamedArgLists() { return namedResults; } private FindInvocationsVisitor(Declaration declaration) { this.declaration=declaration; } @Override public void visit(Tree.InvocationExpression that) { super.visit(that); Tree.Primary primary = that.getPrimary(); if (primary instanceof Tree.MemberOrTypeExpression) { if (((Tree.MemberOrTypeExpression) primary).getDeclaration() .refines(declaration)) { Tree.PositionalArgumentList pal = that.getPositionalArgumentList(); if (pal!=null) { posResults.add(pal); } Tree.NamedArgumentList nal = that.getNamedArgumentList(); if (nal!=null) { namedResults.add(nal); } } } } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_refactor_ChangeParametersRefactoring.java
1,506
public class DisableAllocationTests extends ElasticsearchAllocationTestCase { private final ESLogger logger = Loggers.getLogger(DisableAllocationTests.class); @Test public void testClusterDisableAllocation() { AllocationService strategy = createAllocationService(settingsBuilder() .put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_NEW_ALLOCATION, true) .put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_ALLOCATION, true) .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 testClusterDisableReplicaAllocation() { AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.disable_replica_allocation", true) .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 testIndexDisableAllocation() { AllocationService strategy = createAllocationService(settingsBuilder() .build()); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("disabled").settings(ImmutableSettings.builder().put(DisableAllocationDecider.INDEX_ROUTING_ALLOCATION_DISABLE_ALLOCATION, true).put(DisableAllocationDecider.INDEX_ROUTING_ALLOCATION_DISABLE_NEW_ALLOCATION, true)).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_DisableAllocationTests.java
925
public interface LockStore { boolean lock(Data key, String caller, long threadId, long ttl); boolean txnLock(Data key, String caller, long threadId, long ttl); boolean extendLeaseTime(Data key, String caller, long threadId, long ttl); boolean unlock(Data key, String caller, long threadId); boolean isLocked(Data key); boolean isLockedBy(Data key, String caller, long threadId); int getLockCount(Data key); long getRemainingLeaseTime(Data key); boolean canAcquireLock(Data key, String caller, long threadId); Set<Data> getLockedKeys(); boolean forceUnlock(Data dataKey); String getOwnerInfo(Data dataKey); }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockStore.java
109
class CreateProposal extends InitializerProposal { private CreateProposal(String def, String desc, Scope scope, Unit unit, ProducedType returnType, Image image, int offset, TextFileChange change, int exitPos, boolean isObjectOrClass) { super(desc, change, scope, unit, returnType, isObjectOrClass ? new Region(offset, 0): computeSelection(offset, def), image, exitPos, null); } static void addCreateMemberProposal(Collection<ICompletionProposal> proposals, DefinitionGenerator dg, Declaration typeDec, PhasedUnit unit, Tree.Declaration decNode, Tree.Body body, Tree.Statement statement) { IFile file = getFile(unit); TextFileChange change = new TextFileChange("Create Member", file); change.setEdit(new MultiTextEdit()); IDocument doc = EditorUtil.getDocument(change); String indentBefore; String indentAfter; String indent; int offset; List<Tree.Statement> statements = body.getStatements(); String delim = getDefaultLineDelimiter(doc); if (statements.isEmpty()) { String bodyIndent = getIndent(decNode, doc); indent = bodyIndent + getDefaultIndent(); indentBefore = delim + indent; try { boolean singleLineBody = doc.getLineOfOffset(body.getStartIndex()) == doc.getLineOfOffset(body.getStopIndex()); if (singleLineBody) { indentAfter = delim + bodyIndent; } else { indentAfter = ""; } } catch (BadLocationException e) { e.printStackTrace(); indentAfter = delim; } offset = body.getStartIndex()+1; } else { Tree.Statement st; if (statement!=null && statement.getUnit().equals(body.getUnit()) && statement.getStartIndex()>=body.getStartIndex() && statement.getStopIndex()<=body.getStopIndex()) { st = statements.get(0); for (Tree.Statement s: statements) { if (statement.getStartIndex()>=s.getStartIndex() && statement.getStopIndex()<=s.getStopIndex()) { st = s; } } indent = getIndent(st, doc); indentBefore = ""; indentAfter = delim + indent; offset = st.getStartIndex(); } else { st = statements.get(statements.size()-1); indent = getIndent(st, doc); indentBefore = delim + indent; indentAfter = ""; offset = st.getStopIndex()+1; } } String def = indentBefore + dg.generateShared(indent, delim) + indentAfter; int il = applyImports(change, dg.getImports(), unit.getCompilationUnit(), doc); change.addEdit(new InsertEdit(offset, def)); String desc = "Create " + memberKind(dg) + " in '" + typeDec.getName() + "'"; int exitPos = dg.getNode().getStopIndex()+1; proposals.add(new CreateProposal(def, desc, body.getScope(), body.getUnit(), dg.getReturnType(), dg.getImage(), offset+il, change, exitPos, dg instanceof ObjectClassDefinitionGenerator)); } private static String memberKind(DefinitionGenerator dg) { String desc = dg.getDescription(); if (desc.startsWith("function")) { return "method" + desc.substring(8); } if (desc.startsWith("value")) { return "attribute" + desc.substring(5); } if (desc.startsWith("class")) { return "member class" + desc.substring(5); } return desc; } private static void addCreateProposal(Collection<ICompletionProposal> proposals, boolean local, DefinitionGenerator dg, PhasedUnit unit, Tree.Statement statement) { IFile file = getFile(unit); TextFileChange change = new TextFileChange(local ? "Create Local" : "Create Toplevel", file); change.setEdit(new MultiTextEdit()); IDocument doc = EditorUtil.getDocument(change); String indent = getIndent(statement, doc); int offset = statement.getStartIndex(); String delim = getDefaultLineDelimiter(doc); Tree.CompilationUnit cu = unit.getCompilationUnit(); int il = applyImports(change, dg.getImports(), cu, doc); String def = dg.generate(indent, delim) + delim + indent; if (!local) def += delim; change.addEdit(new InsertEdit(offset, def)); String desc = (local ? "Create local " : "Create toplevel ") + dg.getDescription(); final Scope scope = local ? statement.getScope() : cu.getUnit().getPackage(); int exitPos = dg.getNode().getStopIndex()+1; proposals.add(new CreateProposal(def, desc, scope, cu.getUnit(), dg.getReturnType(), dg.getImage(), offset+il, change, exitPos, dg instanceof ObjectClassDefinitionGenerator)); } static void addCreateMemberProposals(Collection<ICompletionProposal> proposals, IProject project, DefinitionGenerator dg, Tree.QualifiedMemberOrTypeExpression qmte, Tree.Statement statement) { Tree.Primary p = ((Tree.QualifiedMemberOrTypeExpression) qmte).getPrimary(); if (p.getTypeModel()!=null) { Declaration typeDec = p.getTypeModel().getDeclaration(); addCreateMemberProposals(proposals, project, dg, typeDec, statement); } } static void addCreateMemberProposals(Collection<ICompletionProposal> proposals, IProject project, DefinitionGenerator dg, Declaration typeDec, Tree.Statement statement) { if (typeDec!=null && typeDec instanceof ClassOrInterface) { for (PhasedUnit unit: getUnits(project)) { if (typeDec.getUnit().equals(unit.getUnit())) { //TODO: "object" declarations? FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typeDec); getRootNode(unit).visit(fdv); Tree.Declaration decNode = (Tree.Declaration) fdv.getDeclarationNode(); Tree.Body body = getClassOrInterfaceBody(decNode); if (body!=null) { addCreateMemberProposal(proposals, dg, typeDec, unit, decNode, body, statement); break; } } } } } static void addCreateLocalProposals(Collection<ICompletionProposal> proposals, IProject project, DefinitionGenerator dg) { //if (!fsv.isToplevel()) { Tree.Statement statement = findStatement(dg.getRootNode(), dg.getNode()); if (statement!=null) { for (PhasedUnit unit: getUnits(project)) { if (unit.getUnit().equals(dg.getRootNode().getUnit())) { addCreateProposal(proposals, true, dg, unit, statement); break; } } } //} } static void addCreateToplevelProposals(Collection<ICompletionProposal> proposals, IProject project, DefinitionGenerator dg) { Tree.Statement statement = findToplevelStatement(dg.getRootNode(), dg.getNode()); if (statement!=null) { for (PhasedUnit unit: getUnits(project)) { if (unit.getUnit().equals(dg.getRootNode().getUnit())) { addCreateProposal(proposals, false, dg, unit, statement); break; } } } } static void addCreateProposals(Tree.CompilationUnit cu, Node node, Collection<ICompletionProposal> proposals, IProject project, IFile file) { Tree.MemberOrTypeExpression smte = (Tree.MemberOrTypeExpression) node; String brokenName = Nodes.getIdentifyingNode(node).getText(); if (!brokenName.isEmpty()) { ValueFunctionDefinitionGenerator vfdg = ValueFunctionDefinitionGenerator.create(brokenName, smte, cu); if (vfdg!=null) { if (smte instanceof Tree.BaseMemberExpression) { addCreateParameterProposal(proposals, project, vfdg); } addCreateProposals(cu, proposals, project, file, smte, vfdg); } ObjectClassDefinitionGenerator ocdg = ObjectClassDefinitionGenerator.create(brokenName, smte, cu); if (ocdg!=null) { addCreateProposals(cu, proposals, project, file, smte, ocdg); } } } private static void addCreateProposals(Tree.CompilationUnit cu, Collection<ICompletionProposal> proposals, IProject project, IFile file, Tree.MemberOrTypeExpression smte, DefinitionGenerator dg) { if (smte instanceof Tree.QualifiedMemberOrTypeExpression) { addCreateMemberProposals(proposals, project, dg, (Tree.QualifiedMemberOrTypeExpression) smte, Nodes.findStatement(cu, smte)); } else { if (!(dg.getNode() instanceof Tree.ExtendedTypeExpression)) { addCreateLocalProposals(proposals, project, dg); ClassOrInterface container = findClassContainer(cu, smte); if (container!=null && container!=smte.getScope()) { //if the statement appears directly in an initializer, propose a local, not a member do { addCreateMemberProposals(proposals, project, dg, container, //TODO: this is a little lame because // it doesn't handle some cases // of nesting Nodes.findStatement(cu, smte)); if (container.getContainer() instanceof Declaration) { Declaration outerContainer = (Declaration) container.getContainer(); container = findClassContainer(outerContainer); } else { break; } } while (container!=null); } } addCreateToplevelProposals(proposals, project, dg); addCreateInNewUnitProposal(proposals, dg, file); } } private static ClassOrInterface findClassContainer(Tree.CompilationUnit cu, Node node){ FindContainerVisitor fcv = new FindContainerVisitor(node); fcv.visit(cu); Tree.Declaration declaration = fcv.getDeclaration(); if(declaration == null || declaration == node) return null; if(declaration instanceof Tree.ClassOrInterface) return (ClassOrInterface) declaration.getDeclarationModel(); if(declaration instanceof Tree.MethodDefinition) return findClassContainer(declaration.getDeclarationModel()); if(declaration instanceof Tree.ObjectDefinition) return findClassContainer(declaration.getDeclarationModel()); return null; } private static ClassOrInterface findClassContainer(Declaration declarationModel) { do { if(declarationModel == null) return null; if(declarationModel instanceof ClassOrInterface) return (ClassOrInterface) declarationModel; if(declarationModel.getContainer() instanceof Declaration) declarationModel = (Declaration)declarationModel.getContainer(); else return null; } while(true); } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CreateProposal.java
3,056
public class PostingsFormatService extends AbstractIndexComponent { private final ImmutableMap<String, PostingsFormatProvider> providers; public final static String DEFAULT_FORMAT = "default"; public PostingsFormatService(Index index) { this(index, ImmutableSettings.Builder.EMPTY_SETTINGS); } public PostingsFormatService(Index index, @IndexSettings Settings indexSettings) { this(index, indexSettings, ImmutableMap.<String, PostingsFormatProvider.Factory>of()); } @Inject public PostingsFormatService(Index index, @IndexSettings Settings indexSettings, Map<String, PostingsFormatProvider.Factory> postingFormatFactories) { super(index, indexSettings); MapBuilder<String, PostingsFormatProvider> providers = MapBuilder.newMapBuilder(); Map<String, Settings> postingsFormatSettings = indexSettings.getGroups(PostingsFormatProvider.POSTINGS_FORMAT_SETTINGS_PREFIX); for (Map.Entry<String, PostingsFormatProvider.Factory> entry : postingFormatFactories.entrySet()) { String name = entry.getKey(); PostingsFormatProvider.Factory factory = entry.getValue(); Settings settings = postingsFormatSettings.get(name); if (settings == null) { settings = ImmutableSettings.Builder.EMPTY_SETTINGS; } providers.put(name, factory.create(name, settings)); } // This is only needed for tests when guice doesn't have the chance to populate the list of PF factories for (PreBuiltPostingsFormatProvider.Factory factory : PostingFormats.listFactories()) { if (providers.containsKey(factory.name())) { continue; } providers.put(factory.name(), factory.get()); } this.providers = providers.immutableMap(); } public PostingsFormatProvider get(String name) throws ElasticsearchIllegalArgumentException { PostingsFormatProvider provider = providers.get(name); if (provider == null) { throw new ElasticsearchIllegalArgumentException("failed to find postings_format [" + name + "]"); } return provider; } }
0true
src_main_java_org_elasticsearch_index_codec_postingsformat_PostingsFormatService.java
482
public class BroadleafActiveDirectoryUserDetailsMapper extends LdapUserDetailsMapper { protected boolean useEmailAddressAsUsername = true; protected boolean additiveRoleNameSubstitutions = false; protected Map<String, String[]> roleNameSubstitutions; @Override public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) { Collection<GrantedAuthority> newAuthorities = new HashSet<GrantedAuthority>(); if (roleNameSubstitutions != null && ! roleNameSubstitutions.isEmpty()) { for (GrantedAuthority authority : authorities) { if (roleNameSubstitutions.containsKey(authority.getAuthority())) { String[] roles = roleNameSubstitutions.get(authority.getAuthority()); for (String role : roles) { newAuthorities.add(new SimpleGrantedAuthority(role.trim())); } if (additiveRoleNameSubstitutions) { newAuthorities.add(authority); } } else { newAuthorities.add(authority); } } } else { newAuthorities.addAll(authorities); } String email = (String)ctx.getObjectAttribute("mail"); UserDetails userDetails = null; if (useEmailAddressAsUsername) { if (email != null) { userDetails = super.mapUserFromContext(ctx, email, newAuthorities); } } if (userDetails == null) { userDetails = super.mapUserFromContext(ctx, username, newAuthorities); } String password = userDetails.getPassword(); if (password == null) { password = userDetails.getUsername(); } BroadleafExternalAuthenticationUserDetails broadleafUser = new BroadleafExternalAuthenticationUserDetails(userDetails.getUsername(), password, userDetails.getAuthorities()); broadleafUser.setFirstName((String)ctx.getObjectAttribute("givenName")); broadleafUser.setLastName((String)ctx.getObjectAttribute("sn")); broadleafUser.setEmail(email); return broadleafUser; } /** * The LDAP server may contain a user name other than an email address. If the email address should be used to map to a Broadleaf user, then * set this to true. The principal will be set to the user's email address returned from the LDAP server. * @param value */ public void setUseEmailAddressAsUsername(boolean value) { this.useEmailAddressAsUsername = value; } /** * This allows you to declaratively set a map containing values that will substitute role names from LDAP to Broadleaf roles names in cases that they might be different. * For example, if you have a role specified in LDAP under "memberOf" with a DN of "Marketing Administrator", you might want to * map that to the role "ADMIN". By default the prefix "ROLE_" will be pre-pended to this name. So to configure this, you would specify: * * <bean class="org.broadleaf.loadtest.web.security.ActiveDirectoryUserDetailsContextMapper"> * <property name="roleMappings"> * <map> * <entry key="Marketing_Administrator" value="CATALOG_ADMIN"/> * </map> * </property> * </bean> * * With this configuration, all roles returned by LDAP that have a DN of "Marketing Administrator" will be converted to "ADMIN" * @param roleNameSubstitutions */ public void setRoleNameSubstitutions(Map<String, String[]> roleNameSubstitutions) { this.roleNameSubstitutions = roleNameSubstitutions; } /** * This should be used in conjunction with the roleNameSubstitutions property. * If this is set to true, this will add the mapped roles to the list of original granted authorities. If set to false, this will replace the original granted * authorities with the mapped ones. Defaults to false. * * @param additiveRoleNameSubstitutions */ public void setAdditiveRoleNameSubstitutions(boolean additiveRoleNameSubstitutions) { this.additiveRoleNameSubstitutions = additiveRoleNameSubstitutions; } }
0true
common_src_main_java_org_broadleafcommerce_common_security_ldap_BroadleafActiveDirectoryUserDetailsMapper.java
3,835
public class FuzzyLikeThisQueryParser implements QueryParser { public static final String NAME = "flt"; private static final ParseField FUZZINESS = Fuzziness.FIELD.withDeprecation("min_similarity"); @Inject public FuzzyLikeThisQueryParser() { } @Override public String[] names() { return new String[]{NAME, "fuzzy_like_this", "fuzzyLikeThis"}; } @Override public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); int maxNumTerms = 25; float boost = 1.0f; List<String> fields = null; String likeText = null; Fuzziness fuzziness = Fuzziness.TWO; int prefixLength = 0; boolean ignoreTF = false; Analyzer analyzer = null; boolean failOnUnsupportedField = true; String queryName = null; XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if ("like_text".equals(currentFieldName) || "likeText".equals(currentFieldName)) { likeText = parser.text(); } else if ("max_query_terms".equals(currentFieldName) || "maxQueryTerms".equals(currentFieldName)) { maxNumTerms = parser.intValue(); } else if ("boost".equals(currentFieldName)) { boost = parser.floatValue(); } else if ("ignore_tf".equals(currentFieldName) || "ignoreTF".equals(currentFieldName)) { ignoreTF = parser.booleanValue(); } else if (FUZZINESS.match(currentFieldName, parseContext.parseFlags())) { fuzziness = Fuzziness.parse(parser); } else if ("prefix_length".equals(currentFieldName) || "prefixLength".equals(currentFieldName)) { prefixLength = parser.intValue(); } else if ("analyzer".equals(currentFieldName)) { analyzer = parseContext.analysisService().analyzer(parser.text()); } else if ("fail_on_unsupported_field".equals(currentFieldName) || "failOnUnsupportedField".equals(currentFieldName)) { failOnUnsupportedField = parser.booleanValue(); } else if ("_name".equals(currentFieldName)) { queryName = parser.text(); } else { throw new QueryParsingException(parseContext.index(), "[flt] query does not support [" + currentFieldName + "]"); } } else if (token == XContentParser.Token.START_ARRAY) { if ("fields".equals(currentFieldName)) { fields = Lists.newLinkedList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { fields.add(parseContext.indexName(parser.text())); } } else { throw new QueryParsingException(parseContext.index(), "[flt] query does not support [" + currentFieldName + "]"); } } } if (likeText == null) { throw new QueryParsingException(parseContext.index(), "fuzzy_like_this requires 'like_text' to be specified"); } if (analyzer == null) { analyzer = parseContext.mapperService().searchAnalyzer(); } FuzzyLikeThisQuery query = new FuzzyLikeThisQuery(maxNumTerms, analyzer); if (fields == null) { fields = Lists.newArrayList(parseContext.defaultField()); } else if (fields.isEmpty()) { throw new QueryParsingException(parseContext.index(), "fuzzy_like_this requires 'fields' to be non-empty"); } for (Iterator<String> it = fields.iterator(); it.hasNext(); ) { final String fieldName = it.next(); if (!Analysis.generatesCharacterTokenStream(analyzer, fieldName)) { if (failOnUnsupportedField) { throw new ElasticsearchIllegalArgumentException("more_like_this doesn't support binary/numeric fields: [" + fieldName + "]"); } else { it.remove(); } } } if (fields.isEmpty()) { return null; } for (String field : fields) { query.addTerms(likeText, field, fuzziness.asSimilarity(), prefixLength); } query.setBoost(boost); query.setIgnoreTF(ignoreTF); if (queryName != null) { parseContext.addNamedQuery(queryName, query); } return query; } }
1no label
src_main_java_org_elasticsearch_index_query_FuzzyLikeThisQueryParser.java
180
@Component("blURLHandlerFilter") public class URLHandlerFilter extends OncePerRequestFilter { @Resource(name = "blURLHandlerService") private URLHandlerService urlHandlerService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String contextPath = request.getContextPath(); String requestURIWithoutContext; if (request.getContextPath() != null) { requestURIWithoutContext = request.getRequestURI().substring(request.getContextPath().length()); } else { requestURIWithoutContext = request.getRequestURI(); } URLHandler handler = urlHandlerService.findURLHandlerByURI(requestURIWithoutContext); if (handler != null) { if (URLRedirectType.FORWARD == handler.getUrlRedirectType()) { request.getRequestDispatcher(handler.getNewURL()).forward(request, response); } else if (URLRedirectType.REDIRECT_PERM == handler.getUrlRedirectType()) { String url = UrlUtil.fixRedirectUrl(contextPath, handler.getNewURL()); response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader( "Location", url); response.setHeader( "Connection", "close" ); } else if (URLRedirectType.REDIRECT_TEMP == handler.getUrlRedirectType()) { String url = UrlUtil.fixRedirectUrl(contextPath, handler.getNewURL()); response.sendRedirect(url); } } else { filterChain.doFilter(request, response); } } /** * If the url does not include "//" then the system will ensure that the application context * is added to the start of the URL. * * @param url * @return */ protected String fixRedirectUrl(String contextPath, String url) { if (url.indexOf("//") < 0) { if (contextPath != null && (! "".equals(contextPath))) { if (! url.startsWith("/")) { url = "/" + url; } if (! url.startsWith(contextPath)) { url = contextPath + url; } } } return url; } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_web_URLHandlerFilter.java
1,649
public static class DHTConfiguration implements ODHTConfiguration { private final HashSet<String> undistributableClusters; private final OServer server; public DHTConfiguration(final OServer iServer) { server = iServer; undistributableClusters = new HashSet<String>(); undistributableClusters.add(OStorage.CLUSTER_DEFAULT_NAME.toLowerCase()); undistributableClusters.add(OMetadataDefault.CLUSTER_INTERNAL_NAME.toLowerCase()); undistributableClusters.add(OMetadataDefault.CLUSTER_INDEX_NAME.toLowerCase()); undistributableClusters.add(OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME.toLowerCase()); undistributableClusters.add(ORole.CLASS_NAME.toLowerCase()); undistributableClusters.add(OUser.CLASS_NAME.toLowerCase()); undistributableClusters.add(OMVRBTreeRIDProvider.PERSISTENT_CLASS_NAME.toLowerCase()); undistributableClusters.add(OSecurityShared.RESTRICTED_CLASSNAME.toLowerCase()); undistributableClusters.add(OSecurityShared.IDENTITY_CLASSNAME.toLowerCase()); undistributableClusters.add(OFunction.CLASS_NAME.toLowerCase()); } @Override public Set<String> getDistributedStorageNames() { return server.getAvailableStorageNames().keySet(); } @Override public Set<String> getUndistributableClusters() { return undistributableClusters; } }
0true
distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_oldsharding_OAutoshardingPlugin.java
327
EntryListener listener1 = new EntryAdapter() { public void entryAdded(EntryEvent event) { latch1Add.countDown(); } public void entryRemoved(EntryEvent event) { latch1Remove.countDown(); } };
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java
1,729
operation.setResponseHandler(new ResponseHandler() { @Override public void sendResponse(Object obj) { if (checkIfMapLoaded.decrementAndGet() == 0) { loaded.set(true); } } public boolean isLocal() { return true; } });
1no label
hazelcast_src_main_java_com_hazelcast_map_DefaultRecordStore.java
4,489
class CleanFilesRequestHandler extends BaseTransportRequestHandler<RecoveryCleanFilesRequest> { @Override public RecoveryCleanFilesRequest newInstance() { return new RecoveryCleanFilesRequest(); } @Override public String executor() { return ThreadPool.Names.GENERIC; } @Override public void messageReceived(RecoveryCleanFilesRequest request, TransportChannel channel) throws Exception { RecoveryStatus onGoingRecovery = onGoingRecoveries.get(request.recoveryId()); if (onGoingRecovery == null) { // shard is getting closed on us throw new IndexShardClosedException(request.shardId()); } if (onGoingRecovery.isCanceled()) { onGoingRecovery.sentCanceledToSource = true; throw new IndexShardClosedException(request.shardId()); } Store store = onGoingRecovery.indexShard.store(); // first, we go and move files that were created with the recovery id suffix to // the actual names, its ok if we have a corrupted index here, since we have replicas // to recover from in case of a full cluster shutdown just when this code executes... String prefix = "recovery." + onGoingRecovery.startTime + "."; Set<String> filesToRename = Sets.newHashSet(); for (String existingFile : store.directory().listAll()) { if (existingFile.startsWith(prefix)) { filesToRename.add(existingFile.substring(prefix.length(), existingFile.length())); } } Exception failureToRename = null; if (!filesToRename.isEmpty()) { // first, go and delete the existing ones final Directory directory = store.directory(); for (String file : filesToRename) { try { directory.deleteFile(file); } catch (Throwable ex) { logger.debug("failed to delete file [{}]", ex, file); } } for (String fileToRename : filesToRename) { // now, rename the files... and fail it it won't work store.renameFile(prefix + fileToRename, fileToRename); } } // now write checksums store.writeChecksums(onGoingRecovery.checksums); for (String existingFile : store.directory().listAll()) { // don't delete snapshot file, or the checksums file (note, this is extra protection since the Store won't delete checksum) if (!request.snapshotFiles().contains(existingFile) && !Store.isChecksum(existingFile)) { try { store.directory().deleteFile(existingFile); } catch (Exception e) { // ignore, we don't really care, will get deleted later on } } } channel.sendResponse(TransportResponse.Empty.INSTANCE); } }
1no label
src_main_java_org_elasticsearch_indices_recovery_RecoveryTarget.java
3,484
public static interface ParseListener<ParseContext> { public static final ParseListener EMPTY = new ParseListenerAdapter(); /** * Called before a field is added to the document. Return <tt>true</tt> to include * it in the document. */ boolean beforeFieldAdded(FieldMapper fieldMapper, Field fieldable, ParseContext parseContent); }
0true
src_main_java_org_elasticsearch_index_mapper_DocumentMapper.java
1,021
public static class Presentation { public static class Tab { public static class Name { public static final String OrderItems = "OrderImpl_Order_Items_Tab"; public static final String FulfillmentGroups = "OrderImpl_Fulfillment_Groups_Tab"; public static final String Payment = "OrderImpl_Payment_Tab"; public static final String Advanced = "OrderImpl_Advanced_Tab"; } public static class Order { public static final int OrderItems = 2000; public static final int FulfillmentGroups = 3000; public static final int Payment = 4000; public static final int Advanced = 5000; } } public static class Group { public static class Name { public static final String General = "OrderImpl_Order"; } public static class Order { public static final int General = 1000; } } public static class FieldOrder { public static final int NAME = 1000; public static final int CUSTOMER = 2000; public static final int TOTAL = 3000; public static final int STATUS = 4000; public static final int SUBTOTAL = 5000; public static final int ORDERNUMBER = 6000; public static final int TOTALTAX = 7000; public static final int TOTALFGCHARGES = 8000; public static final int SUBMITDATE = 9000; public static final int EMAILADDRESS = 10000; public static final int ADJUSTMENTS = 1000; public static final int OFFERCODES = 2000; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_OrderImpl.java
918
public class FulfillmentGroupAdjustmentAnswer implements IAnswer<FulfillmentGroupAdjustment> { @Override public FulfillmentGroupAdjustment answer() throws Throwable { return new FulfillmentGroupAdjustmentImpl(); } }
0true
core_broadleaf-framework_src_test_java_org_broadleafcommerce_core_offer_service_processor_FulfillmentGroupOfferProcessorTest.java
1,120
@SuppressWarnings("deprecation") public class LegacyOrderBaseTest extends LegacyCommonSetupBaseTest { @Resource(name = "blOrderService") protected LegacyCartService cartService; private int bundleCount = 0; protected Customer createNamedCustomer() { Customer customer = customerService.createCustomerFromId(null); customer.setUsername(String.valueOf(customer.getId())); return customer; } public Order setUpNamedOrder() throws PricingException { Customer customer = customerService.saveCustomer(createNamedCustomer()); Order order = cartService.createNamedOrderForCustomer("Boxes Named Order", customer); Product newProduct = addTestProduct("Cube Box", "Boxes"); Category newCategory = newProduct.getDefaultCategory(); cartService.addSkuToOrder(order.getId(), newProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2); return order; } public Order setUpAnonymousCartWithInactiveSku() throws PricingException { Customer customer = customerService.saveCustomer(createNamedCustomer()); Order order = cartService.createNewCartForCustomer(customer); Product newProduct = addTestProduct("Plastic Crate", "Crates"); Product newInactiveProduct = addTestProduct("Plastic Crate", "Crates", false); Category newCategory = newProduct.getDefaultCategory(); cartService.addSkuToOrder(order.getId(), newProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2); cartService.addSkuToOrder(order.getId(), newInactiveProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2); cartService.addBundleItemToOrder(order, createBundleOrderItemRequest()); cartService.addBundleItemToOrder(order, createBundleOrderItemRequestWithInactiveSku()); return order; } public Order setUpAnonymousCartWithGiftWrap() throws PricingException { Customer customer = customerService.saveCustomer(createNamedCustomer()); Order order = cartService.createNewCartForCustomer(customer); Product newProduct = addTestProduct("Plastic Crate", "Crates"); Product newInactiveProduct = addTestProduct("Plastic Crate", "Crates"); Product giftWrapProduct = addTestProduct("Gift Box", "Gift Wraps"); Category newCategory = newProduct.getDefaultCategory(); List<OrderItem> addedItems = new ArrayList<OrderItem>(); addedItems.add(cartService.addSkuToOrder(order.getId(), newProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2)); addedItems.add(cartService.addSkuToOrder(order.getId(), newInactiveProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2)); cartService.addGiftWrapItemToOrder(order, createGiftWrapOrderItemRequest(giftWrapProduct, giftWrapProduct.getDefaultSku(), 1, addedItems)); return order; } public Order setUpAnonymousCartWithInactiveGiftWrap() throws PricingException { Customer customer = customerService.saveCustomer(createNamedCustomer()); Order order = cartService.createNewCartForCustomer(customer); Product newProduct = addTestProduct("Plastic Crate", "Crates"); Product newInactiveProduct = addTestProduct("Plastic Crate", "Crates", false); Product giftWrapProduct = addTestProduct("Gift Box", "Gift Wraps"); Category newCategory = newProduct.getDefaultCategory(); List<OrderItem> addedItems = new ArrayList<OrderItem>(); addedItems.add(cartService.addSkuToOrder(order.getId(), newProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2)); addedItems.add(cartService.addSkuToOrder(order.getId(), newInactiveProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2)); cartService.addGiftWrapItemToOrder(order, createGiftWrapOrderItemRequest(giftWrapProduct, giftWrapProduct.getDefaultSku(), 1, addedItems)); return order; } public Order initializeExistingCartWithInactiveSkuAndInactiveBundle(Customer customer) throws PricingException { Product newProduct = addTestProduct("Plastic Crate", "Crates"); Product newInactiveProduct = addTestProduct("Plastic Crate", "Crates", false); Category newCategory = newProduct.getDefaultCategory(); Order order = cartService.createNewCartForCustomer(customer); cartService.addSkuToOrder(order.getId(), newProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2); cartService.addSkuToOrder(order.getId(), newInactiveProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2); cartService.addBundleItemToOrder(order, createBundleOrderItemRequest()); cartService.addBundleItemToOrder(order, createBundleOrderItemRequestWithInactiveSku()); return order; } public Order initializeExistingCart(Customer customer) throws PricingException { Product newProduct = addTestProduct("Plastic Crate", "Crates"); Product newOtherProduct = addTestProduct("Plastic Crate", "Crates"); Category newCategory = newProduct.getDefaultCategory(); Order order = cartService.createNewCartForCustomer(customer); cartService.addSkuToOrder(order.getId(), newProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2); cartService.addSkuToOrder(order.getId(), newOtherProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2); return order; } public BundleOrderItemRequest createBundleOrderItemRequest() { Product screwProduct = addTestProduct("Bookshelf", "Components"); Product shelfProduct = addTestProduct("Bookshelf", "Components"); Product bracketsProduct = addTestProduct("Bookshelf", "Components"); Category category = screwProduct.getDefaultCategory(); List<DiscreteOrderItemRequest> discreteOrderItems = new ArrayList<DiscreteOrderItemRequest>(); discreteOrderItems.add(createDiscreteOrderItemRequest(screwProduct, screwProduct.getDefaultSku(), 20)); discreteOrderItems.add(createDiscreteOrderItemRequest(shelfProduct, shelfProduct.getDefaultSku(), 3)); discreteOrderItems.add(createDiscreteOrderItemRequest(bracketsProduct, bracketsProduct.getDefaultSku(), 6)); BundleOrderItemRequest itemRequest = new BundleOrderItemRequest(); itemRequest.setCategory(category); itemRequest.setName("test bundle " + bundleCount++); itemRequest.setQuantity(1); itemRequest.setDiscreteOrderItems(discreteOrderItems); return itemRequest; } public BundleOrderItemRequest createBundleOrderItemRequestWithInactiveSku() { Product drawerProduct = addTestProduct("Drawer System", "Systems"); Product nailsProduct = addTestProduct("Drawer System", "Systems"); Product tracksProduct = addTestProduct("Drawer System", "Systems", false); Category category = drawerProduct.getDefaultCategory(); List<DiscreteOrderItemRequest> discreteOrderItems = new ArrayList<DiscreteOrderItemRequest>(); discreteOrderItems.add(createDiscreteOrderItemRequest(drawerProduct, drawerProduct.getDefaultSku(), 20)); discreteOrderItems.add(createDiscreteOrderItemRequest(nailsProduct, nailsProduct.getDefaultSku(), 3)); discreteOrderItems.add(createDiscreteOrderItemRequest(tracksProduct, tracksProduct.getDefaultSku(), 6)); BundleOrderItemRequest itemRequest = new BundleOrderItemRequest(); itemRequest.setCategory(category); itemRequest.setName("test bundle " + bundleCount++); itemRequest.setQuantity(1); itemRequest.setDiscreteOrderItems(discreteOrderItems); return itemRequest; } public DiscreteOrderItemRequest createDiscreteOrderItemRequest(Product product, Sku sku, int quantity) { DiscreteOrderItemRequest request = new DiscreteOrderItemRequest(); request.setSku(sku); request.setQuantity(quantity); request.setProduct(product); request.setCategory(product.getDefaultCategory()); return request; } public GiftWrapOrderItemRequest createGiftWrapOrderItemRequest(Product product, Sku sku, int quantity, List<OrderItem> wrappedItems) { GiftWrapOrderItemRequest request = new GiftWrapOrderItemRequest(); request.setSku(sku); request.setQuantity(quantity); request.setProduct(product); request.setCategory(product.getDefaultCategory()); request.setWrappedItems(wrappedItems); return request; } public Order setUpAnonymousCartWithInactiveBundleGiftWrap() throws PricingException { Customer customer = customerService.saveCustomer(createNamedCustomer()); Order order = cartService.createNewCartForCustomer(customer); Product newProduct = addTestProduct("Plastic Crate", "Crates"); Product newInactiveProduct = addTestProduct("Plastic Crate", "Crates", false); Product giftWrapProduct = addTestProduct("Gift Box", "Gift Wraps"); Category category = newProduct.getDefaultCategory(); List<DiscreteOrderItemRequest> discreteOrderItems = new ArrayList<DiscreteOrderItemRequest>(); discreteOrderItems.add(createDiscreteOrderItemRequest(newProduct, newProduct.getDefaultSku(), 1)); discreteOrderItems.add(createDiscreteOrderItemRequest(newInactiveProduct, newInactiveProduct.getDefaultSku(), 1)); discreteOrderItems.add(createGiftWrapOrderItemRequest(giftWrapProduct, giftWrapProduct.getDefaultSku(), 1, new ArrayList<OrderItem>())); BundleOrderItemRequest itemRequest = new BundleOrderItemRequest(); itemRequest.setCategory(category); itemRequest.setName("test bundle " + bundleCount++); itemRequest.setQuantity(1); itemRequest.setDiscreteOrderItems(discreteOrderItems); BundleOrderItem newBundle = (BundleOrderItem) cartService.addBundleItemToOrder(order, itemRequest); List<OrderItem> addedItems = new ArrayList<OrderItem>(); GiftWrapOrderItem giftItem = null; for (DiscreteOrderItem addedItem : newBundle.getDiscreteOrderItems()) { if (addedItem instanceof GiftWrapOrderItem) { giftItem = (GiftWrapOrderItem) addedItem; } else { addedItems.add(addedItem); } } for (OrderItem addedItem : addedItems) { addedItem.setGiftWrapOrderItem(giftItem); } giftItem.getWrappedItems().addAll(addedItems); order = cartService.save(order, false); return order; } public Order setUpAnonymousCartWithBundleGiftWrap() throws PricingException { Customer customer = customerService.saveCustomer(createNamedCustomer()); Order order = cartService.createNewCartForCustomer(customer); BundleOrderItemRequest itemRequest = createBundleOrderItemRequestWithGiftWrap(); BundleOrderItem newBundle = (BundleOrderItem) cartService.addBundleItemToOrder(order, itemRequest); List<OrderItem> addedItems = new ArrayList<OrderItem>(); GiftWrapOrderItem giftItem = null; for (DiscreteOrderItem addedItem : newBundle.getDiscreteOrderItems()) { if (addedItem instanceof GiftWrapOrderItem) { giftItem = (GiftWrapOrderItem) addedItem; } else { addedItems.add(addedItem); } } for (OrderItem addedItem : addedItems) { addedItem.setGiftWrapOrderItem(giftItem); } giftItem.getWrappedItems().addAll(addedItems); order = cartService.save(order, false); return order; } protected BundleOrderItemRequest createBundleOrderItemRequestWithGiftWrap() { Product newProduct = addTestProduct("Plastic Crate", "Crates"); Product newActiveProduct = addTestProduct("Plastic Crate", "Crates"); Product giftWrapProduct = addTestProduct("Gift Box", "Gift Wraps"); Category category = newProduct.getDefaultCategory(); List<DiscreteOrderItemRequest> discreteOrderItems = new ArrayList<DiscreteOrderItemRequest>(); discreteOrderItems.add(createDiscreteOrderItemRequest(newProduct, newProduct.getDefaultSku(), 1)); discreteOrderItems.add(createDiscreteOrderItemRequest(newActiveProduct, newActiveProduct.getDefaultSku(), 1)); discreteOrderItems.add(createGiftWrapOrderItemRequest(giftWrapProduct, giftWrapProduct.getDefaultSku(), 1, new ArrayList<OrderItem>())); BundleOrderItemRequest itemRequest = new BundleOrderItemRequest(); itemRequest.setCategory(category); itemRequest.setName("test bundle " + bundleCount++); itemRequest.setQuantity(1); itemRequest.setDiscreteOrderItems(discreteOrderItems); return itemRequest; } public Order setUpAnonymousCartWithBundleGiftWrapReferringToRootItems() throws PricingException { Customer customer = customerService.saveCustomer(createNamedCustomer()); Order order = cartService.createNewCartForCustomer(customer); Product newProduct = addTestProduct("Plastic Bowl", "Bowls"); Product newActiveProduct = addTestProduct("Plastic Bowl", "Bowls"); Category newCategory = newProduct.getDefaultCategory(); List<OrderItem> addedItems = new ArrayList<OrderItem>(); addedItems.add(cartService.addSkuToOrder(order.getId(), newProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2)); addedItems.add(cartService.addSkuToOrder(order.getId(), newActiveProduct.getDefaultSku().getId(), newProduct.getId(), newCategory.getId(), 2)); BundleOrderItem newBundle = (BundleOrderItem) cartService.addBundleItemToOrder(order, createBundleOrderItemRequestWithGiftWrap()); GiftWrapOrderItem giftItem = null; for (DiscreteOrderItem addedItem : newBundle.getDiscreteOrderItems()) { if (addedItem instanceof GiftWrapOrderItem) { giftItem = (GiftWrapOrderItem) addedItem; } } for (OrderItem addedItem : addedItems) { addedItem.setGiftWrapOrderItem(giftItem); } giftItem.getWrappedItems().addAll(addedItems); order = cartService.save(order, false); return order; } public Order setUpAnonymousCartWithBundleGiftWrapReferringItemsInAnotherBundle() throws PricingException { Customer customer = customerService.saveCustomer(createNamedCustomer()); Order order = cartService.createNewCartForCustomer(customer); BundleOrderItem newBundle = (BundleOrderItem) cartService.addBundleItemToOrder(order, createBundleOrderItemRequest()); BundleOrderItem newBundle2 = (BundleOrderItem) cartService.addBundleItemToOrder(order, createBundleOrderItemRequestWithGiftWrap()); GiftWrapOrderItem giftItem = null; for (DiscreteOrderItem addedItem : newBundle2.getDiscreteOrderItems()) { if (addedItem instanceof GiftWrapOrderItem) { giftItem = (GiftWrapOrderItem) addedItem; } } for (DiscreteOrderItem addedItem : newBundle.getDiscreteOrderItems()) { addedItem.setGiftWrapOrderItem(giftItem); } giftItem.getWrappedItems().addAll(newBundle.getDiscreteOrderItems()); order = cartService.save(order, false); return order; } }
0true
integration_src_test_java_org_broadleafcommerce_core_order_service_legacy_LegacyOrderBaseTest.java
732
@Service("blRelatedProductsService") /* * Service that provides method for finding a product's related products. */ public class RelatedProductsServiceImpl implements RelatedProductsService { @Resource(name="blCategoryDao") protected CategoryDao categoryDao; @Resource(name="blProductDao") protected ProductDao productDao; @Resource(name="blCatalogService") protected CatalogService catalogService; @Override public List<? extends PromotableProduct> findRelatedProducts(RelatedProductDTO relatedProductDTO) { Product product = lookupProduct(relatedProductDTO); Category category = lookupCategory(relatedProductDTO); if (RelatedProductTypeEnum.FEATURED.equals(relatedProductDTO.getType())) { return buildFeaturedProductsList(product, category, relatedProductDTO); } else if (RelatedProductTypeEnum.CROSS_SALE.equals(relatedProductDTO.getType())) { return buildCrossSaleProductsList(product, category, relatedProductDTO); } else if (RelatedProductTypeEnum.UP_SALE.equals(relatedProductDTO.getType())) { return buildUpSaleProductsList(product, category, relatedProductDTO); } else { throw new IllegalArgumentException("RelatedProductType " + relatedProductDTO.getType() + " not supported."); } } /** * Returns the featured products for the past in product/category * @param product * @param category * @param relatedProductDTO * @return */ protected List<? extends PromotableProduct> buildFeaturedProductsList(Product product, Category category, RelatedProductDTO relatedProductDTO) { List<FeaturedProduct> returnFeaturedProducts = null; if (product != null) { category = product.getDefaultCategory(); } if (category != null) { if (relatedProductDTO.isCumulativeResults()) { returnFeaturedProducts = category.getCumulativeFeaturedProducts(); } else { returnFeaturedProducts = category.getFeaturedProducts(); } } removeCurrentProductFromReturnList(product, returnFeaturedProducts); returnFeaturedProducts = (List<FeaturedProduct>)removeDuplicatesFromList(returnFeaturedProducts); return resizeList(returnFeaturedProducts, relatedProductDTO.getQuantity()); } private List<? extends PromotableProduct> removeDuplicatesFromList(List <? extends PromotableProduct> returnPromotableProducts) { Set<PromotableProduct> productSet = new LinkedHashSet<PromotableProduct>(); Set<Product> relatedProductSet = new LinkedHashSet<Product>(); if (returnPromotableProducts != null) { for(PromotableProduct p : returnPromotableProducts) { if (!relatedProductSet.contains(p.getRelatedProduct())){ productSet.add(p); relatedProductSet.add(p.getRelatedProduct()); } } } else { return null; } returnPromotableProducts.clear(); returnPromotableProducts.addAll(new ArrayList(productSet)); return returnPromotableProducts; } private void removeCurrentProductFromReturnList(Product product, List<? extends PromotableProduct> returnPromotableProducts) { if (product != null && returnPromotableProducts != null) { Iterator<? extends PromotableProduct> productIterator = returnPromotableProducts.iterator(); while (productIterator.hasNext()) { PromotableProduct promotableProduct = productIterator.next(); if (product.getId().equals(promotableProduct.getRelatedProduct().getId())) { productIterator.remove(); } } } } /** * Returns the upSale products for the past in product/category * @param product * @param category * @param relatedProductDTO * @return */ protected List<? extends PromotableProduct> buildUpSaleProductsList(Product product, Category category, RelatedProductDTO relatedProductDTO) { List<? extends PromotableProduct> returnUpSaleProducts = null; if (product != null) { if (relatedProductDTO.isCumulativeResults()) { returnUpSaleProducts = product.getCumulativeUpSaleProducts(); } else { returnUpSaleProducts = product.getUpSaleProducts(); } } else if (category != null) { if (relatedProductDTO.isCumulativeResults()) { returnUpSaleProducts = category.getCumulativeUpSaleProducts(); } else { returnUpSaleProducts = category.getUpSaleProducts(); } } removeCurrentProductFromReturnList(product, returnUpSaleProducts); returnUpSaleProducts = removeDuplicatesFromList(returnUpSaleProducts); return resizeList(returnUpSaleProducts, relatedProductDTO.getQuantity()); } /** * Returns the crossSale products for the past in product/category * @param product * @param category * @param relatedProductDTO * @return */ protected List<? extends PromotableProduct> buildCrossSaleProductsList(Product product, Category category, RelatedProductDTO relatedProductDTO) { List<? extends PromotableProduct> crossSaleProducts = null; if (product != null) { if (relatedProductDTO.isCumulativeResults()) { crossSaleProducts = product.getCumulativeCrossSaleProducts(); } else { crossSaleProducts = product.getCrossSaleProducts(); } } else if (category != null) { if (relatedProductDTO.isCumulativeResults()) { crossSaleProducts = category.getCumulativeCrossSaleProducts(); } else { crossSaleProducts = category.getCrossSaleProducts(); } } removeCurrentProductFromReturnList(product, crossSaleProducts); crossSaleProducts = removeDuplicatesFromList(crossSaleProducts); return resizeList(crossSaleProducts, relatedProductDTO.getQuantity()); } /** * Resizes the list to match the passed in quantity. If the quantity is greater than the size of the list or null, * the originalList is returned. * * @param originalList * @param qty * @return */ protected List<? extends PromotableProduct> resizeList(List<? extends PromotableProduct> originalList, Integer qty) { if (qty != null && originalList != null && originalList.size() > qty) { return originalList.subList(0, qty); } else { return originalList; } } protected Product lookupProduct(RelatedProductDTO relatedProductDTO) { if (relatedProductDTO.getProductId() != null) { return productDao.readProductById(relatedProductDTO.getProductId()); } else { return null; } } protected Category lookupCategory(RelatedProductDTO relatedProductDTO) { if (relatedProductDTO.getCategoryId() != null) { return categoryDao.readCategoryById(relatedProductDTO.getCategoryId()); } else { return null; } } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_service_RelatedProductsServiceImpl.java
254
service.submit(runnable, selector, new ExecutionCallback() { public void onResponse(Object response) { result.set(response); responseLatch.countDown(); } public void onFailure(Throwable t) { } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceSubmitTest.java
1,254
public class TransportClientNodesService extends AbstractComponent { private final TimeValue nodesSamplerInterval; private final long pingTimeout; private final ClusterName clusterName; private final TransportService transportService; private final ThreadPool threadPool; private final Version version; // nodes that are added to be discovered private volatile ImmutableList<DiscoveryNode> listedNodes = ImmutableList.of(); private final Object mutex = new Object(); private volatile ImmutableList<DiscoveryNode> nodes = ImmutableList.of(); private volatile ImmutableList<DiscoveryNode> filteredNodes = ImmutableList.of(); private final AtomicInteger tempNodeIdGenerator = new AtomicInteger(); private final NodeSampler nodesSampler; private volatile ScheduledFuture nodesSamplerFuture; private final AtomicInteger randomNodeGenerator = new AtomicInteger(); private final boolean ignoreClusterName; private volatile boolean closed; @Inject public TransportClientNodesService(Settings settings, ClusterName clusterName, TransportService transportService, ThreadPool threadPool, Version version) { super(settings); this.clusterName = clusterName; this.transportService = transportService; this.threadPool = threadPool; this.version = version; this.nodesSamplerInterval = componentSettings.getAsTime("nodes_sampler_interval", timeValueSeconds(5)); this.pingTimeout = componentSettings.getAsTime("ping_timeout", timeValueSeconds(5)).millis(); this.ignoreClusterName = componentSettings.getAsBoolean("ignore_cluster_name", false); if (logger.isDebugEnabled()) { logger.debug("node_sampler_interval[" + nodesSamplerInterval + "]"); } if (componentSettings.getAsBoolean("sniff", false)) { this.nodesSampler = new SniffNodesSampler(); } else { this.nodesSampler = new SimpleNodeSampler(); } this.nodesSamplerFuture = threadPool.schedule(nodesSamplerInterval, ThreadPool.Names.GENERIC, new ScheduledNodeSampler()); // we want the transport service to throw connect exceptions, so we can retry transportService.throwConnectException(true); } public ImmutableList<TransportAddress> transportAddresses() { ImmutableList.Builder<TransportAddress> lstBuilder = ImmutableList.builder(); for (DiscoveryNode listedNode : listedNodes) { lstBuilder.add(listedNode.address()); } return lstBuilder.build(); } public ImmutableList<DiscoveryNode> connectedNodes() { return this.nodes; } public ImmutableList<DiscoveryNode> filteredNodes() { return this.filteredNodes; } public ImmutableList<DiscoveryNode> listedNodes() { return this.listedNodes; } public TransportClientNodesService addTransportAddresses(TransportAddress... transportAddresses) { synchronized (mutex) { if (closed) { throw new ElasticsearchIllegalStateException("transport client is closed, can't add an address"); } List<TransportAddress> filtered = Lists.newArrayListWithExpectedSize(transportAddresses.length); for (TransportAddress transportAddress : transportAddresses) { boolean found = false; for (DiscoveryNode otherNode : listedNodes) { if (otherNode.address().equals(transportAddress)) { found = true; logger.debug("address [{}] already exists with [{}], ignoring...", transportAddress, otherNode); break; } } if (!found) { filtered.add(transportAddress); } } if (filtered.isEmpty()) { return this; } ImmutableList.Builder<DiscoveryNode> builder = ImmutableList.builder(); builder.addAll(listedNodes()); for (TransportAddress transportAddress : filtered) { DiscoveryNode node = new DiscoveryNode("#transport#-" + tempNodeIdGenerator.incrementAndGet(), transportAddress, version); logger.debug("adding address [{}]", node); builder.add(node); } listedNodes = builder.build(); nodesSampler.sample(); } return this; } public TransportClientNodesService removeTransportAddress(TransportAddress transportAddress) { synchronized (mutex) { if (closed) { throw new ElasticsearchIllegalStateException("transport client is closed, can't remove an address"); } ImmutableList.Builder<DiscoveryNode> builder = ImmutableList.builder(); for (DiscoveryNode otherNode : listedNodes) { if (!otherNode.address().equals(transportAddress)) { builder.add(otherNode); } else { logger.debug("removing address [{}]", otherNode); } } listedNodes = builder.build(); nodesSampler.sample(); } return this; } public <T> T execute(NodeCallback<T> callback) throws ElasticsearchException { ImmutableList<DiscoveryNode> nodes = this.nodes; if (nodes.isEmpty()) { throw new NoNodeAvailableException(); } int index = randomNodeGenerator.incrementAndGet(); if (index < 0) { index = 0; randomNodeGenerator.set(0); } for (int i = 0; i < nodes.size(); i++) { DiscoveryNode node = nodes.get((index + i) % nodes.size()); try { return callback.doWithNode(node); } catch (ElasticsearchException e) { if (!(e.unwrapCause() instanceof ConnectTransportException)) { throw e; } } } throw new NoNodeAvailableException(); } public <Response> void execute(NodeListenerCallback<Response> callback, ActionListener<Response> listener) throws ElasticsearchException { ImmutableList<DiscoveryNode> nodes = this.nodes; if (nodes.isEmpty()) { throw new NoNodeAvailableException(); } int index = randomNodeGenerator.incrementAndGet(); if (index < 0) { index = 0; randomNodeGenerator.set(0); } RetryListener<Response> retryListener = new RetryListener<Response>(callback, listener, nodes, index); try { callback.doWithNode(nodes.get((index) % nodes.size()), retryListener); } catch (ElasticsearchException e) { if (e.unwrapCause() instanceof ConnectTransportException) { retryListener.onFailure(e); } else { throw e; } } } public static class RetryListener<Response> implements ActionListener<Response> { private final NodeListenerCallback<Response> callback; private final ActionListener<Response> listener; private final ImmutableList<DiscoveryNode> nodes; private final int index; private volatile int i; public RetryListener(NodeListenerCallback<Response> callback, ActionListener<Response> listener, ImmutableList<DiscoveryNode> nodes, int index) { this.callback = callback; this.listener = listener; this.nodes = nodes; this.index = index; } @Override public void onResponse(Response response) { listener.onResponse(response); } @Override public void onFailure(Throwable e) { if (ExceptionsHelper.unwrapCause(e) instanceof ConnectTransportException) { int i = ++this.i; if (i >= nodes.size()) { listener.onFailure(new NoNodeAvailableException()); } else { try { callback.doWithNode(nodes.get((index + i) % nodes.size()), this); } catch (Throwable e1) { // retry the next one... onFailure(e); } } } else { listener.onFailure(e); } } } public void close() { synchronized (mutex) { if (closed) { return; } closed = true; nodesSamplerFuture.cancel(true); for (DiscoveryNode node : nodes) { transportService.disconnectFromNode(node); } for (DiscoveryNode listedNode : listedNodes) { transportService.disconnectFromNode(listedNode); } nodes = ImmutableList.of(); } } abstract class NodeSampler { public void sample() { synchronized (mutex) { if (closed) { return; } doSample(); } } protected abstract void doSample(); /** * validates a set of potentially newly discovered nodes and returns an immutable * list of the nodes that has passed. */ protected ImmutableList<DiscoveryNode> validateNewNodes(Set<DiscoveryNode> nodes) { for (Iterator<DiscoveryNode> it = nodes.iterator(); it.hasNext(); ) { DiscoveryNode node = it.next(); if (!transportService.nodeConnected(node)) { try { logger.trace("connecting to node [{}]", node); transportService.connectToNode(node); } catch (Throwable e) { it.remove(); logger.debug("failed to connect to discovered node [" + node + "]", e); } } } return new ImmutableList.Builder<DiscoveryNode>().addAll(nodes).build(); } } class ScheduledNodeSampler implements Runnable { @Override public void run() { try { nodesSampler.sample(); if (!closed) { nodesSamplerFuture = threadPool.schedule(nodesSamplerInterval, ThreadPool.Names.GENERIC, this); } } catch (Exception e) { logger.warn("failed to sample", e); } } } class SimpleNodeSampler extends NodeSampler { @Override protected void doSample() { HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>(); HashSet<DiscoveryNode> newFilteredNodes = new HashSet<DiscoveryNode>(); for (DiscoveryNode listedNode : listedNodes) { if (!transportService.nodeConnected(listedNode)) { try { // its a listed node, light connect to it... logger.trace("connecting to listed node (light) [{}]", listedNode); transportService.connectToNodeLight(listedNode); } catch (Throwable e) { logger.debug("failed to connect to node [{}], removed from nodes list", e, listedNode); continue; } } try { NodesInfoResponse nodeInfo = transportService.submitRequest(listedNode, NodesInfoAction.NAME, Requests.nodesInfoRequest("_local"), TransportRequestOptions.options().withType(TransportRequestOptions.Type.STATE).withTimeout(pingTimeout), new FutureTransportResponseHandler<NodesInfoResponse>() { @Override public NodesInfoResponse newInstance() { return new NodesInfoResponse(); } }).txGet(); if (!ignoreClusterName && !clusterName.equals(nodeInfo.getClusterName())) { logger.warn("node {} not part of the cluster {}, ignoring...", listedNode, clusterName); newFilteredNodes.add(listedNode); } else if (nodeInfo.getNodes().length != 0) { // use discovered information but do keep the original transport address, so people can control which address is exactly used. DiscoveryNode nodeWithInfo = nodeInfo.getNodes()[0].getNode(); newNodes.add(new DiscoveryNode(nodeWithInfo.name(), nodeWithInfo.id(), nodeWithInfo.getHostName(), nodeWithInfo.getHostAddress(), listedNode.address(), nodeWithInfo.attributes(), nodeWithInfo.version())); } else { // although we asked for one node, our target may not have completed initialization yet and doesn't have cluster nodes logger.debug("node {} didn't return any discovery info, temporarily using transport discovery node", listedNode); newNodes.add(listedNode); } } catch (Throwable e) { logger.info("failed to get node info for {}, disconnecting...", e, listedNode); transportService.disconnectFromNode(listedNode); } } nodes = validateNewNodes(newNodes); filteredNodes = ImmutableList.copyOf(newFilteredNodes); } } class SniffNodesSampler extends NodeSampler { @Override protected void doSample() { // the nodes we are going to ping include the core listed nodes that were added // and the last round of discovered nodes Set<DiscoveryNode> nodesToPing = Sets.newHashSet(); for (DiscoveryNode node : listedNodes) { nodesToPing.add(node); } for (DiscoveryNode node : nodes) { nodesToPing.add(node); } final CountDownLatch latch = new CountDownLatch(nodesToPing.size()); final ConcurrentMap<DiscoveryNode, ClusterStateResponse> clusterStateResponses = ConcurrentCollections.newConcurrentMap(); for (final DiscoveryNode listedNode : nodesToPing) { threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new Runnable() { @Override public void run() { try { if (!transportService.nodeConnected(listedNode)) { try { // if its one of hte actual nodes we will talk to, not to listed nodes, fully connect if (nodes.contains(listedNode)) { logger.trace("connecting to cluster node [{}]", listedNode); transportService.connectToNode(listedNode); } else { // its a listed node, light connect to it... logger.trace("connecting to listed node (light) [{}]", listedNode); transportService.connectToNodeLight(listedNode); } } catch (Exception e) { logger.debug("failed to connect to node [{}], ignoring...", e, listedNode); latch.countDown(); return; } } transportService.sendRequest(listedNode, ClusterStateAction.NAME, Requests.clusterStateRequest() .clear().nodes(true).local(true), TransportRequestOptions.options().withType(TransportRequestOptions.Type.STATE).withTimeout(pingTimeout), new BaseTransportResponseHandler<ClusterStateResponse>() { @Override public ClusterStateResponse newInstance() { return new ClusterStateResponse(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(ClusterStateResponse response) { clusterStateResponses.put(listedNode, response); latch.countDown(); } @Override public void handleException(TransportException e) { logger.info("failed to get local cluster state for {}, disconnecting...", e, listedNode); transportService.disconnectFromNode(listedNode); latch.countDown(); } }); } catch (Throwable e) { logger.info("failed to get local cluster state info for {}, disconnecting...", e, listedNode); transportService.disconnectFromNode(listedNode); latch.countDown(); } } }); } try { latch.await(); } catch (InterruptedException e) { return; } HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>(listedNodes); HashSet<DiscoveryNode> newFilteredNodes = new HashSet<DiscoveryNode>(); for (Map.Entry<DiscoveryNode, ClusterStateResponse> entry : clusterStateResponses.entrySet()) { if (!ignoreClusterName && !clusterName.equals(entry.getValue().getClusterName())) { logger.warn("node {} not part of the cluster {}, ignoring...", entry.getValue().getState().nodes().localNode(), clusterName); newFilteredNodes.add(entry.getKey()); continue; } for (ObjectCursor<DiscoveryNode> cursor : entry.getValue().getState().nodes().dataNodes().values()) { newNodes.add(cursor.value); } } nodes = validateNewNodes(newNodes); filteredNodes = ImmutableList.copyOf(newFilteredNodes); } } public static interface NodeCallback<T> { T doWithNode(DiscoveryNode node) throws ElasticsearchException; } public static interface NodeListenerCallback<Response> { void doWithNode(DiscoveryNode node, ActionListener<Response> listener) throws ElasticsearchException; } }
1no label
src_main_java_org_elasticsearch_client_transport_TransportClientNodesService.java
1,357
@Deprecated public class OPaginatedWithoutRidReuseCluster extends ODurableComponent implements OCluster { public static final String DEF_EXTENSION = ".pcl"; private static final int DISK_PAGE_SIZE = DISK_CACHE_PAGE_SIZE.getValueAsInteger(); private static final int LOWEST_FREELIST_BOUNDARY = PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY .getValueAsInteger(); private final static int FREE_LIST_SIZE = DISK_PAGE_SIZE - LOWEST_FREELIST_BOUNDARY; private OCompression compression; public static final String TYPE = "PHYSICAL"; private static final int PAGE_INDEX_OFFSET = 16; private static final int RECORD_POSITION_MASK = 0xFFFF; private static final int ONE_KB = 1024; private ODiskCache diskCache; private String name; private OLocalPaginatedStorage storageLocal; private volatile int id; private long fileId; private OStoragePaginatedClusterConfiguration config; private final OModificationLock externalModificationLock = new OModificationLock(); private OCacheEntry pinnedStateEntry; public OPaginatedWithoutRidReuseCluster() { super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean()); } @Override public void configure(OStorage storage, int id, String clusterName, String location, int dataSegmentId, Object... parameters) throws IOException { externalModificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { config = new OStoragePaginatedClusterConfiguration(storage.getConfiguration(), id, clusterName, null, true, OStoragePaginatedClusterConfiguration.DEFAULT_GROW_FACTOR, OStoragePaginatedClusterConfiguration.DEFAULT_GROW_FACTOR, OGlobalConfiguration.STORAGE_COMPRESSION_METHOD.getValueAsString()); config.name = clusterName; init((OLocalPaginatedStorage) storage, config); } finally { releaseExclusiveLock(); } } finally { externalModificationLock.releaseModificationLock(); } } @Override public void configure(OStorage storage, OStorageClusterConfiguration config) throws IOException { externalModificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { init((OLocalPaginatedStorage) storage, config); } finally { releaseExclusiveLock(); } } finally { externalModificationLock.releaseModificationLock(); } } private void init(OLocalPaginatedStorage storage, OStorageClusterConfiguration config) throws IOException { OFileUtils.checkValidName(config.getName()); this.config = (OStoragePaginatedClusterConfiguration) config; this.compression = OCompressionFactory.INSTANCE.getCompression(this.config.compression); storageLocal = storage; init(storage.getWALInstance()); diskCache = storageLocal.getDiskCache(); name = config.getName(); this.id = config.getId(); } public boolean exists() { return diskCache.exists(name + DEF_EXTENSION); } @Override public void create(int startSize) throws IOException { externalModificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { fileId = diskCache.openFile(name + DEF_EXTENSION); startDurableOperation(null); initCusterState(); endDurableOperation(null, false); if (config.root.clusters.size() <= config.id) config.root.clusters.add(config); else config.root.clusters.set(config.id, config); } finally { releaseExclusiveLock(); } } finally { externalModificationLock.releaseModificationLock(); } } @Override public void open() throws IOException { externalModificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { fileId = diskCache.openFile(name + DEF_EXTENSION); pinnedStateEntry = diskCache.load(fileId, 0, false); try { diskCache.pinPage(pinnedStateEntry); } finally { diskCache.release(pinnedStateEntry); } } finally { releaseExclusiveLock(); } } finally { externalModificationLock.releaseModificationLock(); } } @Override public void close() throws IOException { close(true); } public void close(boolean flush) throws IOException { externalModificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { if (flush) synch(); diskCache.closeFile(fileId, flush); } finally { releaseExclusiveLock(); } } finally { externalModificationLock.releaseModificationLock(); } } @Override public void delete() throws IOException { externalModificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { diskCache.deleteFile(fileId); } finally { releaseExclusiveLock(); } } finally { externalModificationLock.releaseModificationLock(); } } @Override public void set(ATTRIBUTES attribute, Object value) throws IOException { if (attribute == null) throw new IllegalArgumentException("attribute is null"); final String stringValue = value != null ? value.toString() : null; externalModificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { switch (attribute) { case NAME: setNameInternal(stringValue); break; case USE_WAL: setUseWalInternal(stringValue); break; case RECORD_GROW_FACTOR: setRecordGrowFactorInternal(stringValue); break; case RECORD_OVERFLOW_GROW_FACTOR: setRecordOverflowGrowFactorInternal(stringValue); break; case COMPRESSION: setCompressionInternal(stringValue); break; } } finally { releaseExclusiveLock(); } } finally { externalModificationLock.releaseModificationLock(); } } private void setCompressionInternal(String stringValue) { try { compression = OCompressionFactory.INSTANCE.getCompression(stringValue); config.compression = stringValue; storageLocal.getConfiguration().update(); } catch (IllegalArgumentException e) { throw new OStorageException("Invalid value for " + ATTRIBUTES.COMPRESSION + " attribute. ", e); } } private void setRecordOverflowGrowFactorInternal(String stringValue) { try { float growFactor = Float.parseFloat(stringValue); if (growFactor < 1) throw new OStorageException(ATTRIBUTES.RECORD_OVERFLOW_GROW_FACTOR + " can not be less than 1"); config.recordOverflowGrowFactor = growFactor; storageLocal.getConfiguration().update(); } catch (NumberFormatException nfe) { throw new OStorageException("Invalid value for cluster attribute " + ATTRIBUTES.RECORD_OVERFLOW_GROW_FACTOR + " was passed [" + stringValue + "].", nfe); } } private void setRecordGrowFactorInternal(String stringValue) { try { float growFactor = Float.parseFloat(stringValue); if (growFactor < 1) throw new OStorageException(ATTRIBUTES.RECORD_GROW_FACTOR + " can not be less than 1"); config.recordGrowFactor = growFactor; storageLocal.getConfiguration().update(); } catch (NumberFormatException nfe) { throw new OStorageException("Invalid value for cluster attribute " + ATTRIBUTES.RECORD_GROW_FACTOR + " was passed [" + stringValue + "].", nfe); } } private void setUseWalInternal(String stringValue) { if (!(stringValue.equals("true") || stringValue.equals("false"))) throw new OStorageException("Invalid value for cluster attribute " + ATTRIBUTES.USE_WAL + " was passed [" + stringValue + "]."); config.useWal = Boolean.valueOf(stringValue); storageLocal.getConfiguration().update(); } private void setNameInternal(String newName) throws IOException { diskCache.renameFile(fileId, this.name, newName); config.name = newName; storageLocal.renameCluster(name, newName); name = newName; storageLocal.getConfiguration().update(); } @Override public boolean useWal() { acquireSharedLock(); try { return config.useWal; } finally { releaseSharedLock(); } } @Override public float recordGrowFactor() { acquireSharedLock(); try { return config.recordGrowFactor; } finally { releaseSharedLock(); } } @Override public float recordOverflowGrowFactor() { acquireSharedLock(); try { return config.recordOverflowGrowFactor; } finally { releaseSharedLock(); } } @Override public String compression() { acquireSharedLock(); try { return config.compression; } finally { releaseSharedLock(); } } @Override public void convertToTombstone(OClusterPosition iPosition) throws IOException { throw new UnsupportedOperationException("convertToTombstone"); } public OPhysicalPosition createRecord(byte[] content, final ORecordVersion recordVersion, final byte recordType) throws IOException { externalModificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { final OStorageTransaction transaction = storageLocal.getStorageTransaction(); content = compression.compress(content); int grownContentSize = (int) (config.recordGrowFactor * content.length); int entryContentLength = grownContentSize + 2 * OByteSerializer.BYTE_SIZE + OIntegerSerializer.INT_SIZE + OLongSerializer.LONG_SIZE; if (entryContentLength < OClusterPage.MAX_RECORD_SIZE) { startDurableOperation(transaction); byte[] entryContent = new byte[entryContentLength]; int entryPosition = 0; entryContent[entryPosition] = recordType; entryPosition++; OIntegerSerializer.INSTANCE.serializeNative(content.length, entryContent, entryPosition); entryPosition += OIntegerSerializer.INT_SIZE; System.arraycopy(content, 0, entryContent, entryPosition, content.length); entryPosition += grownContentSize; entryContent[entryPosition] = 1; entryPosition++; OLongSerializer.INSTANCE.serializeNative(-1L, entryContent, entryPosition); ODurablePage.TrackMode trackMode = getTrackMode(); final AddEntryResult addEntryResult = addEntry(recordVersion, entryContent, trackMode); updateClusterState(trackMode, 1, addEntryResult.recordsSizeDiff); endDurableOperation(transaction, false); return createPhysicalPosition(recordType, addEntryResult.pagePointer, addEntryResult.recordVersion); } else { startDurableOperation(transaction); final OClusterPage.TrackMode trackMode = getTrackMode(); int entrySize = grownContentSize + OIntegerSerializer.INT_SIZE + OByteSerializer.BYTE_SIZE; int fullEntryPosition = 0; byte[] fullEntry = new byte[entrySize]; fullEntry[fullEntryPosition] = recordType; fullEntryPosition++; OIntegerSerializer.INSTANCE.serializeNative(content.length, fullEntry, fullEntryPosition); fullEntryPosition += OIntegerSerializer.INT_SIZE; System.arraycopy(content, 0, fullEntry, fullEntryPosition, content.length); long prevPageRecordPointer = -1; long firstPagePointer = -1; ORecordVersion version = null; int from = 0; int to = from + (OClusterPage.MAX_RECORD_SIZE - OByteSerializer.BYTE_SIZE - OLongSerializer.LONG_SIZE); int recordsSizeDiff = 0; do { byte[] entryContent = new byte[to - from + OByteSerializer.BYTE_SIZE + OLongSerializer.LONG_SIZE]; System.arraycopy(fullEntry, from, entryContent, 0, to - from); if (from > 0) entryContent[entryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 0; else entryContent[entryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 1; OLongSerializer.INSTANCE.serializeNative(-1L, entryContent, entryContent.length - OLongSerializer.LONG_SIZE); final AddEntryResult addEntryResult = addEntry(recordVersion, entryContent, trackMode); recordsSizeDiff += addEntryResult.recordsSizeDiff; if (firstPagePointer == -1) { firstPagePointer = addEntryResult.pagePointer; version = addEntryResult.recordVersion; } long addedPagePointer = addEntryResult.pagePointer; if (prevPageRecordPointer >= 0) { long prevPageIndex = prevPageRecordPointer >>> PAGE_INDEX_OFFSET; int prevPageRecordPosition = (int) (prevPageRecordPointer & RECORD_POSITION_MASK); final OCacheEntry prevPageCacheEntry = diskCache.load(fileId, prevPageIndex, false); final OCachePointer prevPageMemoryPointer = prevPageCacheEntry.getCachePointer(); prevPageMemoryPointer.acquireExclusiveLock(); try { final OClusterPage prevPage = new OClusterPage(prevPageMemoryPointer.getDataPointer(), false, ODurablePage.TrackMode.FULL); int prevRecordPageOffset = prevPage.getRecordPageOffset(prevPageRecordPosition); int prevPageRecordSize = prevPage.getRecordSize(prevPageRecordPosition); prevPage.setLongValue(prevRecordPageOffset + prevPageRecordSize - OLongSerializer.LONG_SIZE, addedPagePointer); logPageChanges(prevPage, fileId, prevPageIndex, false); prevPageCacheEntry.markDirty(); } finally { prevPageMemoryPointer.releaseExclusiveLock(); diskCache.release(prevPageCacheEntry); } } prevPageRecordPointer = addedPagePointer; from = to; to = to + (OClusterPage.MAX_RECORD_SIZE - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE); if (to > fullEntry.length) to = fullEntry.length; } while (from < to); updateClusterState(trackMode, 1, recordsSizeDiff); endDurableOperation(transaction, false); return createPhysicalPosition(recordType, firstPagePointer, version); } } finally { releaseExclusiveLock(); } } finally { externalModificationLock.releaseModificationLock(); } } private void updateClusterState(ODurablePage.TrackMode trackMode, long sizeDiff, long recordsSizeDiff) throws IOException { diskCache.loadPinnedPage(pinnedStateEntry); OCachePointer statePointer = pinnedStateEntry.getCachePointer(); statePointer.acquireExclusiveLock(); try { OPaginatedClusterState paginatedClusterState = new OPaginatedClusterState(statePointer.getDataPointer(), trackMode); paginatedClusterState.setSize(paginatedClusterState.getSize() + sizeDiff); paginatedClusterState.setRecordsSize(paginatedClusterState.getRecordsSize() + recordsSizeDiff); logPageChanges(paginatedClusterState, fileId, pinnedStateEntry.getPageIndex(), false); pinnedStateEntry.markDirty(); } finally { statePointer.releaseExclusiveLock(); diskCache.release(pinnedStateEntry); } } private OPhysicalPosition createPhysicalPosition(byte recordType, long firstPagePointer, ORecordVersion version) { final OPhysicalPosition physicalPosition = new OPhysicalPosition(); physicalPosition.recordType = recordType; physicalPosition.recordSize = -1; physicalPosition.dataSegmentId = -1; physicalPosition.dataSegmentPos = -1; physicalPosition.clusterPosition = OClusterPositionFactory.INSTANCE.valueOf(firstPagePointer); physicalPosition.recordVersion = version; return physicalPosition; } public ORawBuffer readRecord(OClusterPosition clusterPosition) throws IOException { acquireSharedLock(); try { long pagePointer = clusterPosition.longValue(); int recordPosition = (int) (pagePointer & RECORD_POSITION_MASK); long pageIndex = pagePointer >>> PAGE_INDEX_OFFSET; if (diskCache.getFilledUpTo(fileId) <= pageIndex) return null; ORecordVersion recordVersion = null; OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false); OCachePointer pointer = cacheEntry.getCachePointer(); try { final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, ODurablePage.TrackMode.NONE); int recordPageOffset = localPage.getRecordPageOffset(recordPosition); if (recordPageOffset < 0) return null; recordVersion = localPage.getRecordVersion(recordPosition); } finally { diskCache.release(cacheEntry); } byte[] fullContent = readFullEntry(clusterPosition); if (fullContent == null) return null; int fullContentPosition = 0; byte recordType = fullContent[fullContentPosition]; fullContentPosition++; int readContentSize = OIntegerSerializer.INSTANCE.deserializeNative(fullContent, fullContentPosition); fullContentPosition += OIntegerSerializer.INT_SIZE; byte[] recordContent = new byte[readContentSize]; System.arraycopy(fullContent, fullContentPosition, recordContent, 0, recordContent.length); recordContent = compression.uncompress(recordContent); return new ORawBuffer(recordContent, recordVersion, recordType); } finally { releaseSharedLock(); } } private byte[] readFullEntry(OClusterPosition clusterPosition) throws IOException { long pagePointer = clusterPosition.longValue(); int recordPosition = (int) (pagePointer & RECORD_POSITION_MASK); long pageIndex = pagePointer >>> PAGE_INDEX_OFFSET; if (diskCache.getFilledUpTo(fileId) <= pageIndex) return null; final List<byte[]> recordChunks = new ArrayList<byte[]>(); int contentSize = 0; long nextPagePointer = -1; boolean firstEntry = true; do { OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false); OCachePointer pointer = cacheEntry.getCachePointer(); try { final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, ODurablePage.TrackMode.NONE); int recordPageOffset = localPage.getRecordPageOffset(recordPosition); if (recordPageOffset < 0) { if (recordChunks.isEmpty()) return null; else throw new OStorageException("Content of record " + new ORecordId(id, clusterPosition) + " was broken."); } byte[] content = localPage.getBinaryValue(recordPageOffset, localPage.getRecordSize(recordPosition)); if (firstEntry && content[content.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] == 0) return null; recordChunks.add(content); nextPagePointer = OLongSerializer.INSTANCE.deserializeNative(content, content.length - OLongSerializer.LONG_SIZE); contentSize += content.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE; firstEntry = false; } finally { diskCache.release(cacheEntry); } pageIndex = nextPagePointer >>> PAGE_INDEX_OFFSET; recordPosition = (int) (nextPagePointer & RECORD_POSITION_MASK); } while (nextPagePointer >= 0); byte[] fullContent; if (recordChunks.size() == 1) fullContent = recordChunks.get(0); else { fullContent = new byte[contentSize + OLongSerializer.LONG_SIZE + OByteSerializer.BYTE_SIZE]; int fullContentPosition = 0; for (byte[] recordChuck : recordChunks) { System.arraycopy(recordChuck, 0, fullContent, fullContentPosition, recordChuck.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE); fullContentPosition += recordChuck.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE; } } return fullContent; } public boolean deleteRecord(OClusterPosition clusterPosition) throws IOException { externalModificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { final OStorageTransaction transaction = storageLocal.getStorageTransaction(); long pagePointer = clusterPosition.longValue(); int recordPosition = (int) (pagePointer & RECORD_POSITION_MASK); long pageIndex = pagePointer >>> PAGE_INDEX_OFFSET; if (diskCache.getFilledUpTo(fileId) <= pageIndex) return false; final OClusterPage.TrackMode trackMode = getTrackMode(); long nextPagePointer = -1; int removedContentSize = 0; do { final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false); final OCachePointer pointer = cacheEntry.getCachePointer(); pointer.acquireExclusiveLock(); int initialFreePageIndex; try { final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, trackMode); initialFreePageIndex = calculateFreePageIndex(localPage); int recordPageOffset = localPage.getRecordPageOffset(recordPosition); if (recordPageOffset < 0) { if (removedContentSize == 0) return false; else throw new OStorageException("Content of record " + new ORecordId(id, clusterPosition) + " was broken."); } else if (removedContentSize == 0) { startDurableOperation(transaction); } byte[] content = localPage.getBinaryValue(recordPageOffset, localPage.getRecordSize(recordPosition)); int initialFreeSpace = localPage.getFreeSpace(); localPage.deleteRecord(recordPosition); removedContentSize += localPage.getFreeSpace() - initialFreeSpace; nextPagePointer = OLongSerializer.INSTANCE.deserializeNative(content, content.length - OLongSerializer.LONG_SIZE); logPageChanges(localPage, fileId, pageIndex, false); cacheEntry.markDirty(); } finally { pointer.releaseExclusiveLock(); diskCache.release(cacheEntry); } updateFreePagesIndex(initialFreePageIndex, pageIndex, trackMode); pageIndex = nextPagePointer >>> PAGE_INDEX_OFFSET; recordPosition = (int) (nextPagePointer & RECORD_POSITION_MASK); } while (nextPagePointer >= 0); updateClusterState(trackMode, -1, -removedContentSize); endDurableOperation(transaction, false); return true; } finally { releaseExclusiveLock(); } } finally { externalModificationLock.releaseModificationLock(); } } public void updateRecord(OClusterPosition clusterPosition, byte[] content, final ORecordVersion recordVersion, final byte recordType) throws IOException { externalModificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { final OStorageTransaction transaction = storageLocal.getStorageTransaction(); byte[] fullEntryContent = readFullEntry(clusterPosition); if (fullEntryContent == null) return; content = compression.compress(content); int updatedContentLength = content.length + 2 * OByteSerializer.BYTE_SIZE + OIntegerSerializer.INT_SIZE + OLongSerializer.LONG_SIZE; long pagePointer = clusterPosition.longValue(); int recordPosition = (int) (pagePointer & RECORD_POSITION_MASK); long pageIndex = pagePointer >>> PAGE_INDEX_OFFSET; byte[] recordEntry; if (updatedContentLength <= fullEntryContent.length) recordEntry = new byte[fullEntryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE]; else { int grownContent = (int) (content.length * config.recordOverflowGrowFactor); recordEntry = new byte[grownContent + OByteSerializer.BYTE_SIZE + OIntegerSerializer.INT_SIZE]; } final OClusterPage.TrackMode trackMode = getTrackMode(); startDurableOperation(transaction); int entryPosition = 0; recordEntry[entryPosition] = recordType; entryPosition++; OIntegerSerializer.INSTANCE.serializeNative(content.length, recordEntry, entryPosition); entryPosition += OIntegerSerializer.INT_SIZE; System.arraycopy(content, 0, recordEntry, entryPosition, content.length); int recordsSizeDiff = 0; long prevPageRecordPointer = -1; int currentPos = 0; while (pagePointer >= 0 && currentPos < recordEntry.length) { recordPosition = (int) (pagePointer & RECORD_POSITION_MASK); pageIndex = pagePointer >>> PAGE_INDEX_OFFSET; int freePageIndex; final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false); final OCachePointer dataPointer = cacheEntry.getCachePointer(); dataPointer.acquireExclusiveLock(); try { final OClusterPage localPage = new OClusterPage(dataPointer.getDataPointer(), false, trackMode); int freeSpace = localPage.getFreeSpace(); freePageIndex = calculateFreePageIndex(localPage); int recordPageOffset = localPage.getRecordPageOffset(recordPosition); int chunkSize = localPage.getRecordSize(recordPosition); long nextPagePointer = localPage.getLongValue(recordPageOffset + +chunkSize - OLongSerializer.LONG_SIZE); int newChunkLen = Math.min(recordEntry.length - currentPos + OLongSerializer.LONG_SIZE + OByteSerializer.BYTE_SIZE, chunkSize); int dataLen = newChunkLen - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE; byte[] newRecordChunk = new byte[newChunkLen]; System.arraycopy(recordEntry, currentPos, newRecordChunk, 0, dataLen); if (currentPos > 0) newRecordChunk[newRecordChunk.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 0; else newRecordChunk[newRecordChunk.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 1; OLongSerializer.INSTANCE.serializeNative(-1L, newRecordChunk, newRecordChunk.length - OLongSerializer.LONG_SIZE); if (prevPageRecordPointer >= 0) { long prevPageIndex = prevPageRecordPointer >>> PAGE_INDEX_OFFSET; int prevPageRecordPosition = (int) (prevPageRecordPointer & RECORD_POSITION_MASK); final OCacheEntry prevPageCacheEntry = diskCache.load(fileId, prevPageIndex, false); final OCachePointer prevPageMemoryPointer = prevPageCacheEntry.getCachePointer(); prevPageMemoryPointer.acquireExclusiveLock(); try { final OClusterPage prevPage = new OClusterPage(prevPageMemoryPointer.getDataPointer(), false, trackMode); int prevRecordPageOffset = prevPage.getRecordPageOffset(prevPageRecordPosition); int prevPageRecordSize = prevPage.getRecordSize(prevPageRecordPosition); prevPage.setLongValue(prevRecordPageOffset + prevPageRecordSize - OLongSerializer.LONG_SIZE, pagePointer); logPageChanges(prevPage, fileId, prevPageIndex, false); prevPageCacheEntry.markDirty(); } finally { prevPageMemoryPointer.releaseExclusiveLock(); diskCache.release(prevPageCacheEntry); } } localPage.replaceRecord(recordPosition, newRecordChunk, recordVersion.getCounter() != -2 ? recordVersion : null); currentPos += dataLen; recordsSizeDiff += freeSpace - localPage.getFreeSpace(); prevPageRecordPointer = pagePointer; pagePointer = nextPagePointer; logPageChanges(localPage, fileId, pageIndex, false); cacheEntry.markDirty(); } finally { dataPointer.releaseExclusiveLock(); diskCache.release(cacheEntry); } updateFreePagesIndex(freePageIndex, pageIndex, trackMode); } int from = currentPos; int to = from + (OClusterPage.MAX_RECORD_SIZE - OByteSerializer.BYTE_SIZE - OLongSerializer.LONG_SIZE); if (to > recordEntry.length) to = recordEntry.length; while (from < to) { byte[] entryContent = new byte[to - from + OByteSerializer.BYTE_SIZE + OLongSerializer.LONG_SIZE]; System.arraycopy(recordEntry, from, entryContent, 0, to - from); if (from > 0) entryContent[entryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 0; else entryContent[entryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 1; OLongSerializer.INSTANCE.serializeNative(-1L, entryContent, entryContent.length - OLongSerializer.LONG_SIZE); final AddEntryResult addEntryResult = addEntry(recordVersion, entryContent, trackMode); recordsSizeDiff += addEntryResult.recordsSizeDiff; long addedPagePointer = addEntryResult.pagePointer; if (prevPageRecordPointer >= 0) { long prevPageIndex = prevPageRecordPointer >>> PAGE_INDEX_OFFSET; int prevPageRecordPosition = (int) (prevPageRecordPointer & RECORD_POSITION_MASK); final OCacheEntry prevPageCacheEntry = diskCache.load(fileId, prevPageIndex, false); final OCachePointer prevPageMemoryPointer = prevPageCacheEntry.getCachePointer(); prevPageMemoryPointer.acquireExclusiveLock(); try { final OClusterPage prevPage = new OClusterPage(prevPageMemoryPointer.getDataPointer(), false, trackMode); int recordPageOffset = prevPage.getRecordPageOffset(prevPageRecordPosition); int prevPageRecordSize = prevPage.getRecordSize(prevPageRecordPosition); prevPage.setLongValue(recordPageOffset + prevPageRecordSize - OLongSerializer.LONG_SIZE, addedPagePointer); logPageChanges(prevPage, fileId, prevPageIndex, false); prevPageCacheEntry.markDirty(); } finally { prevPageMemoryPointer.releaseExclusiveLock(); diskCache.release(prevPageCacheEntry); } } prevPageRecordPointer = addedPagePointer; from = to; to = to + (OClusterPage.MAX_RECORD_SIZE - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE); if (to > recordEntry.length) to = recordEntry.length; } updateClusterState(trackMode, 0, recordsSizeDiff); endDurableOperation(transaction, false); } finally { releaseExclusiveLock(); } } finally { externalModificationLock.releaseModificationLock(); } } private AddEntryResult addEntry(ORecordVersion recordVersion, byte[] entryContent, OClusterPage.TrackMode trackMode) throws IOException { final FindFreePageResult findFreePageResult = findFreePage(entryContent.length, trackMode); int freePageIndex = findFreePageResult.freePageIndex; long pageIndex = findFreePageResult.pageIndex; boolean newRecord = freePageIndex >= FREE_LIST_SIZE; final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false); final OCachePointer pagePointer = cacheEntry.getCachePointer(); pagePointer.acquireExclusiveLock(); int recordSizesDiff; int position; final ORecordVersion finalVersion; try { final OClusterPage localPage = new OClusterPage(pagePointer.getDataPointer(), newRecord, trackMode); assert newRecord || freePageIndex == calculateFreePageIndex(localPage); int initialFreeSpace = localPage.getFreeSpace(); position = localPage.appendRecord(recordVersion, entryContent, false); assert position >= 0; finalVersion = localPage.getRecordVersion(position); int freeSpace = localPage.getFreeSpace(); recordSizesDiff = initialFreeSpace - freeSpace; logPageChanges(localPage, fileId, pageIndex, newRecord); cacheEntry.markDirty(); } finally { pagePointer.releaseExclusiveLock(); diskCache.release(cacheEntry); } updateFreePagesIndex(freePageIndex, pageIndex, trackMode); return new AddEntryResult((pageIndex << PAGE_INDEX_OFFSET) | position, finalVersion, recordSizesDiff); } private FindFreePageResult findFreePage(int contentSize, OClusterPage.TrackMode trackMode) throws IOException { diskCache.loadPinnedPage(pinnedStateEntry); OCachePointer pinnedPagePointer = pinnedStateEntry.getCachePointer(); try { while (true) { int freePageIndex = contentSize / ONE_KB; freePageIndex -= PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getValueAsInteger(); if (freePageIndex < 0) freePageIndex = 0; OPaginatedClusterState freePageLists = new OPaginatedClusterState(pinnedPagePointer.getDataPointer(), ODurablePage.TrackMode.NONE); long pageIndex; do { pageIndex = freePageLists.getFreeListPage(freePageIndex); freePageIndex++; } while (pageIndex < 0 && freePageIndex < FREE_LIST_SIZE); if (pageIndex < 0) pageIndex = diskCache.getFilledUpTo(fileId); else freePageIndex--; if (freePageIndex < FREE_LIST_SIZE) { OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false); OCachePointer pointer = cacheEntry.getCachePointer(); int realFreePageIndex; try { OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, ODurablePage.TrackMode.NONE); realFreePageIndex = calculateFreePageIndex(localPage); } finally { diskCache.release(cacheEntry); } if (realFreePageIndex != freePageIndex) { OLogManager.instance().warn(this, "Page in file %s with index %d was placed in wrong free list, this error will be fixed automatically.", name + DEF_EXTENSION, pageIndex); updateFreePagesIndex(freePageIndex, pageIndex, trackMode); continue; } } return new FindFreePageResult(pageIndex, freePageIndex); } } finally { diskCache.release(pinnedStateEntry); } } private void updateFreePagesIndex(int prevFreePageIndex, long pageIndex, OClusterPage.TrackMode trackMode) throws IOException { final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false); final OCachePointer pointer = cacheEntry.getCachePointer(); pointer.acquireExclusiveLock(); try { final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, trackMode); int newFreePageIndex = calculateFreePageIndex(localPage); if (prevFreePageIndex == newFreePageIndex) return; long nextPageIndex = localPage.getNextPage(); long prevPageIndex = localPage.getPrevPage(); if (prevPageIndex >= 0) { final OCacheEntry prevPageCacheEntry = diskCache.load(fileId, prevPageIndex, false); final OCachePointer prevPagePointer = prevPageCacheEntry.getCachePointer(); prevPagePointer.acquireExclusiveLock(); try { final OClusterPage prevPage = new OClusterPage(prevPagePointer.getDataPointer(), false, trackMode); assert calculateFreePageIndex(prevPage) == prevFreePageIndex; prevPage.setNextPage(nextPageIndex); logPageChanges(prevPage, fileId, prevPageIndex, false); prevPageCacheEntry.markDirty(); } finally { prevPagePointer.releaseExclusiveLock(); diskCache.release(prevPageCacheEntry); } } if (nextPageIndex >= 0) { final OCacheEntry nextPageCacheEntry = diskCache.load(fileId, nextPageIndex, false); final OCachePointer nextPagePointer = nextPageCacheEntry.getCachePointer(); nextPagePointer.acquireExclusiveLock(); try { final OClusterPage nextPage = new OClusterPage(nextPagePointer.getDataPointer(), false, trackMode); if (calculateFreePageIndex(nextPage) != prevFreePageIndex) calculateFreePageIndex(nextPage); assert calculateFreePageIndex(nextPage) == prevFreePageIndex; nextPage.setPrevPage(prevPageIndex); logPageChanges(nextPage, fileId, nextPageIndex, false); nextPageCacheEntry.markDirty(); } finally { nextPagePointer.releaseExclusiveLock(); diskCache.release(nextPageCacheEntry); } } localPage.setNextPage(-1); localPage.setPrevPage(-1); if (prevFreePageIndex < 0 && newFreePageIndex < 0) return; if (prevFreePageIndex >= 0 && prevFreePageIndex < FREE_LIST_SIZE) { if (prevPageIndex < 0) updateFreePagesList(prevFreePageIndex, nextPageIndex); } if (newFreePageIndex >= 0) { long oldFreePage; diskCache.loadPinnedPage(pinnedStateEntry); OCachePointer freeListPointer = pinnedStateEntry.getCachePointer(); try { OPaginatedClusterState clusterFreeList = new OPaginatedClusterState(freeListPointer.getDataPointer(), ODurablePage.TrackMode.NONE); oldFreePage = clusterFreeList.getFreeListPage(newFreePageIndex); } finally { diskCache.release(pinnedStateEntry); } if (oldFreePage >= 0) { final OCacheEntry oldFreePageCacheEntry = diskCache.load(fileId, oldFreePage, false); final OCachePointer oldFreePagePointer = oldFreePageCacheEntry.getCachePointer(); oldFreePagePointer.acquireExclusiveLock(); try { final OClusterPage oldFreeLocalPage = new OClusterPage(oldFreePagePointer.getDataPointer(), false, trackMode); assert calculateFreePageIndex(oldFreeLocalPage) == newFreePageIndex; oldFreeLocalPage.setPrevPage(pageIndex); logPageChanges(oldFreeLocalPage, fileId, oldFreePage, false); oldFreePageCacheEntry.markDirty(); } finally { oldFreePagePointer.releaseExclusiveLock(); diskCache.release(oldFreePageCacheEntry); } localPage.setNextPage(oldFreePage); localPage.setPrevPage(-1); } updateFreePagesList(newFreePageIndex, pageIndex); } logPageChanges(localPage, fileId, pageIndex, false); cacheEntry.markDirty(); } finally { pointer.releaseExclusiveLock(); diskCache.release(cacheEntry); } } private void updateFreePagesList(int freeListIndex, long pageIndex) throws IOException { ODurablePage.TrackMode trackMode = getTrackMode(); diskCache.loadPinnedPage(pinnedStateEntry); OCachePointer statePointer = pinnedStateEntry.getCachePointer(); statePointer.acquireExclusiveLock(); try { OPaginatedClusterState paginatedClusterState = new OPaginatedClusterState(statePointer.getDataPointer(), trackMode); paginatedClusterState.setFreeListPage(freeListIndex, pageIndex); logPageChanges(paginatedClusterState, fileId, pinnedStateEntry.getPageIndex(), false); pinnedStateEntry.markDirty(); } finally { statePointer.releaseExclusiveLock(); diskCache.release(pinnedStateEntry); } } private int calculateFreePageIndex(OClusterPage localPage) { int newFreePageIndex; if (localPage.isEmpty()) newFreePageIndex = FREE_LIST_SIZE - 1; else { newFreePageIndex = (localPage.getMaxRecordSize() - (ONE_KB - 1)) / ONE_KB; newFreePageIndex -= LOWEST_FREELIST_BOUNDARY; } return newFreePageIndex; } @Override public long getTombstonesCount() { return 0; } @Override public boolean hasTombstonesSupport() { return false; } @Override public void truncate() throws IOException { storageLocal.checkForClusterPermissions(getName()); externalModificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { if (config.useWal) startDurableOperation(null); diskCache.truncateFile(fileId); initCusterState(); if (config.useWal) endDurableOperation(null, false); } finally { releaseExclusiveLock(); } } finally { externalModificationLock.releaseModificationLock(); } storageLocal.scheduleFullCheckpoint(); } private void initCusterState() throws IOException { ODurablePage.TrackMode trackMode = getTrackMode(); pinnedStateEntry = diskCache.allocateNewPage(fileId); OCachePointer statePointer = pinnedStateEntry.getCachePointer(); statePointer.acquireExclusiveLock(); try { OPaginatedClusterState paginatedClusterState = new OPaginatedClusterState(statePointer.getDataPointer(), trackMode); diskCache.pinPage(pinnedStateEntry); paginatedClusterState.setSize(0); paginatedClusterState.setRecordsSize(0); for (int i = 0; i < FREE_LIST_SIZE; i++) paginatedClusterState.setFreeListPage(i, -1); logPageChanges(paginatedClusterState, fileId, pinnedStateEntry.getPageIndex(), true); pinnedStateEntry.markDirty(); } finally { statePointer.releaseExclusiveLock(); diskCache.release(pinnedStateEntry); } } @Override public String getType() { return TYPE; } @Override public int getDataSegmentId() { return -1; } @Override public boolean addPhysicalPosition(OPhysicalPosition iPPosition) throws IOException { throw new UnsupportedOperationException("addPhysicalPosition"); } @Override public OPhysicalPosition getPhysicalPosition(OPhysicalPosition position) throws IOException { acquireSharedLock(); try { OClusterPosition clusterPosition = position.clusterPosition; long pagePointer = clusterPosition.longValue(); long pageIndex = pagePointer >>> PAGE_INDEX_OFFSET; int recordPosition = (int) (pagePointer & RECORD_POSITION_MASK); long pagesCount = diskCache.getFilledUpTo(fileId); if (pageIndex >= pagesCount) return null; OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false); OCachePointer pointer = cacheEntry.getCachePointer(); try { final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, ODurablePage.TrackMode.NONE); int recordPageOffset = localPage.getRecordPageOffset(recordPosition); if (recordPageOffset < 0) return null; int recordSize = localPage.getRecordSize(recordPosition); if (localPage.getByteValue(recordPageOffset + recordSize - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE) == 0) return null; final OPhysicalPosition physicalPosition = new OPhysicalPosition(); physicalPosition.dataSegmentId = -1; physicalPosition.dataSegmentPos = -1; physicalPosition.recordSize = -1; physicalPosition.recordType = localPage.getByteValue(recordPageOffset); physicalPosition.recordVersion = localPage.getRecordVersion(recordPosition); physicalPosition.clusterPosition = position.clusterPosition; return physicalPosition; } finally { diskCache.release(cacheEntry); } } finally { releaseSharedLock(); } } @Override public void updateDataSegmentPosition(OClusterPosition iPosition, int iDataSegmentId, long iDataPosition) throws IOException { throw new UnsupportedOperationException("updateDataSegmentPosition"); } @Override public void removePhysicalPosition(OClusterPosition iPosition) throws IOException { throw new UnsupportedOperationException("updateDataSegmentPosition"); } @Override public void updateRecordType(OClusterPosition iPosition, byte iRecordType) throws IOException { throw new UnsupportedOperationException("updateRecordType"); } @Override public void updateVersion(OClusterPosition iPosition, ORecordVersion iVersion) throws IOException { throw new UnsupportedOperationException("updateVersion"); } @Override public long getEntries() { acquireSharedLock(); try { diskCache.loadPinnedPage(pinnedStateEntry); OCachePointer statePointer = pinnedStateEntry.getCachePointer(); try { return new OPaginatedClusterState(statePointer.getDataPointer(), ODurablePage.TrackMode.NONE).getSize(); } finally { diskCache.release(pinnedStateEntry); } } catch (IOException ioe) { throw new OStorageException("Error during retrieval of size of " + name + " cluster."); } finally { releaseSharedLock(); } } @Override public OClusterPosition getFirstPosition() throws IOException { acquireSharedLock(); try { final OPhysicalPosition[] physicalPositions = findFirstPhysicalPosition(0, 0); if (physicalPositions.length == 0) return OClusterPosition.INVALID_POSITION; return physicalPositions[0].clusterPosition; } finally { releaseSharedLock(); } } @Override public OClusterPosition getLastPosition() throws IOException { acquireSharedLock(); try { long pagesCount = diskCache.getFilledUpTo(fileId); for (long i = pagesCount - 1; i >= 0; i--) { OCacheEntry cacheEntry = diskCache.load(fileId, i, false); OCachePointer pagePointer = cacheEntry.getCachePointer(); try { final OClusterPage localPage = new OClusterPage(pagePointer.getDataPointer(), false, ODurablePage.TrackMode.NONE); final int recordsCount = localPage.getRecordsCount(); if (recordsCount > 0) { int recordPosition = Integer.MAX_VALUE; for (int n = 0; n < recordsCount; n++) { recordPosition = localPage.findLastRecord(recordPosition); int recordPageOffset = localPage.getRecordPageOffset(recordPosition); int recordSize = localPage.getRecordSize(recordPosition); if (localPage.getByteValue(recordPageOffset + recordSize - OByteSerializer.BYTE_SIZE - OLongSerializer.LONG_SIZE) == 1) return OClusterPositionFactory.INSTANCE.valueOf((i << PAGE_INDEX_OFFSET) | recordPosition); recordPosition--; } } } finally { diskCache.release(cacheEntry); } } return OClusterPosition.INVALID_POSITION; } finally { releaseSharedLock(); } } @Override public void lock() { throw new UnsupportedOperationException("lock"); } @Override public void unlock() { throw new UnsupportedOperationException("unlock"); } @Override public int getId() { return id; } @Override public void synch() throws IOException { acquireSharedLock(); try { diskCache.flushFile(fileId); } finally { releaseSharedLock(); } } @Override public void setSoftlyClosed(boolean softlyClosed) throws IOException { acquireExclusiveLock(); try { diskCache.setSoftlyClosed(fileId, softlyClosed); } finally { releaseExclusiveLock(); } } @Override public boolean wasSoftlyClosed() throws IOException { acquireSharedLock(); try { return diskCache.wasSoftlyClosed(fileId); } finally { releaseSharedLock(); } } @Override public String getName() { acquireSharedLock(); try { return name; } finally { releaseSharedLock(); } } @Override public long getRecordsSize() throws IOException { acquireSharedLock(); try { diskCache.loadPinnedPage(pinnedStateEntry); OCachePointer statePointer = pinnedStateEntry.getCachePointer(); try { return new OPaginatedClusterState(statePointer.getDataPointer(), ODurablePage.TrackMode.NONE).getRecordsSize(); } finally { diskCache.release(pinnedStateEntry); } } finally { releaseSharedLock(); } } @Override public boolean isHashBased() { return false; } @Override public OClusterEntryIterator absoluteIterator() { acquireSharedLock(); try { return new OClusterEntryIterator(this); } finally { releaseSharedLock(); } } @Override public OPhysicalPosition[] higherPositions(OPhysicalPosition position) throws IOException { acquireSharedLock(); try { OClusterPosition clusterPosition = position.clusterPosition; long pagePointer = clusterPosition.longValue(); long pageIndex; int recordPosition; if (pagePointer >= 0) { pageIndex = pagePointer >>> PAGE_INDEX_OFFSET; recordPosition = (int) (pagePointer & RECORD_POSITION_MASK) + 1; } else { pageIndex = 0; recordPosition = 0; } return findFirstPhysicalPosition(pageIndex, recordPosition); } finally { releaseSharedLock(); } } @Override public OPhysicalPosition[] ceilingPositions(OPhysicalPosition position) throws IOException { acquireSharedLock(); try { OClusterPosition clusterPosition = position.clusterPosition; long pagePointer = clusterPosition.longValue(); long pageIndex = pagePointer >>> PAGE_INDEX_OFFSET; int recordPosition = (int) (pagePointer & RECORD_POSITION_MASK); return findFirstPhysicalPosition(pageIndex, recordPosition); } finally { releaseSharedLock(); } } @Override public OPhysicalPosition[] lowerPositions(OPhysicalPosition position) throws IOException { acquireSharedLock(); try { OClusterPosition clusterPosition = position.clusterPosition; long pagePointer = clusterPosition.longValue(); long pageIndex = pagePointer >>> PAGE_INDEX_OFFSET; int recordPosition = (int) (pagePointer & RECORD_POSITION_MASK) - 1; return findLastPhysicalPosition(pageIndex, recordPosition); } finally { releaseSharedLock(); } } @Override public OPhysicalPosition[] floorPositions(OPhysicalPosition position) throws IOException { acquireSharedLock(); try { OClusterPosition clusterPosition = position.clusterPosition; long pagePointer = clusterPosition.longValue(); long pageIndex = pagePointer >>> PAGE_INDEX_OFFSET; int recordPosition = (int) (pagePointer & RECORD_POSITION_MASK); return findLastPhysicalPosition(pageIndex, recordPosition); } finally { releaseSharedLock(); } } @Override protected void endDurableOperation(OStorageTransaction transaction, boolean rollback) throws IOException { if (!config.useWal) return; super.endDurableOperation(transaction, rollback); } @Override protected void startDurableOperation(OStorageTransaction transaction) throws IOException { if (!config.useWal) return; super.startDurableOperation(transaction); } @Override protected void logPageChanges(ODurablePage localPage, long fileId, long pageIndex, boolean isNewPage) throws IOException { if (!config.useWal) return; super.logPageChanges(localPage, fileId, pageIndex, isNewPage); } @Override protected ODurablePage.TrackMode getTrackMode() { if (!config.useWal) return ODurablePage.TrackMode.NONE; return super.getTrackMode(); } public OModificationLock getExternalModificationLock() { return externalModificationLock; } private OPhysicalPosition[] findFirstPhysicalPosition(long pageIndex, int recordPosition) throws IOException { long pagesCount = diskCache.getFilledUpTo(fileId); pageLoop: for (long i = pageIndex; i < pagesCount; i++) { OCacheEntry cacheEntry = diskCache.load(fileId, i, false); OCachePointer pointer = cacheEntry.getCachePointer(); try { final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, ODurablePage.TrackMode.NONE); int recordsCount = localPage.getRecordsCount(); if (recordsCount > 0) { while (true) { recordPosition = localPage.findFirstRecord(recordPosition); if (recordPosition < 0) { recordPosition = 0; continue pageLoop; } else { int recordPageOffset = localPage.getRecordPageOffset(recordPosition); int recordSize = localPage.getRecordSize(recordPosition); if (localPage.getByteValue(recordPageOffset + recordSize - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE) == 1) { OPhysicalPosition physicalPosition = new OPhysicalPosition(); physicalPosition.clusterPosition = OClusterPositionFactory.INSTANCE.valueOf((i << PAGE_INDEX_OFFSET) | recordPosition); physicalPosition.recordVersion = localPage.getRecordVersion(recordPosition); physicalPosition.recordType = localPage.getByteValue(recordPageOffset); physicalPosition.recordSize = -1; physicalPosition.dataSegmentId = -1; physicalPosition.dataSegmentPos = -1; return new OPhysicalPosition[] { physicalPosition }; } recordPosition++; } } } else recordPosition = 0; } finally { diskCache.release(cacheEntry); } } return new OPhysicalPosition[0]; } private OPhysicalPosition[] findLastPhysicalPosition(long pageIndex, int recordPosition) throws IOException { long pagesCount = diskCache.getFilledUpTo(fileId); long endPageIndex; if (pagesCount <= pageIndex) { recordPosition = Integer.MAX_VALUE; endPageIndex = pagesCount - 1; } else { endPageIndex = pageIndex; } pageLoop: for (long i = endPageIndex; i >= 0; i--) { OCacheEntry cacheEntry = diskCache.load(fileId, i, false); OCachePointer pointer = cacheEntry.getCachePointer(); try { final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, ODurablePage.TrackMode.NONE); int recordsCount = localPage.getRecordsCount(); if (recordsCount > 0) { while (true) { recordPosition = localPage.findLastRecord(recordPosition); if (recordPosition < 0) { recordPosition = Integer.MAX_VALUE; continue pageLoop; } else { int recordPageOffset = localPage.getRecordPageOffset(recordPosition); int recordSize = localPage.getRecordSize(recordPosition); if (localPage.getByteValue(recordPageOffset + recordSize - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE) == 1) { OPhysicalPosition physicalPosition = new OPhysicalPosition(); physicalPosition.clusterPosition = OClusterPositionFactory.INSTANCE.valueOf((i << PAGE_INDEX_OFFSET) | recordPosition); physicalPosition.recordVersion = localPage.getRecordVersion(recordPosition); physicalPosition.recordType = localPage.getByteValue(recordPageOffset); physicalPosition.recordSize = -1; physicalPosition.dataSegmentId = -1; physicalPosition.dataSegmentPos = -1; return new OPhysicalPosition[] { physicalPosition }; } recordPosition--; } } } else recordPosition = Integer.MAX_VALUE; } finally { diskCache.release(cacheEntry); } } return new OPhysicalPosition[0]; } private static final class AddEntryResult { private final long pagePointer; private final ORecordVersion recordVersion; private final int recordsSizeDiff; public AddEntryResult(long pagePointer, ORecordVersion recordVersion, int recordsSizeDiff) { this.pagePointer = pagePointer; this.recordVersion = recordVersion; this.recordsSizeDiff = recordsSizeDiff; } } private static final class FindFreePageResult { private final long pageIndex; private final int freePageIndex; private FindFreePageResult(long pageIndex, int freePageIndex) { this.pageIndex = pageIndex; this.freePageIndex = freePageIndex; } } }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_depricated_OPaginatedWithoutRidReuseCluster.java
160
private class DescendingItr extends AbstractItr { Node<E> startNode() { return last(); } Node<E> nextNode(Node<E> p) { return pred(p); } }
0true
src_main_java_jsr166y_ConcurrentLinkedDeque.java
1,018
public interface OrderAttribute extends Serializable { /** * Gets the id. * * @return the id */ Long getId(); /** * Sets the id. * * @param id the new id */ void setId(Long id); /** * Gets the value. * * @return the value */ String getValue(); /** * Sets the value. * * @param value the new value */ void setValue(String value); /** * Gets the associated order. * * @return the order */ Order getOrder(); /** * Sets the order. * * @param order the associated order */ void setOrder(Order order); /** * Gets the name. * * @return the name */ String getName(); /** * Sets the name. * * @param name the new name */ void setName(String name); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_OrderAttribute.java
1,652
new Thread(new Runnable() { public void run() { map.lock(key); latch.countDown(); } }).start();
0true
hazelcast_src_test_java_com_hazelcast_map_AsyncTest.java
1,990
class SimpleMapStore2 extends SimpleMapStore<String, Long> { SimpleMapStore2(ConcurrentMap<String, Long> store) { super(store); } public Long load(String key) { loadCount.incrementAndGet(); return super.load(key); } public void store(String key, Long value) { storeCount.incrementAndGet(); super.store(key, value); } public void delete(String key) { deleteCount.incrementAndGet(); super.delete(key); } }
0true
hazelcast_src_test_java_com_hazelcast_map_mapstore_MapStoreTest.java
344
static class MapTryLockThread extends TestHelper { public MapTryLockThread(IMap map, String upKey, String downKey){ super(map, upKey, downKey); } public void doRun() throws Exception{ if(map.tryLock(upKey)){ try{ if(map.tryLock(downKey)){ try { work(); }finally { map.unlock(downKey); } } }finally { map.unlock(upKey); } } } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTryLockConcurrentTests.java
955
public class OMemoryInputStream extends InputStream { private byte[] buffer; private int position = 0; public OMemoryInputStream() { } public OMemoryInputStream(final byte[] iBuffer) { setSource(iBuffer); } public byte[] getAsByteArrayFixed(final int iSize) throws IOException { if (position >= buffer.length) return null; final byte[] portion = OArrays.copyOfRange(buffer, position, position + iSize); position += iSize; return portion; } /** * Browse the stream but just return the begin of the byte array. This is used to lazy load the information only when needed. * */ public int getAsByteArrayOffset() { if (position >= buffer.length) return -1; final int begin = position; final int size = OBinaryProtocol.bytes2int(buffer, position); position += OBinaryProtocol.SIZE_INT + size; return begin; } @Override public int read() throws IOException { if (position >= buffer.length) return -1; return buffer[position++] & 0xFF; } @Override public int read(final byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (position >= buffer.length) return -1; int newLen; if (position + len >= buffer.length) newLen = buffer.length - position; else newLen = len; if (off + newLen >= b.length) newLen = b.length - off; if (newLen <= 0) return 0; System.arraycopy(buffer, position, b, off, newLen); position += newLen; return newLen; } public byte[] getAsByteArray(int iOffset) throws IOException { if (buffer == null || iOffset >= buffer.length) return null; final int size = OBinaryProtocol.bytes2int(buffer, iOffset); if (size == 0) return null; iOffset += OBinaryProtocol.SIZE_INT; return OArrays.copyOfRange(buffer, iOffset, iOffset + size); } public byte[] getAsByteArray() throws IOException { if (position >= buffer.length) return null; final int size = OBinaryProtocol.bytes2int(buffer, position); position += OBinaryProtocol.SIZE_INT; final byte[] portion = OArrays.copyOfRange(buffer, position, position + size); position += size; return portion; } public boolean getAsBoolean() throws IOException { return buffer[position++] == 1; } public char getAsChar() throws IOException { final char value = OBinaryProtocol.bytes2char(buffer, position); position += OBinaryProtocol.SIZE_CHAR; return value; } public byte getAsByte() throws IOException { return buffer[position++]; } public long getAsLong() throws IOException { final long value = OBinaryProtocol.bytes2long(buffer, position); position += OBinaryProtocol.SIZE_LONG; return value; } public int getAsInteger() throws IOException { final int value = OBinaryProtocol.bytes2int(buffer, position); position += OBinaryProtocol.SIZE_INT; return value; } public short getAsShort() throws IOException { final short value = OBinaryProtocol.bytes2short(buffer, position); position += OBinaryProtocol.SIZE_SHORT; return value; } public void close() { buffer = null; } public byte peek() { return buffer[position]; } public void setSource(final byte[] iBuffer) { buffer = iBuffer; position = 0; } public OMemoryInputStream jump(final int iOffset) { position += iOffset; return this; } public byte[] move(final int iOffset, final int iCopyToOffset) { final byte[] copy = new byte[buffer.length - iOffset + iCopyToOffset]; System.arraycopy(buffer, iOffset, copy, iCopyToOffset, copy.length); return copy; } public byte[] copy() { if (buffer == null) return null; final int size = position > 0 ? position : buffer.length; final byte[] copy = new byte[size]; System.arraycopy(buffer, 0, copy, 0, size); return copy; } public int getVariableSize() throws IOException { if (position >= buffer.length) return -1; final int size = OBinaryProtocol.bytes2int(buffer, position); position += OBinaryProtocol.SIZE_INT; return size; } public int getSize() { return buffer.length; } public int getPosition() { return position; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_serialization_OMemoryInputStream.java
339
BackendOperation.execute(new BackendOperation.Transactional<Boolean>() { @Override public Boolean call(StoreTransaction txh) throws BackendException { if (checkExpectedValue) store.acquireLock(rowKey,column,expectedValueBuffer,txh); store.mutate(rowKey, additions, deletions, txh); return true; } @Override public String toString() { return "setConfiguration"; } }, txProvider, times, maxOperationWaitTime);
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_backend_KCVSConfiguration.java
500
private final class PartitionImpl implements Partition { private final int partitionId; private PartitionImpl(int partitionId) { this.partitionId = partitionId; } public int getPartitionId() { return partitionId; } public Member getOwner() { final Address owner = getPartitionOwner(partitionId); if (owner != null) { return client.getClientClusterService().getMember(owner); } return null; } @Override public String toString() { final StringBuilder sb = new StringBuilder("PartitionImpl{"); sb.append("partitionId=").append(partitionId); sb.append('}'); return sb.toString(); } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientPartitionServiceImpl.java
1,475
public class CustomerAddressForm implements Serializable { private static final long serialVersionUID = 1L; protected Address address = new AddressImpl(); protected String addressName; protected Long customerAddressId; public CustomerAddressForm() { address.setPhonePrimary(new PhoneImpl()); } public Address getAddress() { return address; } public void setAddress(Address address) { if (address.getPhonePrimary() == null) { address.setPhonePrimary(new PhoneImpl()); } this.address = address; } public String getAddressName() { return addressName; } public void setAddressName(String addressName) { this.addressName = addressName; } public Long getCustomerAddressId() { return customerAddressId; } public void setCustomerAddressId(Long customerAddressId) { this.customerAddressId = customerAddressId; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_account_CustomerAddressForm.java
952
public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters private int options; // Record options used to create the stream. private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link OBase64Utils.InputStream} in DECODE mode. * * @param in * the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream(java.io.InputStream in) { this(in, DECODE); } // end constructor /** * Constructs a {@link OBase64Utils.InputStream} in either ENCODE or DECODE mode. * <p> * Valid options: * * <pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: break lines at 76 characters * (only meaningful when encoding)</i> * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in * the <tt>java.io.InputStream</tt> from which to read data. * @param options * Specified options * @see OBase64Utils#ENCODE * @see OBase64Utils#DECODE * @see OBase64Utils#DO_BREAK_LINES * @since 2.0 */ public InputStream(java.io.InputStream in, int options) { super(in); this.options = options; // Record for later this.breakLines = (options & DO_BREAK_LINES) > 0; this.encode = (options & ENCODE) > 0; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[bufferLength]; this.position = -1; this.lineLength = 0; this.decodabet = getDecodabet(options); } // end constructor /** * Reads enough of the input stream to convert to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ @Override public int read() throws java.io.IOException { // Do we need to get data? if (position < 0) { if (encode) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for (int i = 0; i < 3; i++) { int b = in.read(); // If end of stream, b is -1. if (b >= 0) { b3[i] = (byte) b; numBinaryBytes++; } else { break; // out of for loop } // end else: end of stream } // end for: each needed input byte if (numBinaryBytes > 0) { encode3to4(b3, 0, numBinaryBytes, buffer, 0, options); position = 0; numSigBytes = 4; } // end if: got data else { return -1; // Must be end of stream } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for (i = 0; i < 4; i++) { // Read four "meaningful" bytes: int b = 0; do { b = in.read(); } while (b >= 0 && decodabet[b & 0x7f] <= WHITE_SPACE_ENC); if (b < 0) { break; // Reads a -1 if end of stream } // end if: end of stream b4[i] = (byte) b; } // end for: each needed input byte if (i == 4) { numSigBytes = decode4to3(b4, 0, buffer, 0, options); position = 0; } // end if: got four characters else if (i == 0) { return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException("Improperly padded Base64 input."); } // end } // end else: decode } // end else: get data // Got data? if (position >= 0) { // End of relevant data? if ( /* !encode && */position >= numSigBytes) { return -1; } // end if: got data if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[position++]; if (position >= bufferLength) { position = -1; } // end if: end return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { throw new java.io.IOException("Error in Base64 code reading stream."); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream is reached or <var>len</var> bytes are read. Returns number of bytes * read into array or -1 if end of stream is encountered. * * @param dest * array to hold values * @param off * offset for array * @param len * max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ @Override public int read(byte[] dest, int off, int len) throws java.io.IOException { int i; int b; for (i = 0; i < len; i++) { b = read(); if (b >= 0) { dest[off + i] = (byte) b; } else if (i == 0) { return -1; } else { break; // Out of 'for' loop } // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream
0true
core_src_main_java_com_orientechnologies_orient_core_serialization_OBase64Utils.java
1,371
public class CancellationRequest extends InvocationClientRequest { static final int CANCEL_TRY_COUNT = 50; static final int CANCEL_TRY_PAUSE_MILLIS = 250; private String uuid; private Address target; private int partitionId = -1; private boolean interrupt; public CancellationRequest() { } public CancellationRequest(String uuid, Address target, boolean interrupt) { this.uuid = uuid; this.target = target; this.interrupt = interrupt; } public CancellationRequest(String uuid, int partitionId, boolean interrupt) { this.uuid = uuid; this.partitionId = partitionId; this.interrupt = interrupt; } @Override protected void invoke() { CancellationOperation op = new CancellationOperation(uuid, interrupt); InvocationBuilder builder; if (target != null) { builder = createInvocationBuilder(getServiceName(), op, target); } else { builder = createInvocationBuilder(getServiceName(), op, partitionId); } builder.setTryCount(CANCEL_TRY_COUNT).setTryPauseMillis(CANCEL_TRY_PAUSE_MILLIS); InternalCompletableFuture future = builder.invoke(); boolean result = false; try { result = (Boolean) future.get(); } catch (InterruptedException e) { logException(e); } catch (ExecutionException e) { logException(e); } getEndpoint().sendResponse(result, getCallId()); } private void logException(Exception e) { ILogger logger = getClientEngine().getLogger(CancellationRequest.class); logger.warning(e); } @Override public String getServiceName() { return DistributedExecutorService.SERVICE_NAME; } @Override public int getFactoryId() { return ExecutorPortableHook.F_ID; } @Override public int getClassId() { return ExecutorPortableHook.CANCELLATION_REQUEST; } @Override public void write(PortableWriter writer) throws IOException { writer.writeUTF("u", uuid); writer.writeInt("p", partitionId); writer.writeBoolean("i", interrupt); ObjectDataOutput rawDataOutput = writer.getRawDataOutput(); rawDataOutput.writeObject(target); } @Override public void read(PortableReader reader) throws IOException { uuid = reader.readUTF("u"); partitionId = reader.readInt("p"); interrupt = reader.readBoolean("i"); ObjectDataInput rawDataInput = reader.getRawDataInput(); target = rawDataInput.readObject(); } @Override public Permission getRequiredPermission() { return null; } }
0true
hazelcast_src_main_java_com_hazelcast_executor_client_CancellationRequest.java
2,685
threadPool.schedule(recoverAfterTime, ThreadPool.Names.GENERIC, new Runnable() { @Override public void run() { if (recovered.compareAndSet(false, true)) { logger.trace("performing state recovery..."); gateway.performStateRecovery(recoveryListener); } } });
0true
src_main_java_org_elasticsearch_gateway_GatewayService.java
1,444
@SuppressWarnings("serial") public class OCommandGremlin extends OCommandRequestTextAbstract { public OCommandGremlin() { useCache = true; } public OCommandGremlin(final String iText) { super(iText); useCache = true; } public boolean isIdempotent() { return false; } @Override public String toString() { return "gremlin." + OIOUtils.getStringMaxLength(text, 200, "..."); } }
0true
graphdb_src_main_java_com_orientechnologies_orient_graph_gremlin_OCommandGremlin.java
1,862
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() { public Boolean execute(TransactionalTaskContext context) throws TransactionException { try { final TransactionalMap<String, String> txMap = context.getMap("default"); assertEquals("value0", txMap.getForUpdate("var")); assertEquals("value0", txMap.getForUpdate("var")); assertEquals("value0", txMap.getForUpdate("var")); } catch (Exception e) { } return true; } });
0true
hazelcast_src_test_java_com_hazelcast_map_MapTransactionTest.java
1,232
NONE { @Override <T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors) { return none(c); } };
0true
src_main_java_org_elasticsearch_cache_recycler_PageCacheRecycler.java
993
@Entity @DiscriminatorColumn(name = "TYPE") @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_FULFILLMENT_GROUP_FEE") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "blOrderElements") @AdminPresentationMergeOverrides( { @AdminPresentationMergeOverride(name = "", mergeEntries = @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.READONLY, booleanOverrideValue = true)) } ) public class FulfillmentGroupFeeImpl implements FulfillmentGroupFee, CurrencyCodeIdentifiable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "FulfillmentGroupFeeId") @GenericGenerator( name="FulfillmentGroupFeeId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="FulfillmentGroupFeeImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.order.domain.FulfillmentGroupFeeImpl") } ) @Column(name = "FULFILLMENT_GROUP_FEE_ID") protected Long id; @ManyToOne(targetEntity = FulfillmentGroupImpl.class, optional = false) @JoinColumn(name = "FULFILLMENT_GROUP_ID") protected FulfillmentGroup fulfillmentGroup; @Column(name = "AMOUNT", precision=19, scale=5) @AdminPresentation(friendlyName = "FulfillmentGroupFeeImpl_Amount", prominent = true, gridOrder = 2000, order = 2000) protected BigDecimal amount; @Column(name = "NAME") @AdminPresentation(friendlyName = "FulfillmentGroupFeeImpl_Name", prominent = true, gridOrder = 1000, order = 1000) protected String name; @Column(name = "REPORTING_CODE") @AdminPresentation(friendlyName = "FulfillmentGroupFeeImpl_Reporting_Code", order = 3000) protected String reportingCode; @Column(name = "FEE_TAXABLE_FLAG") @AdminPresentation(friendlyName = "FulfillmentGroupFeeImpl_Taxable", order = 5000) protected Boolean feeTaxable = false; @OneToMany(fetch = FetchType.LAZY, targetEntity = TaxDetailImpl.class, cascade = {CascadeType.ALL}) @JoinTable(name = "BLC_FG_FEE_TAX_XREF", joinColumns = @JoinColumn(name = "FULFILLMENT_GROUP_FEE_ID"), inverseJoinColumns = @JoinColumn(name = "TAX_DETAIL_ID")) @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements") protected List<TaxDetail> taxes = new ArrayList<TaxDetail>(); @Column(name = "TOTAL_FEE_TAX", precision=19, scale=5) @AdminPresentation(friendlyName = "FulfillmentGroupFeeImpl_Total_Fee_Tax", order=4000, fieldType=SupportedFieldType.MONEY) protected BigDecimal totalTax; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public FulfillmentGroup getFulfillmentGroup() { return fulfillmentGroup; } @Override public void setFulfillmentGroup(FulfillmentGroup fulfillmentGroup) { this.fulfillmentGroup = fulfillmentGroup; } @Override public Money getAmount() { return amount == null ? null : BroadleafCurrencyUtils.getMoney(amount, getFulfillmentGroup().getOrder().getCurrency()); } @Override public void setAmount(Money amount) { this.amount = Money.toAmount(amount); } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getReportingCode() { return reportingCode; } @Override public void setReportingCode(String reportingCode) { this.reportingCode = reportingCode; } @Override public Boolean isTaxable() { return feeTaxable == null ? true : feeTaxable; } @Override public void setTaxable(Boolean taxable) { this.feeTaxable = taxable; } @Override public List<TaxDetail> getTaxes() { return taxes; } @Override public void setTaxes(List<TaxDetail> taxes) { this.taxes = taxes; } @Override public Money getTotalTax() { return totalTax == null ? null : BroadleafCurrencyUtils.getMoney(totalTax, getFulfillmentGroup().getOrder().getCurrency()); } @Override public void setTotalTax(Money totalTax) { this.totalTax = Money.toAmount(totalTax); } @Override public String getCurrencyCode() { return ((CurrencyCodeIdentifiable) fulfillmentGroup).getCurrencyCode(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((amount == null) ? 0 : amount.hashCode()); result = prime * result + ((fulfillmentGroup == null) ? 0 : fulfillmentGroup.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((reportingCode == null) ? 0 : reportingCode.hashCode()); result = prime * result + ((taxes == null) ? 0 : taxes.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; } FulfillmentGroupFeeImpl other = (FulfillmentGroupFeeImpl) obj; if (amount == null) { if (other.amount != null) { return false; } } else if (!amount.equals(other.amount)) { return false; } if (fulfillmentGroup == null) { if (other.fulfillmentGroup != null) { return false; } } else if (!fulfillmentGroup.equals(other.fulfillmentGroup)) { return false; } if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (reportingCode == null) { if (other.reportingCode != null) { return false; } } else if (!reportingCode.equals(other.reportingCode)) { return false; } return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_FulfillmentGroupFeeImpl.java
1,589
public interface ODistributedServerManager { public enum STATUS { OFFLINE, STARTING, ONLINE, SHUTDOWNING }; public boolean isEnabled(); public STATUS getStatus(); public boolean checkStatus(STATUS string); public void setStatus(STATUS iStatus); public boolean isNodeAvailable(final String iNodeName); public boolean isOffline(); public String getLocalNodeId(); public String getLocalNodeName(); public ODocument getClusterConfiguration(); public ODocument getNodeConfigurationById(String iNode); public ODocument getLocalNodeConfiguration(); /** * Returns a time taking care about the offset with the cluster time. This allows to have a quite precise idea about information * on date times, such as logs to determine the youngest in case of conflict. * * @return */ public long getDistributedTime(long iTme); /** * Gets a distributed lock * * @param iLockName * name of the lock * @return */ public Lock getLock(String iLockName); public Class<? extends OReplicationConflictResolver> getConfictResolverClass(); public ODistributedConfiguration getDatabaseConfiguration(String iDatabaseName); public ODistributedPartition newPartition(List<String> partition); public Object sendRequest(String iDatabaseName, String iClusterName, OAbstractRemoteTask iTask, EXECUTION_MODE iExecutionMode); public void sendRequest2Node(String iDatabaseName, String iTargetNodeName, OAbstractRemoteTask iTask); public ODistributedPartitioningStrategy getPartitioningStrategy(String partitionStrategy); public ODocument getStats(); }
0true
server_src_main_java_com_orientechnologies_orient_server_distributed_ODistributedServerManager.java
1,140
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class DistributedObjectTest extends HazelcastTestSupport { @Test public void testMap() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getMap("test"); test(instance, object); } @Test public void testQueue() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getQueue("test"); test(instance, object); } @Test public void testTopic() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getTopic("test"); test(instance, object); } @Test public void testMultiMap() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getMultiMap("test"); test(instance, object); } @Test public void testSet() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getSet("test"); test(instance, object); } @Test public void testList() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getList("test"); test(instance, object); } @Test public void testExecutorService() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getExecutorService("test"); test(instance, object); } @Test public void testLock() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getLock("test"); test(instance, object); } @Test public void testLock2() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getLock(System.currentTimeMillis()); test(instance, object); } @Test public void testAtomicLong() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getAtomicLong("test"); test(instance, object); } @Test public void testSemaphore() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getSemaphore("test"); test(instance, object); } @Test public void testCountdownLatch() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getCountDownLatch("test"); test(instance, object); } @Test public void testIdGenerator() { HazelcastInstance instance = createHazelcastInstance(); DistributedObject object = instance.getIdGenerator("test"); test(instance, object); } private void test(HazelcastInstance instance, DistributedObject object) { DistributedObject object2 = instance.getDistributedObject(object.getServiceName(), object.getName()); assertEquals(object.getServiceName(), object2.getServiceName()); assertEquals(object.getName(), object2.getName()); assertEquals(object.getId(), object2.getId()); assertEquals(object, object2); assertTrue(instance.getDistributedObjects().contains(object)); } @Test public void testCustomObject() { Config config = new Config(); config.getServicesConfig().addServiceConfig( new ServiceConfig().setServiceImpl(new TestInitializingObjectService()) .setEnabled(true).setName(TestInitializingObjectService.NAME) ); HazelcastInstance instance = createHazelcastInstance(config); TestInitializingObject object = instance .getDistributedObject(TestInitializingObjectService.NAME, "test-object"); test(instance, object); } @Test public void testInitialization() { int nodeCount = 4; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(nodeCount); Config config = new Config(); config.getServicesConfig().addServiceConfig( new ServiceConfig().setServiceImpl(new TestInitializingObjectService()) .setEnabled(true).setName(TestInitializingObjectService.NAME) ); String serviceName = TestInitializingObjectService.NAME; String objectName = "test-object"; HazelcastInstance[] instances = new HazelcastInstance[nodeCount]; for (int i = 0; i < instances.length; i++) { instances[i] = factory.newHazelcastInstance(config); TestInitializingObject obj2 = instances[i].getDistributedObject(serviceName, objectName); assertTrue(obj2.init.get()); Assert.assertFalse(obj2.error); } } @Test public void testInitialization2() { int nodeCount = 4; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(nodeCount); Config config = new Config(); config.getServicesConfig().addServiceConfig( new ServiceConfig().setServiceImpl(new TestInitializingObjectService()) .setEnabled(true).setName(TestInitializingObjectService.NAME) ); String serviceName = TestInitializingObjectService.NAME; String objectName = "test-object"; HazelcastInstance[] instances = new HazelcastInstance[nodeCount]; for (int i = 0; i < instances.length; i++) { instances[i] = factory.newHazelcastInstance(config); instances[i].getDistributedObject(serviceName, objectName); } for (int i = 0; i < nodeCount; i++) { Node node = TestUtil.getNode(instances[i]); ProxyServiceImpl proxyService = (ProxyServiceImpl) node.nodeEngine.getProxyService(); Operation postJoinOperation = proxyService.getPostJoinOperation(); for (int j = 0; j < nodeCount; j++) { if (i == j) continue; Node node2 = TestUtil.getNode(instances[j]); node.nodeEngine.getOperationService().send(postJoinOperation, node2.address); } } for (int i = 0; i < instances.length; i++) { TestInitializingObject obj = instances[i].getDistributedObject(serviceName, objectName); assertTrue(obj.init.get()); Assert.assertFalse(obj.error); } } private static class TestInitializingObjectService implements RemoteService { static final String NAME = "TestInitializingObjectService"; public DistributedObject createDistributedObject(final String objectName) { return new TestInitializingObject(objectName); } public void destroyDistributedObject(final String objectName) { } } private static class TestInitializingObject implements DistributedObject, InitializingObject { private final String name; private final AtomicBoolean init = new AtomicBoolean(false); private volatile boolean error = false; protected TestInitializingObject(final String name) { this.name = name; } @Override public void initialize() { if (!init.compareAndSet(false, true)) { error = true; throw new IllegalStateException("InitializingObject must be initialized only once!"); } } @Override public String getName() { return name; } @Override public String getServiceName() { return TestInitializingObjectService.NAME; } @Override public Object getId() { return getName(); } @Override public String getPartitionKey() { return getName(); } @Override public void destroy() { } } }
0true
hazelcast_src_test_java_com_hazelcast_core_DistributedObjectTest.java
3,630
public class SimpleDynamicTemplatesTests extends ElasticsearchTestCase { @Test public void testMatchTypeOnly() throws Exception { XContentBuilder builder = JsonXContent.contentBuilder(); builder.startObject().startObject("person").startArray("dynamic_templates").startObject().startObject("test") .field("match_mapping_type", "string") .startObject("mapping").field("index", "no").endObject() .endObject().endObject().endArray().endObject().endObject(); DocumentMapper docMapper = MapperTestUtils.newParser().parse(builder.string()); builder = JsonXContent.contentBuilder(); builder.startObject().field("_id", "1").field("s", "hello").field("l", 1).endObject(); docMapper.parse(builder.bytes()); DocumentFieldMappers mappers = docMapper.mappers(); assertThat(mappers.smartName("s"), Matchers.notNullValue()); assertThat(mappers.smartName("s").mapper().fieldType().indexed(), equalTo(false)); assertThat(mappers.smartName("l"), Matchers.notNullValue()); assertThat(mappers.smartName("l").mapper().fieldType().indexed(), equalTo(true)); } @Test public void testSimple() throws Exception { String mapping = copyToStringFromClasspath("/org/elasticsearch/index/mapper/dynamictemplate/simple/test-mapping.json"); DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping); byte[] json = copyToBytesFromClasspath("/org/elasticsearch/index/mapper/dynamictemplate/simple/test-data.json"); Document doc = docMapper.parse(new BytesArray(json)).rootDoc(); IndexableField f = doc.getField("name"); assertThat(f.name(), equalTo("name")); assertThat(f.stringValue(), equalTo("some name")); assertThat(f.fieldType().indexed(), equalTo(true)); assertThat(f.fieldType().tokenized(), equalTo(false)); FieldMappers fieldMappers = docMapper.mappers().fullName("name"); assertThat(fieldMappers.mappers().size(), equalTo(1)); f = doc.getField("multi1"); assertThat(f.name(), equalTo("multi1")); assertThat(f.stringValue(), equalTo("multi 1")); assertThat(f.fieldType().indexed(), equalTo(true)); assertThat(f.fieldType().tokenized(), equalTo(true)); fieldMappers = docMapper.mappers().fullName("multi1"); assertThat(fieldMappers.mappers().size(), equalTo(1)); f = doc.getField("multi1.org"); assertThat(f.name(), equalTo("multi1.org")); assertThat(f.stringValue(), equalTo("multi 1")); assertThat(f.fieldType().indexed(), equalTo(true)); assertThat(f.fieldType().tokenized(), equalTo(false)); fieldMappers = docMapper.mappers().fullName("multi1.org"); assertThat(fieldMappers.mappers().size(), equalTo(1)); f = doc.getField("multi2"); assertThat(f.name(), equalTo("multi2")); assertThat(f.stringValue(), equalTo("multi 2")); assertThat(f.fieldType().indexed(), equalTo(true)); assertThat(f.fieldType().tokenized(), equalTo(true)); fieldMappers = docMapper.mappers().fullName("multi2"); assertThat(fieldMappers.mappers().size(), equalTo(1)); f = doc.getField("multi2.org"); assertThat(f.name(), equalTo("multi2.org")); assertThat(f.stringValue(), equalTo("multi 2")); assertThat(f.fieldType().indexed(), equalTo(true)); assertThat(f.fieldType().tokenized(), equalTo(false)); fieldMappers = docMapper.mappers().fullName("multi2.org"); assertThat(fieldMappers.mappers().size(), equalTo(1)); } @Test public void testSimpleWithXContentTraverse() throws Exception { String mapping = copyToStringFromClasspath("/org/elasticsearch/index/mapper/dynamictemplate/simple/test-mapping.json"); DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping); docMapper.refreshSource(); docMapper = MapperTestUtils.newParser().parse(docMapper.mappingSource().string()); byte[] json = copyToBytesFromClasspath("/org/elasticsearch/index/mapper/dynamictemplate/simple/test-data.json"); Document doc = docMapper.parse(new BytesArray(json)).rootDoc(); IndexableField f = doc.getField("name"); assertThat(f.name(), equalTo("name")); assertThat(f.stringValue(), equalTo("some name")); assertThat(f.fieldType().indexed(), equalTo(true)); assertThat(f.fieldType().tokenized(), equalTo(false)); FieldMappers fieldMappers = docMapper.mappers().fullName("name"); assertThat(fieldMappers.mappers().size(), equalTo(1)); f = doc.getField("multi1"); assertThat(f.name(), equalTo("multi1")); assertThat(f.stringValue(), equalTo("multi 1")); assertThat(f.fieldType().indexed(), equalTo(true)); assertThat(f.fieldType().tokenized(), equalTo(true)); fieldMappers = docMapper.mappers().fullName("multi1"); assertThat(fieldMappers.mappers().size(), equalTo(1)); f = doc.getField("multi1.org"); assertThat(f.name(), equalTo("multi1.org")); assertThat(f.stringValue(), equalTo("multi 1")); assertThat(f.fieldType().indexed(), equalTo(true)); assertThat(f.fieldType().tokenized(), equalTo(false)); fieldMappers = docMapper.mappers().fullName("multi1.org"); assertThat(fieldMappers.mappers().size(), equalTo(1)); f = doc.getField("multi2"); assertThat(f.name(), equalTo("multi2")); assertThat(f.stringValue(), equalTo("multi 2")); assertThat(f.fieldType().indexed(), equalTo(true)); assertThat(f.fieldType().tokenized(), equalTo(true)); fieldMappers = docMapper.mappers().fullName("multi2"); assertThat(fieldMappers.mappers().size(), equalTo(1)); f = doc.getField("multi2.org"); assertThat(f.name(), equalTo("multi2.org")); assertThat(f.stringValue(), equalTo("multi 2")); assertThat(f.fieldType().indexed(), equalTo(true)); assertThat(f.fieldType().tokenized(), equalTo(false)); fieldMappers = docMapper.mappers().fullName("multi2.org"); assertThat(fieldMappers.mappers().size(), equalTo(1)); } }
0true
src_test_java_org_elasticsearch_index_mapper_dynamictemplate_simple_SimpleDynamicTemplatesTests.java
414
private static final class ExecutionCallbackWrapper<T> implements ExecutionCallback<T> { MultiExecutionCallbackWrapper multiExecutionCallbackWrapper; Member member; private ExecutionCallbackWrapper(MultiExecutionCallbackWrapper multiExecutionCallback, Member member) { this.multiExecutionCallbackWrapper = multiExecutionCallback; this.member = member; } public void onResponse(T response) { multiExecutionCallbackWrapper.onResponse(member, response); } public void onFailure(Throwable t) { } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientExecutorServiceProxy.java
1,118
public static class RequestInfo { public RequestInfo(SearchRequest source, int i) { request = source; numTerms = i; } SearchRequest request; int numTerms; }
0true
src_test_java_org_elasticsearch_benchmark_scripts_score_BasicScriptBenchmark.java
1,081
public class OrderBaseTest extends CommonSetupBaseTest { protected Customer createNamedCustomer() { Customer customer = customerService.createCustomerFromId(null); customer.setUsername(String.valueOf(customer.getId())); return customer; } public Order setUpNamedOrder() throws AddToCartException { Customer customer = customerService.saveCustomer(createNamedCustomer()); Order order = orderService.createNamedOrderForCustomer("Boxes Named Order", customer); Product newProduct = addTestProduct("Cube Box", "Boxes"); Category newCategory = newProduct.getDefaultCategory(); order = orderService.addItem(order.getId(), new OrderItemRequestDTO(newProduct.getId(), newProduct.getDefaultSku().getId(), newCategory.getId(), 2), true); return order; } public Order setUpCartWithActiveSku() throws AddToCartException { Customer customer = customerService.saveCustomer(createNamedCustomer()); Order order = orderService.createNewCartForCustomer(customer); Product newProduct = addTestProduct("Plastic Crate Active", "Crates"); Category newCategory = newProduct.getDefaultCategory(); order = orderService.addItem(order.getId(), new OrderItemRequestDTO(newProduct.getId(), newProduct.getDefaultSku().getId(), newCategory.getId(), 1), true); return order; } public Order setUpCartWithInactiveSku() throws AddToCartException { Customer customer = customerService.saveCustomer(createNamedCustomer()); Order order = orderService.createNewCartForCustomer(customer); Product newProduct = addTestProduct("Plastic Crate Should Be Inactive", "Crates"); Category newCategory = newProduct.getDefaultCategory(); order = orderService.addItem(order.getId(), new OrderItemRequestDTO(newProduct.getId(), newProduct.getDefaultSku().getId(), newCategory.getId(), 1), true); // Make the SKU inactive newProduct.getDefaultSku().setActiveEndDate(DateUtils.addDays(new Date(), -1)); catalogService.saveSku(newProduct.getDefaultSku()); return order; } }
0true
integration_src_test_java_org_broadleafcommerce_core_order_service_OrderBaseTest.java
935
threadPool.executor(executor).execute(new Runnable() { @Override public void run() { int shardIndex = -1; for (final ShardIterator shardIt : shardsIts) { shardIndex++; final ShardRouting shard = shardIt.firstOrNull(); if (shard != null) { if (shard.currentNodeId().equals(nodes.localNodeId())) { performOperation(shardIt, shardIndex, false); } } } } });
0true
src_main_java_org_elasticsearch_action_support_broadcast_TransportBroadcastOperationAction.java
226
private static final class SimulateLoadTask implements Callable, Serializable, HazelcastInstanceAware { private static final long serialVersionUID = 1; private final int delay; private final int taskId; private final String latchId; private transient HazelcastInstance hz; private SimulateLoadTask(int delay, int taskId, String latchId) { this.delay = delay; this.taskId = taskId; this.latchId = latchId; } @Override public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { this.hz = hazelcastInstance; } @Override public Object call() throws Exception { try { Thread.sleep(delay * ONE_THOUSAND); } catch (InterruptedException e) { throw new RuntimeException(e); } hz.getCountDownLatch(latchId).countDown(); System.out.println("Finished task:" + taskId); return null; } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_examples_ClientTestApp.java
443
@Deprecated public @interface AdminPresentationMapOverride { /** * The name of the property whose AdminPresentation annotation should be overwritten * * @return the name of the property that should be overwritten */ String name(); /** * The AdminPresentation to overwrite the property with * * @return the AdminPresentation being mapped to the attribute */ AdminPresentationMap value(); }
0true
common_src_main_java_org_broadleafcommerce_common_presentation_override_AdminPresentationMapOverride.java
1,651
map.addEntryListener(new EntryAdapter<String, String>() { public void entryEvicted(EntryEvent<String, String> event) { latch.countDown(); } }, true);
0true
hazelcast_src_test_java_com_hazelcast_map_AsyncTest.java
34
@SuppressWarnings("unchecked") public abstract class OMVRBTreeEntry<K, V> implements Map.Entry<K, V>, Comparable<OMVRBTreeEntry<K, V>> { protected OMVRBTree<K, V> tree; private int pageSplitItems; public static final int BINARY_SEARCH_THRESHOLD = 10; /** * Constructor called on unmarshalling. * */ protected OMVRBTreeEntry(final OMVRBTree<K, V> iTree) { tree = iTree; } public abstract void setLeft(OMVRBTreeEntry<K, V> left); public abstract OMVRBTreeEntry<K, V> getLeft(); public abstract void setRight(OMVRBTreeEntry<K, V> right); public abstract OMVRBTreeEntry<K, V> getRight(); public abstract OMVRBTreeEntry<K, V> setParent(OMVRBTreeEntry<K, V> parent); public abstract OMVRBTreeEntry<K, V> getParent(); protected abstract OMVRBTreeEntry<K, V> getLeftInMemory(); protected abstract OMVRBTreeEntry<K, V> getParentInMemory(); protected abstract OMVRBTreeEntry<K, V> getRightInMemory(); protected abstract OMVRBTreeEntry<K, V> getNextInMemory(); /** * Returns the first Entry only by traversing the memory, or null if no such. */ public OMVRBTreeEntry<K, V> getFirstInMemory() { OMVRBTreeEntry<K, V> node = this; OMVRBTreeEntry<K, V> prev = this; while (node != null) { prev = node; node = node.getPreviousInMemory(); } return prev; } /** * Returns the previous of the current Entry only by traversing the memory, or null if no such. */ public OMVRBTreeEntry<K, V> getPreviousInMemory() { OMVRBTreeEntry<K, V> t = this; OMVRBTreeEntry<K, V> p = null; if (t.getLeftInMemory() != null) { p = t.getLeftInMemory(); while (p.getRightInMemory() != null) p = p.getRightInMemory(); } else { p = t.getParentInMemory(); while (p != null && t == p.getLeftInMemory()) { t = p; p = p.getParentInMemory(); } } return p; } protected OMVRBTree<K, V> getTree() { return tree; } public int getDepth() { int level = 0; OMVRBTreeEntry<K, V> entry = this; while (entry.getParent() != null) { level++; entry = entry.getParent(); } return level; } /** * Returns the key. * * @return the key */ public K getKey() { return getKey(tree.pageIndex); } public K getKey(final int iIndex) { if (iIndex >= getSize()) throw new IndexOutOfBoundsException("Requested index " + iIndex + " when the range is 0-" + getSize()); tree.pageIndex = iIndex; return getKeyAt(iIndex); } protected abstract K getKeyAt(final int iIndex); /** * Returns the value associated with the key. * * @return the value associated with the key */ public V getValue() { if (tree.pageIndex == -1) return getValueAt(0); return getValueAt(tree.pageIndex); } public V getValue(final int iIndex) { tree.pageIndex = iIndex; return getValueAt(iIndex); } protected abstract V getValueAt(int iIndex); public int getFreeSpace() { return getPageSize() - getSize(); } /** * Execute a binary search between the keys of the node. The keys are always kept ordered. It update the pageIndex attribute with * the most closer key found (useful for the next inserting). * * @param iKey * Key to find * @return The value found if any, otherwise null */ protected V search(final K iKey) { tree.pageItemFound = false; int size = getSize(); if (size == 0) return null; // CHECK THE LOWER LIMIT if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare(iKey, getKeyAt(0)); else tree.pageItemComparator = ((Comparable<? super K>) iKey).compareTo(getKeyAt(0)); if (tree.pageItemComparator == 0) { // FOUND: SET THE INDEX AND RETURN THE NODE tree.pageItemFound = true; tree.pageIndex = 0; return getValueAt(tree.pageIndex); } else if (tree.pageItemComparator < 0) { // KEY OUT OF FIRST ITEM: AVOID SEARCH AND RETURN THE FIRST POSITION tree.pageIndex = 0; return null; } else { // CHECK THE UPPER LIMIT if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare((K) iKey, getKeyAt(size - 1)); else tree.pageItemComparator = ((Comparable<? super K>) iKey).compareTo(getKeyAt(size - 1)); if (tree.pageItemComparator > 0) { // KEY OUT OF LAST ITEM: AVOID SEARCH AND RETURN THE LAST POSITION tree.pageIndex = size; return null; } } if (size < BINARY_SEARCH_THRESHOLD) return linearSearch(iKey); else return binarySearch(iKey); } /** * Linear search inside the node * * @param iKey * Key to search * @return Value if found, otherwise null and the tree.pageIndex updated with the closest-after-first position valid for further * inserts. */ private V linearSearch(final K iKey) { V value = null; int i = 0; tree.pageItemComparator = -1; for (int s = getSize(); i < s; ++i) { if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare(getKeyAt(i), iKey); else tree.pageItemComparator = ((Comparable<? super K>) getKeyAt(i)).compareTo(iKey); if (tree.pageItemComparator == 0) { // FOUND: SET THE INDEX AND RETURN THE NODE tree.pageItemFound = true; value = getValueAt(i); break; } else if (tree.pageItemComparator > 0) break; } tree.pageIndex = i; return value; } /** * Binary search inside the node * * @param iKey * Key to search * @return Value if found, otherwise null and the tree.pageIndex updated with the closest-after-first position valid for further * inserts. */ private V binarySearch(final K iKey) { int low = 0; int high = getSize() - 1; int mid = 0; while (low <= high) { mid = (low + high) >>> 1; Object midVal = getKeyAt(mid); if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare((K) midVal, iKey); else tree.pageItemComparator = ((Comparable<? super K>) midVal).compareTo(iKey); if (tree.pageItemComparator == 0) { // FOUND: SET THE INDEX AND RETURN THE NODE tree.pageItemFound = true; tree.pageIndex = mid; return getValueAt(tree.pageIndex); } if (low == high) break; if (tree.pageItemComparator < 0) low = mid + 1; else high = mid; } tree.pageIndex = mid; return null; } protected abstract void insert(final int iPosition, final K key, final V value); protected abstract void remove(); protected abstract void setColor(boolean iColor); public abstract boolean getColor(); public abstract int getSize(); public K getLastKey() { return getKey(getSize() - 1); } public K getFirstKey() { return getKey(0); } protected abstract void copyFrom(final OMVRBTreeEntry<K, V> iSource); public int getPageSplitItems() { return pageSplitItems; } protected void init() { pageSplitItems = (int) (getPageSize() * tree.pageLoadFactor); } public abstract int getPageSize(); /** * Compares two nodes by their first keys. */ public int compareTo(final OMVRBTreeEntry<K, V> o) { if (o == null) return 1; if (o == this) return 0; if (getSize() == 0) return -1; if (o.getSize() == 0) return 1; if (tree.comparator != null) return tree.comparator.compare(getFirstKey(), o.getFirstKey()); return ((Comparable<K>) getFirstKey()).compareTo(o.getFirstKey()); } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { int idx = tree.pageIndex; if (idx > -1 && idx < getSize()) return getKeyAt(idx) + "=" + getValueAt(idx); return null; } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeEntry.java
4,663
private final PercolatorType queryCountPercolator = new PercolatorType() { @Override public byte id() { return 0x02; } @Override public ReduceResult reduce(List<PercolateShardResponse> shardResults) { return countPercolator.reduce(shardResults); } @Override public PercolateShardResponse doPercolate(PercolateShardRequest request, PercolateContext context) { long count = 0; Engine.Searcher percolatorSearcher = context.indexShard().acquireSearcher("percolate"); try { Count countCollector = count(logger, context); queryBasedPercolating(percolatorSearcher, context, countCollector); count = countCollector.counter(); } catch (Throwable e) { logger.warn("failed to execute", e); } finally { percolatorSearcher.release(); } return new PercolateShardResponse(count, context, request.index(), request.shardId()); } };
1no label
src_main_java_org_elasticsearch_percolator_PercolatorService.java
290
private static class StoreSnapshot extends PrefetchingIterator<File> implements ResourceIterator<File> { private final Iterator<File> files; private final Resource[] thingsToCloseWhenDone; StoreSnapshot( Iterator<File> files, Resource... thingsToCloseWhenDone ) { this.files = files; this.thingsToCloseWhenDone = thingsToCloseWhenDone; } @Override protected File fetchNextOrNull() { return files.hasNext() ? files.next() : null; } @Override public void close() { for ( Resource resource : thingsToCloseWhenDone ) { resource.close(); } } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreFileListing.java
712
constructors[COLLECTION_COMPARE_AND_REMOVE] = new ConstructorFunction<Integer, Portable>() { public Portable createNew(Integer arg) { return new CollectionCompareAndRemoveRequest(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
326
public class ExternalTransactionControlIT { public @Rule ImpermanentDatabaseRule dbRule = new ImpermanentDatabaseRule(); private enum Labels implements Label { MY_LABEL; } @Test public void shouldAllowSuspendingAndResumingTransactions() throws Exception { // Given //noinspection deprecation GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI(); TransactionManager tm = db.getDependencyResolver().resolveDependency( TransactionManager.class ); Node node = createNode(); // And that I have added a label to a node in a transaction try ( org.neo4j.graphdb.Transaction ignored = db.beginTx() ) { node.addLabel( Labels.MY_LABEL ); // When Transaction jtaTx = tm.suspend(); // Then assertThat(node, inTx(db, not( hasLabel( Labels.MY_LABEL ) ))); // And when tm.resume( jtaTx ); // Then assertTrue("The label should be visible when I've resumed the transaction.", node.hasLabel( Labels.MY_LABEL )); } } @Test public void shouldBeAbleToUseJTATransactionManagerForTxManagement() throws Exception { // Given //noinspection deprecation GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI(); TransactionManager tm = db.getDependencyResolver().resolveDependency( TransactionManager.class ); // When tm.begin(); Node node = db.createNode(); node.addLabel( Labels.MY_LABEL ); tm.commit(); // Then assertThat(node, inTx(db, hasLabel( Labels.MY_LABEL ))); } @Test public void shouldBeAbleToMoveTransactionToAnotherThread() throws Exception { // Given //noinspection deprecation GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI(); final TransactionManager tm = db.getDependencyResolver().resolveDependency( TransactionManager.class ); final Node node = createNode(); // And that I have added a label to a node in a transaction try ( org.neo4j.graphdb.Transaction ignored = db.beginTx() ) { node.addLabel( Labels.MY_LABEL ); // And that I suspend the transaction in this thread final Transaction jtaTx = tm.suspend(); boolean result; try { // When OtherThreadExecutor<Boolean> otherThread = new OtherThreadExecutor<>( "Thread to resume tx in", null ); result = otherThread.execute( new OtherThreadExecutor.WorkerCommand<Boolean, Boolean>() { @Override public Boolean doWork( Boolean ignore ) { try { tm.resume( jtaTx ); // Then return node.hasLabel( Labels.MY_LABEL ); } catch ( Exception e ) { throw new RuntimeException( e ); } finally { try { tm.suspend(); } catch ( SystemException e ) { throw new RuntimeException( e ); } } } } ); } finally { // Need to resume this transaction so that we can close it cleanly. tm.resume( jtaTx ); } // Then assertTrue("The label should be visible when I've resumed the transaction.", result); } } private Node createNode() { GraphDatabaseService db = dbRule.getGraphDatabaseService(); try ( org.neo4j.graphdb.Transaction tx = db.beginTx() ) { Node node = db.createNode(); tx.success(); return node; } } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_ExternalTransactionControlIT.java
2,036
public interface InjectionListener<I> { /** * Invoked by Guice after it injects the fields and methods of instance. * * @param injectee instance that Guice injected dependencies into */ void afterInjection(I injectee); }
0true
src_main_java_org_elasticsearch_common_inject_spi_InjectionListener.java
2,841
private static class DefaultNodeGroup implements NodeGroup { final PartitionTable groupPartitionTable = new PartitionTable(); final Map<Address, PartitionTable> nodePartitionTables = new HashMap<Address, PartitionTable>(); final Set<Address> nodes = nodePartitionTables.keySet(); final Collection<PartitionTable> nodeTables = nodePartitionTables.values(); final LinkedList<Integer> partitionQ = new LinkedList<Integer>(); @Override public void addNode(Address address) { nodePartitionTables.put(address, new PartitionTable()); } @Override public boolean hasNode(Address address) { return nodes.contains(address); } @Override public Set<Address> getNodes() { return nodes; } @Override public PartitionTable getPartitionTable(Address address) { return nodePartitionTables.get(address); } @Override public void resetPartitions() { groupPartitionTable.reset(); partitionQ.clear(); for (PartitionTable table : nodeTables) { table.reset(); } } @Override public int getPartitionCount(int index) { return groupPartitionTable.size(index); } @Override public boolean containsPartition(Integer partitionId) { return groupPartitionTable.contains(partitionId); } @Override public boolean ownPartition(Address address, int index, Integer partitionId) { if (!hasNode(address)) { String error = "Address does not belong to this group: " + address.toString(); logger.warning(error); return false; } if (containsPartition(partitionId)) { if (logger.isFinestEnabled()) { String error = "Partition[" + partitionId + "] is already owned by this group! " + "Duplicate!"; logger.finest(error); } return false; } groupPartitionTable.add(index, partitionId); return nodePartitionTables.get(address).add(index, partitionId); } @Override public boolean addPartition(int replicaIndex, Integer partitionId) { if (containsPartition(partitionId)) { return false; } if (groupPartitionTable.add(replicaIndex, partitionId)) { partitionQ.add(partitionId); return true; } return false; } @Override public Iterator<Integer> getPartitionsIterator(final int index) { final Iterator<Integer> iter = groupPartitionTable.getPartitions(index).iterator(); return new Iterator<Integer>() { Integer current = null; @Override public boolean hasNext() { return iter.hasNext(); } @Override public Integer next() { return (current = iter.next()); } @Override public void remove() { iter.remove(); doRemovePartition(index, current); } }; } @Override public boolean removePartition(int index, Integer partitionId) { if (groupPartitionTable.remove(index, partitionId)) { doRemovePartition(index, partitionId); return true; } return false; } private void doRemovePartition(int index, Integer partitionId) { for (PartitionTable table : nodeTables) { if (table.remove(index, partitionId)) { break; } } } @Override public void postProcessPartitionTable(int index) { if (nodes.size() == 1) { PartitionTable table = nodeTables.iterator().next(); while (!partitionQ.isEmpty()) { table.add(index, partitionQ.poll()); } } else { int totalCount = getPartitionCount(index); int avgCount = totalCount / nodes.size(); List<PartitionTable> underLoadedStates = new LinkedList<PartitionTable>(); for (PartitionTable table : nodeTables) { Set<Integer> partitions = table.getPartitions(index); if (partitions.size() > avgCount) { Iterator<Integer> iter = partitions.iterator(); while (partitions.size() > avgCount) { Integer partitionId = iter.next(); iter.remove(); partitionQ.add(partitionId); } } else { underLoadedStates.add(table); } } if (!partitionQ.isEmpty()) { for (PartitionTable table : underLoadedStates) { while (table.size(index) < avgCount) { table.add(index, partitionQ.poll()); } } } while (!partitionQ.isEmpty()) { for (PartitionTable table : nodeTables) { table.add(index, partitionQ.poll()); if (partitionQ.isEmpty()) { break; } } } } } @Override public String toString() { return "DefaultNodeGroupRegistry [nodes=" + nodes + "]"; } }
1no label
hazelcast_src_main_java_com_hazelcast_partition_impl_PartitionStateGeneratorImpl.java
300
public class SequenceCharacterIterator implements CharacterIterator { private int fIndex= -1; private final CharSequence fSequence; private final int fFirst; private final int fLast; private void invariant() { Assert.isTrue(fIndex >= fFirst); Assert.isTrue(fIndex <= fLast); } /** * Creates an iterator for the entire sequence. * * @param sequence the sequence backing this iterator */ public SequenceCharacterIterator(CharSequence sequence) { this(sequence, 0); } /** * Creates an iterator. * * @param sequence the sequence backing this iterator * @param first the first character to consider * @throws IllegalArgumentException if the indices are out of bounds */ public SequenceCharacterIterator(CharSequence sequence, int first) throws IllegalArgumentException { this(sequence, first, sequence.length()); } /** * Creates an iterator. * * @param sequence the sequence backing this iterator * @param first the first character to consider * @param last the last character index to consider * @throws IllegalArgumentException if the indices are out of bounds */ public SequenceCharacterIterator(CharSequence sequence, int first, int last) throws IllegalArgumentException { if (sequence == null) throw new NullPointerException(); if (first < 0 || first > last) throw new IllegalArgumentException(); if (last > sequence.length()) throw new IllegalArgumentException(); fSequence= sequence; fFirst= first; fLast= last; fIndex= first; invariant(); } /* * @see java.text.CharacterIterator#first() */ public char first() { return setIndex(getBeginIndex()); } /* * @see java.text.CharacterIterator#last() */ public char last() { if (fFirst == fLast) return setIndex(getEndIndex()); else return setIndex(getEndIndex() - 1); } /* * @see java.text.CharacterIterator#current() */ public char current() { if (fIndex >= fFirst && fIndex < fLast) return fSequence.charAt(fIndex); else return DONE; } /* * @see java.text.CharacterIterator#next() */ public char next() { return setIndex(Math.min(fIndex + 1, getEndIndex())); } /* * @see java.text.CharacterIterator#previous() */ public char previous() { if (fIndex > getBeginIndex()) { return setIndex(fIndex - 1); } else { return DONE; } } /* * @see java.text.CharacterIterator#setIndex(int) */ public char setIndex(int position) { if (position >= getBeginIndex() && position <= getEndIndex()) fIndex= position; else throw new IllegalArgumentException(); invariant(); return current(); } /* * @see java.text.CharacterIterator#getBeginIndex() */ public int getBeginIndex() { return fFirst; } /* * @see java.text.CharacterIterator#getEndIndex() */ public int getEndIndex() { return fLast; } /* * @see java.text.CharacterIterator#getIndex() */ public int getIndex() { return fIndex; } /* * @see java.text.CharacterIterator#clone() */ @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_SequenceCharacterIterator.java
2,898
public class NumericDoubleAnalyzer extends NumericAnalyzer<NumericDoubleTokenizer> { private final static IntObjectOpenHashMap<NamedAnalyzer> builtIn; static { builtIn = new IntObjectOpenHashMap<NamedAnalyzer>(); builtIn.put(Integer.MAX_VALUE, new NamedAnalyzer("_double/max", AnalyzerScope.GLOBAL, new NumericDoubleAnalyzer(Integer.MAX_VALUE))); for (int i = 0; i <= 64; i += 4) { builtIn.put(i, new NamedAnalyzer("_double/" + i, AnalyzerScope.GLOBAL, new NumericDoubleAnalyzer(i))); } } public static NamedAnalyzer buildNamedAnalyzer(int precisionStep) { NamedAnalyzer namedAnalyzer = builtIn.get(precisionStep); if (namedAnalyzer == null) { namedAnalyzer = new NamedAnalyzer("_double/" + precisionStep, AnalyzerScope.INDEX, new NumericDoubleAnalyzer(precisionStep)); } return namedAnalyzer; } private final int precisionStep; public NumericDoubleAnalyzer() { this(NumericUtils.PRECISION_STEP_DEFAULT); } public NumericDoubleAnalyzer(int precisionStep) { this.precisionStep = precisionStep; } @Override protected NumericDoubleTokenizer createNumericTokenizer(Reader reader, char[] buffer) throws IOException { return new NumericDoubleTokenizer(reader, precisionStep, buffer); } }
0true
src_main_java_org_elasticsearch_index_analysis_NumericDoubleAnalyzer.java
1,317
public interface LocalNodeMasterListener { /** * Called when local node is elected to be the master */ void onMaster(); /** * Called when the local node used to be the master, a new master was elected and it's no longer the local node. */ void offMaster(); /** * The name of the executor that the implementation of the callbacks of this lister should be executed on. The thread * that is responsible for managing instances of this lister is the same thread handling the cluster state events. If * the work done is the callbacks above is inexpensive, this value may be {@link org.elasticsearch.threadpool.ThreadPool.Names#SAME SAME} * (indicating that the callbaks will run on the same thread as the cluster state events are fired with). On the other hand, * if the logic in the callbacks are heavier and take longer to process (or perhaps involve blocking due to IO operations), * prefer to execute them on a separte more appropriate executor (eg. {@link org.elasticsearch.threadpool.ThreadPool.Names#GENERIC GENERIC} * or {@link org.elasticsearch.threadpool.ThreadPool.Names#MANAGEMENT MANAGEMENT}). * * @return The name of the executor that will run the callbacks of this listener. */ String executorName(); }
0true
src_main_java_org_elasticsearch_cluster_LocalNodeMasterListener.java
1,150
public class OSQLMethodNormalize extends OAbstractSQLMethod { public static final String NAME = "normalize"; public OSQLMethodNormalize() { super(NAME, 0, 2); } @Override public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) { if (ioResult != null) { final Normalizer.Form form = iMethodParams != null && iMethodParams.length > 0 ? Normalizer.Form .valueOf(OStringSerializerHelper.getStringContent(iMethodParams[0].toString())) : Normalizer.Form.NFD; String normalized = Normalizer.normalize(ioResult.toString(), form); if (iMethodParams != null && iMethodParams.length > 1) { normalized = normalized.replaceAll(OStringSerializerHelper.getStringContent(iMethodParams[0].toString()), ""); } else { normalized = normalized.replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); } ioResult = normalized; } return ioResult; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodNormalize.java
1,035
public static class FieldOrder { public static final int NAME = 1000; public static final int PRICE = 2000; public static final int QUANTITY = 3000; public static final int RETAILPRICE = 4000; public static final int SALEPRICE = 5000; public static final int TOTALTAX = 6000; public static final int CATEGORY = 1000; public static final int PRICEDETAILS = 1000; public static final int ADJUSTMENTS = 2000; public static final int DISCOUNTALLOWED = 3000; }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_OrderItemImpl.java
7
fBrowser.addOpenWindowListener(new OpenWindowListener() { @Override public void open(WindowEvent event) { event.required= true; // Cancel opening of new windows } });
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_browser_BrowserInformationControl.java
2,763
public class HttpStats implements Streamable, ToXContent { private long serverOpen; private long totalOpen; HttpStats() { } public HttpStats(long serverOpen, long totalOpen) { this.serverOpen = serverOpen; this.totalOpen = totalOpen; } public long getServerOpen() { return this.serverOpen; } public long getTotalOpen() { return this.totalOpen; } public static HttpStats readHttpStats(StreamInput in) throws IOException { HttpStats stats = new HttpStats(); stats.readFrom(in); return stats; } @Override public void readFrom(StreamInput in) throws IOException { serverOpen = in.readVLong(); totalOpen = in.readVLong(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVLong(serverOpen); out.writeVLong(totalOpen); } static final class Fields { static final XContentBuilderString HTTP = new XContentBuilderString("http"); static final XContentBuilderString CURRENT_OPEN = new XContentBuilderString("current_open"); static final XContentBuilderString TOTAL_OPENED = new XContentBuilderString("total_opened"); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(Fields.HTTP); builder.field(Fields.CURRENT_OPEN, serverOpen); builder.field(Fields.TOTAL_OPENED, totalOpen); builder.endObject(); return builder; } }
0true
src_main_java_org_elasticsearch_http_HttpStats.java
1,098
public class QueueStoreConfigReadOnly extends QueueStoreConfig { public QueueStoreConfigReadOnly(QueueStoreConfig config) { super(config); } public QueueStoreConfig setStoreImplementation(QueueStore storeImplementation) { throw new UnsupportedOperationException("This config is read-only"); } public QueueStoreConfig setEnabled(boolean enabled) { throw new UnsupportedOperationException("This config is read-only"); } public QueueStoreConfig setClassName(String className) { throw new UnsupportedOperationException("This config is read-only"); } public QueueStoreConfig setProperties(Properties properties) { throw new UnsupportedOperationException("This config is read-only"); } public QueueStoreConfig setProperty(String name, String value) { throw new UnsupportedOperationException("This config is read-only"); } public QueueStoreConfig setFactoryClassName(String factoryClassName) { throw new UnsupportedOperationException("This config is read-only"); } public QueueStoreConfig setFactoryImplementation(QueueStoreFactory factoryImplementation) { throw new UnsupportedOperationException("This config is read-only"); } }
0true
hazelcast_src_main_java_com_hazelcast_config_QueueStoreConfigReadOnly.java
87
public interface StaticAssetService extends SandBoxItemListener { public StaticAsset findStaticAssetById(Long id); public List<StaticAsset> readAllStaticAssets(); public StaticAsset findStaticAssetByFullUrl(String fullUrl, SandBox targetSandBox); /** * Used when uploading a file to Broadleaf. This method will create the corresponding * asset. * * Depending on the the implementation, the actual asset may be saved to the DB or to * the file system. The default implementation {@link StaticAssetServiceImpl} has a * environment properties that determine this behavior <code>asset.use.filesystem.storage</code>, and * <code>asset.server.file.system.path</code>. * * The properties allows for implementors to update other Asset properties at the * same time they are uploading a file. The default implementation uses this for an optional URL to * be specified. * * @see StaticAssetServiceImpl * * @param file - the file being uploaded * @param properties - additional meta-data properties * @return * @throws IOException */ public StaticAsset createStaticAssetFromFile(MultipartFile file, Map<String, String> properties); /** * This method is intended to be called from within the CMS * admin only. * * Adds the passed in page to the DB. * * Creates a sandbox/site if one doesn't already exist. */ public StaticAsset addStaticAsset(StaticAsset staticAsset, SandBox destinationSandbox); /** * This method is intended to be called from within the CMS * admin only. * * Updates the page according to the following rules: * * 1. If sandbox has changed from null to a value * This means that the user is editing an item in production and * the edit is taking place in a sandbox. * * Clone the page and add it to the new sandbox and set the cloned * page's originalPageId to the id of the page being updated. * * 2. If the sandbox has changed from one value to another * This means that the user is moving the item from one sandbox * to another. * * Update the siteId for the page to the one associated with the * new sandbox * * 3. If the sandbox has changed from a value to null * This means that the item is moving from the sandbox to production. * * If the page has an originalPageId, then update that page by * setting it's archived flag to true. * * Then, update the siteId of the page being updated to be the * siteId of the original page. * * 4. If the sandbox is the same then just update the page. */ public StaticAsset updateStaticAsset(StaticAsset staticAsset, SandBox sandbox); /** * If deleting and item where page.originalPageId != null * then the item is deleted from the database. * * If the originalPageId is null, then this method marks * the items as deleted within the passed in sandbox. * * * @param staticAsset * @param destinationSandbox * @return */ public void deleteStaticAsset(StaticAsset staticAsset, SandBox destinationSandbox); public Long countAssets(SandBox sandbox, Criteria criteria); public List<StaticAsset> findAssets(SandBox sandbox, Criteria criteria); /** * Returns the value configured to mark an item as a static URL. * * OOB BLC maintains this value in common.properties. * * @return */ public String getStaticAssetUrlPrefix(); public void setStaticAssetUrlPrefix(String prefix); /** * Returns the value configured for the current environment * for the static asset url prefix. If this is different than * the common value, then the URLs will get rewritten by the * FieldMapWrapper when called from the DisplayContentTag or * ProcessURLFilter. * * @return */ public String getStaticAssetEnvironmentUrlPrefix(); /** * Returns the secure value of the environment url prefix (e.g. prefixed with https if needed). * * @return */ public String getStaticAssetEnvironmentSecureUrlPrefix(); /** * Sets the environment url prefix. * @param prefix */ public void setStaticAssetEnvironmentUrlPrefix(String prefix); /** * If set to true, then this service will not use the SandBox concept * and will instead automatically promote images to production * as they are entered into the system. * * This is recommended for the best workflow within the BLC-CMS and has * been set as the default behavior. * */ public boolean getAutomaticallyApproveAndPromoteStaticAssets(); /** * If set to true, then this service will not use the SandBox concept * and will instead automatically promote images to production * as they are entered into the system. * * This is recommended for the best workflow within the BLC-CMS and has * been set as the default behavior. * */ public void setAutomaticallyApproveAndPromoteStaticAssets(boolean setting); /** * This method will take in an assetPath (think image url) and convert it if * the value contains the asseturlprefix. * @see StaticAssetService#getStaticAssetUrlPrefix() * @see StaticAssetService#getStaticAssetEnvironmentUrlPrefix() * * @param assetPath - The path to rewrite if it is a cms managed asset * @param contextPath - The context path of the web application (if applicable) * @param secureRequest - True if the request is being served over https * @return */ public String convertAssetPath(String assetPath, String contextPath, boolean secureRequest); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_service_StaticAssetService.java
1,078
public class OSQLFilter extends OSQLPredicate implements OCommandPredicate { public OSQLFilter(final String iText, final OCommandContext iContext, final String iFilterKeyword) { super(); context = iContext; parserText = iText; parserTextUpperCase = iText.toUpperCase(); try { final int lastPos = parserGetCurrentPosition(); final String lastText = parserText; final String lastTextUpperCase = parserTextUpperCase; text(parserText.substring(lastPos)); parserText = lastText; parserTextUpperCase = lastTextUpperCase; parserMoveCurrentPosition(lastPos); } catch (OQueryParsingException e) { if (e.getText() == null) // QUERY EXCEPTION BUT WITHOUT TEXT: NEST IT throw new OQueryParsingException("Error on parsing query", parserText, parserGetCurrentPosition(), e); throw e; } catch (Throwable t) { throw new OQueryParsingException("Error on parsing query", parserText, parserGetCurrentPosition(), t); } } public Object evaluate(final ORecord<?> iRecord, final ODocument iCurrentResult, final OCommandContext iContext) { if (rootCondition == null) return true; return rootCondition.evaluate(iRecord, iCurrentResult, iContext); } public OSQLFilterCondition getRootCondition() { return rootCondition; } @Override public String toString() { if (rootCondition != null) return "Parsed: " + rootCondition.toString(); return "Unparsed: " + parserText; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_filter_OSQLFilter.java
1,220
public class PaymentProcessContextFactory implements ProcessContextFactory { @Resource(name = "blSecurePaymentInfoService") protected SecurePaymentInfoService securePaymentInfoService; @Resource(name = "blOrderService") protected OrderService orderService; protected PaymentActionType paymentActionType; public ProcessContext createContext(Object seedData) throws WorkflowException { if (!(seedData instanceof PaymentSeed)) { throw new WorkflowException("Seed data instance is incorrect. " + "Required class is " + PaymentSeed.class.getName() + " " + "but found class: " + seedData.getClass().getName()); } PaymentSeed paymentSeed = (PaymentSeed) seedData; Map<PaymentInfo, Referenced> secureMap = paymentSeed.getInfos(); if (secureMap == null) { secureMap = new HashMap<PaymentInfo, Referenced>(); List<PaymentInfo> paymentInfoList = orderService.findPaymentInfosForOrder(paymentSeed.getOrder()); if (paymentInfoList == null || paymentInfoList.size() == 0) { throw new WorkflowException("No payment info instances associated with the order -- id: " + paymentSeed.getOrder().getId()); } Iterator<PaymentInfo> infos = paymentInfoList.iterator(); while (infos.hasNext()) { PaymentInfo info = infos.next(); secureMap.put(info, securePaymentInfoService.findSecurePaymentInfo(info.getReferenceNumber(), info.getType())); } } CombinedPaymentContextSeed combinedSeed = new CombinedPaymentContextSeed(secureMap, paymentActionType, paymentSeed.getOrder().getTotal(), paymentSeed.getPaymentResponse(), paymentSeed.getTransactionAmount()); WorkflowPaymentContext response = new WorkflowPaymentContext(); response.setSeedData(combinedSeed); return response; } public PaymentActionType getPaymentActionType() { return paymentActionType; } public void setPaymentActionType(PaymentActionType paymentActionType) { this.paymentActionType = paymentActionType; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_workflow_PaymentProcessContextFactory.java
911
public abstract class AbstractListenableActionFuture<T, L> extends AdapterActionFuture<T, L> implements ListenableActionFuture<T> { final boolean listenerThreaded; final ThreadPool threadPool; volatile Object listeners; boolean executedListeners = false; protected AbstractListenableActionFuture(boolean listenerThreaded, ThreadPool threadPool) { this.listenerThreaded = listenerThreaded; this.threadPool = threadPool; } public boolean listenerThreaded() { return false; // we control execution of the listener } public ThreadPool threadPool() { return threadPool; } public void addListener(final ActionListener<T> listener) { internalAddListener(listener); } public void addListener(final Runnable listener) { internalAddListener(listener); } public void internalAddListener(Object listener) { boolean executeImmediate = false; synchronized (this) { if (executedListeners) { executeImmediate = true; } else { Object listeners = this.listeners; if (listeners == null) { listeners = listener; } else if (listeners instanceof List) { ((List) this.listeners).add(listener); } else { Object orig = listeners; listeners = Lists.newArrayListWithCapacity(2); ((List) listeners).add(orig); ((List) listeners).add(listener); } this.listeners = listeners; } } if (executeImmediate) { executeListener(listener); } } @Override protected void done() { super.done(); synchronized (this) { executedListeners = true; } Object listeners = this.listeners; if (listeners != null) { if (listeners instanceof List) { List list = (List) listeners; for (Object listener : list) { executeListener(listener); } } else { executeListener(listeners); } } } private void executeListener(final Object listener) { if (listenerThreaded) { if (listener instanceof Runnable) { threadPool.generic().execute((Runnable) listener); } else { threadPool.generic().execute(new Runnable() { @Override public void run() { ActionListener<T> lst = (ActionListener<T>) listener; try { lst.onResponse(actionGet()); } catch (ElasticsearchException e) { lst.onFailure(e); } } }); } } else { if (listener instanceof Runnable) { ((Runnable) listener).run(); } else { ActionListener<T> lst = (ActionListener<T>) listener; try { lst.onResponse(actionGet()); } catch (ElasticsearchException e) { lst.onFailure(e); } } } } }
0true
src_main_java_org_elasticsearch_action_support_AbstractListenableActionFuture.java
421
public class RestoreSnapshotResponse extends ActionResponse implements ToXContent { @Nullable private RestoreInfo restoreInfo; RestoreSnapshotResponse(@Nullable RestoreInfo restoreInfo) { this.restoreInfo = restoreInfo; } RestoreSnapshotResponse() { } /** * Returns restore information if snapshot was completed before this method returned, null otherwise * * @return restore information or null */ public RestoreInfo getRestoreInfo() { return restoreInfo; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); restoreInfo = RestoreInfo.readOptionalRestoreInfo(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeOptionalStreamable(restoreInfo); } public RestStatus status() { if (restoreInfo == null) { return RestStatus.ACCEPTED; } return restoreInfo.status(); } static final class Fields { static final XContentBuilderString SNAPSHOT = new XContentBuilderString("snapshot"); static final XContentBuilderString ACCEPTED = new XContentBuilderString("accepted"); } @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { if (restoreInfo != null) { builder.field(Fields.SNAPSHOT); restoreInfo.toXContent(builder, params); } else { builder.field(Fields.ACCEPTED, true); } return builder; } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_restore_RestoreSnapshotResponse.java
1,552
public class OServerMain { private static OServer instance; public static OServer create() throws Exception { instance = new OServer(); return instance; } public static OServer server() { return instance; } public static void main(final String[] args) throws Exception { instance = OServerMain.create(); instance.startup().activate(); } }
0true
server_src_main_java_com_orientechnologies_orient_server_OServerMain.java
376
public class MetadataNamingStrategy extends org.springframework.jmx.export.naming.MetadataNamingStrategy { public ObjectName getObjectName(Object managedBean, String beanKey) throws MalformedObjectNameException { managedBean = AspectUtil.exposeRootBean(managedBean); return super.getObjectName(managedBean, beanKey); } }
0true
common_src_main_java_org_broadleafcommerce_common_jmx_MetadataNamingStrategy.java
6
Collections.sort(abbreviationsForPhrase, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.length() - o2.length(); } });
0true
tableViews_src_main_java_gov_nasa_arc_mct_abbreviation_impl_AbbreviationsManager.java
317
public class NodesHotThreadsAction extends ClusterAction<NodesHotThreadsRequest, NodesHotThreadsResponse, NodesHotThreadsRequestBuilder> { public static final NodesHotThreadsAction INSTANCE = new NodesHotThreadsAction(); public static final String NAME = "cluster/nodes/hot_threads"; private NodesHotThreadsAction() { super(NAME); } @Override public NodesHotThreadsResponse newResponse() { return new NodesHotThreadsResponse(); } @Override public NodesHotThreadsRequestBuilder newRequestBuilder(ClusterAdminClient client) { return new NodesHotThreadsRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_hotthreads_NodesHotThreadsAction.java
109
public static class Adapter implements Monitor { @Override public void txStarted( Xid xid ) { } @Override public void txCommitted( Xid xid ) { } @Override public void txRolledBack( Xid xid ) { } @Override public void txManagerStopped() { } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TxManager.java