Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
1,556
assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { Hashtable table = new Hashtable(); table.put("type", type); table.put("name", name); table.put("instance", hz.getName()); ObjectName name = new ObjectName("com.hazelcast", table); try { ObjectInstance mbean = mbs.getObjectInstance(name); } catch (InstanceNotFoundException e) { fail(e.getMessage()); } } });
0true
hazelcast_src_test_java_com_hazelcast_jmx_MBeanTest.java
1,249
public class DefaultSchemaProvider implements SchemaProvider { public static final DefaultSchemaProvider INSTANCE = new DefaultSchemaProvider(); private DefaultSchemaProvider() {} @Override public EdgeLabelDefinition getEdgeLabel(String name) { return new EdgeLabelDefinition(name, FaunusElement.NO_ID, Multiplicity.MULTI,false); } @Override public PropertyKeyDefinition getPropertyKey(String name) { return new PropertyKeyDefinition(name, FaunusElement.NO_ID, Cardinality.SINGLE,Object.class); } @Override public RelationTypeDefinition getRelationType(String name) { return null; } @Override public VertexLabelDefinition getVertexLabel(String name) { return new VertexLabelDefinition(name, FaunusElement.NO_ID,false,false); } public static SchemaProvider asBackupProvider(final SchemaProvider provider) { return asBackupProvider(provider,INSTANCE); } public static SchemaProvider asBackupProvider(final SchemaProvider provider, final SchemaProvider backup) { return new SchemaProvider() { @Override public EdgeLabelDefinition getEdgeLabel(String name) { EdgeLabelDefinition def = provider.getEdgeLabel(name); if (def!=null) return def; else return backup.getEdgeLabel(name); } @Override public PropertyKeyDefinition getPropertyKey(String name) { PropertyKeyDefinition def = provider.getPropertyKey(name); if (def!=null) return def; else return backup.getPropertyKey(name); } @Override public RelationTypeDefinition getRelationType(String name) { return provider.getRelationType(name); } @Override public VertexLabelDefinition getVertexLabel(String name) { VertexLabelDefinition def = provider.getVertexLabel(name); if (def!=null) return def; else return backup.getVertexLabel(name); } }; } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_DefaultSchemaProvider.java
586
nodeEngine.getExecutionService().execute(ExecutionService.SYSTEM_EXECUTOR, new Runnable() { public void run() { if (added) { service.memberAdded(event); } else { service.memberRemoved(event); } } });
0true
hazelcast_src_main_java_com_hazelcast_cluster_ClusterServiceImpl.java
925
final Object myNextVal = makeDbCall(iMyDb, new ODbRelatedCall<Object>() { public Object call() { return myIterator.next(); } });
0true
core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java
2,136
public class LoggerInfoStream extends PrintStream { public static final String SUFFIX = ".lucene"; /** * Creates a new {@link LoggerInfoStream} based on the provided logger * by appending to its <tt>NAME</tt> the {@link #SUFFIX}. */ public static LoggerInfoStream getInfoStream(ESLogger logger) { try { return new LoggerInfoStream(Loggers.getLogger(logger, SUFFIX)); } catch (UnsupportedEncodingException e) { // no UTF-8 ? throw new RuntimeException(e); } } /** * Creates a new {@link LoggerInfoStream} based on the provided name * by appending to it the {@link #SUFFIX}. */ public static LoggerInfoStream getInfoStream(String name) { try { return new LoggerInfoStream(Loggers.getLogger(name + SUFFIX)); } catch (UnsupportedEncodingException e) { // no UTF-8 ? throw new RuntimeException(e); } } private final ESLogger logger; /** * Constucts a new instance based on the provided logger. Will output * each {@link #println(String)} operation as a trace level. * @throws UnsupportedEncodingException */ public LoggerInfoStream(ESLogger logger) throws UnsupportedEncodingException { super((OutputStream) null, false, Charsets.UTF_8.name()); this.logger = logger; } /** * Override only the method Lucene actually uses. */ @Override public void println(String x) { logger.trace(x); } }
0true
src_main_java_org_elasticsearch_common_lucene_LoggerInfoStream.java
379
public class ClusterRerouteAction extends ClusterAction<ClusterRerouteRequest, ClusterRerouteResponse, ClusterRerouteRequestBuilder> { public static final ClusterRerouteAction INSTANCE = new ClusterRerouteAction(); public static final String NAME = "cluster/reroute"; private ClusterRerouteAction() { super(NAME); } @Override public ClusterRerouteResponse newResponse() { return new ClusterRerouteResponse(); } @Override public ClusterRerouteRequestBuilder newRequestBuilder(ClusterAdminClient client) { return new ClusterRerouteRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_reroute_ClusterRerouteAction.java
298
new Thread() { public void run() { l.forceUnlock(); latch.countDown(); } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_lock_ClientLockTest.java
214
interface SocketChannelWrapperFactory { SocketChannelWrapper wrapSocketChannel(SocketChannel socketChannel, boolean client) throws Exception; }
0true
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientConnectionManagerImpl.java
997
public static class Group { public static class Name { public static final String Pricing = "FulfillmentGroupImpl_Pricing"; } public static class Order { public static final int General = 1000; public static final int Pricing = 2000; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_FulfillmentGroupImpl.java
31
static final class ThenCombine<T,U,V> extends Completion { final CompletableFuture<? extends T> src; final CompletableFuture<? extends U> snd; final BiFun<? super T,? super U,? extends V> fn; final CompletableFuture<V> dst; final Executor executor; ThenCombine(CompletableFuture<? extends T> src, CompletableFuture<? extends U> snd, BiFun<? super T,? super U,? extends V> fn, CompletableFuture<V> dst, Executor executor) { this.src = src; this.snd = snd; this.fn = fn; this.dst = dst; this.executor = executor; } public final void run() { final CompletableFuture<? extends T> a; final CompletableFuture<? extends U> b; final BiFun<? super T,? super U,? extends V> fn; final CompletableFuture<V> dst; Object r, s; T t; U u; Throwable ex; if ((dst = this.dst) != null && (fn = this.fn) != null && (a = this.src) != null && (r = a.result) != null && (b = this.snd) != null && (s = b.result) != null && compareAndSet(0, 1)) { if (r instanceof AltResult) { ex = ((AltResult)r).ex; t = null; } else { ex = null; @SuppressWarnings("unchecked") T tr = (T) r; t = tr; } if (ex != null) u = null; else if (s instanceof AltResult) { ex = ((AltResult)s).ex; u = null; } else { @SuppressWarnings("unchecked") U us = (U) s; u = us; } Executor e = executor; V v = null; if (ex == null) { try { if (e != null) e.execute(new AsyncCombine<T,U,V>(t, u, fn, dst)); else v = fn.apply(t, u); } catch (Throwable rex) { ex = rex; } } if (e == null || ex != null) dst.internalComplete(v, ex); } } private static final long serialVersionUID = 5232453952276885070L; }
0true
src_main_java_jsr166e_CompletableFuture.java
2,891
public class NGramTokenizerFactoryTests extends ElasticsearchTokenStreamTestCase { @Test public void testParseTokenChars() { final Index index = new Index("test"); final String name = "ngr"; final Settings indexSettings = ImmutableSettings.EMPTY; for (String tokenChars : Arrays.asList("letters", "number", "DIRECTIONALITY_UNDEFINED")) { final Settings settings = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3).put("token_chars", tokenChars).build(); try { new NGramTokenizerFactory(index, indexSettings, name, settings).create(new StringReader("")); fail(); } catch (ElasticsearchIllegalArgumentException expected) { // OK } } for (String tokenChars : Arrays.asList("letter", " digit ", "punctuation", "DIGIT", "CoNtRoL", "dash_punctuation")) { final Settings settings = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3).put("token_chars", tokenChars).build(); new NGramTokenizerFactory(index, indexSettings, name, settings).create(new StringReader("")); // no exception } } @Test public void testPreTokenization() throws IOException { // Make sure that pretokenization works well and that it can be used even with token chars which are supplementary characters final Index index = new Index("test"); final String name = "ngr"; final Settings indexSettings = ImmutableSettings.EMPTY; Settings settings = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3).put("token_chars", "letter,digit").build(); assertTokenStreamContents(new NGramTokenizerFactory(index, indexSettings, name, settings).create(new StringReader("Åbc déf g\uD801\uDC00f ")), new String[] {"Åb", "Åbc", "bc", "dé", "déf", "éf", "g\uD801\uDC00", "g\uD801\uDC00f", "\uD801\uDC00f"}); settings = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3).put("token_chars", "letter,digit,punctuation,whitespace,symbol").build(); assertTokenStreamContents(new NGramTokenizerFactory(index, indexSettings, name, settings).create(new StringReader(" a!$ 9")), new String[] {" a", " a!", "a!", "a!$", "!$", "!$ ", "$ ", "$ 9", " 9"}); } @Test public void testPreTokenizationEdge() throws IOException { // Make sure that pretokenization works well and that it can be used even with token chars which are supplementary characters final Index index = new Index("test"); final String name = "ngr"; final Settings indexSettings = ImmutableSettings.EMPTY; Settings settings = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3).put("token_chars", "letter,digit").build(); assertTokenStreamContents(new EdgeNGramTokenizerFactory(index, indexSettings, name, settings).create(new StringReader("Åbc déf g\uD801\uDC00f ")), new String[] {"Åb", "Åbc", "dé", "déf", "g\uD801\uDC00", "g\uD801\uDC00f"}); settings = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3).put("token_chars", "letter,digit,punctuation,whitespace,symbol").build(); assertTokenStreamContents(new EdgeNGramTokenizerFactory(index, indexSettings, name, settings).create(new StringReader(" a!$ 9")), new String[] {" a", " a!"}); } @Test public void testBackwardsCompatibilityEdgeNgramTokenizer() throws IllegalArgumentException, IllegalAccessException { int iters = atLeast(20); final Index index = new Index("test"); final String name = "ngr"; for (int i = 0; i < iters; i++) { Version v = randomVersion(random()); if (v.onOrAfter(Version.V_0_90_2)) { Builder builder = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3).put("token_chars", "letter,digit"); boolean compatVersion = false; if ((compatVersion = random().nextBoolean())) { builder.put("version", "4." + random().nextInt(3)); builder.put("side", "back"); } Settings settings = builder.build(); Settings indexSettings = ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, v.id).build(); Tokenizer edgeNGramTokenizer = new EdgeNGramTokenizerFactory(index, indexSettings, name, settings).create(new StringReader( "foo bar")); if (compatVersion) { assertThat(edgeNGramTokenizer, instanceOf(Lucene43EdgeNGramTokenizer.class)); } else { assertThat(edgeNGramTokenizer, instanceOf(EdgeNGramTokenizer.class)); } } else { Settings settings = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3).put("side", "back").build(); Settings indexSettings = ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, v.id).build(); Tokenizer edgeNGramTokenizer = new EdgeNGramTokenizerFactory(index, indexSettings, name, settings).create(new StringReader( "foo bar")); assertThat(edgeNGramTokenizer, instanceOf(Lucene43EdgeNGramTokenizer.class)); } } Settings settings = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3).put("side", "back").build(); Settings indexSettings = ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build(); try { new EdgeNGramTokenizerFactory(index, indexSettings, name, settings).create(new StringReader("foo bar")); fail("should fail side:back is not supported anymore"); } catch (ElasticsearchIllegalArgumentException ex) { } } @Test public void testBackwardsCompatibilityNgramTokenizer() throws IllegalArgumentException, IllegalAccessException { int iters = atLeast(20); for (int i = 0; i < iters; i++) { final Index index = new Index("test"); final String name = "ngr"; Version v = randomVersion(random()); if (v.onOrAfter(Version.V_0_90_2)) { Builder builder = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3).put("token_chars", "letter,digit"); boolean compatVersion = false; if ((compatVersion = random().nextBoolean())) { builder.put("version", "4." + random().nextInt(3)); } Settings settings = builder.build(); Settings indexSettings = ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, v.id).build(); Tokenizer nGramTokenizer = new NGramTokenizerFactory(index, indexSettings, name, settings).create(new StringReader( "foo bar")); if (compatVersion) { assertThat(nGramTokenizer, instanceOf(Lucene43NGramTokenizer.class)); } else { assertThat(nGramTokenizer, instanceOf(NGramTokenizer.class)); } } else { Settings settings = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3).build(); Settings indexSettings = ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, v.id).build(); Tokenizer nGramTokenizer = new NGramTokenizerFactory(index, indexSettings, name, settings).create(new StringReader( "foo bar")); assertThat(nGramTokenizer, instanceOf(Lucene43NGramTokenizer.class)); } } } @Test public void testBackwardsCompatibilityEdgeNgramTokenFilter() throws IllegalArgumentException, IllegalAccessException { int iters = atLeast(20); for (int i = 0; i < iters; i++) { final Index index = new Index("test"); final String name = "ngr"; Version v = randomVersion(random()); if (v.onOrAfter(Version.V_0_90_2)) { Builder builder = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3); boolean compatVersion = false; if ((compatVersion = random().nextBoolean())) { builder.put("version", "4." + random().nextInt(3)); } boolean reverse = random().nextBoolean(); if (reverse) { builder.put("side", "back"); } Settings settings = builder.build(); Settings indexSettings = ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, v.id).build(); TokenStream edgeNGramTokenFilter = new EdgeNGramTokenFilterFactory(index, indexSettings, name, settings).create(new MockTokenizer(new StringReader( "foo bar"))); if (compatVersion) { assertThat(edgeNGramTokenFilter, instanceOf(EdgeNGramTokenFilter.class)); } else if (reverse && !compatVersion){ assertThat(edgeNGramTokenFilter, instanceOf(ReverseStringFilter.class)); } else { assertThat(edgeNGramTokenFilter, instanceOf(EdgeNGramTokenFilter.class)); } } else { Builder builder = ImmutableSettings.builder().put("min_gram", 2).put("max_gram", 3); boolean reverse = random().nextBoolean(); if (reverse) { builder.put("side", "back"); } Settings settings = builder.build(); Settings indexSettings = ImmutableSettings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, v.id).build(); TokenStream edgeNGramTokenFilter = new EdgeNGramTokenFilterFactory(index, indexSettings, name, settings).create(new MockTokenizer(new StringReader( "foo bar"))); assertThat(edgeNGramTokenFilter, instanceOf(EdgeNGramTokenFilter.class)); } } } private Version randomVersion(Random random) throws IllegalArgumentException, IllegalAccessException { Field[] declaredFields = Version.class.getDeclaredFields(); List<Field> versionFields = new ArrayList<Field>(); for (Field field : declaredFields) { if ((field.getModifiers() & Modifier.STATIC) != 0 && field.getName().startsWith("V_") && field.getType() == Version.class) { versionFields.add(field); } } return (Version) versionFields.get(random.nextInt(versionFields.size())).get(Version.class); } }
0true
src_test_java_org_elasticsearch_index_analysis_NGramTokenizerFactoryTests.java
295
public abstract class DistributedStoreManager extends AbstractStoreManager { public enum Deployment { /** * Connects to storage backend over the network or some other connection with significant latency */ REMOTE, /** * Connects to storage backend over localhost or some other connection with very low latency */ LOCAL, /** * Embedded with storage backend and communicates inside the JVM */ EMBEDDED } private static final Logger log = LoggerFactory.getLogger(DistributedStoreManager.class); private static final Random random = new Random(); protected final String[] hostnames; protected final int port; protected final Duration connectionTimeoutMS; protected final int pageSize; protected final String username; protected final String password; protected final TimestampProvider times; // TODO remove public DistributedStoreManager(Configuration storageConfig, int portDefault) { super(storageConfig); this.hostnames = storageConfig.get(STORAGE_HOSTS); Preconditions.checkArgument(hostnames.length > 0, "No hostname configured"); if (storageConfig.has(STORAGE_PORT)) this.port = storageConfig.get(STORAGE_PORT); else this.port = portDefault; this.connectionTimeoutMS = storageConfig.get(CONNECTION_TIMEOUT); this.pageSize = storageConfig.get(PAGE_SIZE); this.times = storageConfig.get(TIMESTAMP_PROVIDER); if (storageConfig.has(AUTH_USERNAME)) { this.username = storageConfig.get(AUTH_USERNAME); this.password = storageConfig.get(AUTH_PASSWORD); } else { this.username=null; this.password=null; } } /** * Returns a randomly chosen host name. This is used to pick one host when multiple are configured * * @return */ protected String getSingleHostname() { return hostnames[random.nextInt(hostnames.length)]; } /** * Whether authentication is enabled for this storage backend * * @return */ public boolean hasAuthentication() { return username!=null; } /** * Returns the default configured page size for this storage backend. The page size is used to determine * the number of records to request at a time when streaming result data. * @return */ public int getPageSize() { return pageSize; } /* * TODO this should go away once we have a TitanConfig that encapsulates TimestampProvider */ public TimestampProvider getTimestampProvider() { return times; } /** * Returns the {@link Deployment} mode of this connection to the storage backend * * @return */ public abstract Deployment getDeployment(); @Override public String toString() { String hn = getSingleHostname(); return hn.substring(0, Math.min(hn.length(), 256)) + ":" + port; } /** * This method attempts to generate Rid in the following three ways, in order, * returning the value produced by the first successful attempt in the sequence. * <p/> * <ol> * <li> * If {@code config} contains {@see GraphDatabaseConfiguration#INSTANCE_RID_RAW_KEY}, * then read it as a String value. Convert the String returned into a char[] and * call {@code org.apache.commons.codec.binary.Hex#decodeHex on the char[]}. The * byte[] returned by {@code decodeHex} is then returned as Rid. * </li> * <li> * If {@code config} contains {@see GraphDatabaseConfiguration#INSTANCE_RID_SHORT_KEY}, * then read it as a short value. Call {@see java.net.InetAddress#getLocalHost()}, * and on its return value call {@see java.net.InetAddress#getAddress()} to retrieve * the machine's IP address in byte[] form. The returned Rid is a byte[] containing * the localhost address bytes in its lower indices and the short value in its * penultimate and final indices. * </li> * <li> * If both of the previous failed, then call * {@see java.lang.management.RuntimeMXBean#getName()} and then call * {@code String#getBytes()} on the returned value. Return a Rid as described in the * previous point, replacing the short value with the byte[] representing the JVM name. * </li> * </ol> * * @param config commons config from which to read Rid-related keys * @return A byte array which should uniquely identify this machine */ // public static byte[] getRid(Configuration config) { // Preconditions.checkArgument(config.has(UNIQUE_INSTANCE_ID)); // return config.get(UNIQUE_INSTANCE_ID).getBytes(); // // byte tentativeRid[] = null; // // if (config.has(GraphDatabaseConfiguration.INSTANCE_RID_RAW)) { // String ridText = // config.get(GraphDatabaseConfiguration.INSTANCE_RID_RAW); // try { // tentativeRid = Hex.decodeHex(ridText.toCharArray()); // } catch (DecoderException e) { // throw new TitanConfigurationException("Could not decode hex value", e); // } // // log.debug("Set rid from hex string: 0x{}", ridText); // } else { // final byte[] endBytes; // // if (config.has(GraphDatabaseConfiguration.INSTANCE_RID_SHORT)) { // // short s = config.get( // GraphDatabaseConfiguration.INSTANCE_RID_SHORT); // // endBytes = new byte[2]; // // endBytes[0] = (byte) ((s & 0x0000FF00) >> 8); // endBytes[1] = (byte) (s & 0x000000FF); // } else { // //endBytes = ManagementFactory.getRuntimeMXBean().getName().getBytes(); // endBytes = new StringBuilder(String.valueOf(Thread.currentThread().getId())) // .append("@") // .append(ManagementFactory.getRuntimeMXBean().getName()) // .toString() // .getBytes(); // } // // byte[] addrBytes; // try { // addrBytes = Inet4Address.getLocalHost().getAddress(); // } catch (UnknownHostException e) { // throw new TitanConfigurationException("Unknown host specified", e); // } // // tentativeRid = new byte[addrBytes.length + endBytes.length]; // System.arraycopy(addrBytes, 0, tentativeRid, 0, addrBytes.length); // System.arraycopy(endBytes, 0, tentativeRid, addrBytes.length, endBytes.length); // // if (log.isDebugEnabled()) { // log.debug("Set rid: 0x{}", new String(Hex.encodeHex(tentativeRid))); // } // } // // return tentativeRid; // } protected void sleepAfterWrite(StoreTransaction txh, MaskedTimestamp mustPass) throws BackendException { assert mustPass.getDeletionTime(times.getUnit()) < mustPass.getAdditionTime(times.getUnit()); try { times.sleepPast(mustPass.getAdditionTime()); } catch (InterruptedException e) { throw new PermanentBackendException("Unexpected interrupt", e); } } /** * Helper class to create the deletion and addition timestamps for a particular transaction. * It needs to be ensured that the deletion time is prior to the addition time since * some storage backends use the time to resolve conflicts. */ public class MaskedTimestamp { private final Timepoint t; public MaskedTimestamp(Timepoint commitTime) { Preconditions.checkNotNull(commitTime); this.t=commitTime; } public MaskedTimestamp(StoreTransaction txh) { this(txh.getConfiguration().getCommitTime()); } public long getDeletionTime(TimeUnit unit) { return t.getTimestamp(unit) & 0xFFFFFFFFFFFFFFFEL; // zero the LSB } public long getNativeDeletionTime() { assert t.getProvider().equals(times); return t.getNativeTimestamp() & 0xFFFFFFFFFFFFFFFEL; // zero the LSB } public Timepoint getDeletionTime() { return new StandardTimepoint(getDeletionTime(t.getNativeUnit()), t.getProvider()); } public long getAdditionTime(TimeUnit unit) { return (t.getTimestamp(unit) & 0xFFFFFFFFFFFFFFFEL) | 1L; // force the LSB to 1 } public long getNativeAdditionTime() { assert t.getProvider().equals(times); return (t.getNativeTimestamp() & 0xFFFFFFFFFFFFFFFEL) | 1L; // force the LSB to 1 } public Timepoint getAdditionTime() { return new StandardTimepoint(getAdditionTime(t.getNativeUnit()), t.getProvider()); } } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_common_DistributedStoreManager.java
2,632
ping(new PingListener() { @Override public void onPing(PingResponse[] pings) { response.set(pings); latch.countDown(); } }, timeout);
0true
src_main_java_org_elasticsearch_discovery_zen_ping_multicast_MulticastZenPing.java
1,190
.moduleManagerFactory(new ModuleManagerFactory(){ @Override public ModuleManager createModuleManager(Context context) { return new JDTModuleManager(context, javaProject); } });
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_builder_CeylonBuilder.java
1,034
public class OCommandExecutorSQLDelegate extends OCommandExecutorSQLAbstract { protected OCommandExecutorSQLAbstract delegate; @SuppressWarnings("unchecked") public OCommandExecutorSQLDelegate parse(final OCommandRequest iCommand) { if (iCommand instanceof OCommandRequestText) { final OCommandRequestText textRequest = (OCommandRequestText) iCommand; final String text = textRequest.getText(); final String textUpperCase = text.toUpperCase(Locale.ENGLISH); delegate = (OCommandExecutorSQLAbstract) OSQLEngine.getInstance().getCommand(textUpperCase); if (delegate == null) throw new OCommandExecutorNotFoundException("Cannot find a command executor for the command request: " + iCommand); delegate.setContext(context); delegate.setLimit(iCommand.getLimit()); delegate.parse(iCommand); delegate.setProgressListener(progressListener); } else throw new OCommandExecutionException("Cannot find a command executor for the command request: " + iCommand); return this; } public Object execute(final Map<Object, Object> iArgs) { return delegate.execute(iArgs); } @Override public OCommandContext getContext() { return delegate.getContext(); } @Override public String toString() { return delegate.toString(); } public String getSyntax() { return delegate.getSyntax(); } @Override public String getFetchPlan() { return delegate.getFetchPlan(); } public boolean isIdempotent() { return delegate.isIdempotent(); } public OCommandExecutorSQLAbstract getDelegate() { return delegate; } }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLDelegate.java
2,717
static class AllocateDangledRequest extends TransportRequest { DiscoveryNode fromNode; IndexMetaData[] indices; AllocateDangledRequest() { } AllocateDangledRequest(DiscoveryNode fromNode, IndexMetaData[] indices) { this.fromNode = fromNode; this.indices = indices; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); fromNode = DiscoveryNode.readNode(in); indices = new IndexMetaData[in.readVInt()]; for (int i = 0; i < indices.length; i++) { indices[i] = IndexMetaData.Builder.readFrom(in); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); fromNode.writeTo(out); out.writeVInt(indices.length); for (IndexMetaData indexMetaData : indices) { IndexMetaData.Builder.writeTo(indexMetaData, out); } } }
0true
src_main_java_org_elasticsearch_gateway_local_state_meta_LocalAllocateDangledIndices.java
923
return new Comparator<PromotableOrderItemPriceDetail>() { @Override public int compare(PromotableOrderItemPriceDetail o1, PromotableOrderItemPriceDetail o2) { Money price = o1.getPromotableOrderItem().getPriceBeforeAdjustments(applyToSalePrice); Money price2 = o2.getPromotableOrderItem().getPriceBeforeAdjustments(applyToSalePrice); // highest amount first return price2.compareTo(price); } };
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_processor_ItemOfferProcessorImpl.java
1,151
public class OSQLMethodPrefix extends OAbstractSQLMethod { public static final String NAME = "prefix"; public OSQLMethodPrefix() { super(NAME, 1); } @Override public Object execute(OIdentifiable iRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) { final Object v = getParameterValue(iRecord, iMethodParams[0].toString()); if (v != null) { ioResult = ioResult != null ? v + ioResult.toString() : null; } return ioResult; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodPrefix.java
174
@SuppressWarnings("serial") public class OModifiableInteger extends Number implements Comparable<OModifiableInteger> { public int value; public OModifiableInteger() { value = 0; } public OModifiableInteger(final int iValue) { value = iValue; } public void setValue(final int iValue) { value = iValue; } public int getValue() { return value; } public void increment() { value++; } public void increment(final int iValue) { value += iValue; } public void decrement() { value--; } public void decrement(final int iValue) { value -= iValue; } public int compareTo(final OModifiableInteger anotherInteger) { int thisVal = value; int anotherVal = anotherInteger.value; return (thisVal < anotherVal) ? -1 : ((thisVal == anotherVal) ? 0 : 1); } @Override public byte byteValue() { return (byte) value; } @Override public short shortValue() { return (short) value; } @Override public float floatValue() { return value; } @Override public double doubleValue() { return value; } @Override public int intValue() { return value; } @Override public long longValue() { return value; } public Integer toInteger() { return Integer.valueOf(this.value); } @Override public boolean equals(final Object o) { if (o instanceof OModifiableInteger) { return value == ((OModifiableInteger) o).value; } return false; } @Override public int hashCode() { return value; } @Override public String toString() { return String.valueOf(this.value); } }
0true
commons_src_main_java_com_orientechnologies_common_types_OModifiableInteger.java
70
public abstract class AllPartitionsClientRequest extends ClientRequest { @Override final void process() throws Exception { ClientEndpoint endpoint = getEndpoint(); OperationFactory operationFactory = new OperationFactoryWrapper(createOperationFactory(), endpoint.getUuid()); Map<Integer, Object> map = clientEngine.invokeOnAllPartitions(getServiceName(), operationFactory); Object result = reduce(map); endpoint.sendResponse(result, getCallId()); } protected abstract OperationFactory createOperationFactory(); protected abstract Object reduce(Map<Integer, Object> map); }
0true
hazelcast_src_main_java_com_hazelcast_client_AllPartitionsClientRequest.java
1,168
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_ORDER_PAYMENT_DETAILS") @AdminPresentationMergeOverrides( { @AdminPresentationMergeOverride(name = "", mergeEntries = @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.READONLY, booleanOverrideValue = true)) } ) public class PaymentInfoDetailImpl implements PaymentInfoDetail, CurrencyCodeIdentifiable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "PaymentInfoDetailId") @GenericGenerator( name="PaymentInfoDetailId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="PaymentInfoDetailImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.payment.domain.PaymentInfoDetailImpl") } ) @Column(name = "PAYMENT_DETAIL_ID") protected Long id; @ManyToOne(targetEntity = PaymentInfoImpl.class, optional = false) @JoinColumn(name = "PAYMENT_INFO") @AdminPresentation(excluded = true) protected PaymentInfo paymentInfo; @Column(name = "PAYMENT_INFO_DETAIL_TYPE") @AdminPresentation(friendlyName = "PaymentInfoDetailTypeImpl_Type", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.core.payment.domain.PaymentInfoDetailType", prominent = true, gridOrder = 1000) protected String type; @Column(name = "PAYMENT_AMOUNT") @AdminPresentation(friendlyName = "PaymentInfoDetailTypeImpl_Amount", fieldType = SupportedFieldType.MONEY, prominent = true, gridOrder = 2000) protected BigDecimal amount; @ManyToOne(targetEntity = BroadleafCurrencyImpl.class) @JoinColumn(name = "CURRENCY_CODE") @AdminPresentation(excluded = true) protected BroadleafCurrency currency; @Column(name = "DATE_RECORDED") @AdminPresentation(friendlyName = "PaymentInfoDetailTypeImpl_Date", prominent = true, gridOrder = 3000) protected Date date; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public PaymentInfo getPaymentInfo() { return paymentInfo; } @Override public void setPaymentInfo(PaymentInfo paymentInfo) { this.paymentInfo = paymentInfo; } @Override public PaymentInfoDetailType getType() { return PaymentInfoDetailType.getInstance(type); } @Override public void setType(PaymentInfoDetailType type) { this.type = (type == null) ? null : type.getType(); } @Override public Money getAmount() { return amount == null ? BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, getCurrency()) : BroadleafCurrencyUtils.getMoney(amount, getCurrency()); } @Override public void setAmount(Money amount) { this.amount = amount.getAmount(); } @Override public BroadleafCurrency getCurrency() { return currency; } @Override public void setCurrency(BroadleafCurrency currency) { this.currency = currency; } @Override public Date getDate() { return date; } @Override public void setDate(Date date) { this.date = date; } @Override public String getCurrencyCode() { if (currency != null) { return currency.getCurrencyCode(); } return ((CurrencyCodeIdentifiable) paymentInfo).getCurrencyCode(); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_domain_PaymentInfoDetailImpl.java
811
public interface OSchema { public int countClasses(); public OClass createClass(final Class<?> iClass); public OClass createClass(final Class<?> iClass, final int iDefaultClusterId); public OClass createClass(final String iClassName); public OClass createClass(final String iClassName, final OClass iSuperClass); public OClass createClass(final String iClassName, final OClass iSuperClass, final OStorage.CLUSTER_TYPE iType); public OClass createClass(final String iClassName, final int iDefaultClusterId); public OClass createClass(final String iClassName, final OClass iSuperClass, final int iDefaultClusterId); public OClass createClass(final String iClassName, final OClass iSuperClass, final int[] iClusterIds); public OClass createAbstractClass(final Class<?> iClass); public OClass createAbstractClass(final String iClassName); public OClass createAbstractClass(final String iClassName, final OClass iSuperClass); public void dropClass(final String iClassName); public <RET extends ODocumentWrapper> RET reload(); public boolean existsClass(final String iClassName); public OClass getClass(final Class<?> iClass); /** * Returns the OClass instance by class name. * * If the class is not configured and the database has an entity manager with the requested class as registered, then creates a * schema class for it at the fly. * * If the database nor the entity manager have not registered class with specified name, returns null. * * @param iClassName * Name of the class to retrieve * @return class instance or null if class with given name is not configured. */ public OClass getClass(final String iClassName); public OClass getOrCreateClass(final String iClassName); public OClass getOrCreateClass(final String iClassName, final OClass iSuperClass); public Collection<OClass> getClasses(); public void create(); @Deprecated public int getVersion(); public ORID getIdentity(); /** * Do nothing. Starting from 1.0rc2 the schema is auto saved! * * @COMPATIBILITY 1.0rc1 */ public <RET extends ODocumentWrapper> RET save(); /** * Returns all the classes that rely on a cluster * * @param name * Cluster name */ public Set<OClass> getClassesRelyOnCluster(String iClusterName); }
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OSchema.java
1,720
EntryListener<Object, Object> listener = new EntryListener<Object, Object>() { public void entryAdded(EntryEvent<Object, Object> event) { addedKey[0] = event.getKey(); addedValue[0] = event.getValue(); } public void entryRemoved(EntryEvent<Object, Object> event) { removedKey[0] = event.getKey(); removedValue[0] = event.getOldValue(); } public void entryUpdated(EntryEvent<Object, Object> event) { updatedKey[0] = event.getKey(); oldValue[0] = event.getOldValue(); newValue[0] = event.getValue(); } public void entryEvicted(EntryEvent<Object, Object> event) { } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
4,666
private final PercolatorType scoringPercolator = new PercolatorType() { @Override public byte id() { return 0x05; } @Override public ReduceResult reduce(List<PercolateShardResponse> shardResults) { return matchPercolator.reduce(shardResults); } @Override public PercolateShardResponse doPercolate(PercolateShardRequest request, PercolateContext context) { Engine.Searcher percolatorSearcher = context.indexShard().acquireSearcher("percolate"); try { MatchAndScore matchAndScore = matchAndScore(logger, context, highlightPhase); queryBasedPercolating(percolatorSearcher, context, matchAndScore); List<BytesRef> matches = matchAndScore.matches(); List<Map<String, HighlightField>> hls = matchAndScore.hls(); float[] scores = matchAndScore.scores().toArray(); long count = matchAndScore.counter(); BytesRef[] finalMatches = matches.toArray(new BytesRef[matches.size()]); return new PercolateShardResponse(finalMatches, hls, count, scores, context, request.index(), request.shardId()); } catch (Throwable e) { logger.debug("failed to execute", e); throw new PercolateException(context.indexShard().shardId(), "failed to execute", e); } finally { percolatorSearcher.release(); } } };
1no label
src_main_java_org_elasticsearch_percolator_PercolatorService.java
330
public interface ODataSegmentStrategy { /** * Tells to the database in what data segment put the new record. Default strategy always use data segment 0 (default). * * @param iDatabase * Database instance * @param iRecord * Record istance * @return The data segment id */ public int assignDataSegmentId(ODatabase iDatabase, ORecord<?> iRecord); }
0true
core_src_main_java_com_orientechnologies_orient_core_db_ODataSegmentStrategy.java
3,510
final class SmartIndexNameSearchAnalyzer extends AnalyzerWrapper { private final Analyzer defaultAnalyzer; SmartIndexNameSearchAnalyzer(Analyzer defaultAnalyzer) { this.defaultAnalyzer = defaultAnalyzer; } @Override protected Analyzer getWrappedAnalyzer(String fieldName) { int dotIndex = fieldName.indexOf('.'); if (dotIndex != -1) { String possibleType = fieldName.substring(0, dotIndex); DocumentMapper possibleDocMapper = mappers.get(possibleType); if (possibleDocMapper != null) { return possibleDocMapper.mappers().searchAnalyzer(); } } FieldMappers mappers = fieldMappers.fullName(fieldName); if (mappers != null && mappers.mapper() != null && mappers.mapper().searchAnalyzer() != null) { return mappers.mapper().searchAnalyzer(); } mappers = fieldMappers.indexName(fieldName); if (mappers != null && mappers.mapper() != null && mappers.mapper().searchAnalyzer() != null) { return mappers.mapper().searchAnalyzer(); } return defaultAnalyzer; } @Override protected TokenStreamComponents wrapComponents(String fieldName, TokenStreamComponents components) { return components; } }
0true
src_main_java_org_elasticsearch_index_mapper_MapperService.java
2,605
threadPool.generic().execute(new Runnable() { @Override public void run() { for (Listener listener : listeners) { listener.onNodeFailure(node, reason); } } });
0true
src_main_java_org_elasticsearch_discovery_zen_fd_NodesFaultDetection.java
148
public class TestXaLogicalLogFiles { @Test public void shouldDetectLegacyLogs() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when( fs.fileExists( new File( "logical_log.active" ) )).thenReturn( false ); when(fs.fileExists(new File("logical_log"))).thenReturn(true); when(fs.fileExists(new File("logical_log.1"))).thenReturn(false); when(fs.fileExists(new File("logical_log.2"))).thenReturn(false); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.LEGACY_WITHOUT_LOG_ROTATION)); } @Test public void shouldDetectNoActiveFile() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(false); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(false); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.NO_ACTIVE_FILE)); } @Test public void shouldDetectLog1Active() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(false); StoreChannel fc = mockedStoreChannel( XaLogicalLogTokens.LOG1 ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn( fc ); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.LOG_1_ACTIVE)); } @Test public void shouldDetectLog2Active() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(false); when(fs.fileExists(new File("logical_log.2"))).thenReturn(true); StoreChannel fc = mockedStoreChannel( XaLogicalLogTokens.LOG2 ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn(fc); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.LOG_2_ACTIVE)); } @Test public void shouldDetectCleanShutdown() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(false); StoreChannel fc = mockedStoreChannel( XaLogicalLogTokens.CLEAN ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn(fc); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.CLEAN)); } @Test public void shouldDetectDualLog1() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(true); StoreChannel fc = mockedStoreChannel( XaLogicalLogTokens.LOG1 ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn(fc); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.DUAL_LOGS_LOG_1_ACTIVE)); } @Test public void shouldDetectDualLog2() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(true); StoreChannel fc = mockedStoreChannel( XaLogicalLogTokens.LOG2 ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn(fc); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.DUAL_LOGS_LOG_2_ACTIVE)); } @Test(expected=IllegalStateException.class) public void shouldThrowIllegalStateExceptionOnUnrecognizedActiveContent() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(true); StoreChannel fc = mockedStoreChannel( ';' ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn(fc); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); files.determineState(); } private StoreChannel mockedStoreChannel( char c ) throws IOException { return new MockedFileChannel(ByteBuffer.allocate(4).putChar(c).array()); } 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
1,474
public class CyclicPathFilterMap { public static final String CLASS = Tokens.makeNamespace(CyclicPathFilterMap.class) + ".class"; public enum Counters { PATHS_FILTERED } public static Configuration createConfiguration(final Class<? extends Element> klass) { final Configuration configuration = new EmptyConfiguration(); configuration.setClass(CLASS, klass, Element.class); configuration.setBoolean(Tokens.TITAN_HADOOP_PIPELINE_TRACK_PATHS, true); return configuration; } public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> { private boolean isVertex; private HashSet set = new HashSet(); @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class); } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { long pathsFiltered = 0l; if (this.isVertex) { if (value.hasPaths()) { final Iterator<List<FaunusPathElement.MicroElement>> itty = value.getPaths().iterator(); while (itty.hasNext()) { final List<FaunusPathElement.MicroElement> path = itty.next(); this.set.clear(); this.set.addAll(path); if (path.size() != this.set.size()) { itty.remove(); pathsFiltered++; } } } } else { for (final Edge e : value.getEdges(Direction.BOTH)) { final StandardFaunusEdge edge = (StandardFaunusEdge) e; if (edge.hasPaths()) { final Iterator<List<FaunusPathElement.MicroElement>> itty = edge.getPaths().iterator(); while (itty.hasNext()) { final List<FaunusPathElement.MicroElement> path = itty.next(); this.set.clear(); this.set.addAll(path); if (path.size() != this.set.size()) { itty.remove(); pathsFiltered++; } } } } } DEFAULT_COMPAT.incrementContextCounter(context, Counters.PATHS_FILTERED, pathsFiltered); context.write(NullWritable.get(), value); } } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_filter_CyclicPathFilterMap.java
644
@Test public class OPropertyMapIndexDefinitionTest { private OPropertyMapIndexDefinition propertyIndexByKey; private OPropertyMapIndexDefinition propertyIndexByValue; private OPropertyMapIndexDefinition propertyIndexByIntegerKey; private final Map<String, Integer> mapToTest = new HashMap<String, Integer>(); @BeforeClass public void beforeClass() { mapToTest.put("st1", 1); mapToTest.put("st2", 2); } @BeforeMethod public void beforeMethod() { propertyIndexByKey = new OPropertyMapIndexDefinition("testClass", "fOne", OType.STRING, OPropertyMapIndexDefinition.INDEX_BY.KEY); propertyIndexByIntegerKey = new OPropertyMapIndexDefinition("testClass", "fTwo", OType.INTEGER, OPropertyMapIndexDefinition.INDEX_BY.KEY); propertyIndexByValue = new OPropertyMapIndexDefinition("testClass", "fOne", OType.INTEGER, OPropertyMapIndexDefinition.INDEX_BY.VALUE); } public void testCreateValueByKeySingleParameter() { final Object result = propertyIndexByKey.createValue(Collections.singletonList(mapToTest)); Assert.assertTrue(result instanceof Collection); final Collection<?> collectionResult = (Collection<?>) result; Assert.assertEquals(collectionResult.size(), 2); Assert.assertTrue(collectionResult.contains("st1")); Assert.assertTrue(collectionResult.contains("st2")); } public void testCreateValueByValueSingleParameter() { final Object result = propertyIndexByValue.createValue(Collections.singletonList(mapToTest)); Assert.assertTrue(result instanceof Collection); final Collection<?> collectionResult = (Collection<?>) result; Assert.assertEquals(collectionResult.size(), 2); Assert.assertTrue(collectionResult.contains(1)); Assert.assertTrue(collectionResult.contains(2)); } public void testCreateValueByKeyTwoParameters() { final Object result = propertyIndexByKey.createValue(Arrays.asList(mapToTest, "25")); Assert.assertTrue(result instanceof Collection); final Collection<?> collectionResult = (Collection<?>) result; Assert.assertEquals(collectionResult.size(), 2); Assert.assertTrue(collectionResult.contains("st1")); Assert.assertTrue(collectionResult.contains("st2")); } public void testCreateValueByValueTwoParameters() { final Object result = propertyIndexByValue.createValue(Arrays.asList(mapToTest, "25")); Assert.assertTrue(result instanceof Collection); final Collection<?> collectionResult = (Collection<?>) result; Assert.assertEquals(collectionResult.size(), 2); Assert.assertTrue(collectionResult.contains(1)); Assert.assertTrue(collectionResult.contains(2)); } public void testCreateValueWrongParameter() { final Object result = propertyIndexByKey.createValue(Collections.singletonList("tt")); Assert.assertNull(result); } public void testCreateValueByKeySingleParameterArrayParams() { final Object result = propertyIndexByKey.createValue(mapToTest); Assert.assertTrue(result instanceof Collection); final Collection<?> collectionResult = (Collection<?>) result; Assert.assertEquals(collectionResult.size(), 2); Assert.assertTrue(collectionResult.contains("st1")); Assert.assertTrue(collectionResult.contains("st2")); } public void testCreateValueByValueSingleParameterArrayParams() { final Object result = propertyIndexByValue.createValue(mapToTest); Assert.assertTrue(result instanceof Collection); final Collection<?> collectionResult = (Collection<?>) result; Assert.assertEquals(collectionResult.size(), 2); Assert.assertTrue(collectionResult.contains(1)); Assert.assertTrue(collectionResult.contains(2)); } public void testCreateValueByKeyTwoParametersArrayParams() { final Object result = propertyIndexByKey.createValue(mapToTest, "25"); Assert.assertTrue(result instanceof Collection); final Collection<?> collectionResult = (Collection<?>) result; Assert.assertEquals(collectionResult.size(), 2); Assert.assertTrue(collectionResult.contains("st1")); Assert.assertTrue(collectionResult.contains("st2")); } public void testCreateValueByValueTwoParametersArrayParams() { final Object result = propertyIndexByValue.createValue(mapToTest, "25"); Assert.assertTrue(result instanceof Collection); final Collection<?> collectionResult = (Collection<?>) result; Assert.assertEquals(collectionResult.size(), 2); Assert.assertTrue(collectionResult.contains(1)); Assert.assertTrue(collectionResult.contains(2)); } public void testCreateValueWrongParameterArrayParams() { final Object result = propertyIndexByKey.createValue("tt"); Assert.assertNull(result); } public void testGetDocumentValueByKeyToIndex() { final ODocument document = new ODocument(); document.field("fOne", mapToTest); document.field("fTwo", 10); final Object result = propertyIndexByKey.getDocumentValueToIndex(document); Assert.assertTrue(result instanceof Collection); final Collection<?> collectionResult = (Collection<?>) result; Assert.assertEquals(collectionResult.size(), 2); Assert.assertTrue(collectionResult.contains("st1")); Assert.assertTrue(collectionResult.contains("st2")); } public void testGetDocumentValueByValueToIndex() { final ODocument document = new ODocument(); document.field("fOne", mapToTest); document.field("fTwo", 10); final Object result = propertyIndexByValue.getDocumentValueToIndex(document); Assert.assertTrue(result instanceof Collection); final Collection<?> collectionResult = (Collection<?>) result; Assert.assertEquals(collectionResult.size(), 2); Assert.assertTrue(collectionResult.contains(1)); Assert.assertTrue(collectionResult.contains(2)); } public void testGetFields() { final List<String> result = propertyIndexByKey.getFields(); Assert.assertEquals(result.size(), 1); Assert.assertEquals(result.get(0), "fOne"); } public void testGetTypes() { final OType[] result = propertyIndexByKey.getTypes(); Assert.assertEquals(result.length, 1); Assert.assertEquals(result[0], OType.STRING); } public void testEmptyIndexByKeyReload() { final ODatabaseDocumentTx database = new ODatabaseDocumentTx("memory:propertytest"); database.create(); propertyIndexByKey = new OPropertyMapIndexDefinition("tesClass", "fOne", OType.STRING, OPropertyMapIndexDefinition.INDEX_BY.KEY); final ODocument docToStore = propertyIndexByKey.toStream(); database.save(docToStore); final ODocument docToLoad = database.load(docToStore.getIdentity()); final OPropertyIndexDefinition result = new OPropertyMapIndexDefinition(); result.fromStream(docToLoad); database.drop(); Assert.assertEquals(result, propertyIndexByKey); } public void testEmptyIndexByValueReload() { final ODatabaseDocumentTx database = new ODatabaseDocumentTx("memory:propertytest"); database.create(); propertyIndexByValue = new OPropertyMapIndexDefinition("tesClass", "fOne", OType.INTEGER, OPropertyMapIndexDefinition.INDEX_BY.VALUE); final ODocument docToStore = propertyIndexByValue.toStream(); database.save(docToStore); final ODocument docToLoad = database.load(docToStore.getIdentity()); final OPropertyIndexDefinition result = new OPropertyMapIndexDefinition(); result.fromStream(docToLoad); database.drop(); Assert.assertEquals(result, propertyIndexByValue); } public void testCreateSingleValueByKey() { final Object result = propertyIndexByKey.createSingleValue("tt"); Assert.assertEquals(result, "tt"); } public void testCreateSingleValueByValue() { final Object result = propertyIndexByValue.createSingleValue("12"); Assert.assertEquals(result, 12); } @Test(expectedExceptions = NumberFormatException.class) public void testCreateWrongSingleValueByValue() { propertyIndexByValue.createSingleValue("tt"); } @Test(expectedExceptions = NullPointerException.class) public void testIndexByIsRequired() { new OPropertyMapIndexDefinition("testClass", "testField", OType.STRING, null); } public void testCreateDDLByKey() { final String ddl = propertyIndexByKey.toCreateIndexDDL("testIndex", "unique").toLowerCase(); Assert.assertEquals(ddl, "create index testindex on testclass ( fone by key ) unique"); } public void testCreateDDLByValue() { final String ddl = propertyIndexByValue.toCreateIndexDDL("testIndex", "unique").toLowerCase(); Assert.assertEquals(ddl, "create index testindex on testclass ( fone by value ) unique"); } public void testProcessChangeEventAddKey() { final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>(); final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>(); final OMultiValueChangeEvent<String, String> multiValueChangeEvent = new OMultiValueChangeEvent<String, String>( OMultiValueChangeEvent.OChangeType.ADD, "key1", "value1"); propertyIndexByKey.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove); final Map<Object, Integer> addedKeys = new HashMap<Object, Integer>(); addedKeys.put("key1", 1); final Map<Object, Integer> removedKeys = new HashMap<Object, Integer>(); Assert.assertEquals(keysToAdd, addedKeys); Assert.assertEquals(keysToRemove, removedKeys); } public void testProcessChangeEventAddKeyWithConversion() { final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>(); final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>(); final OMultiValueChangeEvent<String, String> multiValueChangeEvent = new OMultiValueChangeEvent<String, String>( OMultiValueChangeEvent.OChangeType.ADD, "12", "value1"); propertyIndexByIntegerKey.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove); final Map<Object, Integer> addedKeys = new HashMap<Object, Integer>(); addedKeys.put(12, 1); final Map<Object, Integer> removedKeys = new HashMap<Object, Integer>(); Assert.assertEquals(keysToAdd, addedKeys); Assert.assertEquals(keysToRemove, removedKeys); } public void testProcessChangeEventAddValue() { final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>(); final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>(); final OMultiValueChangeEvent<String, Integer> multiValueChangeEvent = new OMultiValueChangeEvent<String, Integer>( OMultiValueChangeEvent.OChangeType.ADD, "key1", 42); propertyIndexByValue.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove); final Map<Object, Integer> addedKeys = new HashMap<Object, Integer>(); addedKeys.put(42, 1); final Map<Object, Integer> removedKeys = new HashMap<Object, Integer>(); Assert.assertEquals(keysToAdd, addedKeys); Assert.assertEquals(keysToRemove, removedKeys); } public void testProcessChangeEventAddValueWithConversion() { final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>(); final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>(); final OMultiValueChangeEvent<String, String> multiValueChangeEvent = new OMultiValueChangeEvent<String, String>( OMultiValueChangeEvent.OChangeType.ADD, "12", "42"); propertyIndexByValue.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove); final Map<Object, Integer> addedKeys = new HashMap<Object, Integer>(); addedKeys.put(42, 1); final Map<Object, Integer> removedKeys = new HashMap<Object, Integer>(); Assert.assertEquals(keysToAdd, addedKeys); Assert.assertEquals(keysToRemove, removedKeys); } public void testProcessChangeEventRemoveKey() { final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>(); final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>(); final OMultiValueChangeEvent<String, String> multiValueChangeEvent = new OMultiValueChangeEvent<String, String>( OMultiValueChangeEvent.OChangeType.REMOVE, "key1", "value1"); propertyIndexByKey.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove); final Map<Object, Integer> addedKeys = new HashMap<Object, Integer>(); final Map<Object, Integer> removedKeys = new HashMap<Object, Integer>(); removedKeys.put("key1", 1); Assert.assertEquals(keysToAdd, addedKeys); Assert.assertEquals(keysToRemove, removedKeys); } public void testProcessChangeEventRemoveKeyWithConversion() { final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>(); final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>(); final OMultiValueChangeEvent<String, String> multiValueChangeEvent = new OMultiValueChangeEvent<String, String>( OMultiValueChangeEvent.OChangeType.REMOVE, "12", "value1"); propertyIndexByIntegerKey.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove); final Map<Object, Integer> addedKeys = new HashMap<Object, Integer>(); final Map<Object, Integer> removedKeys = new HashMap<Object, Integer>(); removedKeys.put(12, 1); Assert.assertEquals(keysToAdd, addedKeys); Assert.assertEquals(keysToRemove, removedKeys); } public void testProcessChangeEventRemoveValue() { final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>(); final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>(); final OMultiValueChangeEvent<String, Integer> multiValueChangeEvent = new OMultiValueChangeEvent<String, Integer>( OMultiValueChangeEvent.OChangeType.REMOVE, "key1", null, 42); propertyIndexByValue.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove); final Map<Object, Integer> addedKeys = new HashMap<Object, Integer>(); final Map<Object, Integer> removedKeys = new HashMap<Object, Integer>(); removedKeys.put(42, 1); Assert.assertEquals(keysToAdd, addedKeys); Assert.assertEquals(keysToRemove, removedKeys); } public void testProcessChangeEventRemoveValueWithConversion() { final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>(); final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>(); final OMultiValueChangeEvent<String, String> multiValueChangeEvent = new OMultiValueChangeEvent<String, String>( OMultiValueChangeEvent.OChangeType.REMOVE, "12", null, "42"); propertyIndexByValue.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove); final Map<Object, Integer> addedKeys = new HashMap<Object, Integer>(); final Map<Object, Integer> removedKeys = new HashMap<Object, Integer>(); removedKeys.put(42, 1); Assert.assertEquals(keysToAdd, addedKeys); Assert.assertEquals(keysToRemove, removedKeys); } public void testProcessChangeEventUpdateKey() { final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>(); final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>(); final OMultiValueChangeEvent<String, Integer> multiValueChangeEvent = new OMultiValueChangeEvent<String, Integer>( OMultiValueChangeEvent.OChangeType.UPDATE, "key1", 42); propertyIndexByKey.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove); Assert.assertTrue(keysToAdd.isEmpty()); Assert.assertTrue(keysToRemove.isEmpty()); } public void testProcessChangeEventUpdateValue() { final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>(); final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>(); final OMultiValueChangeEvent<String, Integer> multiValueChangeEvent = new OMultiValueChangeEvent<String, Integer>( OMultiValueChangeEvent.OChangeType.UPDATE, "key1", 41, 42); propertyIndexByValue.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove); final Map<Object, Integer> addedKeys = new HashMap<Object, Integer>(); addedKeys.put(41, 1); final Map<Object, Integer> removedKeys = new HashMap<Object, Integer>(); removedKeys.put(42, 1); Assert.assertEquals(keysToAdd, addedKeys); Assert.assertEquals(keysToRemove, removedKeys); } public void testProcessChangeEventUpdateValueWithConversion() { final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>(); final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>(); final OMultiValueChangeEvent<String, String> multiValueChangeEvent = new OMultiValueChangeEvent<String, String>( OMultiValueChangeEvent.OChangeType.UPDATE, "12", "42", "41"); propertyIndexByValue.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove); final Map<Object, Integer> addedKeys = new HashMap<Object, Integer>(); addedKeys.put(42, 1); final Map<Object, Integer> removedKeys = new HashMap<Object, Integer>(); removedKeys.put(41, 1); Assert.assertEquals(keysToAdd, addedKeys); Assert.assertEquals(keysToRemove, removedKeys); } }
0true
core_src_test_java_com_orientechnologies_orient_core_index_OPropertyMapIndexDefinitionTest.java
234
public interface CLevelInterface { public org.apache.cassandra.db.ConsistencyLevel getDB(); public org.apache.cassandra.thrift.ConsistencyLevel getThrift(); public com.netflix.astyanax.model.ConsistencyLevel getAstyanax(); }
0true
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_CLevelInterface.java
1,430
public final class CleanupService { private final String name; private final ScheduledExecutorService executor; public CleanupService(final String name) { this.name = name; executor = Executors.newSingleThreadScheduledExecutor(new CleanupThreadFactory()); } public void registerCache(final LocalRegionCache cache) { executor.scheduleWithFixedDelay(new Runnable() { public void run() { cache.cleanup(); } }, 60, 60, TimeUnit.SECONDS); } public void stop() { executor.shutdownNow(); } private class CleanupThreadFactory implements ThreadFactory { public Thread newThread(final Runnable r) { final Thread thread = new CleanupThread(r, name + ".hibernate.cleanup"); thread.setDaemon(true); return thread; } } private static class CleanupThread extends Thread { private CleanupThread(final Runnable target, final String name) { super(target, name); } public void run() { try { super.run(); } catch (OutOfMemoryError e) { OutOfMemoryErrorDispatcher.onOutOfMemory(e); } } } }
0true
hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_local_CleanupService.java
1,115
public class UpdateCartException extends Exception { private static final long serialVersionUID = 1L; public UpdateCartException() { super(); } public UpdateCartException(String message, Throwable cause) { super(message, cause); } public UpdateCartException(String message) { super(message); } public UpdateCartException(Throwable cause) { super(cause); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_exception_UpdateCartException.java
1,664
EntryListener<Object, Object> listener = new EntryListener<Object, Object>() { public void entryAdded(EntryEvent<Object, Object> event) { addedKey[0] = event.getKey(); addedValue[0] = event.getValue(); } public void entryRemoved(EntryEvent<Object, Object> event) { removedKey[0] = event.getKey(); removedValue[0] = event.getOldValue(); } public void entryUpdated(EntryEvent<Object, Object> event) { updatedKey[0] = event.getKey(); oldValue[0] = event.getOldValue(); newValue[0] = event.getValue(); } public void entryEvicted(EntryEvent<Object, Object> event) { } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
12
static final class AsyncCombine<T,U,V> extends Async { final T arg1; final U arg2; final BiFun<? super T,? super U,? extends V> fn; final CompletableFuture<V> dst; AsyncCombine(T arg1, U arg2, BiFun<? super T,? super U,? extends V> fn, CompletableFuture<V> dst) { this.arg1 = arg1; this.arg2 = arg2; this.fn = fn; this.dst = dst; } public final boolean exec() { CompletableFuture<V> d; V v; Throwable ex; if ((d = this.dst) != null && d.result == null) { try { v = fn.apply(arg1, arg2); ex = null; } catch (Throwable rex) { ex = rex; v = null; } d.internalComplete(v, ex); } return true; } private static final long serialVersionUID = 5232453952276885070L; }
0true
src_main_java_jsr166e_CompletableFuture.java
553
abstract class ClientTxnProxy implements TransactionalObject { final String objectName; final TransactionContextProxy proxy; ClientTxnProxy(String objectName, TransactionContextProxy proxy) { this.objectName = objectName; this.proxy = proxy; } final <T> T invoke(ClientRequest request) { if (request instanceof BaseTransactionRequest) { ((BaseTransactionRequest) request).setTxnId(proxy.getTxnId()); ((BaseTransactionRequest) request).setClientThreadId(Thread.currentThread().getId()); } final ClientInvocationServiceImpl invocationService = (ClientInvocationServiceImpl) proxy.getClient().getInvocationService(); final SerializationService ss = proxy.getClient().getSerializationService(); try { final Future f = invocationService.send(request, proxy.getConnection()); return ss.toObject(f.get()); } catch (Exception e) { throw ExceptionUtil.rethrow(e); } } abstract void onDestroy(); public final void destroy() { onDestroy(); ClientDestroyRequest request = new ClientDestroyRequest(objectName, getServiceName()); invoke(request); } public Object getId() { return objectName; } public String getPartitionKey() { return StringPartitioningStrategy.getPartitionKey(getName()); } Data toData(Object obj) { return proxy.getClient().getSerializationService().toData(obj); } Object toObject(Data data) { return proxy.getClient().getSerializationService().toObject(data); } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_txn_proxy_ClientTxnProxy.java
1,936
@Service("blFormBuilderService") public class FormBuilderServiceImpl implements FormBuilderService { private static final Log LOG = LogFactory.getLog(FormBuilderServiceImpl.class); @Resource(name = "blAdminEntityService") protected AdminEntityService adminEntityService; @Resource (name = "blAdminNavigationService") protected AdminNavigationService navigationService; @Resource(name = "blFormBuilderExtensionManagers") protected List<FormBuilderExtensionManager> extensionManagers; @Resource(name="blEntityConfiguration") protected EntityConfiguration entityConfiguration; protected static final VisibilityEnum[] FORM_HIDDEN_VISIBILITIES = new VisibilityEnum[] { VisibilityEnum.HIDDEN_ALL, VisibilityEnum.FORM_HIDDEN }; protected static final VisibilityEnum[] GRID_HIDDEN_VISIBILITIES = new VisibilityEnum[] { VisibilityEnum.HIDDEN_ALL, VisibilityEnum.GRID_HIDDEN }; @Override public ListGrid buildMainListGrid(DynamicResultSet drs, ClassMetadata cmd, String sectionKey) throws ServiceException { List<Field> headerFields = new ArrayList<Field>(); ListGrid.Type type = ListGrid.Type.MAIN; String idProperty = "id"; for (Property p : cmd.getProperties()) { if (p.getMetadata() instanceof BasicFieldMetadata) { BasicFieldMetadata fmd = (BasicFieldMetadata) p.getMetadata(); if (SupportedFieldType.ID.equals(fmd.getFieldType())) { idProperty = fmd.getName(); } if (fmd.isProminent() != null && fmd.isProminent() && !ArrayUtils.contains(getGridHiddenVisibilities(), fmd.getVisibility())) { Field hf = createHeaderField(p, fmd); headerFields.add(hf); } } } ListGrid listGrid = createListGrid(cmd.getCeilingType(), headerFields, type, drs, sectionKey, 0, idProperty); if (CollectionUtils.isNotEmpty(listGrid.getHeaderFields())) { // Set the first column to be able to link to the main entity listGrid.getHeaderFields().iterator().next().setMainEntityLink(true); } else { String message = "There are no listgrid header fields configured for the class " + cmd.getCeilingType(); message += "Please mark some @AdminPresentation fields with 'prominent = true'"; LOG.error(message); } return listGrid; } protected Field createHeaderField(Property p, BasicFieldMetadata fmd) { Field hf; if (fmd.getFieldType().equals(SupportedFieldType.EXPLICIT_ENUMERATION) || fmd.getFieldType().equals(SupportedFieldType.BROADLEAF_ENUMERATION) || fmd.getFieldType().equals(SupportedFieldType.DATA_DRIVEN_ENUMERATION) || fmd.getFieldType().equals(SupportedFieldType.EMPTY_ENUMERATION)) { hf = new ComboField(); ((ComboField) hf).setOptions(fmd.getEnumerationValues()); } else { hf = new Field(); } hf.withName(p.getName()) .withFriendlyName(fmd.getFriendlyName()) .withOrder(fmd.getGridOrder()) .withColumnWidth(fmd.getColumnWidth()) .withForeignKeyDisplayValueProperty(fmd.getForeignKeyDisplayValueProperty()) .withForeignKeyClass(fmd.getForeignKeyClass()) .withOwningEntityClass(fmd.getOwningClass() != null ? fmd.getOwningClass() : fmd.getTargetClass()); String fieldType = fmd.getFieldType() == null ? null : fmd.getFieldType().toString(); hf.setFieldType(fieldType); return hf; } @Override public ListGrid buildCollectionListGrid(String containingEntityId, DynamicResultSet drs, Property field, String sectionKey) throws ServiceException { FieldMetadata fmd = field.getMetadata(); // Get the class metadata for this particular field PersistencePackageRequest ppr = PersistencePackageRequest.fromMetadata(fmd); ClassMetadata cmd = adminEntityService.getClassMetadata(ppr); List<Field> headerFields = new ArrayList<Field>(); ListGrid.Type type = null; boolean editable = false; boolean sortable = false; boolean readOnly = false; boolean hideIdColumn = false; boolean canFilterAndSort = true; String idProperty = "id"; for (Property property : cmd.getProperties()) { if (property.getMetadata() instanceof BasicFieldMetadata && SupportedFieldType.ID==((BasicFieldMetadata) property.getMetadata()).getFieldType() && //make sure it's a property for this entity - not an association !property.getName().contains(".")) { idProperty = property.getName(); break; } } // Get the header fields for this list grid. Note that the header fields are different depending on the // kind of field this is. if (fmd instanceof BasicFieldMetadata) { readOnly = ((BasicFieldMetadata) fmd).getReadOnly(); for (Property p : cmd.getProperties()) { if (p.getMetadata() instanceof BasicFieldMetadata) { BasicFieldMetadata md = (BasicFieldMetadata) p.getMetadata(); if (SupportedFieldType.ID.equals(md.getFieldType())) { idProperty = md.getName(); } if (md.isProminent() != null && md.isProminent() && !ArrayUtils.contains(getGridHiddenVisibilities(), md.getVisibility())) { Field hf = createHeaderField(p, md); headerFields.add(hf); } } } type = ListGrid.Type.TO_ONE; } else if (fmd instanceof BasicCollectionMetadata) { readOnly = !((BasicCollectionMetadata) fmd).isMutable(); for (Property p : cmd.getProperties()) { if (p.getMetadata() instanceof BasicFieldMetadata) { BasicFieldMetadata md = (BasicFieldMetadata) p.getMetadata(); if (md.isProminent() != null && md.isProminent() && !ArrayUtils.contains(getGridHiddenVisibilities(), md.getVisibility())) { Field hf = createHeaderField(p, md); headerFields.add(hf); } } } type = ListGrid.Type.BASIC; if (((BasicCollectionMetadata) fmd).getAddMethodType().equals(AddMethodType.PERSIST)) { editable = true; } } else if (fmd instanceof AdornedTargetCollectionMetadata) { readOnly = !((AdornedTargetCollectionMetadata) fmd).isMutable(); AdornedTargetCollectionMetadata atcmd = (AdornedTargetCollectionMetadata) fmd; for (String fieldName : atcmd.getGridVisibleFields()) { Property p = cmd.getPMap().get(fieldName); BasicFieldMetadata md = (BasicFieldMetadata) p.getMetadata(); Field hf = createHeaderField(p, md); headerFields.add(hf); } type = ListGrid.Type.ADORNED; if (atcmd.getMaintainedAdornedTargetFields().length > 0) { editable = true; } AdornedTargetList adornedList = (AdornedTargetList) atcmd.getPersistencePerspective() .getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST); sortable = StringUtils.isNotBlank(adornedList.getSortField()); } else if (fmd instanceof MapMetadata) { readOnly = !((MapMetadata) fmd).isMutable(); MapMetadata mmd = (MapMetadata) fmd; Property p2 = cmd.getPMap().get("key"); BasicFieldMetadata keyMd = (BasicFieldMetadata) p2.getMetadata(); keyMd.setFriendlyName("Key"); Field hf = createHeaderField(p2, keyMd); headerFields.add(hf); if (mmd.isSimpleValue()) { Property valueProperty = cmd.getPMap().get("value"); BasicFieldMetadata valueMd = (BasicFieldMetadata) valueProperty.getMetadata(); valueMd.setFriendlyName("Value"); hf = createHeaderField(valueProperty, valueMd); headerFields.add(hf); idProperty = "key"; hideIdColumn = true; } else { for (Property p : cmd.getProperties()) { if (p.getMetadata() instanceof BasicFieldMetadata) { BasicFieldMetadata md = (BasicFieldMetadata) p.getMetadata(); if (md.getTargetClass().equals(mmd.getValueClassName())) { if (md.isProminent() != null && md.isProminent() && !ArrayUtils.contains(getGridHiddenVisibilities(), md.getVisibility())) { hf = createHeaderField(p, md); headerFields.add(hf); } } } } } type = ListGrid.Type.MAP; editable = true; canFilterAndSort = false; } String ceilingType = ""; if (fmd instanceof BasicFieldMetadata) { ceilingType = cmd.getCeilingType(); } else if (fmd instanceof CollectionMetadata) { ceilingType = ((CollectionMetadata) fmd).getCollectionCeilingEntity(); } if (CollectionUtils.isEmpty(headerFields)) { String message = "There are no listgrid header fields configured for the class " + ceilingType + " and property '" + field.getName() + "'."; if (type == ListGrid.Type.ADORNED || type == ListGrid.Type.ADORNED_WITH_FORM) { message += " Please configure 'gridVisibleFields' in your @AdminPresentationAdornedTargetCollection configuration"; } else { message += " Please mark some @AdminPresentation fields with 'prominent = true'"; } LOG.error(message); } ListGrid listGrid = createListGrid(ceilingType, headerFields, type, drs, sectionKey, fmd.getOrder(), idProperty); listGrid.setSubCollectionFieldName(field.getName()); listGrid.setFriendlyName(field.getMetadata().getFriendlyName()); if (StringUtils.isEmpty(listGrid.getFriendlyName())) { listGrid.setFriendlyName(field.getName()); } listGrid.setContainingEntityId(containingEntityId); listGrid.setReadOnly(readOnly); listGrid.setHideIdColumn(hideIdColumn); listGrid.setCanFilterAndSort(canFilterAndSort); if (editable) { listGrid.getRowActions().add(DefaultListGridActions.UPDATE); } if (readOnly) { listGrid.getRowActions().add(DefaultListGridActions.VIEW); } if (sortable) { listGrid.setCanFilterAndSort(false); listGrid.getToolbarActions().add(DefaultListGridActions.REORDER); } listGrid.getRowActions().add(DefaultListGridActions.REMOVE); return listGrid; } protected ListGrid createListGrid(String className, List<Field> headerFields, ListGrid.Type type, DynamicResultSet drs, String sectionKey, int order, String idProperty) { // Create the list grid and set some basic attributes ListGrid listGrid = new ListGrid(); listGrid.setClassName(className); listGrid.getHeaderFields().addAll(headerFields); listGrid.setListGridType(type); listGrid.setSectionKey(sectionKey); listGrid.setOrder(order); listGrid.setIdProperty(idProperty); listGrid.setStartIndex(drs.getStartIndex()); listGrid.setTotalRecords(drs.getTotalRecords()); listGrid.setPageSize(drs.getPageSize()); AdminSection section = navigationService.findAdminSectionByClass(className); if (section != null) { listGrid.setExternalEntitySectionKey(section.getUrl()); } // For each of the entities (rows) in the list grid, we need to build the associated // ListGridRecord and set the required fields on the record. These fields are the same ones // that are used for the header fields. for (Entity e : drs.getRecords()) { ListGridRecord record = new ListGridRecord(); record.setListGrid(listGrid); if (e.findProperty(idProperty) != null) { record.setId(e.findProperty(idProperty).getValue()); } for (Field headerField : headerFields) { Property p = e.findProperty(headerField.getName()); if (p != null) { Field recordField = new Field().withName(headerField.getName()) .withFriendlyName(headerField.getFriendlyName()) .withOrder(p.getMetadata().getOrder()); if (headerField instanceof ComboField) { recordField.setValue(((ComboField) headerField).getOption(p.getValue())); recordField.setDisplayValue(p.getDisplayValue()); } else { recordField.setValue(p.getValue()); recordField.setDisplayValue(p.getDisplayValue()); } recordField.setDerived(isDerivedField(headerField, recordField, p)); record.getFields().add(recordField); } } if (e.findProperty(AdminMainEntity.MAIN_ENTITY_NAME_PROPERTY) != null) { Field hiddenField = new Field().withName(AdminMainEntity.MAIN_ENTITY_NAME_PROPERTY); hiddenField.setValue(e.findProperty(AdminMainEntity.MAIN_ENTITY_NAME_PROPERTY).getValue()); record.getHiddenFields().add(hiddenField); } listGrid.getRecords().add(record); } return listGrid; } /** * Determines whether or not a particular field in a record is derived. By default this checks the {@link BasicFieldMetadata} * for the given Property to see if something on the backend has marked it as derived * * @param headerField the header for this recordField * @param recordField the recordField being populated * @param p the property that relates to this recordField * @return whether or not this field is derived * @see {@link #createListGrid(String, List, org.broadleafcommerce.openadmin.web.form.component.ListGrid.Type, DynamicResultSet, String, int, String)} */ protected Boolean isDerivedField(Field headerField, Field recordField, Property p) { return BooleanUtils.isTrue(((BasicFieldMetadata) p.getMetadata()).getIsDerived()); } protected void setEntityFormFields(EntityForm ef, List<Property> properties) { for (Property property : properties) { if (property.getMetadata() instanceof BasicFieldMetadata) { BasicFieldMetadata fmd = (BasicFieldMetadata) property.getMetadata(); if (!ArrayUtils.contains(getFormHiddenVisibilities(), fmd.getVisibility())) { // Depending on visibility, field for the particular property is not created on the form String fieldType = fmd.getFieldType() == null ? null : fmd.getFieldType().toString(); // Create the field and set some basic attributes Field f; if (fieldType.equals(SupportedFieldType.BROADLEAF_ENUMERATION.toString()) || fieldType.equals(SupportedFieldType.EXPLICIT_ENUMERATION.toString()) || fieldType.equals(SupportedFieldType.DATA_DRIVEN_ENUMERATION.toString()) || fieldType.equals(SupportedFieldType.EMPTY_ENUMERATION.toString())) { // We're dealing with fields that should render as drop-downs, so set their possible values f = new ComboField(); ((ComboField) f).setOptions(fmd.getEnumerationValues()); } else if (fieldType.equals(SupportedFieldType.RULE_SIMPLE.toString()) || fieldType.equals(SupportedFieldType.RULE_WITH_QUANTITY.toString())) { // We're dealing with rule builders, so we'll create those specialized fields f = new RuleBuilderField(); ((RuleBuilderField) f).setJsonFieldName(property.getName() + "Json"); ((RuleBuilderField) f).setDataWrapper(new DataWrapper()); ((RuleBuilderField) f).setFieldBuilder(fmd.getRuleIdentifier()); String blankJsonString = "{\"data\":[]}"; ((RuleBuilderField) f).setJson(blankJsonString); DataWrapper dw = convertJsonToDataWrapper(blankJsonString); if (dw != null) { ((RuleBuilderField) f).setDataWrapper(dw); } if (fieldType.equals(SupportedFieldType.RULE_SIMPLE.toString())) { ((RuleBuilderField) f).setStyleClass("rule-builder-simple"); } else if (fieldType.equals(SupportedFieldType.RULE_WITH_QUANTITY.toString())) { ((RuleBuilderField) f).setStyleClass("rule-builder-complex"); } } else if (LookupType.DROPDOWN.equals(fmd.getLookupType())) { // We're dealing with a to-one field that wants to be rendered as a dropdown instead of in a // modal, so we'll provision the combo field here. Available options will be set as part of a // subsequent operation f = new ComboField(); } else if (fieldType.equals(SupportedFieldType.MEDIA.toString())) { f = new MediaField(); } else { // Create a default field since there was no specialized handler f = new Field(); } Boolean required = fmd.getRequiredOverride(); if (required == null) { required = fmd.getRequired(); } f.withName(property.getName()) .withFieldType(fieldType) .withOrder(fmd.getOrder()) .withFriendlyName(fmd.getFriendlyName()) .withForeignKeyDisplayValueProperty(fmd.getForeignKeyDisplayValueProperty()) .withForeignKeyClass(fmd.getForeignKeyClass()) .withOwningEntityClass(fmd.getOwningClass()!=null?fmd.getOwningClass():fmd.getInheritedFromType()) .withRequired(required) .withReadOnly(fmd.getReadOnly()) .withTranslatable(fmd.getTranslatable()) .withAlternateOrdering((Boolean) fmd.getAdditionalMetadata().get(Field.ALTERNATE_ORDERING)) .withLargeEntry(fmd.isLargeEntry()) .withHint(fmd.getHint()) .withTooltip(fmd.getTooltip()) .withHelp(fmd.getHelpText()); if (StringUtils.isBlank(f.getFriendlyName())) { f.setFriendlyName(f.getName()); } // Add the field to the appropriate FieldGroup ef.addField(f, fmd.getGroup(), fmd.getGroupOrder(), fmd.getTab(), fmd.getTabOrder()); } } } } @Override public void removeNonApplicableFields(ClassMetadata cmd, EntityForm entityForm, String entityType) { for (Property p : cmd.getProperties()) { if (!ArrayUtils.contains(p.getMetadata().getAvailableToTypes(), entityType)) { entityForm.removeField(p.getName()); } } } @Override public EntityForm createEntityForm(ClassMetadata cmd) throws ServiceException { EntityForm ef = createStandardEntityForm(); populateEntityForm(cmd, ef); return ef; } @Override public void populateEntityForm(ClassMetadata cmd, EntityForm ef) throws ServiceException { ef.setCeilingEntityClassname(cmd.getCeilingType()); AdminSection section = navigationService.findAdminSectionByClass(cmd.getCeilingType()); if (section != null) { ef.setSectionKey(section.getUrl()); } else { ef.setSectionKey(cmd.getCeilingType()); } setEntityFormFields(ef, Arrays.asList(cmd.getProperties())); populateDropdownToOneFields(ef, cmd); } @Override public EntityForm createEntityForm(ClassMetadata cmd, Entity entity) throws ServiceException { EntityForm ef = createStandardEntityForm(); populateEntityForm(cmd, entity, ef); return ef; } @Override public void populateEntityForm(ClassMetadata cmd, Entity entity, EntityForm ef) throws ServiceException { // Get the empty form with appropriate fields populateEntityForm(cmd, ef); String idProperty = adminEntityService.getIdProperty(cmd); ef.setId(entity.findProperty(idProperty).getValue()); ef.setEntityType(entity.getType()[0]); populateEntityFormFieldValues(cmd, entity, ef); Property p = entity.findProperty(BasicPersistenceModule.MAIN_ENTITY_NAME_PROPERTY); if (p != null) { ef.setMainEntityName(p.getValue()); } } @Override public void populateEntityFormFieldValues(ClassMetadata cmd, Entity entity, EntityForm ef) { // Set the appropriate property values for (Property p : cmd.getProperties()) { if (p.getMetadata() instanceof BasicFieldMetadata) { BasicFieldMetadata basicFM = (BasicFieldMetadata) p.getMetadata(); Property entityProp = entity.findProperty(p.getName()); boolean explicitlyShown = VisibilityEnum.FORM_EXPLICITLY_SHOWN.equals(basicFM.getVisibility()); //always show special map fields if (p.getName().equals("key") || p.getName().equals("priorKey")) { explicitlyShown = true; } if (entityProp == null && explicitlyShown) { Field field = ef.findField(p.getName()); if (field != null) { field.setValue(null); } } else if (entityProp == null && !SupportedFieldType.PASSWORD_CONFIRM.equals(basicFM.getExplicitFieldType())) { ef.removeField(p.getName()); } else { Field field = ef.findField(p.getName()); if (field != null) { if (basicFM.getFieldType()==SupportedFieldType.RULE_SIMPLE || basicFM.getFieldType()==SupportedFieldType.RULE_WITH_QUANTITY) { RuleBuilderField rbf = (RuleBuilderField) field; if (entity.getPMap().containsKey(rbf.getJsonFieldName())) { String json = entity.getPMap().get(rbf.getJsonFieldName()).getValue(); rbf.setJson(json); DataWrapper dw = convertJsonToDataWrapper(json); if (dw != null) { rbf.setDataWrapper(dw); } } } if (basicFM.getFieldType() == SupportedFieldType.MEDIA) { field.setValue(entityProp.getValue()); field.setDisplayValue(entityProp.getDisplayValue()); MediaField mf = (MediaField) field; mf.setMedia(convertJsonToMedia(entityProp.getUnHtmlEncodedValue())); } else if (!SupportedFieldType.PASSWORD_CONFIRM.equals(basicFM.getExplicitFieldType())){ field.setValue(entityProp.getValue()); field.setDisplayValue(entityProp.getDisplayValue()); } } } } } } protected Media convertJsonToMedia(String json) { if (json != null && !"".equals(json)) { try { ObjectMapper om = new ObjectMapper(); om.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); return om.readValue(json, entityConfiguration.lookupEntityClass(MediaDto.class.getName(), MediaDto.class)); } catch (Exception e) { LOG.warn("Error parsing json to media " + json, e); } } return entityConfiguration.createEntityInstance(MediaDto.class.getName(), MediaDto.class); } /** * When using Thymeleaf, we need to convert the JSON string back to * a DataWrapper object because Thymeleaf escapes JSON strings. * Thymeleaf uses it's own object de-serializer * see: https://github.com/thymeleaf/thymeleaf/issues/84 * see: http://forum.thymeleaf.org/Spring-Javascript-and-escaped-JSON-td4024739.html * @param json * @return DataWrapper * @throws IOException */ protected DataWrapper convertJsonToDataWrapper(String json) { ObjectMapper mapper = new ObjectMapper(); DataDTODeserializer dtoDeserializer = new DataDTODeserializer(); SimpleModule module = new SimpleModule("DataDTODeserializerModule", new Version(1, 0, 0, null)); module.addDeserializer(DataDTO.class, dtoDeserializer); mapper.registerModule(module); try { return mapper.readValue(json, DataWrapper.class); } catch (IOException e) { throw new RuntimeException(e); } } protected void populateDropdownToOneFields(EntityForm ef, ClassMetadata cmd) throws ServiceException { for (Property p : cmd.getProperties()) { if (p.getMetadata() instanceof BasicFieldMetadata) { BasicFieldMetadata fmd = (BasicFieldMetadata) p.getMetadata(); if (LookupType.DROPDOWN.equals(fmd.getLookupType()) && !ArrayUtils.contains(getFormHiddenVisibilities(), fmd.getVisibility())) { // Get the records PersistencePackageRequest toOnePpr = PersistencePackageRequest.standard() .withCeilingEntityClassname(fmd.getForeignKeyClass()); Entity[] rows = adminEntityService.getRecords(toOnePpr).getRecords(); // Determine the id field String idProp = null; ClassMetadata foreignClassMd = adminEntityService.getClassMetadata(toOnePpr); for (Property foreignP : foreignClassMd.getProperties()) { if (foreignP.getMetadata() instanceof BasicFieldMetadata) { BasicFieldMetadata foreignFmd = (BasicFieldMetadata) foreignP.getMetadata(); if (SupportedFieldType.ID.equals(foreignFmd.getFieldType())) { idProp = foreignP.getName(); } } } if (idProp == null) { throw new RuntimeException("Could not determine ID property for " + fmd.getForeignKeyClass()); } // Determine the display field String displayProp = fmd.getLookupDisplayProperty(); // Build the options map Map<String, String> options = new HashMap<String, String>(); for (Entity row : rows) { String displayValue = row.findProperty(displayProp).getDisplayValue(); if (StringUtils.isBlank(displayValue)) { displayValue = row.findProperty(displayProp).getValue(); } options.put(row.findProperty(idProp).getValue(), displayValue); } // Set the options on the entity field ComboField cf = (ComboField) ef.findField(p.getName()); cf.setOptions(options); } } } } @Override public EntityForm createEntityForm(ClassMetadata cmd, Entity entity, Map<String, DynamicResultSet> collectionRecords) throws ServiceException { EntityForm ef = createStandardEntityForm(); populateEntityForm(cmd, entity, collectionRecords, ef); return ef; } @Override public void populateEntityForm(ClassMetadata cmd, Entity entity, Map<String, DynamicResultSet> collectionRecords, EntityForm ef) throws ServiceException { // Get the form with values for this entity populateEntityForm(cmd, entity, ef); // Attach the sub-collection list grids and specialty UI support for (Property p : cmd.getProperties()) { if (p.getMetadata() instanceof BasicFieldMetadata) { continue; } if (!ArrayUtils.contains(p.getMetadata().getAvailableToTypes(), entity.getType()[0])) { continue; } DynamicResultSet subCollectionEntities = collectionRecords.get(p.getName()); String containingEntityId = entity.getPMap().get(ef.getIdProperty()).getValue(); ListGrid listGrid = buildCollectionListGrid(containingEntityId, subCollectionEntities, p, ef.getSectionKey()); listGrid.setListGridType(ListGrid.Type.INLINE); CollectionMetadata md = ((CollectionMetadata) p.getMetadata()); ef.addListGrid(listGrid, md.getTab(), md.getTabOrder()); } for (ListGrid lg : ef.getAllListGrids()) { // We always want the add option to be the first toolbar action for consistency if (lg.getToolbarActions().isEmpty()) { lg.addToolbarAction(DefaultListGridActions.ADD); } else { lg.getToolbarActions().add(0, DefaultListGridActions.ADD); } } if (CollectionUtils.isEmpty(ef.getActions())) { ef.addAction(DefaultEntityFormActions.SAVE); } ef.addAction(DefaultEntityFormActions.DELETE); addAdditionalEntityFormActions(ef); } protected void addAdditionalEntityFormActions(EntityForm ef) { if (extensionManagers != null && !extensionManagers.isEmpty()) { for (FormBuilderExtensionManager mgr : extensionManagers) { if (mgr.canHandle(ef)) { mgr.addFormExtensions(ef); } } } } @Override public void populateEntityFormFields(EntityForm ef, Entity entity) { populateEntityFormFields(ef, entity, true, true); } @Override public void populateEntityFormFields(EntityForm ef, Entity entity, boolean populateType, boolean populateId) { if (populateId) { ef.setId(entity.findProperty(ef.getIdProperty()).getValue()); } if (populateType) { ef.setEntityType(entity.getType()[0]); } for (Entry<String, Field> entry : ef.getFields().entrySet()) { Property entityProp = entity.findProperty(entry.getKey()); if (entityProp != null) { entry.getValue().setValue(entityProp.getValue()); entry.getValue().setDisplayValue(entityProp.getDisplayValue()); } } } @Override public void populateAdornedEntityFormFields(EntityForm ef, Entity entity, AdornedTargetList adornedList) { Field field = ef.getFields().get(adornedList.getTargetObjectPath() + "." + adornedList.getTargetIdProperty()); Property entityProp = entity.findProperty(ef.getIdProperty()); field.setValue(entityProp.getValue()); if (StringUtils.isNotBlank(adornedList.getSortField())) { field = ef.getFields().get(adornedList.getSortField()); entityProp = entity.findProperty(adornedList.getSortField()); if (field != null && entityProp != null) { field.setValue(entityProp.getValue()); } } } @Override public void populateMapEntityFormFields(EntityForm ef, Entity entity) { Field field = ef.getFields().get("priorKey"); Property entityProp = entity.findProperty("key"); if (field != null && entityProp != null) { field.setValue(entityProp.getValue()); } } @Override public EntityForm buildAdornedListForm(AdornedTargetCollectionMetadata adornedMd, AdornedTargetList adornedList, String parentId) throws ServiceException { EntityForm ef = createStandardEntityForm(); return buildAdornedListForm(adornedMd, adornedList, parentId, ef); } @Override public EntityForm buildAdornedListForm(AdornedTargetCollectionMetadata adornedMd, AdornedTargetList adornedList, String parentId, EntityForm ef) throws ServiceException { ef.setEntityType(adornedList.getAdornedTargetEntityClassname()); // Get the metadata for this adorned field PersistencePackageRequest request = PersistencePackageRequest.adorned() .withCeilingEntityClassname(adornedMd.getCollectionCeilingEntity()) .withAdornedList(adornedList); ClassMetadata collectionMetadata = adminEntityService.getClassMetadata(request); // We want our entity form to only render the maintained adorned target fields List<Property> entityFormProperties = new ArrayList<Property>(); for (String targetFieldName : adornedMd.getMaintainedAdornedTargetFields()) { Property p = collectionMetadata.getPMap().get(targetFieldName); if (p.getMetadata() instanceof BasicFieldMetadata) { ((BasicFieldMetadata) p.getMetadata()).setVisibility(VisibilityEnum.VISIBLE_ALL); entityFormProperties.add(p); } } // Set the maintained fields on the form setEntityFormFields(ef, entityFormProperties); // Add these two additional hidden fields that are required for persistence Field f = new Field() .withName(adornedList.getLinkedObjectPath() + "." + adornedList.getLinkedIdProperty()) .withFieldType(SupportedFieldType.HIDDEN.toString()) .withValue(parentId); ef.addHiddenField(f); f = new Field() .withName(adornedList.getTargetObjectPath() + "." + adornedList.getTargetIdProperty()) .withFieldType(SupportedFieldType.HIDDEN.toString()) .withIdOverride("adornedTargetIdProperty"); ef.addHiddenField(f); if (StringUtils.isNotBlank(adornedList.getSortField())) { f = new Field() .withName(adornedList.getSortField()) .withFieldType(SupportedFieldType.HIDDEN.toString()); ef.addHiddenField(f); } return ef; } @Override public EntityForm buildMapForm(MapMetadata mapMd, final MapStructure mapStructure, ClassMetadata cmd, String parentId) throws ServiceException { EntityForm ef = createStandardEntityForm(); return buildMapForm(mapMd, mapStructure, cmd, parentId, ef); } @Override public EntityForm buildMapForm(MapMetadata mapMd, final MapStructure mapStructure, ClassMetadata cmd, String parentId, EntityForm ef) throws ServiceException { ForeignKey foreignKey = (ForeignKey) mapMd.getPersistencePerspective() .getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY); ef.setEntityType(foreignKey.getForeignKeyClass()); Field keyField; if (!mapMd.getForceFreeFormKeys()) { // We will use a combo field to render the key choices ComboField temp = new ComboField(); temp.withName("key") .withFieldType("combo_field") .withFriendlyName("Key"); if (mapMd.getKeys() != null) { // The keys can be explicitly set in the annotation... temp.setOptions(mapMd.getKeys()); } else { // Or they could be based on a different entity PersistencePackageRequest ppr = PersistencePackageRequest.standard() .withCeilingEntityClassname(mapMd.getMapKeyOptionEntityClass()); DynamicResultSet drs = adminEntityService.getRecords(ppr); for (Entity entity : drs.getRecords()) { String keyValue = entity.getPMap().get(mapMd.getMapKeyOptionEntityValueField()).getValue(); String keyDisplayValue = entity.getPMap().get(mapMd.getMapKeyOptionEntityDisplayField()).getValue(); temp.putOption(keyValue, keyDisplayValue); } } keyField = temp; } else { keyField = new Field().withName("key") .withFieldType(SupportedFieldType.STRING.toString()) .withFriendlyName("Key"); } keyField.setRequired(true); ef.addMapKeyField(keyField); // Set the fields for this form List<Property> mapFormProperties; if (mapMd.isSimpleValue()) { ef.setIdProperty("key"); mapFormProperties = new ArrayList<Property>(); Property valueProp = cmd.getPMap().get("value"); mapFormProperties.add(valueProp); } else { mapFormProperties = new ArrayList<Property>(Arrays.asList(cmd.getProperties())); CollectionUtils.filter(mapFormProperties, new Predicate() { @Override public boolean evaluate(Object object) { Property p = (Property) object; return ArrayUtils.contains(p.getMetadata().getAvailableToTypes(), mapStructure.getValueClassName()); } }); } setEntityFormFields(ef, mapFormProperties); Field f = new Field() .withName("priorKey") .withFieldType(SupportedFieldType.HIDDEN.toString()); ef.addHiddenField(f); return ef; } protected EntityForm createStandardEntityForm() { EntityForm ef = new EntityForm(); ef.addAction(DefaultEntityFormActions.SAVE); return ef; } protected VisibilityEnum[] getGridHiddenVisibilities() { return FormBuilderServiceImpl.GRID_HIDDEN_VISIBILITIES; } protected VisibilityEnum[] getFormHiddenVisibilities() { return FormBuilderServiceImpl.FORM_HIDDEN_VISIBILITIES; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_web_service_FormBuilderServiceImpl.java
1,085
public class IndexAliasesTests extends ElasticsearchIntegrationTest { @Test public void testAliases() throws Exception { logger.info("--> creating index [test]"); createIndex("test"); ensureGreen(); logger.info("--> aliasing index [test] with [alias1]"); assertAcked(admin().indices().prepareAliases().addAlias("test", "alias1")); logger.info("--> indexing against [alias1], should work now"); IndexResponse indexResponse = client().index(indexRequest("alias1").type("type1").id("1").source(source("1", "test"))).actionGet(); assertThat(indexResponse.getIndex(), equalTo("test")); logger.info("--> creating index [test_x]"); createIndex("test_x"); ensureGreen(); logger.info("--> remove [alias1], Aliasing index [test_x] with [alias1]"); assertAcked(admin().indices().prepareAliases().removeAlias("test", "alias1").addAlias("test_x", "alias1")); logger.info("--> indexing against [alias1], should work against [test_x]"); indexResponse = client().index(indexRequest("alias1").type("type1").id("1").source(source("1", "test"))).actionGet(); assertThat(indexResponse.getIndex(), equalTo("test_x")); } @Test public void testFailedFilter() throws Exception { logger.info("--> creating index [test]"); createIndex("test"); ensureGreen(); try { logger.info("--> aliasing index [test] with [alias1] and filter [t]"); admin().indices().prepareAliases().addAlias("test", "alias1", "{ t }").get(); fail(); } catch (Exception e) { // all is well } } @Test public void testFilteringAliases() throws Exception { logger.info("--> creating index [test]"); createIndex("test"); ensureGreen(); logger.info("--> aliasing index [test] with [alias1] and filter [user:kimchy]"); FilterBuilder filter = termFilter("user", "kimchy"); assertAcked(admin().indices().prepareAliases().addAlias("test", "alias1", filter)); // For now just making sure that filter was stored with the alias logger.info("--> making sure that filter was stored with alias [alias1] and filter [user:kimchy]"); ClusterState clusterState = admin().cluster().prepareState().get().getState(); IndexMetaData indexMd = clusterState.metaData().index("test"); assertThat(indexMd.aliases().get("alias1").filter().string(), equalTo("{\"term\":{\"user\":\"kimchy\"}}")); } @Test public void testEmptyFilter() throws Exception { logger.info("--> creating index [test]"); createIndex("test"); ensureGreen(); logger.info("--> aliasing index [test] with [alias1] and empty filter"); assertAcked(admin().indices().prepareAliases().addAlias("test", "alias1", "{}")); } @Test public void testSearchingFilteringAliasesSingleIndex() throws Exception { logger.info("--> creating index [test]"); createIndex("test"); ensureGreen(); logger.info("--> adding filtering aliases to index [test]"); assertAcked(admin().indices().prepareAliases().addAlias("test", "alias1")); assertAcked(admin().indices().prepareAliases().addAlias("test", "alias2")); assertAcked(admin().indices().prepareAliases().addAlias("test", "foos", termFilter("name", "foo"))); assertAcked(admin().indices().prepareAliases().addAlias("test", "bars", termFilter("name", "bar"))); assertAcked(admin().indices().prepareAliases().addAlias("test", "tests", termFilter("name", "test"))); logger.info("--> indexing against [test]"); client().index(indexRequest("test").type("type1").id("1").source(source("1", "foo test")).refresh(true)).actionGet(); client().index(indexRequest("test").type("type1").id("2").source(source("2", "bar test")).refresh(true)).actionGet(); client().index(indexRequest("test").type("type1").id("3").source(source("3", "baz test")).refresh(true)).actionGet(); client().index(indexRequest("test").type("type1").id("4").source(source("4", "something else")).refresh(true)).actionGet(); logger.info("--> checking single filtering alias search"); SearchResponse searchResponse = client().prepareSearch("foos").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "1"); logger.info("--> checking single filtering alias wildcard search"); searchResponse = client().prepareSearch("fo*").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "1"); searchResponse = client().prepareSearch("tests").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "1", "2", "3"); logger.info("--> checking single filtering alias search with sort"); searchResponse = client().prepareSearch("tests").setQuery(QueryBuilders.matchAllQuery()).addSort("_uid", SortOrder.ASC).get(); assertHits(searchResponse.getHits(), "1", "2", "3"); logger.info("--> checking single filtering alias search with global facets"); searchResponse = client().prepareSearch("tests").setQuery(QueryBuilders.matchQuery("name", "bar")) .addFacet(FacetBuilders.termsFacet("test").field("name").global(true)) .get(); assertThat(((TermsFacet) searchResponse.getFacets().facet("test")).getEntries().size(), equalTo(4)); logger.info("--> checking single filtering alias search with global facets and sort"); searchResponse = client().prepareSearch("tests").setQuery(QueryBuilders.matchQuery("name", "bar")) .addFacet(FacetBuilders.termsFacet("test").field("name").global(true)) .addSort("_uid", SortOrder.ASC).get(); assertThat(((TermsFacet) searchResponse.getFacets().facet("test")).getEntries().size(), equalTo(4)); logger.info("--> checking single filtering alias search with non-global facets"); searchResponse = client().prepareSearch("tests").setQuery(QueryBuilders.matchQuery("name", "bar")) .addFacet(FacetBuilders.termsFacet("test").field("name").global(false)) .addSort("_uid", SortOrder.ASC).get(); assertThat(((TermsFacet) searchResponse.getFacets().facet("test")).getEntries().size(), equalTo(2)); searchResponse = client().prepareSearch("foos", "bars").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "1", "2"); logger.info("--> checking single non-filtering alias search"); searchResponse = client().prepareSearch("alias1").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "1", "2", "3", "4"); logger.info("--> checking non-filtering alias and filtering alias search"); searchResponse = client().prepareSearch("alias1", "foos").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "1", "2", "3", "4"); logger.info("--> checking index and filtering alias search"); searchResponse = client().prepareSearch("test", "foos").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "1", "2", "3", "4"); logger.info("--> checking index and alias wildcard search"); searchResponse = client().prepareSearch("te*", "fo*").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "1", "2", "3", "4"); } @Test public void testSearchingFilteringAliasesTwoIndices() throws Exception { logger.info("--> creating index [test1]"); createIndex("test1"); logger.info("--> creating index [test2]"); createIndex("test2"); ensureGreen(); logger.info("--> adding filtering aliases to index [test1]"); assertAcked(admin().indices().prepareAliases().addAlias("test1", "aliasToTest1")); assertAcked(admin().indices().prepareAliases().addAlias("test1", "aliasToTests")); assertAcked(admin().indices().prepareAliases().addAlias("test1", "foos", termFilter("name", "foo"))); assertAcked(admin().indices().prepareAliases().addAlias("test1", "bars", termFilter("name", "bar"))); logger.info("--> adding filtering aliases to index [test2]"); assertAcked(admin().indices().prepareAliases().addAlias("test2", "aliasToTest2")); assertAcked(admin().indices().prepareAliases().addAlias("test2", "aliasToTests")); assertAcked(admin().indices().prepareAliases().addAlias("test2", "foos", termFilter("name", "foo"))); logger.info("--> indexing against [test1]"); client().index(indexRequest("test1").type("type1").id("1").source(source("1", "foo test"))).get(); client().index(indexRequest("test1").type("type1").id("2").source(source("2", "bar test"))).get(); client().index(indexRequest("test1").type("type1").id("3").source(source("3", "baz test"))).get(); client().index(indexRequest("test1").type("type1").id("4").source(source("4", "something else"))).get(); logger.info("--> indexing against [test2]"); client().index(indexRequest("test2").type("type1").id("5").source(source("5", "foo test"))).get(); client().index(indexRequest("test2").type("type1").id("6").source(source("6", "bar test"))).get(); client().index(indexRequest("test2").type("type1").id("7").source(source("7", "baz test"))).get(); client().index(indexRequest("test2").type("type1").id("8").source(source("8", "something else"))).get(); refresh(); logger.info("--> checking filtering alias for two indices"); SearchResponse searchResponse = client().prepareSearch("foos").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "1", "5"); assertThat(client().prepareCount("foos").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(2L)); logger.info("--> checking filtering alias for one index"); searchResponse = client().prepareSearch("bars").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "2"); assertThat(client().prepareCount("bars").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(1L)); logger.info("--> checking filtering alias for two indices and one complete index"); searchResponse = client().prepareSearch("foos", "test1").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "1", "2", "3", "4", "5"); assertThat(client().prepareCount("foos", "test1").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(5L)); logger.info("--> checking filtering alias for two indices and non-filtering alias for one index"); searchResponse = client().prepareSearch("foos", "aliasToTest1").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "1", "2", "3", "4", "5"); assertThat(client().prepareCount("foos", "aliasToTest1").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(5L)); logger.info("--> checking filtering alias for two indices and non-filtering alias for both indices"); searchResponse = client().prepareSearch("foos", "aliasToTests").setQuery(QueryBuilders.matchAllQuery()).get(); assertThat(searchResponse.getHits().totalHits(), equalTo(8L)); assertThat(client().prepareCount("foos", "aliasToTests").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(8L)); logger.info("--> checking filtering alias for two indices and non-filtering alias for both indices"); searchResponse = client().prepareSearch("foos", "aliasToTests").setQuery(QueryBuilders.termQuery("name", "something")).get(); assertHits(searchResponse.getHits(), "4", "8"); assertThat(client().prepareCount("foos", "aliasToTests").setQuery(QueryBuilders.termQuery("name", "something")).get().getCount(), equalTo(2L)); } @Test public void testSearchingFilteringAliasesMultipleIndices() throws Exception { logger.info("--> creating indices"); createIndex("test1", "test2", "test3"); ensureGreen(); logger.info("--> adding aliases to indices"); assertAcked(admin().indices().prepareAliases().addAlias("test1", "alias12")); assertAcked(admin().indices().prepareAliases().addAlias("test2", "alias12")); logger.info("--> adding filtering aliases to indices"); assertAcked(admin().indices().prepareAliases().addAlias("test1", "filter1", termFilter("name", "test1"))); assertAcked(admin().indices().prepareAliases().addAlias("test2", "filter23", termFilter("name", "foo"))); assertAcked(admin().indices().prepareAliases().addAlias("test3", "filter23", termFilter("name", "foo"))); assertAcked(admin().indices().prepareAliases().addAlias("test1", "filter13", termFilter("name", "baz"))); assertAcked(admin().indices().prepareAliases().addAlias("test3", "filter13", termFilter("name", "baz"))); logger.info("--> indexing against [test1]"); client().index(indexRequest("test1").type("type1").id("11").source(source("11", "foo test1"))).get(); client().index(indexRequest("test1").type("type1").id("12").source(source("12", "bar test1"))).get(); client().index(indexRequest("test1").type("type1").id("13").source(source("13", "baz test1"))).get(); client().index(indexRequest("test2").type("type1").id("21").source(source("21", "foo test2"))).get(); client().index(indexRequest("test2").type("type1").id("22").source(source("22", "bar test2"))).get(); client().index(indexRequest("test2").type("type1").id("23").source(source("23", "baz test2"))).get(); client().index(indexRequest("test3").type("type1").id("31").source(source("31", "foo test3"))).get(); client().index(indexRequest("test3").type("type1").id("32").source(source("32", "bar test3"))).get(); client().index(indexRequest("test3").type("type1").id("33").source(source("33", "baz test3"))).get(); refresh(); logger.info("--> checking filtering alias for multiple indices"); SearchResponse searchResponse = client().prepareSearch("filter23", "filter13").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "21", "31", "13", "33"); assertThat(client().prepareCount("filter23", "filter13").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(4L)); searchResponse = client().prepareSearch("filter23", "filter1").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "21", "31", "11", "12", "13"); assertThat(client().prepareCount("filter23", "filter1").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(5L)); searchResponse = client().prepareSearch("filter13", "filter1").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "11", "12", "13", "33"); assertThat(client().prepareCount("filter13", "filter1").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(4L)); searchResponse = client().prepareSearch("filter13", "filter1", "filter23").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "11", "12", "13", "21", "31", "33"); assertThat(client().prepareCount("filter13", "filter1", "filter23").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(6L)); searchResponse = client().prepareSearch("filter23", "filter13", "test2").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "21", "22", "23", "31", "13", "33"); assertThat(client().prepareCount("filter23", "filter13", "test2").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(6L)); searchResponse = client().prepareSearch("filter23", "filter13", "test1", "test2").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "11", "12", "13", "21", "22", "23", "31", "33"); assertThat(client().prepareCount("filter23", "filter13", "test1", "test2").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(8L)); } @Test public void testDeletingByQueryFilteringAliases() throws Exception { logger.info("--> creating index [test1] and [test2"); createIndex("test1", "test2"); ensureGreen(); logger.info("--> adding filtering aliases to index [test1]"); assertAcked(admin().indices().prepareAliases().addAlias("test1", "aliasToTest1")); assertAcked(admin().indices().prepareAliases().addAlias("test1", "aliasToTests")); assertAcked(admin().indices().prepareAliases().addAlias("test1", "foos", termFilter("name", "foo"))); assertAcked(admin().indices().prepareAliases().addAlias("test1", "bars", termFilter("name", "bar"))); assertAcked(admin().indices().prepareAliases().addAlias("test1", "tests", termFilter("name", "test"))); logger.info("--> adding filtering aliases to index [test2]"); assertAcked(admin().indices().prepareAliases().addAlias("test2", "aliasToTest2")); assertAcked(admin().indices().prepareAliases().addAlias("test2", "aliasToTests")); assertAcked(admin().indices().prepareAliases().addAlias("test2", "foos", termFilter("name", "foo"))); assertAcked(admin().indices().prepareAliases().addAlias("test2", "tests", termFilter("name", "test"))); logger.info("--> indexing against [test1]"); client().index(indexRequest("test1").type("type1").id("1").source(source("1", "foo test"))).get(); client().index(indexRequest("test1").type("type1").id("2").source(source("2", "bar test"))).get(); client().index(indexRequest("test1").type("type1").id("3").source(source("3", "baz test"))).get(); client().index(indexRequest("test1").type("type1").id("4").source(source("4", "something else"))).get(); logger.info("--> indexing against [test2]"); client().index(indexRequest("test2").type("type1").id("5").source(source("5", "foo test"))).get(); client().index(indexRequest("test2").type("type1").id("6").source(source("6", "bar test"))).get(); client().index(indexRequest("test2").type("type1").id("7").source(source("7", "baz test"))).get(); client().index(indexRequest("test2").type("type1").id("8").source(source("8", "something else"))).get(); refresh(); logger.info("--> checking counts before delete"); assertThat(client().prepareCount("bars").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(1L)); logger.info("--> delete by query from a single alias"); client().prepareDeleteByQuery("bars").setQuery(QueryBuilders.termQuery("name", "test")).get(); logger.info("--> verify that only one record was deleted"); assertThat(client().prepareCount("test1").setQuery(QueryBuilders.matchAllQuery()).get().getCount(), equalTo(3L)); logger.info("--> delete by query from an aliases pointing to two indices"); client().prepareDeleteByQuery("foos").setQuery(QueryBuilders.matchAllQuery()).get(); logger.info("--> verify that proper records were deleted"); SearchResponse searchResponse = client().prepareSearch("aliasToTests").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "3", "4", "6", "7", "8"); logger.info("--> delete by query from an aliases and an index"); client().prepareDeleteByQuery("tests", "test2").setQuery(QueryBuilders.matchAllQuery()).get(); logger.info("--> verify that proper records were deleted"); searchResponse = client().prepareSearch("aliasToTests").setQuery(QueryBuilders.matchAllQuery()).get(); assertHits(searchResponse.getHits(), "4"); } @Test public void testDeleteAliases() throws Exception { logger.info("--> creating index [test1] and [test2]"); createIndex("test1", "test2"); ensureGreen(); logger.info("--> adding filtering aliases to index [test1]"); assertAcked(admin().indices().prepareAliases().addAlias("test1", "aliasToTest1") .addAlias("test1", "aliasToTests") .addAlias("test1", "foos", termFilter("name", "foo")) .addAlias("test1", "bars", termFilter("name", "bar")) .addAlias("test1", "tests", termFilter("name", "test"))); logger.info("--> adding filtering aliases to index [test2]"); assertAcked(admin().indices().prepareAliases().addAlias("test2", "aliasToTest2") .addAlias("test2", "aliasToTests") .addAlias("test2", "foos", termFilter("name", "foo")) .addAlias("test2", "tests", termFilter("name", "test"))); String[] indices = {"test1", "test2"}; String[] aliases = {"aliasToTest1", "foos", "bars", "tests", "aliasToTest2", "aliasToTests"}; admin().indices().prepareAliases().removeAlias(indices, aliases).get(); AliasesExistResponse response = admin().indices().prepareAliasesExist(aliases).get(); assertThat(response.exists(), equalTo(false)); } @Test public void testWaitForAliasCreationMultipleShards() throws Exception { logger.info("--> creating index [test]"); createIndex("test"); ensureGreen(); for (int i = 0; i < 10; i++) { assertAcked(admin().indices().prepareAliases().addAlias("test", "alias" + i)); client().index(indexRequest("alias" + i).type("type1").id("1").source(source("1", "test"))).get(); } } @Test public void testWaitForAliasCreationSingleShard() throws Exception { logger.info("--> creating index [test]"); assertAcked(admin().indices().create(createIndexRequest("test").settings(settingsBuilder().put("index.numberOfReplicas", 0).put("index.numberOfShards", 1))).get()); ensureGreen(); for (int i = 0; i < 10; i++) { assertAcked(admin().indices().prepareAliases().addAlias("test", "alias" + i)); client().index(indexRequest("alias" + i).type("type1").id("1").source(source("1", "test"))).get(); } } @Test public void testWaitForAliasSimultaneousUpdate() throws Exception { final int aliasCount = 10; logger.info("--> creating index [test]"); createIndex("test"); ensureGreen(); ExecutorService executor = Executors.newFixedThreadPool(aliasCount); for (int i = 0; i < aliasCount; i++) { final String aliasName = "alias" + i; executor.submit(new Runnable() { @Override public void run() { assertAcked(admin().indices().prepareAliases().addAlias("test", aliasName)); client().index(indexRequest(aliasName).type("type1").id("1").source(source("1", "test"))).actionGet(); } }); } executor.shutdown(); boolean done = executor.awaitTermination(10, TimeUnit.SECONDS); assertThat(done, equalTo(true)); if (!done) { executor.shutdownNow(); } } @Test public void testSameAlias() throws Exception { logger.info("--> creating index [test]"); createIndex("test"); ensureGreen(); logger.info("--> creating alias1 "); assertAcked((admin().indices().prepareAliases().addAlias("test", "alias1"))); TimeValue timeout = TimeValue.timeValueSeconds(2); logger.info("--> recreating alias1 "); StopWatch stopWatch = new StopWatch(); stopWatch.start(); assertAcked((admin().indices().prepareAliases().addAlias("test", "alias1").setTimeout(timeout))); assertThat(stopWatch.stop().lastTaskTime().millis(), lessThan(timeout.millis())); logger.info("--> modifying alias1 to have a filter"); stopWatch.start(); assertAcked((admin().indices().prepareAliases().addAlias("test", "alias1", termFilter("name", "foo")).setTimeout(timeout))); assertThat(stopWatch.stop().lastTaskTime().millis(), lessThan(timeout.millis())); logger.info("--> recreating alias1 with the same filter"); stopWatch.start(); assertAcked((admin().indices().prepareAliases().addAlias("test", "alias1", termFilter("name", "foo")).setTimeout(timeout))); assertThat(stopWatch.stop().lastTaskTime().millis(), lessThan(timeout.millis())); logger.info("--> recreating alias1 with a different filter"); stopWatch.start(); assertAcked((admin().indices().prepareAliases().addAlias("test", "alias1", termFilter("name", "bar")).setTimeout(timeout))); assertThat(stopWatch.stop().lastTaskTime().millis(), lessThan(timeout.millis())); logger.info("--> verify that filter was updated"); AliasMetaData aliasMetaData = cluster().clusterService().state().metaData().aliases().get("alias1").get("test"); assertThat(aliasMetaData.getFilter().toString(), equalTo("{\"term\":{\"name\":\"bar\"}}")); logger.info("--> deleting alias1"); stopWatch.start(); assertAcked((admin().indices().prepareAliases().removeAlias("test", "alias1").setTimeout(timeout))); assertThat(stopWatch.stop().lastTaskTime().millis(), lessThan(timeout.millis())); } @Test(expected = AliasesMissingException.class) public void testIndicesRemoveNonExistingAliasResponds404() throws Exception { logger.info("--> creating index [test]"); createIndex("test"); ensureGreen(); logger.info("--> deleting alias1 which does not exist"); assertAcked((admin().indices().prepareAliases().removeAlias("test", "alias1"))); } @Test public void testIndicesGetAliases() throws Exception { Settings indexSettings = ImmutableSettings.settingsBuilder() .put("index.number_of_shards", 1) .put("index.number_of_replicas", 0) .build(); logger.info("--> creating indices [foobar, test, test123, foobarbaz, bazbar]"); assertAcked(prepareCreate("foobar").setSettings(indexSettings)); assertAcked(prepareCreate("test").setSettings(indexSettings)); assertAcked(prepareCreate("test123").setSettings(indexSettings)); assertAcked(prepareCreate("foobarbaz").setSettings(indexSettings)); assertAcked(prepareCreate("bazbar").setSettings(indexSettings)); ensureGreen(); logger.info("--> creating aliases [alias1, alias2]"); assertAcked(admin().indices().prepareAliases().addAlias("foobar", "alias1").addAlias("foobar", "alias2")); logger.info("--> getting alias1"); GetAliasesResponse getResponse = admin().indices().prepareGetAliases("alias1").get(); assertThat(getResponse, notNullValue()); assertThat(getResponse.getAliases().size(), equalTo(1)); assertThat(getResponse.getAliases().get("foobar").size(), equalTo(1)); assertThat(getResponse.getAliases().get("foobar").get(0), notNullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).alias(), equalTo("alias1")); assertThat(getResponse.getAliases().get("foobar").get(0).getFilter(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).getSearchRouting(), nullValue()); AliasesExistResponse existsResponse = admin().indices().prepareAliasesExist("alias1").get(); assertThat(existsResponse.exists(), equalTo(true)); logger.info("--> getting all aliases that start with alias*"); getResponse = admin().indices().prepareGetAliases("alias*").get(); assertThat(getResponse, notNullValue()); assertThat(getResponse.getAliases().size(), equalTo(1)); assertThat(getResponse.getAliases().get("foobar").size(), equalTo(2)); assertThat(getResponse.getAliases().get("foobar").get(0), notNullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).alias(), equalTo("alias2")); assertThat(getResponse.getAliases().get("foobar").get(0).getFilter(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).getSearchRouting(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(1), notNullValue()); assertThat(getResponse.getAliases().get("foobar").get(1).alias(), equalTo("alias1")); assertThat(getResponse.getAliases().get("foobar").get(1).getFilter(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(1).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(1).getSearchRouting(), nullValue()); existsResponse = admin().indices().prepareAliasesExist("alias*").get(); assertThat(existsResponse.exists(), equalTo(true)); logger.info("--> creating aliases [bar, baz, foo]"); assertAcked(admin().indices().prepareAliases() .addAlias("bazbar", "bar") .addAlias("bazbar", "bac", termFilter("field", "value")) .addAlias("foobar", "foo")); assertAcked(admin().indices().prepareAliases() .addAliasAction(new AliasAction(AliasAction.Type.ADD, "foobar", "bac").routing("bla"))); logger.info("--> getting bar and baz for index bazbar"); getResponse = admin().indices().prepareGetAliases("bar", "bac").addIndices("bazbar").get(); assertThat(getResponse, notNullValue()); assertThat(getResponse.getAliases().size(), equalTo(1)); assertThat(getResponse.getAliases().get("bazbar").size(), equalTo(2)); assertThat(getResponse.getAliases().get("bazbar").get(0), notNullValue()); assertThat(getResponse.getAliases().get("bazbar").get(0).alias(), equalTo("bac")); assertThat(getResponse.getAliases().get("bazbar").get(0).getFilter().string(), containsString("term")); assertThat(getResponse.getAliases().get("bazbar").get(0).getFilter().string(), containsString("field")); assertThat(getResponse.getAliases().get("bazbar").get(0).getFilter().string(), containsString("value")); assertThat(getResponse.getAliases().get("bazbar").get(0).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(0).getSearchRouting(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1), notNullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1).alias(), equalTo("bar")); assertThat(getResponse.getAliases().get("bazbar").get(1).getFilter(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1).getSearchRouting(), nullValue()); existsResponse = admin().indices().prepareAliasesExist("bar", "bac") .addIndices("bazbar").get(); assertThat(existsResponse.exists(), equalTo(true)); logger.info("--> getting *b* for index baz*"); getResponse = admin().indices().prepareGetAliases("*b*").addIndices("baz*").get(); assertThat(getResponse, notNullValue()); assertThat(getResponse.getAliases().size(), equalTo(1)); assertThat(getResponse.getAliases().get("bazbar").size(), equalTo(2)); assertThat(getResponse.getAliases().get("bazbar").get(0), notNullValue()); assertThat(getResponse.getAliases().get("bazbar").get(0).alias(), equalTo("bac")); assertThat(getResponse.getAliases().get("bazbar").get(0).getFilter().string(), containsString("term")); assertThat(getResponse.getAliases().get("bazbar").get(0).getFilter().string(), containsString("field")); assertThat(getResponse.getAliases().get("bazbar").get(0).getFilter().string(), containsString("value")); assertThat(getResponse.getAliases().get("bazbar").get(0).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(0).getSearchRouting(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1), notNullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1).alias(), equalTo("bar")); assertThat(getResponse.getAliases().get("bazbar").get(1).getFilter(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1).getSearchRouting(), nullValue()); existsResponse = admin().indices().prepareAliasesExist("*b*") .addIndices("baz*").get(); assertThat(existsResponse.exists(), equalTo(true)); logger.info("--> getting *b* for index *bar"); getResponse = admin().indices().prepareGetAliases("b*").addIndices("*bar").get(); assertThat(getResponse, notNullValue()); assertThat(getResponse.getAliases().size(), equalTo(2)); assertThat(getResponse.getAliases().get("bazbar").size(), equalTo(2)); assertThat(getResponse.getAliases().get("bazbar").get(0), notNullValue()); assertThat(getResponse.getAliases().get("bazbar").get(0).alias(), equalTo("bac")); assertThat(getResponse.getAliases().get("bazbar").get(0).getFilter().string(), containsString("term")); assertThat(getResponse.getAliases().get("bazbar").get(0).getFilter().string(), containsString("field")); assertThat(getResponse.getAliases().get("bazbar").get(0).getFilter().string(), containsString("value")); assertThat(getResponse.getAliases().get("bazbar").get(0).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(0).getSearchRouting(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1), notNullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1).alias(), equalTo("bar")); assertThat(getResponse.getAliases().get("bazbar").get(1).getFilter(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("bazbar").get(1).getSearchRouting(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0), notNullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).alias(), equalTo("bac")); assertThat(getResponse.getAliases().get("foobar").get(0).getFilter(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).getIndexRouting(), equalTo("bla")); assertThat(getResponse.getAliases().get("foobar").get(0).getSearchRouting(), equalTo("bla")); existsResponse = admin().indices().prepareAliasesExist("b*") .addIndices("*bar").get(); assertThat(existsResponse.exists(), equalTo(true)); logger.info("--> getting f* for index *bar"); getResponse = admin().indices().prepareGetAliases("f*").addIndices("*bar").get(); assertThat(getResponse, notNullValue()); assertThat(getResponse.getAliases().size(), equalTo(1)); assertThat(getResponse.getAliases().get("foobar").get(0), notNullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).alias(), equalTo("foo")); assertThat(getResponse.getAliases().get("foobar").get(0).getFilter(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).getSearchRouting(), nullValue()); existsResponse = admin().indices().prepareAliasesExist("f*") .addIndices("*bar").get(); assertThat(existsResponse.exists(), equalTo(true)); // alias at work logger.info("--> getting f* for index *bac"); getResponse = admin().indices().prepareGetAliases("foo").addIndices("*bac").get(); assertThat(getResponse, notNullValue()); assertThat(getResponse.getAliases().size(), equalTo(1)); assertThat(getResponse.getAliases().get("foobar").size(), equalTo(1)); assertThat(getResponse.getAliases().get("foobar").get(0), notNullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).alias(), equalTo("foo")); assertThat(getResponse.getAliases().get("foobar").get(0).getFilter(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).getSearchRouting(), nullValue()); existsResponse = admin().indices().prepareAliasesExist("foo") .addIndices("*bac").get(); assertThat(existsResponse.exists(), equalTo(true)); logger.info("--> getting foo for index foobar"); getResponse = admin().indices().prepareGetAliases("foo").addIndices("foobar").get(); assertThat(getResponse, notNullValue()); assertThat(getResponse.getAliases().size(), equalTo(1)); assertThat(getResponse.getAliases().get("foobar").get(0), notNullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).alias(), equalTo("foo")); assertThat(getResponse.getAliases().get("foobar").get(0).getFilter(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).getIndexRouting(), nullValue()); assertThat(getResponse.getAliases().get("foobar").get(0).getSearchRouting(), nullValue()); existsResponse = admin().indices().prepareAliasesExist("foo") .addIndices("foobar").get(); assertThat(existsResponse.exists(), equalTo(true)); // alias at work again logger.info("--> getting * for index *bac"); getResponse = admin().indices().prepareGetAliases("*").addIndices("*bac").get(); assertThat(getResponse, notNullValue()); assertThat(getResponse.getAliases().size(), equalTo(2)); assertThat(getResponse.getAliases().get("foobar").size(), equalTo(4)); assertThat(getResponse.getAliases().get("bazbar").size(), equalTo(2)); existsResponse = admin().indices().prepareAliasesExist("*") .addIndices("*bac").get(); assertThat(existsResponse.exists(), equalTo(true)); assertAcked(admin().indices().prepareAliases() .removeAlias("foobar", "foo")); getResponse = admin().indices().prepareGetAliases("foo").addIndices("foobar").get(); assertThat(getResponse.getAliases().isEmpty(), equalTo(true)); existsResponse = admin().indices().prepareAliasesExist("foo").addIndices("foobar").get(); assertThat(existsResponse.exists(), equalTo(false)); } @Test(expected = IndexMissingException.class) public void testAddAliasNullIndex() { admin().indices().prepareAliases().addAliasAction(AliasAction.newAddAliasAction(null, "alias1")).get(); } @Test(expected = ActionRequestValidationException.class) public void testAddAliasEmptyIndex() { admin().indices().prepareAliases().addAliasAction(AliasAction.newAddAliasAction("", "alias1")).get(); } @Test(expected = ActionRequestValidationException.class) public void testAddAliasNullAlias() { admin().indices().prepareAliases().addAliasAction(AliasAction.newAddAliasAction("index1", null)).get(); } @Test(expected = ActionRequestValidationException.class) public void testAddAliasEmptyAlias() { admin().indices().prepareAliases().addAliasAction(AliasAction.newAddAliasAction("index1", "")).get(); } @Test public void testAddAliasNullAliasNullIndex() { try { admin().indices().prepareAliases().addAliasAction(AliasAction.newAddAliasAction(null, null)).get(); assertTrue("Should throw " + ActionRequestValidationException.class.getSimpleName(), false); } catch (ActionRequestValidationException e) { assertThat(e.validationErrors(), notNullValue()); assertThat(e.validationErrors().size(), equalTo(1)); } } @Test public void testAddAliasEmptyAliasEmptyIndex() { try { admin().indices().prepareAliases().addAliasAction(AliasAction.newAddAliasAction("", "")).get(); assertTrue("Should throw " + ActionRequestValidationException.class.getSimpleName(), false); } catch (ActionRequestValidationException e) { assertThat(e.validationErrors(), notNullValue()); assertThat(e.validationErrors().size(), equalTo(2)); } } @Test(expected = ActionRequestValidationException.class) public void tesRemoveAliasNullIndex() { admin().indices().prepareAliases().addAliasAction(AliasAction.newRemoveAliasAction(null, "alias1")).get(); } @Test(expected = ActionRequestValidationException.class) public void tesRemoveAliasEmptyIndex() { admin().indices().prepareAliases().addAliasAction(AliasAction.newRemoveAliasAction("", "alias1")).get(); } @Test(expected = ActionRequestValidationException.class) public void tesRemoveAliasNullAlias() { admin().indices().prepareAliases().addAliasAction(AliasAction.newRemoveAliasAction("index1", null)).get(); } @Test(expected = ActionRequestValidationException.class) public void tesRemoveAliasEmptyAlias() { admin().indices().prepareAliases().addAliasAction(AliasAction.newRemoveAliasAction("index1", "")).get(); } @Test public void testRemoveAliasNullAliasNullIndex() { try { admin().indices().prepareAliases().addAliasAction(AliasAction.newRemoveAliasAction(null, null)).get(); fail("Should throw " + ActionRequestValidationException.class.getSimpleName()); } catch (ActionRequestValidationException e) { assertThat(e.validationErrors(), notNullValue()); assertThat(e.validationErrors().size(), equalTo(2)); } } @Test public void testRemoveAliasEmptyAliasEmptyIndex() { try { admin().indices().prepareAliases().addAliasAction(AliasAction.newAddAliasAction("", "")).get(); fail("Should throw " + ActionRequestValidationException.class.getSimpleName()); } catch (ActionRequestValidationException e) { assertThat(e.validationErrors(), notNullValue()); assertThat(e.validationErrors().size(), equalTo(2)); } } @Test public void testGetAllAliasesWorks() { createIndex("index1"); createIndex("index2"); ensureYellow(); assertAcked(admin().indices().prepareAliases().addAlias("index1", "alias1").addAlias("index2", "alias2")); GetAliasesResponse response = admin().indices().prepareGetAliases().get(); assertThat(response.getAliases(), hasKey("index1")); assertThat(response.getAliases(), hasKey("index1")); } private void assertHits(SearchHits hits, String... ids) { assertThat(hits.totalHits(), equalTo((long) ids.length)); Set<String> hitIds = newHashSet(); for (SearchHit hit : hits.getHits()) { hitIds.add(hit.id()); } assertThat(hitIds, containsInAnyOrder(ids)); } private String source(String id, String nameValue) { return "{ \"id\" : \"" + id + "\", \"name\" : \"" + nameValue + "\" }"; } }
0true
src_test_java_org_elasticsearch_aliases_IndexAliasesTests.java
196
InjectedTransactionValidator ALLOW_ALL = new InjectedTransactionValidator(){ @Override public void assertInjectionAllowed( long lastCommittedTxWhenTransactionStarted ) throws XAException { // Always ok. } };
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_InjectedTransactionValidator.java
884
public class PromotableCandidateItemOfferImpl extends AbstractPromotionRounding implements PromotableCandidateItemOffer, OfferHolder { private static final long serialVersionUID = 1L; protected Offer offer; protected PromotableOrder promotableOrder; protected Money potentialSavings; protected int uses = 0; protected HashMap<OfferItemCriteria, List<PromotableOrderItem>> candidateQualifiersMap = new HashMap<OfferItemCriteria, List<PromotableOrderItem>>(); protected HashMap<OfferItemCriteria, List<PromotableOrderItem>> candidateTargetsMap = new HashMap<OfferItemCriteria, List<PromotableOrderItem>>(); protected List<PromotableOrderItem> legacyCandidateTargets = new ArrayList<PromotableOrderItem>(); public PromotableCandidateItemOfferImpl(PromotableOrder promotableOrder, Offer offer) { assert (offer != null); assert (promotableOrder != null); this.offer = offer; this.promotableOrder = promotableOrder; } @Override public BroadleafCurrency getCurrency() { return promotableOrder.getOrderCurrency(); } @Override public Money calculateSavingsForOrderItem(PromotableOrderItem orderItem, int qtyToReceiveSavings) { Money savings = new Money(promotableOrder.getOrderCurrency()); Money price = orderItem.getPriceBeforeAdjustments(getOffer().getApplyDiscountToSalePrice()); BigDecimal offerUnitValue = PromotableOfferUtility.determineOfferUnitValue(offer, this); savings = PromotableOfferUtility.computeAdjustmentValue(price, offerUnitValue, this, this); return savings.multiply(qtyToReceiveSavings); } /** * Returns the number of items that potentially could be targets for the offer. Due to combination or bogo * logic, they may not all get the tiered offer price. */ @Override public int calculateTargetQuantityForTieredOffer() { int returnQty = 0; for (OfferItemCriteria itemCriteria : getCandidateQualifiersMap().keySet()) { List<PromotableOrderItem> candidateTargets = getCandidateTargetsMap().get(itemCriteria); for (PromotableOrderItem promotableOrderItem : candidateTargets) { returnQty += promotableOrderItem.getQuantity(); } } return returnQty; } @Override public Money getPotentialSavings() { if (potentialSavings == null) { return new Money(promotableOrder.getOrderCurrency()); } return potentialSavings; } @Override public void setPotentialSavings(Money potentialSavings) { this.potentialSavings = potentialSavings; } @Override public boolean hasQualifyingItemCriteria() { return (offer.getQualifyingItemCriteria() != null && !offer.getQualifyingItemCriteria().isEmpty()); } /** * Determines the maximum number of times this promotion can be used based on the * ItemCriteria and promotion's maxQty setting. */ @Override public int calculateMaximumNumberOfUses() { int maxMatchesFound = 9999; // set arbitrarily high / algorithm will adjust down //iterate through the target criteria and find the least amount of max uses. This will be the overall //max usage, since the target criteria are grouped together in "and" style. int numberOfUsesForThisItemCriteria = maxMatchesFound; for (OfferItemCriteria targetCriteria : getOffer().getTargetItemCriteria()) { int temp = calculateMaxUsesForItemCriteria(targetCriteria, getOffer()); numberOfUsesForThisItemCriteria = Math.min(numberOfUsesForThisItemCriteria, temp); } maxMatchesFound = Math.min(maxMatchesFound, numberOfUsesForThisItemCriteria); int offerMaxUses = getOffer().isUnlimitedUsePerOrder() ? maxMatchesFound : getOffer().getMaxUsesPerOrder(); return Math.min(maxMatchesFound, offerMaxUses); } @Override public int calculateMaxUsesForItemCriteria(OfferItemCriteria itemCriteria, Offer promotion) { int numberOfTargets = 0; int numberOfUsesForThisItemCriteria = 9999; if (itemCriteria != null) { List<PromotableOrderItem> candidateTargets = getCandidateTargetsMap().get(itemCriteria); for(PromotableOrderItem potentialTarget : candidateTargets) { numberOfTargets += potentialTarget.getQuantity(); } numberOfUsesForThisItemCriteria = numberOfTargets / itemCriteria.getQuantity(); } return numberOfUsesForThisItemCriteria; } @Override public HashMap<OfferItemCriteria, List<PromotableOrderItem>> getCandidateQualifiersMap() { return candidateQualifiersMap; } @Override public void setCandidateQualifiersMap(HashMap<OfferItemCriteria, List<PromotableOrderItem>> candidateItemsMap) { this.candidateQualifiersMap = candidateItemsMap; } @Override public HashMap<OfferItemCriteria, List<PromotableOrderItem>> getCandidateTargetsMap() { return candidateTargetsMap; } @Override public void setCandidateTargetsMap(HashMap<OfferItemCriteria, List<PromotableOrderItem>> candidateItemsMap) { this.candidateTargetsMap = candidateItemsMap; } @Override public int getPriority() { return offer.getPriority(); } @Override public Offer getOffer() { return offer; } @Override public int getUses() { return uses; } @Override public void addUse() { uses++; } @Override public void resetUses() { uses = 0; } @Override public boolean isLegacyOffer() { return offer.getQualifyingItemCriteria().isEmpty() && offer.getTargetItemCriteria().isEmpty(); } @Override public List<PromotableOrderItem> getLegacyCandidateTargets() { return legacyCandidateTargets; } @Override public void setLegacyCandidateTargets(List<PromotableOrderItem> candidateTargets) { this.legacyCandidateTargets = candidateTargets; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableCandidateItemOfferImpl.java
5,788
public class VersionFetchSubPhase implements FetchSubPhase { @Override public Map<String, ? extends SearchParseElement> parseElements() { return ImmutableMap.of("version", new VersionParseElement()); } @Override public boolean hitsExecutionNeeded(SearchContext context) { return false; } @Override public void hitsExecute(SearchContext context, InternalSearchHit[] hits) throws ElasticsearchException { } @Override public boolean hitExecutionNeeded(SearchContext context) { return context.version(); } @Override public void hitExecute(SearchContext context, HitContext hitContext) throws ElasticsearchException { // it might make sense to cache the TermDocs on a shared fetch context and just skip here) // it is going to mean we work on the high level multi reader and not the lower level reader as is // the case below... long version; try { version = Versions.loadVersion( hitContext.readerContext().reader(), new Term(UidFieldMapper.NAME, hitContext.fieldVisitor().uid().toBytesRef()) ); } catch (IOException e) { throw new ElasticsearchException("Could not query index for _version", e); } if (version < 0) { version = -1; } hitContext.hit().version(version); } }
1no label
src_main_java_org_elasticsearch_search_fetch_version_VersionFetchSubPhase.java
139
public class DistributedObjectListenerRequest extends CallableClientRequest implements RetryableRequest { public DistributedObjectListenerRequest() { } @Override public Object call() throws Exception { ProxyService proxyService = clientEngine.getProxyService(); String registrationId = proxyService.addProxyListener(new MyDistributedObjectListener()); endpoint.setDistributedObjectListener(registrationId); return registrationId; } @Override public String getServiceName() { return null; } @Override public int getFactoryId() { return ClientPortableHook.ID; } @Override public int getClassId() { return ClientPortableHook.LISTENER; } private class MyDistributedObjectListener implements DistributedObjectListener { @Override public void distributedObjectCreated(DistributedObjectEvent event) { send(event); } @Override public void distributedObjectDestroyed(DistributedObjectEvent event) { } private void send(DistributedObjectEvent event) { if (endpoint.live()) { PortableDistributedObjectEvent portableEvent = new PortableDistributedObjectEvent( event.getEventType(), event.getDistributedObject().getName(), event.getServiceName()); endpoint.sendEvent(portableEvent, getCallId()); } } } @Override public Permission getRequiredPermission() { return null; } }
1no label
hazelcast_src_main_java_com_hazelcast_client_DistributedObjectListenerRequest.java
1,571
public static class Multi extends Decision { private final List<Decision> decisions = Lists.newArrayList(); /** * Add a decission to this {@link Multi}decision instance * @param decision {@link Decision} to add * @return {@link Multi}decision instance with the given decision added */ public Multi add(Decision decision) { decisions.add(decision); return this; } @Override public Type type() { Type ret = Type.YES; for (int i = 0; i < decisions.size(); i++) { Type type = decisions.get(i).type(); if (type == Type.NO) { return type; } else if (type == Type.THROTTLE) { ret = type; } } return ret; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Decision decision : decisions) { sb.append("[").append(decision.toString()).append("]"); } return sb.toString(); } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_decider_Decision.java
1,724
public class Iterators2Tests extends ElasticsearchTestCase { public void testDeduplicateSorted() { final List<String> list = Lists.newArrayList(); for (int i = randomInt(100); i >= 0; --i) { final int frequency = randomIntBetween(1, 10); final String s = randomAsciiOfLength(randomIntBetween(2, 20)); for (int j = 0; j < frequency; ++j) { list.add(s); } } CollectionUtil.introSort(list); final List<String> deduplicated = Lists.newArrayList(); for (Iterator<String> it = Iterators2.deduplicateSorted(list.iterator(), Ordering.natural()); it.hasNext(); ) { deduplicated.add(it.next()); } assertEquals(Lists.newArrayList(Sets.newTreeSet(list)), deduplicated); } }
0true
src_test_java_org_elasticsearch_common_collect_Iterators2Tests.java
1,775
public class EnvelopeBuilder extends ShapeBuilder { public static final GeoShapeType TYPE = GeoShapeType.ENVELOPE; protected Coordinate topLeft; protected Coordinate bottomRight; public EnvelopeBuilder topLeft(Coordinate topLeft) { this.topLeft = topLeft; return this; } public EnvelopeBuilder topLeft(double longitude, double latitude) { return topLeft(coordinate(longitude, latitude)); } public EnvelopeBuilder bottomRight(Coordinate bottomRight) { this.bottomRight = bottomRight; return this; } public EnvelopeBuilder bottomRight(double longitude, double latitude) { return bottomRight(coordinate(longitude, latitude)); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(FIELD_TYPE, TYPE.shapename); builder.startArray(FIELD_COORDINATES); toXContent(builder, topLeft); toXContent(builder, bottomRight); builder.endArray(); return builder.endObject(); } @Override public Rectangle build() { return SPATIAL_CONTEXT.makeRectangle(topLeft.x, bottomRight.x, bottomRight.y, topLeft.y); } @Override public GeoShapeType type() { return TYPE; } }
0true
src_main_java_org_elasticsearch_common_geo_builders_EnvelopeBuilder.java
983
public static class Group { public static class Name { } public static class Order { } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_DiscreteOrderItemImpl.java
68
static class NodeHolder { Node node; public NodeHolder(Node node) { this.node = node; } public NodeHolder getSub(String name) { if (node != null) { for (org.w3c.dom.Node node : new AbstractXmlConfigHelper.IterableNodeList(this.node.getChildNodes())) { String nodeName = cleanNodeName(node.getNodeName()); if (name.equals(nodeName)) { return new NodeHolder(node); } } } return new NodeHolder(null); } public List<NodeHolder> getSubNodes(String name) { List<NodeHolder> list = new ArrayList<NodeHolder>(); if (node != null) { for (org.w3c.dom.Node node : new AbstractXmlConfigHelper.IterableNodeList(this.node.getChildNodes())) { String nodeName = cleanNodeName(node.getNodeName()); if (name.equals(nodeName)) { list.add(new NodeHolder(node)); } } } return list; } public List<String> getList(String name, AwsConfig awsConfig) { List<String> list = new ArrayList<String>(); if (node == null) return list; for (org.w3c.dom.Node node : new AbstractXmlConfigHelper.IterableNodeList(this.node.getChildNodes())) { String nodeName = cleanNodeName(node.getNodeName()); if (!"item".equals(nodeName)) continue; final NodeHolder nodeHolder = new NodeHolder(node); final String state = getState(nodeHolder); final String ip = getIp(name, nodeHolder); final String instanceName = getInstanceName(nodeHolder); if (ip != null) { if (!acceptState(state)) { logger.finest(format("Ignoring EC2 instance [%s][%s] reason: the instance is not running but %s", instanceName, ip, state)); } else if (!acceptTag(awsConfig, node)) { logger.finest(format("Ignoring EC2 instance [%s][%s] reason: tag-key/tag-value don't match", instanceName, ip)); } else if (!acceptGroupName(awsConfig, node)) { logger.finest(format("Ignoring EC2 instance [%s][%s] reason: security-group-name doesn't match", instanceName, ip)); } else { list.add(ip); logger.finest(format("Accepting EC2 instance [%s][%s]",instanceName, ip)); } } } return list; } private boolean acceptState(String state) { return "running".equals(state); } private static String getState(NodeHolder nodeHolder) { final NodeHolder instancestate = nodeHolder.getSub("instancestate"); return instancestate.getSub("name").getNode().getFirstChild().getNodeValue(); } private static String getInstanceName(NodeHolder nodeHolder) { final NodeHolder tagSetNode = nodeHolder.getSub("tagset"); if (tagSetNode.getNode() == null) { return null; } final NodeList childNodes = tagSetNode.getNode().getChildNodes(); for (int k = 0; k < childNodes.getLength(); k++) { Node item = childNodes.item(k); if (!item.getNodeName().equals("item")) continue; NodeHolder itemHolder = new NodeHolder(item); final Node keyNode = itemHolder.getSub("key").getNode(); if (keyNode == null || keyNode.getFirstChild() == null) continue; final String nodeValue = keyNode.getFirstChild().getNodeValue(); if (!"Name".equals(nodeValue)) continue; final Node valueNode = itemHolder.getSub("value").getNode(); if (valueNode == null || valueNode.getFirstChild() == null) continue; return valueNode.getFirstChild().getNodeValue(); } return null; } private static String getIp(String name, NodeHolder nodeHolder) { final Node node1 = nodeHolder.getSub(name).getNode(); return node1 == null ? null : node1.getFirstChild().getNodeValue(); } private boolean acceptTag(AwsConfig awsConfig, Node node) { return applyTagFilter(node, awsConfig.getTagKey(), awsConfig.getTagValue()); } private boolean acceptGroupName(AwsConfig awsConfig, Node node) { return applyFilter(node, awsConfig.getSecurityGroupName(), "groupset", "groupname"); } private boolean applyFilter(Node node, String filter, String set, String filterField) { if (nullOrEmpty(filter)) { return true; } else { for (NodeHolder group : new NodeHolder(node).getSub(set).getSubNodes("item")) { NodeHolder nh = group.getSub(filterField); if (nh != null && nh.getNode().getFirstChild() != null && filter.equals(nh.getNode().getFirstChild().getNodeValue())) { return true; } } return false; } } private boolean applyTagFilter(Node node, String keyExpected, String valueExpected) { if (nullOrEmpty(keyExpected)) { return true; } else { for (NodeHolder group : new NodeHolder(node).getSub("tagset").getSubNodes("item")) { if (keyEquals(keyExpected, group) && (nullOrEmpty(valueExpected) || valueEquals(valueExpected, group))) { return true; } } return false; } } private boolean valueEquals(String valueExpected, NodeHolder group) { NodeHolder nhValue = group.getSub("value"); return nhValue != null && nhValue.getNode().getFirstChild() != null && valueExpected.equals(nhValue.getNode().getFirstChild().getNodeValue()); } private boolean nullOrEmpty(String keyExpected) { return keyExpected == null || keyExpected.equals(""); } private boolean keyEquals(String keyExpected, NodeHolder group) { NodeHolder nhKey = group.getSub("key"); return nhKey != null && nhKey.getNode().getFirstChild() != null && keyExpected.equals(nhKey.getNode().getFirstChild().getNodeValue()); } public Node getNode() { return node; } }
1no label
hazelcast-cloud_src_main_java_com_hazelcast_aws_utility_CloudyUtility.java
3,715
public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { IpFieldMapper.Builder builder = ipField(name); parseNumberField(builder, name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("null_value")) { builder.nullValue(propNode.toString()); } } return builder; } }
0true
src_main_java_org_elasticsearch_index_mapper_ip_IpFieldMapper.java
1,704
public abstract class OServerCommandAbstract implements OServerCommand { protected OServer server; /** * Default constructor. Disable cache of content at HTTP level */ public OServerCommandAbstract() { } @Override public boolean beforeExecute(final OHttpRequest iRequest, OHttpResponse iResponse) throws IOException { setNoCache(iResponse); return true; } @Override public boolean afterExecute(final OHttpRequest iRequest, OHttpResponse iResponse) throws IOException { return true; } protected String[] checkSyntax(final String iURL, final int iArgumentCount, final String iSyntax) { final List<String> parts = OStringSerializerHelper.smartSplit(iURL, OHttpResponse.URL_SEPARATOR, 1, -1, true, true, false); if (parts.size() < iArgumentCount) throw new OHttpRequestException(iSyntax); final String[] array = new String[parts.size()]; return decodeParts(parts.toArray(array)); } /** * urldecode each request part return the same array instance * * @param parts * @return */ private String[] decodeParts(final String[] parts) { try { if (parts == null) return null; for (int i = 0; i < parts.length; i++) { String part = parts[i]; if (part == null) continue; // NEEDS DECODING part = java.net.URLDecoder.decode(part, "UTF-8"); parts[i] = part; } return parts; } catch (Exception ex) { throw new OException(ex); } } public OServer getServer() { return server; } public void configure(final OServer server) { this.server = server; } protected void setNoCache(final OHttpResponse iResponse) { // DEFAULT = DON'T CACHE iResponse.setHeader("Cache-Control: no-cache, no-store, max-age=0, must-revalidate\r\nPragma: no-cache"); } }
1no label
server_src_main_java_com_orientechnologies_orient_server_network_protocol_http_command_OServerCommandAbstract.java
1,509
public class OObjectEntityClassHandler extends OEntityManagerClassHandler { private static final OObjectEntityClassHandler instance = new OObjectEntityClassHandler(); @Override public void registerEntityClass(Class<?> iClass) { if (!OObjectEntitySerializer.isToSerialize(iClass) && !iClass.isEnum()) registerEntityClass(iClass.getSimpleName(), iClass); } @Override public void registerEntityClass(String iClassName, Class<?> iClass) { if (!OObjectEntitySerializer.isToSerialize(iClass) && !iClass.isEnum()) { OObjectEntitySerializer.registerClass(iClass); super.registerEntityClass(iClassName, iClass); } } @Override public synchronized void deregisterEntityClass(Class<?> iClass) { if (!OObjectEntitySerializer.isToSerialize(iClass) && !iClass.isEnum()) { OObjectEntitySerializer.deregisterClass(iClass); super.deregisterEntityClass(iClass); } } public static synchronized OObjectEntityClassHandler getInstance() { return instance; } }
0true
object_src_main_java_com_orientechnologies_orient_object_entity_OObjectEntityClassHandler.java
524
public class FlushAction extends IndicesAction<FlushRequest, FlushResponse, FlushRequestBuilder> { public static final FlushAction INSTANCE = new FlushAction(); public static final String NAME = "indices/flush"; private FlushAction() { super(NAME); } @Override public FlushResponse newResponse() { return new FlushResponse(); } @Override public FlushRequestBuilder newRequestBuilder(IndicesAdminClient client) { return new FlushRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_flush_FlushAction.java
1,388
public abstract class HibernateStatisticsTestSupport extends HibernateTestSupport { protected SessionFactory sf; protected SessionFactory sf2; @Before public void postConstruct() { sf = createSessionFactory(getCacheProperties()); sf2 = createSessionFactory(getCacheProperties()); } @After public void preDestroy() { if (sf != null) { sf.close(); sf = null; } if (sf2 != null) { sf2.close(); sf2 = null; } Hazelcast.shutdownAll(); } protected HazelcastInstance getHazelcastInstance(SessionFactory sf) { return HazelcastAccessor.getHazelcastInstance(sf); } protected abstract Properties getCacheProperties(); protected void insertDummyEntities(int count) { insertDummyEntities(count, 0); } protected void insertDummyEntities(int count, int childCount) { Session session = sf.openSession(); Transaction tx = session.beginTransaction(); try { for (int i = 0; i < count; i++) { DummyEntity e = new DummyEntity((long) i, "dummy:" + i, i * 123456d, new Date()); session.save(e); for (int j = 0; j < childCount; j++) { DummyProperty p = new DummyProperty("key:" + j, e); session.save(p); } } tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } } @Test public void testEntity() { final HazelcastInstance hz = getHazelcastInstance(sf); assertNotNull(hz); final int count = 100; final int childCount = 3; insertDummyEntities(count, childCount); sleep(1); List<DummyEntity> list = new ArrayList<DummyEntity>(count); Session session = sf.openSession(); try { for (int i = 0; i < count; i++) { DummyEntity e = (DummyEntity) session.get(DummyEntity.class, (long) i); session.evict(e); list.add(e); } } finally { session.close(); } session = sf.openSession(); Transaction tx = session.beginTransaction(); try { for (DummyEntity dummy : list) { dummy.setDate(new Date()); session.update(dummy); } tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } Statistics stats = sf.getStatistics(); Map<?, ?> cache = hz.getMap(DummyEntity.class.getName()); Map<?, ?> propCache = hz.getMap(DummyProperty.class.getName()); Map<?, ?> propCollCache = hz.getMap(DummyEntity.class.getName() + ".properties"); assertEquals((childCount + 1) * count, stats.getEntityInsertCount()); // twice put of entity and properties (on load and update) and once put of collection // TODO: fix next assertion -> // assertEquals((childCount + 1) * count * 2, stats.getSecondLevelCachePutCount()); assertEquals(childCount * count, stats.getEntityLoadCount()); assertEquals(count, stats.getSecondLevelCacheHitCount()); // collection cache miss assertEquals(count, stats.getSecondLevelCacheMissCount()); assertEquals(count, cache.size()); assertEquals(count * childCount, propCache.size()); assertEquals(count, propCollCache.size()); sf.getCache().evictEntityRegion(DummyEntity.class); sf.getCache().evictEntityRegion(DummyProperty.class); assertEquals(0, cache.size()); assertEquals(0, propCache.size()); stats.logSummary(); } @Test public void testQuery() { final int entityCount = 10; final int queryCount = 3; insertDummyEntities(entityCount); sleep(1); List<DummyEntity> list = null; for (int i = 0; i < queryCount; i++) { list = executeQuery(sf); assertEquals(entityCount, list.size()); sleep(1); } assertNotNull(list); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); try { for (DummyEntity dummy : list) { session.delete(dummy); } tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } Statistics stats = sf.getStatistics(); assertEquals(1, stats.getQueryCachePutCount()); assertEquals(1, stats.getQueryCacheMissCount()); assertEquals(queryCount - 1, stats.getQueryCacheHitCount()); assertEquals(1, stats.getQueryExecutionCount()); assertEquals(entityCount, stats.getEntityInsertCount()); // FIXME // HazelcastRegionFactory puts into L2 cache 2 times; 1 on insert, 1 on query execution // assertEquals(entityCount, stats.getSecondLevelCachePutCount()); assertEquals(entityCount, stats.getEntityLoadCount()); assertEquals(entityCount, stats.getEntityDeleteCount()); assertEquals(entityCount * (queryCount - 1) * 2, stats.getSecondLevelCacheHitCount()); // collection cache miss assertEquals(entityCount, stats.getSecondLevelCacheMissCount()); stats.logSummary(); } protected List<DummyEntity> executeQuery(SessionFactory factory) { Session session = factory.openSession(); try { Query query = session.createQuery("from " + DummyEntity.class.getName()); query.setCacheable(true); return query.list(); } finally { session.close(); } } @Test public void testQuery2() { final int entityCount = 10; final int queryCount = 2; insertDummyEntities(entityCount); sleep(1); List<DummyEntity> list = null; for (int i = 0; i < queryCount; i++) { list = executeQuery(sf); assertEquals(entityCount, list.size()); sleep(1); } for (int i = 0; i < queryCount; i++) { list = executeQuery(sf2); assertEquals(entityCount, list.size()); sleep(1); } assertNotNull(list); DummyEntity toDelete = list.get(0); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); try { session.delete(toDelete); tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } assertEquals(entityCount - 1, executeQuery(sf).size()); assertEquals(entityCount - 1, executeQuery(sf2).size()); } }
0true
hazelcast-hibernate_hazelcast-hibernate4_src_test_java_com_hazelcast_hibernate_HibernateStatisticsTestSupport.java
2,887
@AnalysisSettingsRequired public class MappingCharFilterFactory extends AbstractCharFilterFactory { private final NormalizeCharMap normMap; @Inject public MappingCharFilterFactory(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name); List<String> rules = Analysis.getWordList(env, settings, "mappings"); if (rules == null) { throw new ElasticsearchIllegalArgumentException("mapping requires either `mappings` or `mappings_path` to be configured"); } NormalizeCharMap.Builder normMapBuilder = new NormalizeCharMap.Builder(); parseRules(rules, normMapBuilder); normMap = normMapBuilder.build(); } @Override public Reader create(Reader tokenStream) { return new MappingCharFilter(normMap, tokenStream); } // source => target private static Pattern rulePattern = Pattern.compile("(.*)\\s*=>\\s*(.*)\\s*$"); /** * parses a list of MappingCharFilter style rules into a normalize char map */ private void parseRules(List<String> rules, NormalizeCharMap.Builder map) { for (String rule : rules) { Matcher m = rulePattern.matcher(rule); if (!m.find()) throw new RuntimeException("Invalid Mapping Rule : [" + rule + "]"); String lhs = parseString(m.group(1).trim()); String rhs = parseString(m.group(2).trim()); if (lhs == null || rhs == null) throw new RuntimeException("Invalid Mapping Rule : [" + rule + "]. Illegal mapping."); map.add(lhs, rhs); } } char[] out = new char[256]; private String parseString(String s) { int readPos = 0; int len = s.length(); int writePos = 0; while (readPos < len) { char c = s.charAt(readPos++); if (c == '\\') { if (readPos >= len) throw new RuntimeException("Invalid escaped char in [" + s + "]"); c = s.charAt(readPos++); switch (c) { case '\\': c = '\\'; break; case 'n': c = '\n'; break; case 't': c = '\t'; break; case 'r': c = '\r'; break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'u': if (readPos + 3 >= len) throw new RuntimeException("Invalid escaped char in [" + s + "]"); c = (char) Integer.parseInt(s.substring(readPos, readPos + 4), 16); readPos += 4; break; } } out[writePos++] = c; } return new String(out, 0, writePos); } }
0true
src_main_java_org_elasticsearch_index_analysis_MappingCharFilterFactory.java
295
.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { if (!restoring) { IRegion r = RestorePreviousSelectionAction.this.editor.getSelection(); if (r.getLength()==0) { previous.clear(); } previous.add(r);//new Region(r.getOffset(), r.getLength())); if (previous.size()>20) { previous.remove(0); } setEnabled(previous.size()>1); } } });
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_RestorePreviousSelectionAction.java
242
private static class KeyIterationPredicate implements Predicate<Row<ByteBuffer, ByteBuffer>> { @Override public boolean apply(@Nullable Row<ByteBuffer, ByteBuffer> row) { return (row != null) && row.getColumns().size() > 0; } }
0true
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_astyanax_AstyanaxKeyColumnValueStore.java
1,414
clusterService.submitStateUpdateTask("remove-index-template [" + request.name + "]", Priority.URGENT, new TimeoutClusterStateUpdateTask() { @Override public TimeValue timeout() { return request.masterTimeout; } @Override public void onFailure(String source, Throwable t) { listener.onFailure(t); } @Override public ClusterState execute(ClusterState currentState) { Set<String> templateNames = Sets.newHashSet(); for (ObjectCursor<String> cursor : currentState.metaData().templates().keys()) { String templateName = cursor.value; if (Regex.simpleMatch(request.name, templateName)) { templateNames.add(templateName); } } if (templateNames.isEmpty()) { // if its a match all pattern, and no templates are found (we have none), don't // fail with index missing... if (Regex.isMatchAllPattern(request.name)) { return currentState; } throw new IndexTemplateMissingException(request.name); } MetaData.Builder metaData = MetaData.builder(currentState.metaData()); for (String templateName : templateNames) { metaData.removeTemplate(templateName); } return ClusterState.builder(currentState).metaData(metaData).build(); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { listener.onResponse(new RemoveResponse(true)); } });
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataIndexTemplateService.java
1,019
applyTailIndexes(lastIndexValuesMajor, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } });
0true
core_src_main_java_com_orientechnologies_orient_core_sql_OChainedIndexProxy.java
1,536
public class ManagedConnectionFactoryImpl extends JcaBase implements ManagedConnectionFactory, ResourceAdapterAssociation { private static final long serialVersionUID = -4889598421534961926L; /** * Identity generator */ private static final AtomicInteger ID_GEN = new AtomicInteger(); /** * Identity */ private final transient int id; /** * Access to this resource adapter instance itself */ private ResourceAdapterImpl resourceAdapter; /** * Definies which events should be traced * * @see HzConnectionEvent */ private Set<HzConnectionEvent> hzConnectionTracingEvents; /** * Should connection events be traced or not * * @see #hzConnectionTracingEvents */ private boolean connectionTracingDetail; public ManagedConnectionFactoryImpl() { id = ID_GEN.incrementAndGet(); } /* (non-Javadoc) * @see javax.resource.spi.ManagedConnectionFactory#createConnectionFactory() */ public HazelcastConnectionFactory createConnectionFactory() throws ResourceException { return createConnectionFactory(null); } /* (non-Javadoc) * @see javax.resource.spi.ManagedConnectionFactory#createConnectionFactory(javax.resource.spi.ConnectionManager) */ public HazelcastConnectionFactory createConnectionFactory(ConnectionManager cm) throws ResourceException { log(Level.FINEST, "createConnectionFactory cm: " + cm); logHzConnectionEvent(this, HzConnectionEvent.FACTORY_INIT); return new ConnectionFactoryImpl(this, cm); } /* (non-Javadoc) * @see javax.resource.spi.ManagedConnectionFactory * #createManagedConnection(javax.security.auth.Subject, javax.resource.spi.ConnectionRequestInfo) */ public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { log(Level.FINEST, "createManagedConnection"); return new ManagedConnectionImpl(cxRequestInfo, this); } /** * Getter for the RAR property 'connectionTracingEvents' */ public String getConnectionTracingEvents() { return this.hzConnectionTracingEvents.toString(); } /** * Setter for the RAR property 'connectionTracingDetails'. * This method is called by the container */ public void setConnectionTracingDetail(boolean connectionTracingDetail) { this.connectionTracingDetail = connectionTracingDetail; } /** * Getter for the RAR property 'connectionTracingDetails' */ public boolean isConnectionTracingDetail() { return connectionTracingDetail; } /* (non-Javadoc) * @see javax.resource.spi.ResourceAdapterAssociation#getResourceAdapter() */ public ResourceAdapterImpl getResourceAdapter() { return resourceAdapter; } /* (non-Javadoc) * @see javax.resource.spi.ResourceAdapterAssociation#setResourceAdapter(javax.resource.spi.ResourceAdapter) */ public void setResourceAdapter(ResourceAdapter resourceAdapter) throws ResourceException { assert resourceAdapter != null; if (resourceAdapter instanceof ResourceAdapterImpl) { this.resourceAdapter = (ResourceAdapterImpl) resourceAdapter; } else { throw new ResourceException(resourceAdapter + " is not the expected ResoruceAdapterImpl but " + resourceAdapter.getClass()); } } /** * Logs (or silently drops) the provided connection event if configured so * * @param eventSource The source from where the event originates * @param event The event to log */ void logHzConnectionEvent(Object eventSource, HzConnectionEvent event) { if (hzConnectionTracingEvents.contains(event)) { StringBuilder sb = new StringBuilder("HZ Connection Event <<"); sb.append(event).append(">> for ").append(eventSource); sb.append(" in thread [").append(Thread.currentThread().getName()); sb.append("]"); if (isConnectionTracingDetail()) { log(Level.INFO, sb.toString()); } else { // log(Level.INFO, sb.toString(), new Exception("Hz Connection Event Call Stack")); } } } /* (non-Javadoc) * @see javax.resource.spi.ManagedConnectionFactory * #matchManagedConnections(java.util.Set, javax.security.auth.Subject, javax.resource.spi.ConnectionRequestInfo) */ public ManagedConnection matchManagedConnections(@SuppressWarnings("rawtypes") Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { log(Level.FINEST, "matchManagedConnections"); if ((null != connectionSet) && !connectionSet.isEmpty()) { for (Object con : (Set<?>) connectionSet) { if (con instanceof ManagedConnectionImpl) { ManagedConnectionImpl conn = (ManagedConnectionImpl) con; ConnectionRequestInfo otherCxRequestInfo = conn.getCxRequestInfo(); if (null == otherCxRequestInfo || otherCxRequestInfo.equals(cxRequestInfo)) { return conn; } } else { log(Level.WARNING, "Unexpected element in list: " + con); } } } // null is interpreted as "create new one" by the container return null; } /** * Setter for the property 'connectionTracingEvents'. * This method is called by the container * * @param tracingSpec A comma delimited list of {@link HzConnectionEvent} */ public void setConnectionTracingEvents(String tracingSpec) { if ((null != tracingSpec) && (0 < tracingSpec.length())) { List<HzConnectionEvent> traceEvents = new ArrayList<HzConnectionEvent>(); for (String traceEventId : tracingSpec.split(",")) { traceEventId = traceEventId.trim(); try { HzConnectionEvent traceEvent = HzConnectionEvent.valueOf(traceEventId); if (null != traceEvent) { traceEvents.add(traceEvent); } } catch (IllegalArgumentException iae) { log(Level.WARNING, "Ignoring illegal token \"" + traceEventId + "\" from connection config-property " + "connectionTracingEvents, valid tokens are " + EnumSet.allOf(HzConnectionEvent.class)); } } this.hzConnectionTracingEvents = EnumSet.copyOf(traceEvents); } else { this.hzConnectionTracingEvents = emptySet(); } } @Override public String toString() { return "hazelcast.ManagedConnectionFactoryImpl [" + id + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ManagedConnectionFactoryImpl other = (ManagedConnectionFactoryImpl) obj; if (id != other.id) { return false; } return true; } }
0true
hazelcast-ra_hazelcast-jca_src_main_java_com_hazelcast_jca_ManagedConnectionFactoryImpl.java
2,619
return AccessController.doPrivileged(new PrivilegedAction<Unsafe>() { @Override public Unsafe run() { try { Class<Unsafe> type = Unsafe.class; try { Field field = type.getDeclaredField("theUnsafe"); field.setAccessible(true); return type.cast(field.get(type)); } catch (Exception e) { for (Field field : type.getDeclaredFields()) { if (type.isAssignableFrom(field.getType())) { field.setAccessible(true); return type.cast(field.get(type)); } } } } catch (Exception e) { throw new RuntimeException("Unsafe unavailable", e); } throw new RuntimeException("Unsafe unavailable"); } });
1no label
hazelcast_src_main_java_com_hazelcast_nio_UnsafeHelper.java
1,249
Collections.sort(bufferPoolLRU, new Comparator<OMMapBufferEntry>() { public int compare(final OMMapBufferEntry o1, final OMMapBufferEntry o2) { return (int) (o1.getLastUsed() - o2.getLastUsed()); } });
0true
core_src_main_java_com_orientechnologies_orient_core_storage_fs_OMMapManagerOld.java
2,009
protected enum STORE_EVENTS { STORE, STORE_ALL, DELETE, DELETE_ALL, LOAD, LOAD_ALL, LOAD_ALL_KEYS }
0true
hazelcast_src_test_java_com_hazelcast_map_mapstore_MapStoreTest.java
2,389
interface BigArray extends Releasable { /** Return the length of this array. */ public long size(); }
0true
src_main_java_org_elasticsearch_common_util_BigArray.java
1,869
@Component("blAdminRequestProcessor") public class BroadleafAdminRequestProcessor extends AbstractBroadleafWebRequestProcessor { protected final Log LOG = LogFactory.getLog(getClass()); @Resource(name = "blSiteResolver") protected BroadleafSiteResolver siteResolver; @Resource(name = "messageSource") protected MessageSource messageSource; @Resource(name = "blLocaleResolver") protected BroadleafLocaleResolver localeResolver; @Resource(name = "blAdminTimeZoneResolver") protected BroadleafTimeZoneResolver broadleafTimeZoneResolver; @Resource(name = "blCurrencyResolver") protected BroadleafCurrencyResolver currencyResolver; @Override public void process(WebRequest request) throws SiteNotFoundException { Site site = siteResolver.resolveSite(request); BroadleafRequestContext brc = new BroadleafRequestContext(); BroadleafRequestContext.setBroadleafRequestContext(brc); brc.setSite(site); brc.setWebRequest(request); brc.setIgnoreSite(site == null); Locale locale = localeResolver.resolveLocale(request); brc.setLocale(locale); brc.setMessageSource(messageSource); TimeZone timeZone = broadleafTimeZoneResolver.resolveTimeZone(request); brc.setTimeZone(timeZone); BroadleafCurrency currency = currencyResolver.resolveCurrency(request); brc.setBroadleafCurrency(currency); } @Override public void postProcess(WebRequest request) { ThreadLocalManager.remove(); //temporary workaround for Thymeleaf issue #18 (resolved in version 2.1) //https://github.com/thymeleaf/thymeleaf-spring3/issues/18 try { Field currentProcessLocale = TemplateEngine.class.getDeclaredField("currentProcessLocale"); currentProcessLocale.setAccessible(true); ((ThreadLocal) currentProcessLocale.get(null)).remove(); Field currentProcessTemplateEngine = TemplateEngine.class.getDeclaredField("currentProcessTemplateEngine"); currentProcessTemplateEngine.setAccessible(true); ((ThreadLocal) currentProcessTemplateEngine.get(null)).remove(); Field currentProcessTemplateName = TemplateEngine.class.getDeclaredField("currentProcessTemplateName"); currentProcessTemplateName.setAccessible(true); ((ThreadLocal) currentProcessTemplateName.get(null)).remove(); } catch (Throwable e) { LOG.warn("Unable to remove Thymeleaf threadlocal variables from request thread", e); } } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_web_filter_BroadleafAdminRequestProcessor.java
4,077
public class TopChildrenQuery extends Query { private static final ParentDocComparator PARENT_DOC_COMP = new ParentDocComparator(); private final CacheRecycler cacheRecycler; private final String parentType; private final String childType; private final ScoreType scoreType; private final int factor; private final int incrementalFactor; private final Query originalChildQuery; // This field will hold the rewritten form of originalChildQuery, so that we can reuse it private Query rewrittenChildQuery; private IndexReader rewriteIndexReader; // Note, the query is expected to already be filtered to only child type docs public TopChildrenQuery(Query childQuery, String childType, String parentType, ScoreType scoreType, int factor, int incrementalFactor, CacheRecycler cacheRecycler) { this.originalChildQuery = childQuery; this.childType = childType; this.parentType = parentType; this.scoreType = scoreType; this.factor = factor; this.incrementalFactor = incrementalFactor; this.cacheRecycler = cacheRecycler; } // Rewrite invocation logic: // 1) query_then_fetch (default): Rewrite is execute as part of the createWeight invocation, when search child docs. // 2) dfs_query_then_fetch:: First rewrite and then createWeight is executed. During query phase rewrite isn't // executed any more because searchContext#queryRewritten() returns true. @Override public Query rewrite(IndexReader reader) throws IOException { if (rewrittenChildQuery == null) { rewrittenChildQuery = originalChildQuery.rewrite(reader); rewriteIndexReader = reader; } // We can always return the current instance, and we can do this b/c the child query is executed separately // before the main query (other scope) in a different IS#search() invocation than the main query. // In fact we only need override the rewrite method because for the dfs phase, to get also global document // frequency for the child query. return this; } @Override public void extractTerms(Set<Term> terms) { rewrittenChildQuery.extractTerms(terms); } @Override public Weight createWeight(IndexSearcher searcher) throws IOException { Recycler.V<ObjectObjectOpenHashMap<Object, ParentDoc[]>> parentDocs = cacheRecycler.hashMap(-1); SearchContext searchContext = SearchContext.current(); searchContext.idCache().refresh(searchContext.searcher().getTopReaderContext().leaves()); int parentHitsResolved; int requestedDocs = (searchContext.from() + searchContext.size()); if (requestedDocs <= 0) { requestedDocs = 1; } int numChildDocs = requestedDocs * factor; Query childQuery; if (rewrittenChildQuery == null) { childQuery = rewrittenChildQuery = searcher.rewrite(originalChildQuery); } else { assert rewriteIndexReader == searcher.getIndexReader(); childQuery = rewrittenChildQuery; } IndexSearcher indexSearcher = new IndexSearcher(searcher.getIndexReader()); indexSearcher.setSimilarity(searcher.getSimilarity()); while (true) { parentDocs.v().clear(); TopDocs topChildDocs = indexSearcher.search(childQuery, numChildDocs); parentHitsResolved = resolveParentDocuments(topChildDocs, searchContext, parentDocs); // check if we found enough docs, if so, break if (parentHitsResolved >= requestedDocs) { break; } // if we did not find enough docs, check if it make sense to search further if (topChildDocs.totalHits <= numChildDocs) { break; } // if not, update numDocs, and search again numChildDocs *= incrementalFactor; if (numChildDocs > topChildDocs.totalHits) { numChildDocs = topChildDocs.totalHits; } } ParentWeight parentWeight = new ParentWeight(rewrittenChildQuery.createWeight(searcher), parentDocs); searchContext.addReleasable(parentWeight); return parentWeight; } int resolveParentDocuments(TopDocs topDocs, SearchContext context, Recycler.V<ObjectObjectOpenHashMap<Object, ParentDoc[]>> parentDocs) { int parentHitsResolved = 0; Recycler.V<ObjectObjectOpenHashMap<Object, Recycler.V<IntObjectOpenHashMap<ParentDoc>>>> parentDocsPerReader = cacheRecycler.hashMap(context.searcher().getIndexReader().leaves().size()); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { int readerIndex = ReaderUtil.subIndex(scoreDoc.doc, context.searcher().getIndexReader().leaves()); AtomicReaderContext subContext = context.searcher().getIndexReader().leaves().get(readerIndex); int subDoc = scoreDoc.doc - subContext.docBase; // find the parent id HashedBytesArray parentId = context.idCache().reader(subContext.reader()).parentIdByDoc(parentType, subDoc); if (parentId == null) { // no parent found continue; } // now go over and find the parent doc Id and reader tuple for (AtomicReaderContext atomicReaderContext : context.searcher().getIndexReader().leaves()) { AtomicReader indexReader = atomicReaderContext.reader(); int parentDocId = context.idCache().reader(indexReader).docById(parentType, parentId); Bits liveDocs = indexReader.getLiveDocs(); if (parentDocId != -1 && (liveDocs == null || liveDocs.get(parentDocId))) { // we found a match, add it and break Recycler.V<IntObjectOpenHashMap<ParentDoc>> readerParentDocs = parentDocsPerReader.v().get(indexReader.getCoreCacheKey()); if (readerParentDocs == null) { readerParentDocs = cacheRecycler.intObjectMap(indexReader.maxDoc()); parentDocsPerReader.v().put(indexReader.getCoreCacheKey(), readerParentDocs); } ParentDoc parentDoc = readerParentDocs.v().get(parentDocId); if (parentDoc == null) { parentHitsResolved++; // we have a hit on a parent parentDoc = new ParentDoc(); parentDoc.docId = parentDocId; parentDoc.count = 1; parentDoc.maxScore = scoreDoc.score; parentDoc.sumScores = scoreDoc.score; readerParentDocs.v().put(parentDocId, parentDoc); } else { parentDoc.count++; parentDoc.sumScores += scoreDoc.score; if (scoreDoc.score > parentDoc.maxScore) { parentDoc.maxScore = scoreDoc.score; } } } } } boolean[] states = parentDocsPerReader.v().allocated; Object[] keys = parentDocsPerReader.v().keys; Object[] values = parentDocsPerReader.v().values; for (int i = 0; i < states.length; i++) { if (states[i]) { Recycler.V<IntObjectOpenHashMap<ParentDoc>> value = (Recycler.V<IntObjectOpenHashMap<ParentDoc>>) values[i]; ParentDoc[] _parentDocs = value.v().values().toArray(ParentDoc.class); Arrays.sort(_parentDocs, PARENT_DOC_COMP); parentDocs.v().put(keys[i], _parentDocs); Releasables.release(value); } } Releasables.release(parentDocsPerReader); return parentHitsResolved; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } TopChildrenQuery that = (TopChildrenQuery) obj; if (!originalChildQuery.equals(that.originalChildQuery)) { return false; } if (!childType.equals(that.childType)) { return false; } if (incrementalFactor != that.incrementalFactor) { return false; } if (getBoost() != that.getBoost()) { return false; } return true; } @Override public int hashCode() { int result = originalChildQuery.hashCode(); result = 31 * result + parentType.hashCode(); result = 31 * result + incrementalFactor; result = 31 * result + Float.floatToIntBits(getBoost()); return result; } public String toString(String field) { StringBuilder sb = new StringBuilder(); sb.append("score_child[").append(childType).append("/").append(parentType).append("](").append(originalChildQuery.toString(field)).append(')'); sb.append(ToStringUtils.boost(getBoost())); return sb.toString(); } private class ParentWeight extends Weight implements Releasable { private final Weight queryWeight; private final Recycler.V<ObjectObjectOpenHashMap<Object, ParentDoc[]>> parentDocs; public ParentWeight(Weight queryWeight, Recycler.V<ObjectObjectOpenHashMap<Object, ParentDoc[]>> parentDocs) throws IOException { this.queryWeight = queryWeight; this.parentDocs = parentDocs; } public Query getQuery() { return TopChildrenQuery.this; } @Override public float getValueForNormalization() throws IOException { float sum = queryWeight.getValueForNormalization(); sum *= getBoost() * getBoost(); return sum; } @Override public void normalize(float norm, float topLevelBoost) { // Nothing to normalize } @Override public boolean release() throws ElasticsearchException { Releasables.release(parentDocs); return true; } @Override public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException { ParentDoc[] readerParentDocs = parentDocs.v().get(context.reader().getCoreCacheKey()); if (readerParentDocs != null) { if (scoreType == ScoreType.MAX) { return new ParentScorer(this, readerParentDocs) { @Override public float score() throws IOException { assert doc.docId >= 0 || doc.docId < NO_MORE_DOCS; return doc.maxScore; } }; } else if (scoreType == ScoreType.AVG) { return new ParentScorer(this, readerParentDocs) { @Override public float score() throws IOException { assert doc.docId >= 0 || doc.docId < NO_MORE_DOCS; return doc.sumScores / doc.count; } }; } else if (scoreType == ScoreType.SUM) { return new ParentScorer(this, readerParentDocs) { @Override public float score() throws IOException { assert doc.docId >= 0 || doc.docId < NO_MORE_DOCS; return doc.sumScores; } }; } throw new ElasticsearchIllegalStateException("No support for score type [" + scoreType + "]"); } return new EmptyScorer(this); } @Override public Explanation explain(AtomicReaderContext context, int doc) throws IOException { return new Explanation(getBoost(), "not implemented yet..."); } } private static abstract class ParentScorer extends Scorer { private final ParentDoc spare = new ParentDoc(); protected final ParentDoc[] docs; protected ParentDoc doc = spare; private int index = -1; ParentScorer(ParentWeight weight, ParentDoc[] docs) throws IOException { super(weight); this.docs = docs; spare.docId = -1; spare.count = -1; } @Override public final int docID() { return doc.docId; } @Override public final int advance(int target) throws IOException { return slowAdvance(target); } @Override public final int nextDoc() throws IOException { if (++index >= docs.length) { doc = spare; doc.count = 0; return (doc.docId = NO_MORE_DOCS); } return (doc = docs[index]).docId; } @Override public final int freq() throws IOException { return doc.count; // The number of matches in the child doc, which is propagated to parent } @Override public final long cost() { return docs.length; } } private static class ParentDocComparator implements Comparator<ParentDoc> { @Override public int compare(ParentDoc o1, ParentDoc o2) { return o1.docId - o2.docId; } } private static class ParentDoc { public int docId; public int count; public float maxScore = Float.NaN; public float sumScores = 0; } }
1no label
src_main_java_org_elasticsearch_index_search_child_TopChildrenQuery.java
182
{ @Override public void notify( DataSourceRegistrationListener listener ) { listener.unregisteredDataSource( dataSource ); } } );
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_XaDataSourceManager.java
1,468
static class AttributesRoutings { public final ImmutableList<ShardRouting> withSameAttribute; public final ImmutableList<ShardRouting> withoutSameAttribute; public final int totalSize; AttributesRoutings(ImmutableList<ShardRouting> withSameAttribute, ImmutableList<ShardRouting> withoutSameAttribute) { this.withSameAttribute = withSameAttribute; this.withoutSameAttribute = withoutSameAttribute; this.totalSize = withoutSameAttribute.size() + withSameAttribute.size(); } }
0true
src_main_java_org_elasticsearch_cluster_routing_IndexShardRoutingTable.java
1,509
public class CartStateInterceptor implements WebRequestInterceptor { @Resource(name = "blCartStateRequestProcessor") protected CartStateRequestProcessor cartStateProcessor; @Override public void preHandle(WebRequest request) throws Exception { cartStateProcessor.process(request); } @Override public void postHandle(WebRequest request, ModelMap model) throws Exception { // unimplemented } @Override public void afterCompletion(WebRequest request, Exception ex) throws Exception { // unimplemented } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_order_security_CartStateInterceptor.java
1,146
@edu.umd.cs.findbugs.annotations.SuppressWarnings("SE_BAD_FIELD") public class EntryEvent<K, V> extends EventObject { private static final long serialVersionUID = -2296203982913729851L; protected final EntryEventType entryEventType; protected K key; protected V oldValue; protected V value; protected final Member member; protected final String name; public EntryEvent(Object source, Member member, int eventType, K key, V value) { this(source, member, eventType, key, null, value); } public EntryEvent(Object source, Member member, int eventType, K key, V oldValue, V value) { super(source); this.name = (String) source; this.member = member; this.key = key; this.oldValue = oldValue; this.value = value; this.entryEventType = EntryEventType.getByType(eventType); } @Override public Object getSource() { return name; } /** * Returns the key of the entry event * * @return the key */ public K getKey() { return key; } /** * Returns the old value of the entry event * * @return */ public V getOldValue() { return this.oldValue; } /** * Returns the value of the entry event * * @return */ public V getValue() { return value; } /** * Returns the member fired this event. * * @return the member fired this event. */ public Member getMember() { return member; } /** * Return the event type * * @return event type */ public EntryEventType getEventType() { return entryEventType; } /** * Returns the name of the map for this event. * * @return name of the map. */ public String getName() { return name; } @Override public String toString() { return "EntryEvent {" + getSource() + "} key=" + getKey() + ", oldValue=" + getOldValue() + ", value=" + getValue() + ", event=" + entryEventType + ", by " + member; } }
1no label
hazelcast_src_main_java_com_hazelcast_core_EntryEvent.java
3,161
public interface AtomicNumericFieldData extends AtomicFieldData<ScriptDocValues> { LongValues getLongValues(); DoubleValues getDoubleValues(); }
0true
src_main_java_org_elasticsearch_index_fielddata_AtomicNumericFieldData.java
1,458
public class OCommandExecutorSQLDeleteEdge extends OCommandExecutorSQLSetAware implements OCommandResultListener { public static final String NAME = "DELETE EDGE"; private ORecordId rid; private String fromExpr; private String toExpr; private int removed = 0; private OCommandRequest query; private OSQLFilter compiledFilter; @SuppressWarnings("unchecked") public OCommandExecutorSQLDeleteEdge parse(final OCommandRequest iRequest) { final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph(); init((OCommandRequestText) iRequest); parserRequiredKeyword("DELETE"); parserRequiredKeyword("EDGE"); OClass clazz = null; String temp = parseOptionalWord(true); while (temp != null) { if (temp.equals("FROM")) { fromExpr = parserRequiredWord(false, "Syntax error", " =><,\r\n"); if (rid != null) throwSyntaxErrorException("FROM '" + fromExpr + "' is not allowed when specify a RID (" + rid + ")"); } else if (temp.equals("TO")) { toExpr = parserRequiredWord(false, "Syntax error", " =><,\r\n"); if (rid != null) throwSyntaxErrorException("TO '" + toExpr + "' is not allowed when specify a RID (" + rid + ")"); } else if (temp.startsWith("#")) { rid = new ORecordId(temp); if (fromExpr != null || toExpr != null) throwSyntaxErrorException("Specifying the RID " + rid + " is not allowed with FROM/TO"); } else if (temp.equals(KEYWORD_WHERE)) { if (clazz == null) // ASSIGN DEFAULT CLASS clazz = graph.getEdgeType(OGraphDatabase.EDGE_CLASS_NAME); final String condition = parserGetCurrentPosition() > -1 ? " " + parserText.substring(parserGetCurrentPosition()) : ""; compiledFilter = OSQLEngine.getInstance().parseCondition(condition, getContext(), KEYWORD_WHERE); break; } else if (temp.length() > 0) { // GET/CHECK CLASS NAME clazz = graph.getEdgeType(temp); if (clazz == null) throw new OCommandSQLParsingException("Class '" + temp + " was not found"); } temp = parseOptionalWord(true); if (parserIsEnded()) break; } if (fromExpr == null && toExpr == null && rid == null) if (clazz == null) // DELETE ALL THE EDGES query = graph.getRawGraph().command(new OSQLAsynchQuery<ODocument>("select from E", this)); else // DELETE EDGES OF CLASS X query = graph.getRawGraph().command(new OSQLAsynchQuery<ODocument>("select from " + clazz.getName(), this)); return this; } /** * Execute the command and return the ODocument object created. */ public Object execute(final Map<Object, Object> iArgs) { if (fromExpr == null && toExpr == null && rid == null && query == null && compiledFilter == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph(); if (rid != null) { // REMOVE PUNCTUAL RID final OrientEdge e = graph.getEdge(rid); if (e != null) { e.remove(); removed = 1; } } else { // MULTIPLE EDGES final Set<OrientEdge> edges = new HashSet<OrientEdge>(); if (query == null) { // SELECTIVE TARGET Set<ORID> fromIds = null; if (fromExpr != null) fromIds = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), fromExpr); Set<ORID> toIds = null; if (toExpr != null) toIds = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), toExpr); if (fromIds != null && toIds != null) { // REMOVE ALL THE EDGES BETWEEN VERTICES for (ORID fromId : fromIds) for (Edge e : graph.getVertex(fromId).getEdges(Direction.OUT)) if (toIds.contains(((OrientEdge) e).getInVertex().getIdentity())) edges.add((OrientEdge) e); } else if (fromIds != null) // REMOVE ALL THE EDGES THAT START FROM A VERTEXES for (ORID fromId : fromIds) edges.add((OrientEdge) graph.getVertex(fromId).getEdges(Direction.OUT)); else if (toIds != null) // REMOVE ALL THE EDGES THAT ARRIVE TO A VERTEXES for (ORID toId : toIds) edges.add((OrientEdge) graph.getVertex(toId).getEdges(Direction.IN)); else throw new OCommandExecutionException("Invalid target"); if (compiledFilter != null) { // ADDITIONAL FILTERING for (Iterator<OrientEdge> it = edges.iterator(); it.hasNext();) { final OrientEdge edge = it.next(); if (!(Boolean) compiledFilter.evaluate((ODocument) edge.getRecord(), null, context)) it.remove(); } } // DELETE THE FOUND EDGES removed = edges.size(); for (OrientEdge edge : edges) edge.remove(); } else // TARGET IS A CLASS + OPTIONAL CONDITION query.execute(iArgs); } return removed; } /** * Delete the current edge. */ public boolean result(final Object iRecord) { final OIdentifiable id = (OIdentifiable) iRecord; if (compiledFilter != null) { // ADDITIONAL FILTERING if (!(Boolean) compiledFilter.evaluate((ODocument) id.getRecord(), null, context)) return false; } if (id.getIdentity().isValid()) { final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph(); final OrientEdge e = graph.getEdge(id); if (e != null) { e.remove(); removed++; return true; } } return false; } @Override public String getSyntax() { return "DELETE EDGE <rid>|FROM <rid>|TO <rid>|<[<class>] [WHERE <conditions>]>"; } @Override public void end() { } }
1no label
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_OCommandExecutorSQLDeleteEdge.java
1,265
@ClusterScope(scope = ElasticsearchIntegrationTest.Scope.TEST, numNodes = 0, transportClientRatio = 1.0) public class TransportClientTests extends ElasticsearchIntegrationTest { @Test public void testPickingUpChangesInDiscoveryNode() { String nodeName = cluster().startNode(ImmutableSettings.builder().put("node.data", false)); TransportClient client = (TransportClient) cluster().client(nodeName); assertThat(client.connectedNodes().get(0).dataNode(), Matchers.equalTo(false)); } }
0true
src_test_java_org_elasticsearch_client_transport_TransportClientTests.java
971
abstract class BaseLockOperation extends AbstractOperation implements PartitionAwareOperation, IdentifiedDataSerializable { public static final long DEFAULT_LOCK_TTL = Long.MAX_VALUE; public static final int ANY_THREAD = 0; protected ObjectNamespace namespace; protected Data key; protected long threadId; protected long ttl = DEFAULT_LOCK_TTL; protected transient Object response; private transient boolean asyncBackup; public BaseLockOperation() { } protected BaseLockOperation(ObjectNamespace namespace, Data key, long threadId) { this.namespace = namespace; this.key = key; this.threadId = threadId; } protected BaseLockOperation(ObjectNamespace namespace, Data key, long threadId, long timeout) { this.namespace = namespace; this.key = key; this.threadId = threadId; setWaitTimeout(timeout); } public BaseLockOperation(ObjectNamespace namespace, Data key, long threadId, long ttl, long timeout) { this.namespace = namespace; this.key = key; this.threadId = threadId; this.ttl = ttl; setWaitTimeout(timeout); } @Override public final Object getResponse() { return response; } protected final LockStoreImpl getLockStore() { LockServiceImpl service = getService(); return service.getLockStore(getPartitionId(), namespace); } public final int getSyncBackupCount() { if (asyncBackup) { return 0; } else { return getLockStore().getBackupCount(); } } public final int getAsyncBackupCount() { LockStoreImpl lockStore = getLockStore(); if (asyncBackup) { return lockStore.getBackupCount() + lockStore.getAsyncBackupCount(); } else { return lockStore.getAsyncBackupCount(); } } public final void setAsyncBackup(boolean asyncBackup) { this.asyncBackup = asyncBackup; } @Override public final String getServiceName() { return LockServiceImpl.SERVICE_NAME; } public final Data getKey() { return key; } @Override public int getFactoryId() { return LockDataSerializerHook.F_ID; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeObject(namespace); key.writeData(out); out.writeLong(threadId); out.writeLong(ttl); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); namespace = in.readObject(); key = new Data(); key.readData(in); threadId = in.readLong(); ttl = in.readLong(); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_lock_operations_BaseLockOperation.java
2,055
public final class StaticInjectionRequest implements Element { private final Object source; private final Class<?> type; StaticInjectionRequest(Object source, Class<?> type) { this.source = checkNotNull(source, "source"); this.type = checkNotNull(type, "type"); } public Object getSource() { return source; } public Class<?> getType() { return type; } /** * Returns the static methods and fields of {@code type} that will be injected to fulfill this * request. * * @return a possibly empty set of injection points. The set has a specified iteration order. All * fields are returned and then all methods. Within the fields, supertype fields are returned * before subtype fields. Similarly, supertype methods are returned before subtype methods. * @throws ConfigurationException if there is a malformed injection point on {@code type}, such as * a field with multiple binding annotations. The exception's {@link * ConfigurationException#getPartialValue() partial value} is a {@code Set<InjectionPoint>} * of the valid injection points. */ public Set<InjectionPoint> getInjectionPoints() throws ConfigurationException { return InjectionPoint.forStaticMethodsAndFields(type); } public void applyTo(Binder binder) { binder.withSource(getSource()).requestStaticInjection(type); } public <T> T acceptVisitor(ElementVisitor<T> visitor) { return visitor.visit(this); } }
0true
src_main_java_org_elasticsearch_common_inject_spi_StaticInjectionRequest.java
168
private static class TestXaCommand extends XaCommand { private final int totalSize; public TestXaCommand( int totalSize ) { this.totalSize = totalSize; } @Override public void execute() { // Do nothing } @Override public void writeToFile( LogBuffer buffer ) throws IOException { buffer.putInt( totalSize ); buffer.put( new byte[totalSize-4/*size of the totalSize integer*/] ); } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestLogPruneStrategy.java
2,023
public class DefaultBindingScopingVisitor<V> implements BindingScopingVisitor<V> { /** * Default visit implementation. Returns {@code null}. */ protected V visitOther() { return null; } public V visitEagerSingleton() { return visitOther(); } public V visitScope(Scope scope) { return visitOther(); } public V visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) { return visitOther(); } public V visitNoScoping() { return visitOther(); } }
0true
src_main_java_org_elasticsearch_common_inject_spi_DefaultBindingScopingVisitor.java
882
public class PromotableCandidateFulfillmentGroupOfferImpl implements PromotableCandidateFulfillmentGroupOffer { private static final long serialVersionUID = 1L; protected HashMap<OfferItemCriteria, List<PromotableOrderItem>> candidateQualifiersMap = new HashMap<OfferItemCriteria, List<PromotableOrderItem>>(); protected Offer offer; protected PromotableFulfillmentGroup promotableFulfillmentGroup; public PromotableCandidateFulfillmentGroupOfferImpl(PromotableFulfillmentGroup promotableFulfillmentGroup, Offer offer) { assert(offer != null); assert(promotableFulfillmentGroup != null); this.offer = offer; this.promotableFulfillmentGroup = promotableFulfillmentGroup; } @Override public HashMap<OfferItemCriteria, List<PromotableOrderItem>> getCandidateQualifiersMap() { return candidateQualifiersMap; } @Override public void setCandidateQualifiersMap(HashMap<OfferItemCriteria, List<PromotableOrderItem>> candidateItemsMap) { this.candidateQualifiersMap = candidateItemsMap; } protected Money getBasePrice() { Money priceToUse = null; if (promotableFulfillmentGroup.getFulfillmentGroup().getRetailFulfillmentPrice() != null) { priceToUse = promotableFulfillmentGroup.getFulfillmentGroup().getRetailFulfillmentPrice(); if ((offer.getApplyDiscountToSalePrice()) && (promotableFulfillmentGroup.getFulfillmentGroup().getSaleFulfillmentPrice() != null)) { priceToUse = promotableFulfillmentGroup.getFulfillmentGroup().getSaleFulfillmentPrice(); } } return priceToUse; } @Override public Money computeDiscountedAmount() { Money discountedAmount = new Money(0); Money priceToUse = getBasePrice(); if (priceToUse != null) { if (offer.getDiscountType().equals(OfferDiscountType.AMOUNT_OFF)) { discountedAmount = BroadleafCurrencyUtils.getMoney(offer.getValue(), promotableFulfillmentGroup.getFulfillmentGroup().getOrder().getCurrency()); } else if (offer.getDiscountType().equals(OfferDiscountType.FIX_PRICE)) { discountedAmount = priceToUse.subtract(BroadleafCurrencyUtils.getMoney(offer.getValue(), promotableFulfillmentGroup.getFulfillmentGroup().getOrder().getCurrency())); } else if (offer.getDiscountType().equals(OfferDiscountType.PERCENT_OFF)) { discountedAmount = priceToUse.multiply(offer.getValue().divide(new BigDecimal("100"))); } if (discountedAmount.greaterThan(priceToUse)) { discountedAmount = priceToUse; } } return discountedAmount; } @Override public Money getDiscountedPrice() { return getBasePrice().subtract(computeDiscountedAmount()); } @Override public Money getDiscountedAmount() { return computeDiscountedAmount(); } @Override public Offer getOffer() { return offer; } @Override public PromotableFulfillmentGroup getFulfillmentGroup() { return promotableFulfillmentGroup; } public int getPriority() { return offer.getPriority(); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableCandidateFulfillmentGroupOfferImpl.java
2,368
public class TrackableJobFuture<V> extends AbstractCompletableFuture<V> implements TrackableJob<V>, JobCompletableFuture<V> { private final String name; private final String jobId; private final JobTracker jobTracker; private final Collator collator; private final CountDownLatch latch; private final MapReduceService mapReduceService; private volatile boolean cancelled; public TrackableJobFuture(String name, String jobId, JobTracker jobTracker, NodeEngine nodeEngine, Collator collator) { super(nodeEngine, nodeEngine.getLogger(TrackableJobFuture.class)); this.name = name; this.jobId = jobId; this.jobTracker = jobTracker; this.collator = collator; this.latch = new CountDownLatch(1); this.mapReduceService = ((NodeEngineImpl) nodeEngine).getService(MapReduceService.SERVICE_NAME); } @Override public void setResult(Object result) { Object finalResult = result; // If collator is available we need to execute it now if (collator != null) { finalResult = collator.collate(((Map) finalResult).entrySet()); } if (finalResult instanceof Throwable && !(finalResult instanceof CancellationException)) { finalResult = new ExecutionException((Throwable) finalResult); } super.setResult(finalResult); latch.countDown(); } @Override public boolean cancel(boolean mayInterruptIfRunning) { Address jobOwner = mapReduceService.getLocalAddress(); if (!mapReduceService.registerJobSupervisorCancellation(name, jobId, jobOwner)) { return false; } JobSupervisor supervisor = mapReduceService.getJobSupervisor(name, jobId); if (supervisor == null || !supervisor.isOwnerNode()) { return false; } Exception exception = new CancellationException("Operation was cancelled by the user"); cancelled = supervisor.cancelAndNotify(exception); return cancelled; } @Override public boolean isCancelled() { return cancelled; } @Override public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { ValidationUtil.isNotNull(unit, "unit"); if (!latch.await(timeout, unit) || !isDone()) { throw new TimeoutException("timeout reached"); } return getResult(); } @Override public JobTracker getJobTracker() { return jobTracker; } @Override public String getName() { return name; } @Override public String getJobId() { return jobId; } @Override public ICompletableFuture<V> getCompletableFuture() { JobSupervisor supervisor = mapReduceService.getJobSupervisor(name, jobId); if (supervisor == null || !supervisor.isOwnerNode()) { return null; } return this; } @Override public JobProcessInformation getJobProcessInformation() { JobSupervisor supervisor = mapReduceService.getJobSupervisor(name, jobId); if (supervisor == null || !supervisor.isOwnerNode()) { return null; } return new JobProcessInformationAdapter(supervisor.getJobProcessInformation()); } /** * This class is just an adapter for retrieving the JobProcess information * from user codebase to prevent exposing the internal array. */ private static final class JobProcessInformationAdapter implements JobProcessInformation { private final JobProcessInformation processInformation; private JobProcessInformationAdapter(JobProcessInformation processInformation) { this.processInformation = processInformation; } @Override public JobPartitionState[] getPartitionStates() { JobPartitionState[] partitionStates = processInformation.getPartitionStates(); return Arrays.copyOf(partitionStates, partitionStates.length); } @Override public int getProcessedRecords() { return processInformation.getProcessedRecords(); } } }
1no label
hazelcast_src_main_java_com_hazelcast_mapreduce_impl_task_TrackableJobFuture.java
1,830
public interface MapInterceptor extends Serializable { /** * Intercept get operation before returning value. * Return another object to change the return value of get(..) * Returning null will cause the get(..) operation return original value, namely return null if you do not want to change anything. * <p/> * Mutations made to value do not affect the stored value. They do affect the returned value. * @param value the original value to be returned as the result of get(..) operation * @return the new value that will be returned by get(..) operation */ Object interceptGet(Object value); /** * Called after get(..) operation is completed. * <p/> * Mutations made to value do not affect the stored value. * @param value the value returned as the result of get(..) operation */ void afterGet(Object value); /** * Intercept put operation before modifying map data. * Return the object to be put into the map. * Returning null will cause the put(..) operation to operate as expected, namely no interception. * Throwing an exception will cancel the put operation. * <p/> * * @param oldValue the value currently in map * @param newValue the new value to be put * @return new value after intercept operation */ Object interceptPut(Object oldValue, Object newValue); /** * Called after put(..) operation is completed. * <p/> * * @param value the value returned as the result of put(..) operation */ void afterPut(Object value); /** * Intercept remove operation before removing the data. * Return the object to be returned as the result of remove operation. * Throwing an exception will cancel the remove operation. * <p/> * * @param removedValue the existing value to be removed * @return the value to be returned as the result of remove operation */ Object interceptRemove(Object removedValue); /** * Called after remove(..) operation is completed. * <p/> * * @param value the value returned as the result of remove(..) operation */ void afterRemove(Object value); }
0true
hazelcast_src_main_java_com_hazelcast_map_MapInterceptor.java
1,517
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> { private final ScriptEngine engine = new FaunusGremlinScriptEngine(); private SafeMapperOutputs outputs; private Text textWritable = new Text(); @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { final FileSystem fs = FileSystem.get(context.getConfiguration()); try { this.engine.eval(new InputStreamReader(fs.open(new Path(context.getConfiguration().get(SCRIPT_PATH))))); this.engine.put(ARGS, context.getConfiguration().getStrings(SCRIPT_ARGS)); this.engine.eval(SETUP_ARGS); } catch (Exception e) { throw new InterruptedException(e.getMessage()); } this.outputs = new SafeMapperOutputs(context); } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { if (value.hasPaths()) { final Object result; try { this.engine.put(V, value); result = engine.eval(MAP_V_ARGS); } catch (Exception e) { throw new InterruptedException(e.getMessage()); } this.textWritable.set((null == result) ? Tokens.NULL : result.toString()); this.outputs.write(Tokens.SIDEEFFECT, NullWritable.get(), this.textWritable); } this.outputs.write(Tokens.GRAPH, NullWritable.get(), value); } @Override public void cleanup(final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { try { this.engine.eval(CLEANUP_ARGS); } catch (Exception e) { throw new InterruptedException(e.getMessage()); } this.outputs.close(); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_ScriptMap.java
4,158
public class InternalIndexShard extends AbstractIndexShardComponent implements IndexShard { private final ThreadPool threadPool; private final IndexSettingsService indexSettingsService; private final MapperService mapperService; private final IndexQueryParserService queryParserService; private final IndexCache indexCache; private final InternalIndicesLifecycle indicesLifecycle; private final Store store; private final MergeSchedulerProvider mergeScheduler; private final Engine engine; private final Translog translog; private final IndexAliasesService indexAliasesService; private final ShardIndexingService indexingService; private final ShardSearchService searchService; private final ShardGetService getService; private final ShardIndexWarmerService shardWarmerService; private final ShardFilterCache shardFilterCache; private final ShardIdCache shardIdCache; private final ShardFieldData shardFieldData; private final PercolatorQueriesRegistry percolatorQueriesRegistry; private final ShardPercolateService shardPercolateService; private final CodecService codecService; private final ShardTermVectorService termVectorService; private final IndexFieldDataService indexFieldDataService; private final IndexService indexService; private final Object mutex = new Object(); private final String checkIndexOnStartup; private long checkIndexTook = 0; private volatile IndexShardState state; private TimeValue refreshInterval; private final TimeValue mergeInterval; private volatile ScheduledFuture refreshScheduledFuture; private volatile ScheduledFuture mergeScheduleFuture; private volatile ShardRouting shardRouting; private RecoveryStatus peerRecoveryStatus; private ApplyRefreshSettings applyRefreshSettings = new ApplyRefreshSettings(); private final MeanMetric refreshMetric = new MeanMetric(); private final MeanMetric flushMetric = new MeanMetric(); @Inject public InternalIndexShard(ShardId shardId, @IndexSettings Settings indexSettings, IndexSettingsService indexSettingsService, IndicesLifecycle indicesLifecycle, Store store, Engine engine, MergeSchedulerProvider mergeScheduler, Translog translog, ThreadPool threadPool, MapperService mapperService, IndexQueryParserService queryParserService, IndexCache indexCache, IndexAliasesService indexAliasesService, ShardIndexingService indexingService, ShardGetService getService, ShardSearchService searchService, ShardIndexWarmerService shardWarmerService, ShardFilterCache shardFilterCache, ShardIdCache shardIdCache, ShardFieldData shardFieldData, PercolatorQueriesRegistry percolatorQueriesRegistry, ShardPercolateService shardPercolateService, CodecService codecService, ShardTermVectorService termVectorService, IndexFieldDataService indexFieldDataService, IndexService indexService) { super(shardId, indexSettings); this.indicesLifecycle = (InternalIndicesLifecycle) indicesLifecycle; this.indexSettingsService = indexSettingsService; this.store = store; this.engine = engine; this.mergeScheduler = mergeScheduler; this.translog = translog; this.threadPool = threadPool; this.mapperService = mapperService; this.queryParserService = queryParserService; this.indexCache = indexCache; this.indexAliasesService = indexAliasesService; this.indexingService = indexingService; this.getService = getService.setIndexShard(this); this.termVectorService = termVectorService.setIndexShard(this); this.searchService = searchService; this.shardWarmerService = shardWarmerService; this.shardFilterCache = shardFilterCache; this.shardIdCache = shardIdCache; this.shardFieldData = shardFieldData; this.percolatorQueriesRegistry = percolatorQueriesRegistry; this.shardPercolateService = shardPercolateService; this.indexFieldDataService = indexFieldDataService; this.indexService = indexService; this.codecService = codecService; state = IndexShardState.CREATED; this.refreshInterval = indexSettings.getAsTime(INDEX_REFRESH_INTERVAL, engine.defaultRefreshInterval()); this.mergeInterval = indexSettings.getAsTime("index.merge.async_interval", TimeValue.timeValueSeconds(1)); indexSettingsService.addListener(applyRefreshSettings); logger.debug("state: [CREATED]"); this.checkIndexOnStartup = indexSettings.get("index.shard.check_on_startup", "false"); } public MergeSchedulerProvider mergeScheduler() { return this.mergeScheduler; } public Store store() { return this.store; } public Engine engine() { return engine; } public Translog translog() { return translog; } public ShardIndexingService indexingService() { return this.indexingService; } @Override public ShardGetService getService() { return this.getService; } @Override public ShardTermVectorService termVectorService() { return termVectorService; } @Override public IndexFieldDataService indexFieldDataService() { return indexFieldDataService; } @Override public MapperService mapperService() { return mapperService; } @Override public IndexService indexService() { return indexService; } @Override public ShardSearchService searchService() { return this.searchService; } @Override public ShardIndexWarmerService warmerService() { return this.shardWarmerService; } @Override public ShardFilterCache filterCache() { return this.shardFilterCache; } @Override public ShardIdCache idCache() { return this.shardIdCache; } @Override public ShardFieldData fieldData() { return this.shardFieldData; } @Override public ShardRouting routingEntry() { return this.shardRouting; } public InternalIndexShard routingEntry(ShardRouting newRouting) { ShardRouting currentRouting = this.shardRouting; if (!newRouting.shardId().equals(shardId())) { throw new ElasticsearchIllegalArgumentException("Trying to set a routing entry with shardId [" + newRouting.shardId() + "] on a shard with shardId [" + shardId() + "]"); } if (currentRouting != null) { if (!newRouting.primary() && currentRouting.primary()) { logger.warn("suspect illegal state: trying to move shard from primary mode to replica mode"); } // if its the same routing, return if (currentRouting.equals(newRouting)) { return this; } } if (state == IndexShardState.POST_RECOVERY) { // if the state is started or relocating (cause it might move right away from started to relocating) // then move to STARTED if (newRouting.state() == ShardRoutingState.STARTED || newRouting.state() == ShardRoutingState.RELOCATING) { // we want to refresh *before* we move to internal STARTED state try { engine.refresh(new Engine.Refresh("cluster_state_started").force(true)); } catch (Throwable t) { logger.debug("failed to refresh due to move to cluster wide started", t); } boolean movedToStarted = false; synchronized (mutex) { // do the check under a mutex, so we make sure to only change to STARTED if in POST_RECOVERY if (state == IndexShardState.POST_RECOVERY) { changeState(IndexShardState.STARTED, "global state is [" + newRouting.state() + "]"); movedToStarted = true; } else { logger.debug("state [{}] not changed, not in POST_RECOVERY, global state is [{}]", state, newRouting.state()); } } if (movedToStarted) { indicesLifecycle.afterIndexShardStarted(this); } } } this.shardRouting = newRouting; indicesLifecycle.shardRoutingChanged(this, currentRouting, newRouting); return this; } /** * Marks the shard as recovering, fails with exception is recovering is not allowed to be set. */ public IndexShardState recovering(String reason) throws IndexShardStartedException, IndexShardRelocatedException, IndexShardRecoveringException, IndexShardClosedException { synchronized (mutex) { if (state == IndexShardState.CLOSED) { throw new IndexShardClosedException(shardId); } if (state == IndexShardState.STARTED) { throw new IndexShardStartedException(shardId); } if (state == IndexShardState.RELOCATED) { throw new IndexShardRelocatedException(shardId); } if (state == IndexShardState.RECOVERING) { throw new IndexShardRecoveringException(shardId); } if (state == IndexShardState.POST_RECOVERY) { throw new IndexShardRecoveringException(shardId); } return changeState(IndexShardState.RECOVERING, reason); } } public InternalIndexShard relocated(String reason) throws IndexShardNotStartedException { synchronized (mutex) { if (state != IndexShardState.STARTED) { throw new IndexShardNotStartedException(shardId, state); } changeState(IndexShardState.RELOCATED, reason); } return this; } @Override public IndexShardState state() { return state; } /** * Changes the state of the current shard * * @param newState the new shard state * @param reason the reason for the state change * @return the previous shard state */ private IndexShardState changeState(IndexShardState newState, String reason) { logger.debug("state: [{}]->[{}], reason [{}]", state, newState, reason); IndexShardState previousState = state; state = newState; this.indicesLifecycle.indexShardStateChanged(this, previousState, reason); return previousState; } @Override public Engine.Create prepareCreate(SourceToParse source) throws ElasticsearchException { long startTime = System.nanoTime(); DocumentMapper docMapper = mapperService.documentMapperWithAutoCreate(source.type()); ParsedDocument doc = docMapper.parse(source); return new Engine.Create(docMapper, docMapper.uidMapper().term(doc.uid().stringValue()), doc).startTime(startTime); } @Override public ParsedDocument create(Engine.Create create) throws ElasticsearchException { writeAllowed(create.origin()); create = indexingService.preCreate(create); if (logger.isTraceEnabled()) { logger.trace("index {}", create.docs()); } engine.create(create); create.endTime(System.nanoTime()); indexingService.postCreate(create); return create.parsedDoc(); } @Override public Engine.Index prepareIndex(SourceToParse source) throws ElasticsearchException { long startTime = System.nanoTime(); DocumentMapper docMapper = mapperService.documentMapperWithAutoCreate(source.type()); ParsedDocument doc = docMapper.parse(source); return new Engine.Index(docMapper, docMapper.uidMapper().term(doc.uid().stringValue()), doc).startTime(startTime); } @Override public ParsedDocument index(Engine.Index index) throws ElasticsearchException { writeAllowed(index.origin()); index = indexingService.preIndex(index); try { if (logger.isTraceEnabled()) { logger.trace("index {}", index.docs()); } engine.index(index); index.endTime(System.nanoTime()); } catch (RuntimeException ex) { indexingService.failedIndex(index); throw ex; } indexingService.postIndex(index); return index.parsedDoc(); } @Override public Engine.Delete prepareDelete(String type, String id, long version) throws ElasticsearchException { long startTime = System.nanoTime(); DocumentMapper docMapper = mapperService.documentMapperWithAutoCreate(type); return new Engine.Delete(type, id, docMapper.uidMapper().term(type, id)).version(version).startTime(startTime); } @Override public void delete(Engine.Delete delete) throws ElasticsearchException { writeAllowed(delete.origin()); delete = indexingService.preDelete(delete); try { if (logger.isTraceEnabled()) { logger.trace("delete [{}]", delete.uid().text()); } engine.delete(delete); delete.endTime(System.nanoTime()); } catch (RuntimeException ex) { indexingService.failedDelete(delete); throw ex; } indexingService.postDelete(delete); } @Override public Engine.DeleteByQuery prepareDeleteByQuery(BytesReference source, @Nullable String[] filteringAliases, String... types) throws ElasticsearchException { long startTime = System.nanoTime(); if (types == null) { types = Strings.EMPTY_ARRAY; } Query query = queryParserService.parseQuery(source).query(); query = filterQueryIfNeeded(query, types); Filter aliasFilter = indexAliasesService.aliasFilter(filteringAliases); Filter parentFilter = mapperService.hasNested() ? indexCache.filter().cache(NonNestedDocsFilter.INSTANCE) : null; return new Engine.DeleteByQuery(query, source, filteringAliases, aliasFilter, parentFilter, types).startTime(startTime); } @Override public void deleteByQuery(Engine.DeleteByQuery deleteByQuery) throws ElasticsearchException { writeAllowed(deleteByQuery.origin()); if (logger.isTraceEnabled()) { logger.trace("delete_by_query [{}]", deleteByQuery.query()); } deleteByQuery = indexingService.preDeleteByQuery(deleteByQuery); engine.delete(deleteByQuery); deleteByQuery.endTime(System.nanoTime()); indexingService.postDeleteByQuery(deleteByQuery); } @Override public Engine.GetResult get(Engine.Get get) throws ElasticsearchException { readAllowed(); return engine.get(get); } @Override public void refresh(Engine.Refresh refresh) throws ElasticsearchException { verifyNotClosed(); if (logger.isTraceEnabled()) { logger.trace("refresh with {}", refresh); } long time = System.nanoTime(); engine.refresh(refresh); refreshMetric.inc(System.nanoTime() - time); } @Override public RefreshStats refreshStats() { return new RefreshStats(refreshMetric.count(), TimeUnit.NANOSECONDS.toMillis(refreshMetric.sum())); } @Override public FlushStats flushStats() { return new FlushStats(flushMetric.count(), TimeUnit.NANOSECONDS.toMillis(flushMetric.sum())); } @Override public DocsStats docStats() { final Engine.Searcher searcher = acquireSearcher("doc_stats"); try { return new DocsStats(searcher.reader().numDocs(), searcher.reader().numDeletedDocs()); } finally { searcher.release(); } } @Override public IndexingStats indexingStats(String... types) { return indexingService.stats(types); } @Override public SearchStats searchStats(String... groups) { return searchService.stats(groups); } @Override public GetStats getStats() { return getService.stats(); } @Override public StoreStats storeStats() { try { return store.stats(); } catch (IOException e) { throw new ElasticsearchException("io exception while building 'store stats'", e); } } @Override public MergeStats mergeStats() { return mergeScheduler.stats(); } @Override public SegmentsStats segmentStats() { return engine.segmentsStats(); } @Override public WarmerStats warmerStats() { return shardWarmerService.stats(); } @Override public FilterCacheStats filterCacheStats() { return shardFilterCache.stats(); } @Override public FieldDataStats fieldDataStats(String... fields) { return shardFieldData.stats(fields); } @Override public PercolatorQueriesRegistry percolateRegistry() { return percolatorQueriesRegistry; } @Override public ShardPercolateService shardPercolateService() { return shardPercolateService; } @Override public IdCacheStats idCacheStats() { return shardIdCache.stats(); } @Override public TranslogStats translogStats() { return translog.stats(); } @Override public CompletionStats completionStats(String... fields) { CompletionStats completionStats = new CompletionStats(); final Engine.Searcher currentSearcher = acquireSearcher("completion_stats"); try { PostingsFormat postingsFormat = this.codecService.postingsFormatService().get(Completion090PostingsFormat.CODEC_NAME).get(); if (postingsFormat instanceof Completion090PostingsFormat) { Completion090PostingsFormat completionPostingsFormat = (Completion090PostingsFormat) postingsFormat; completionStats.add(completionPostingsFormat.completionStats(currentSearcher.reader(), fields)); } } finally { currentSearcher.release(); } return completionStats; } @Override public void flush(Engine.Flush flush) throws ElasticsearchException { // we allows flush while recovering, since we allow for operations to happen // while recovering, and we want to keep the translog at bay (up to deletes, which // we don't gc). verifyStartedOrRecovering(); if (logger.isTraceEnabled()) { logger.trace("flush with {}", flush); } long time = System.nanoTime(); engine.flush(flush); flushMetric.inc(System.nanoTime() - time); } @Override public void optimize(Engine.Optimize optimize) throws ElasticsearchException { verifyStarted(); if (logger.isTraceEnabled()) { logger.trace("optimize with {}", optimize); } engine.optimize(optimize); } @Override public <T> T snapshot(Engine.SnapshotHandler<T> snapshotHandler) throws EngineException { IndexShardState state = this.state; // one time volatile read // we allow snapshot on closed index shard, since we want to do one after we close the shard and before we close the engine if (state == IndexShardState.POST_RECOVERY || state == IndexShardState.STARTED || state == IndexShardState.RELOCATED || state == IndexShardState.CLOSED) { return engine.snapshot(snapshotHandler); } else { throw new IllegalIndexShardStateException(shardId, state, "snapshot is not allowed"); } } @Override public SnapshotIndexCommit snapshotIndex() throws EngineException { IndexShardState state = this.state; // one time volatile read // we allow snapshot on closed index shard, since we want to do one after we close the shard and before we close the engine if (state == IndexShardState.STARTED || state == IndexShardState.RELOCATED || state == IndexShardState.CLOSED) { return engine.snapshotIndex(); } else { throw new IllegalIndexShardStateException(shardId, state, "snapshot is not allowed"); } } @Override public void recover(Engine.RecoveryHandler recoveryHandler) throws EngineException { verifyStarted(); engine.recover(recoveryHandler); } @Override public Engine.Searcher acquireSearcher(String source) { return acquireSearcher(source, Mode.READ); } @Override public Engine.Searcher acquireSearcher(String source, Mode mode) { readAllowed(mode); return engine.acquireSearcher(source); } public void close(String reason) { synchronized (mutex) { indexSettingsService.removeListener(applyRefreshSettings); if (state != IndexShardState.CLOSED) { if (refreshScheduledFuture != null) { refreshScheduledFuture.cancel(true); refreshScheduledFuture = null; } if (mergeScheduleFuture != null) { mergeScheduleFuture.cancel(true); mergeScheduleFuture = null; } } changeState(IndexShardState.CLOSED, reason); } } public long checkIndexTook() { return this.checkIndexTook; } public InternalIndexShard postRecovery(String reason) throws IndexShardStartedException, IndexShardRelocatedException, IndexShardClosedException { synchronized (mutex) { if (state == IndexShardState.CLOSED) { throw new IndexShardClosedException(shardId); } if (state == IndexShardState.STARTED) { throw new IndexShardStartedException(shardId); } if (state == IndexShardState.RELOCATED) { throw new IndexShardRelocatedException(shardId); } if (Booleans.parseBoolean(checkIndexOnStartup, false)) { checkIndex(true); } engine.start(); startScheduledTasksIfNeeded(); changeState(IndexShardState.POST_RECOVERY, reason); } indicesLifecycle.afterIndexShardPostRecovery(this); return this; } /** * After the store has been recovered, we need to start the engine in order to apply operations */ public void performRecoveryPrepareForTranslog() throws ElasticsearchException { if (state != IndexShardState.RECOVERING) { throw new IndexShardNotRecoveringException(shardId, state); } // also check here, before we apply the translog if (Booleans.parseBoolean(checkIndexOnStartup, false)) { checkIndex(true); } // we disable deletes since we allow for operations to be executed against the shard while recovering // but we need to make sure we don't loose deletes until we are done recovering engine.enableGcDeletes(false); engine.start(); } /** * The peer recovery status if this shard recovered from a peer shard. */ public RecoveryStatus peerRecoveryStatus() { return this.peerRecoveryStatus; } public void performRecoveryFinalization(boolean withFlush, RecoveryStatus peerRecoveryStatus) throws ElasticsearchException { performRecoveryFinalization(withFlush); this.peerRecoveryStatus = peerRecoveryStatus; } public void performRecoveryFinalization(boolean withFlush) throws ElasticsearchException { if (withFlush) { engine.flush(new Engine.Flush()); } // clear unreferenced files translog.clearUnreferenced(); engine.refresh(new Engine.Refresh("recovery_finalization").force(true)); synchronized (mutex) { changeState(IndexShardState.POST_RECOVERY, "post recovery"); } indicesLifecycle.afterIndexShardPostRecovery(this); startScheduledTasksIfNeeded(); engine.enableGcDeletes(true); } public void performRecoveryOperation(Translog.Operation operation) throws ElasticsearchException { if (state != IndexShardState.RECOVERING) { throw new IndexShardNotRecoveringException(shardId, state); } try { switch (operation.opType()) { case CREATE: Translog.Create create = (Translog.Create) operation; engine.create(prepareCreate(source(create.source()).type(create.type()).id(create.id()) .routing(create.routing()).parent(create.parent()).timestamp(create.timestamp()).ttl(create.ttl())).version(create.version()) .origin(Engine.Operation.Origin.RECOVERY)); break; case SAVE: Translog.Index index = (Translog.Index) operation; engine.index(prepareIndex(source(index.source()).type(index.type()).id(index.id()) .routing(index.routing()).parent(index.parent()).timestamp(index.timestamp()).ttl(index.ttl())).version(index.version()) .origin(Engine.Operation.Origin.RECOVERY)); break; case DELETE: Translog.Delete delete = (Translog.Delete) operation; Uid uid = Uid.createUid(delete.uid().text()); engine.delete(new Engine.Delete(uid.type(), uid.id(), delete.uid()).version(delete.version()) .origin(Engine.Operation.Origin.RECOVERY)); break; case DELETE_BY_QUERY: Translog.DeleteByQuery deleteByQuery = (Translog.DeleteByQuery) operation; engine.delete(prepareDeleteByQuery(deleteByQuery.source(), deleteByQuery.filteringAliases(), deleteByQuery.types()).origin(Engine.Operation.Origin.RECOVERY)); break; default: throw new ElasticsearchIllegalStateException("No operation defined for [" + operation + "]"); } } catch (ElasticsearchException e) { boolean hasIgnoreOnRecoveryException = false; ElasticsearchException current = e; while (true) { if (current instanceof IgnoreOnRecoveryEngineException) { hasIgnoreOnRecoveryException = true; break; } if (current.getCause() instanceof ElasticsearchException) { current = (ElasticsearchException) current.getCause(); } else { break; } } if (!hasIgnoreOnRecoveryException) { throw e; } } } /** * Returns <tt>true</tt> if this shard can ignore a recovery attempt made to it (since the already doing/done it) */ public boolean ignoreRecoveryAttempt() { IndexShardState state = state(); // one time volatile read return state == IndexShardState.POST_RECOVERY || state == IndexShardState.RECOVERING || state == IndexShardState.STARTED || state == IndexShardState.RELOCATED || state == IndexShardState.CLOSED; } public void readAllowed() throws IllegalIndexShardStateException { readAllowed(Mode.READ); } public void readAllowed(Mode mode) throws IllegalIndexShardStateException { IndexShardState state = this.state; // one time volatile read switch (mode) { case READ: if (state != IndexShardState.STARTED && state != IndexShardState.RELOCATED) { throw new IllegalIndexShardStateException(shardId, state, "operations only allowed when started/relocated"); } break; case WRITE: if (state != IndexShardState.STARTED && state != IndexShardState.RELOCATED && state != IndexShardState.RECOVERING && state != IndexShardState.POST_RECOVERY) { throw new IllegalIndexShardStateException(shardId, state, "operations only allowed when started/relocated"); } break; } } private void writeAllowed(Engine.Operation.Origin origin) throws IllegalIndexShardStateException { IndexShardState state = this.state; // one time volatile read if (origin == Engine.Operation.Origin.PRIMARY) { // for primaries, we only allow to write when actually started (so the cluster has decided we started) // otherwise, we need to retry, we also want to still allow to index if we are relocated in case it fails if (state != IndexShardState.STARTED && state != IndexShardState.RELOCATED) { throw new IllegalIndexShardStateException(shardId, state, "operation only allowed when started/recovering, origin [" + origin + "]"); } } else { // for replicas, we allow to write also while recovering, since we index also during recovery to replicas // and rely on version checks to make sure its consistent if (state != IndexShardState.STARTED && state != IndexShardState.RELOCATED && state != IndexShardState.RECOVERING && state != IndexShardState.POST_RECOVERY) { throw new IllegalIndexShardStateException(shardId, state, "operation only allowed when started/recovering, origin [" + origin + "]"); } } } private void verifyStartedOrRecovering() throws IllegalIndexShardStateException { IndexShardState state = this.state; // one time volatile read if (state != IndexShardState.STARTED && state != IndexShardState.RECOVERING && state != IndexShardState.POST_RECOVERY) { throw new IllegalIndexShardStateException(shardId, state, "operation only allowed when started/recovering"); } } private void verifyNotClosed() throws IllegalIndexShardStateException { IndexShardState state = this.state; // one time volatile read if (state == IndexShardState.CLOSED) { throw new IllegalIndexShardStateException(shardId, state, "operation only allowed when not closed"); } } private void verifyStarted() throws IllegalIndexShardStateException { IndexShardState state = this.state; // one time volatile read if (state != IndexShardState.STARTED) { throw new IndexShardNotStartedException(shardId, state); } } private void startScheduledTasksIfNeeded() { if (refreshInterval.millis() > 0) { refreshScheduledFuture = threadPool.schedule(refreshInterval, ThreadPool.Names.SAME, new EngineRefresher()); logger.debug("scheduling refresher every {}", refreshInterval); } else { logger.debug("scheduled refresher disabled"); } // since we can do async merging, it will not be called explicitly when indexing (adding / deleting docs), and only when flushing // so, make sure we periodically call it, this need to be a small enough value so mergine will actually // happen and reduce the number of segments if (mergeInterval.millis() > 0) { mergeScheduleFuture = threadPool.schedule(mergeInterval, ThreadPool.Names.SAME, new EngineMerger()); logger.debug("scheduling optimizer / merger every {}", mergeInterval); } else { logger.debug("scheduled optimizer / merger disabled"); } } private Query filterQueryIfNeeded(Query query, String[] types) { Filter searchFilter = mapperService.searchFilter(types); if (searchFilter != null) { query = new XFilteredQuery(query, indexCache.filter().cache(searchFilter)); } return query; } public static final String INDEX_REFRESH_INTERVAL = "index.refresh_interval"; private class ApplyRefreshSettings implements IndexSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { synchronized (mutex) { if (state == IndexShardState.CLOSED) { return; } TimeValue refreshInterval = settings.getAsTime(INDEX_REFRESH_INTERVAL, InternalIndexShard.this.refreshInterval); if (!refreshInterval.equals(InternalIndexShard.this.refreshInterval)) { logger.info("updating refresh_interval from [{}] to [{}]", InternalIndexShard.this.refreshInterval, refreshInterval); if (refreshScheduledFuture != null) { refreshScheduledFuture.cancel(false); refreshScheduledFuture = null; } InternalIndexShard.this.refreshInterval = refreshInterval; if (refreshInterval.millis() > 0) { refreshScheduledFuture = threadPool.schedule(refreshInterval, ThreadPool.Names.SAME, new EngineRefresher()); } } } } } class EngineRefresher implements Runnable { @Override public void run() { // we check before if a refresh is needed, if not, we reschedule, otherwise, we fork, refresh, and then reschedule if (!engine().refreshNeeded()) { synchronized (mutex) { if (state != IndexShardState.CLOSED) { refreshScheduledFuture = threadPool.schedule(refreshInterval, ThreadPool.Names.SAME, this); } } return; } threadPool.executor(ThreadPool.Names.REFRESH).execute(new Runnable() { @Override public void run() { try { if (engine.refreshNeeded()) { refresh(new Engine.Refresh("scheduled").force(false)); } } catch (EngineClosedException e) { // we are being closed, ignore } catch (RefreshFailedEngineException e) { if (e.getCause() instanceof InterruptedException) { // ignore, we are being shutdown } else if (e.getCause() instanceof ClosedByInterruptException) { // ignore, we are being shutdown } else if (e.getCause() instanceof ThreadInterruptedException) { // ignore, we are being shutdown } else { if (state != IndexShardState.CLOSED) { logger.warn("Failed to perform scheduled engine refresh", e); } } } catch (Exception e) { if (state != IndexShardState.CLOSED) { logger.warn("Failed to perform scheduled engine refresh", e); } } synchronized (mutex) { if (state != IndexShardState.CLOSED) { refreshScheduledFuture = threadPool.schedule(refreshInterval, ThreadPool.Names.SAME, EngineRefresher.this); } } } }); } } class EngineMerger implements Runnable { @Override public void run() { if (!engine().possibleMergeNeeded()) { synchronized (mutex) { if (state != IndexShardState.CLOSED) { mergeScheduleFuture = threadPool.schedule(mergeInterval, ThreadPool.Names.SAME, this); } } return; } threadPool.executor(ThreadPool.Names.MERGE).execute(new Runnable() { @Override public void run() { try { engine.maybeMerge(); } catch (EngineClosedException e) { // we are being closed, ignore } catch (OptimizeFailedEngineException e) { if (e.getCause() instanceof EngineClosedException) { // ignore, we are being shutdown } else if (e.getCause() instanceof InterruptedException) { // ignore, we are being shutdown } else if (e.getCause() instanceof ClosedByInterruptException) { // ignore, we are being shutdown } else if (e.getCause() instanceof ThreadInterruptedException) { // ignore, we are being shutdown } else { if (state != IndexShardState.CLOSED) { logger.warn("Failed to perform scheduled engine optimize/merge", e); } } } catch (Exception e) { if (state != IndexShardState.CLOSED) { logger.warn("Failed to perform scheduled engine optimize/merge", e); } } synchronized (mutex) { if (state != IndexShardState.CLOSED) { mergeScheduleFuture = threadPool.schedule(mergeInterval, ThreadPool.Names.SAME, EngineMerger.this); } } } }); } } private void checkIndex(boolean throwException) throws IndexShardException { try { checkIndexTook = 0; long time = System.currentTimeMillis(); if (!Lucene.indexExists(store.directory())) { return; } CheckIndex checkIndex = new CheckIndex(store.directory()); BytesStreamOutput os = new BytesStreamOutput(); PrintStream out = new PrintStream(os, false, Charsets.UTF_8.name()); checkIndex.setInfoStream(out); out.flush(); CheckIndex.Status status = checkIndex.checkIndex(); if (!status.clean) { if (state == IndexShardState.CLOSED) { // ignore if closed.... return; } logger.warn("check index [failure]\n{}", new String(os.bytes().toBytes(), Charsets.UTF_8)); if ("fix".equalsIgnoreCase(checkIndexOnStartup)) { if (logger.isDebugEnabled()) { logger.debug("fixing index, writing new segments file ..."); } checkIndex.fixIndex(status); if (logger.isDebugEnabled()) { logger.debug("index fixed, wrote new segments file \"{}\"", status.segmentsFileName); } } else { // only throw a failure if we are not going to fix the index if (throwException) { throw new IndexShardException(shardId, "index check failure"); } } } else { if (logger.isDebugEnabled()) { logger.debug("check index [success]\n{}", new String(os.bytes().toBytes(), Charsets.UTF_8)); } } checkIndexTook = System.currentTimeMillis() - time; } catch (Exception e) { logger.warn("failed to check index", e); } } }
1no label
src_main_java_org_elasticsearch_index_shard_service_InternalIndexShard.java
377
public interface LocaleDao { /** * @return The locale for the passed in code */ public Locale findLocaleByCode(String localeCode); /** * Returns the page template with the passed in id. * * @return The default locale */ public Locale findDefaultLocale(); /** * Returns all supported BLC locales. * @return */ public List<Locale> findAllLocales(); public Locale save(Locale locale); }
0true
common_src_main_java_org_broadleafcommerce_common_locale_dao_LocaleDao.java
5,930
public class SortParseElement implements SearchParseElement { public static final SortField SORT_SCORE = new SortField(null, SortField.Type.SCORE); private static final SortField SORT_SCORE_REVERSE = new SortField(null, SortField.Type.SCORE, true); private static final SortField SORT_DOC = new SortField(null, SortField.Type.DOC); private static final SortField SORT_DOC_REVERSE = new SortField(null, SortField.Type.DOC, true); public static final String SCORE_FIELD_NAME = "_score"; public static final String DOC_FIELD_NAME = "_doc"; private final ImmutableMap<String, SortParser> parsers; public SortParseElement() { ImmutableMap.Builder<String, SortParser> builder = ImmutableMap.builder(); addParser(builder, new ScriptSortParser()); addParser(builder, new GeoDistanceSortParser()); this.parsers = builder.build(); } private void addParser(ImmutableMap.Builder<String, SortParser> parsers, SortParser parser) { for (String name : parser.names()) { parsers.put(name, parser); } } @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token = parser.currentToken(); List<SortField> sortFields = Lists.newArrayListWithCapacity(2); if (token == XContentParser.Token.START_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.START_OBJECT) { addCompoundSortField(parser, context, sortFields); } else if (token == XContentParser.Token.VALUE_STRING) { addSortField(context, sortFields, parser.text(), false, false, null, null, null, null); } else { throw new ElasticsearchIllegalArgumentException("malformed sort format, within the sort array, an object, or an actual string are allowed"); } } } else if (token == XContentParser.Token.VALUE_STRING) { addSortField(context, sortFields, parser.text(), false, false, null, null, null, null); } else if (token == XContentParser.Token.START_OBJECT) { addCompoundSortField(parser, context, sortFields); } else { throw new ElasticsearchIllegalArgumentException("malformed sort format, either start with array, object, or an actual string"); } if (!sortFields.isEmpty()) { // optimize if we just sort on score non reversed, we don't really need sorting boolean sort; if (sortFields.size() > 1) { sort = true; } else { SortField sortField = sortFields.get(0); if (sortField.getType() == SortField.Type.SCORE && !sortField.getReverse()) { sort = false; } else { sort = true; } } if (sort) { context.sort(new Sort(sortFields.toArray(new SortField[sortFields.size()]))); } } } private void addCompoundSortField(XContentParser parser, SearchContext context, List<SortField> sortFields) throws Exception { XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { String fieldName = parser.currentName(); boolean reverse = false; String missing = null; String innerJsonName = null; boolean ignoreUnmapped = false; SortMode sortMode = null; Filter nestedFilter = null; String nestedPath = null; token = parser.nextToken(); if (token == XContentParser.Token.VALUE_STRING) { String direction = parser.text(); if (direction.equals("asc")) { reverse = SCORE_FIELD_NAME.equals(fieldName); } else if (direction.equals("desc")) { reverse = !SCORE_FIELD_NAME.equals(fieldName); } else { throw new ElasticsearchIllegalArgumentException("sort direction [" + fieldName + "] not supported"); } addSortField(context, sortFields, fieldName, reverse, ignoreUnmapped, missing, sortMode, nestedPath, nestedFilter); } else { if (parsers.containsKey(fieldName)) { sortFields.add(parsers.get(fieldName).parse(parser, context)); } else { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { innerJsonName = parser.currentName(); } else if (token.isValue()) { if ("reverse".equals(innerJsonName)) { reverse = parser.booleanValue(); } else if ("order".equals(innerJsonName)) { if ("asc".equals(parser.text())) { reverse = SCORE_FIELD_NAME.equals(fieldName); } else if ("desc".equals(parser.text())) { reverse = !SCORE_FIELD_NAME.equals(fieldName); } } else if ("missing".equals(innerJsonName)) { missing = parser.textOrNull(); } else if ("ignore_unmapped".equals(innerJsonName) || "ignoreUnmapped".equals(innerJsonName)) { ignoreUnmapped = parser.booleanValue(); } else if ("mode".equals(innerJsonName)) { sortMode = SortMode.fromString(parser.text()); } else if ("nested_path".equals(innerJsonName) || "nestedPath".equals(innerJsonName)) { nestedPath = parser.text(); } else { throw new ElasticsearchIllegalArgumentException("sort option [" + innerJsonName + "] not supported"); } } else if (token == XContentParser.Token.START_OBJECT) { if ("nested_filter".equals(innerJsonName) || "nestedFilter".equals(innerJsonName)) { ParsedFilter parsedFilter = context.queryParserService().parseInnerFilter(parser); nestedFilter = parsedFilter == null ? null : parsedFilter.filter(); } else { throw new ElasticsearchIllegalArgumentException("sort option [" + innerJsonName + "] not supported"); } } } addSortField(context, sortFields, fieldName, reverse, ignoreUnmapped, missing, sortMode, nestedPath, nestedFilter); } } } } } private void addSortField(SearchContext context, List<SortField> sortFields, String fieldName, boolean reverse, boolean ignoreUnmapped, @Nullable final String missing, SortMode sortMode, String nestedPath, Filter nestedFilter) { if (SCORE_FIELD_NAME.equals(fieldName)) { if (reverse) { sortFields.add(SORT_SCORE_REVERSE); } else { sortFields.add(SORT_SCORE); } } else if (DOC_FIELD_NAME.equals(fieldName)) { if (reverse) { sortFields.add(SORT_DOC_REVERSE); } else { sortFields.add(SORT_DOC); } } else { FieldMapper fieldMapper = context.smartNameFieldMapper(fieldName); if (fieldMapper == null) { if (ignoreUnmapped) { return; } throw new SearchParseException(context, "No mapping found for [" + fieldName + "] in order to sort on"); } if (!fieldMapper.isSortable()) { throw new SearchParseException(context, "Sorting not supported for field[" + fieldName + "]"); } // Enable when we also know how to detect fields that do tokenize, but only emit one token /*if (fieldMapper instanceof StringFieldMapper) { StringFieldMapper stringFieldMapper = (StringFieldMapper) fieldMapper; if (stringFieldMapper.fieldType().tokenized()) { // Fail early throw new SearchParseException(context, "Can't sort on tokenized string field[" + fieldName + "]"); } }*/ // We only support AVG and SUM on number based fields if (!(fieldMapper instanceof NumberFieldMapper) && (sortMode == SortMode.SUM || sortMode == SortMode.AVG)) { sortMode = null; } if (sortMode == null) { sortMode = resolveDefaultSortMode(reverse); } IndexFieldData.XFieldComparatorSource fieldComparatorSource = context.fieldData().getForField(fieldMapper) .comparatorSource(missing, sortMode); ObjectMapper objectMapper; if (nestedPath != null) { ObjectMappers objectMappers = context.mapperService().objectMapper(nestedPath); if (objectMappers == null) { throw new ElasticsearchIllegalArgumentException("failed to find nested object mapping for explicit nested path [" + nestedPath + "]"); } objectMapper = objectMappers.mapper(); if (!objectMapper.nested().isNested()) { throw new ElasticsearchIllegalArgumentException("mapping for explicit nested path is not mapped as nested: [" + nestedPath + "]"); } } else { objectMapper = context.mapperService().resolveClosestNestedObjectMapper(fieldName); } if (objectMapper != null && objectMapper.nested().isNested()) { Filter rootDocumentsFilter = context.filterCache().cache(NonNestedDocsFilter.INSTANCE); Filter innerDocumentsFilter; if (nestedFilter != null) { innerDocumentsFilter = context.filterCache().cache(nestedFilter); } else { innerDocumentsFilter = context.filterCache().cache(objectMapper.nestedTypeFilter()); } fieldComparatorSource = new NestedFieldComparatorSource(sortMode, fieldComparatorSource, rootDocumentsFilter, innerDocumentsFilter); } sortFields.add(new SortField(fieldMapper.names().indexName(), fieldComparatorSource, reverse)); } } private static SortMode resolveDefaultSortMode(boolean reverse) { return reverse ? SortMode.MAX : SortMode.MIN; } }
1no label
src_main_java_org_elasticsearch_search_sort_SortParseElement.java
2,925
public class PreBuiltTokenFilterFactoryFactory implements TokenFilterFactoryFactory { private final TokenFilterFactory tokenFilterFactory; public PreBuiltTokenFilterFactoryFactory(TokenFilterFactory tokenFilterFactory) { this.tokenFilterFactory = tokenFilterFactory; } @Override public TokenFilterFactory create(String name, Settings settings) { Version indexVersion = settings.getAsVersion(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT); if (!Version.CURRENT.equals(indexVersion)) { return PreBuiltTokenFilters.valueOf(name.toUpperCase(Locale.ROOT)).getTokenFilterFactory(indexVersion); } return tokenFilterFactory; } }
1no label
src_main_java_org_elasticsearch_index_analysis_PreBuiltTokenFilterFactoryFactory.java
1,856
private static class RootModule implements Module { final Stage stage; private RootModule(Stage stage) { this.stage = checkNotNull(stage, "stage"); } public void configure(Binder binder) { binder = binder.withSource(SourceProvider.UNKNOWN_SOURCE); binder.bind(Stage.class).toInstance(stage); binder.bindScope(Singleton.class, SINGLETON); } }
0true
src_main_java_org_elasticsearch_common_inject_InjectorShell.java
39
public class ModuleCompletions { static final class ModuleDescriptorProposal extends CompletionProposal { ModuleDescriptorProposal(int offset, String prefix, String moduleName) { super(offset, prefix, MODULE, "module " + moduleName, "module " + moduleName + " \"1.0.0\" {}"); } @Override public Point getSelection(IDocument document) { return new Point(offset - prefix.length() + text.indexOf('\"')+1, 5); } @Override protected boolean qualifiedNameIsPath() { return true; } } static final class ModuleProposal extends CompletionProposal { private final int len; private final String versioned; private final ModuleDetails module; private final boolean withBody; private final ModuleVersionDetails version; private final String name; private Node node; ModuleProposal(int offset, String prefix, int len, String versioned, ModuleDetails module, boolean withBody, ModuleVersionDetails version, String name, Node node) { super(offset, prefix, MODULE, versioned, versioned.substring(len)); this.len = len; this.versioned = versioned; this.module = module; this.withBody = withBody; this.version = version; this.name = name; this.node = node; } @Override public String getDisplayString() { String str = super.getDisplayString(); /*if (withBody && EditorsUI.getPreferenceStore() .getBoolean(LINKED_MODE)) { str = str.replaceAll("\".*\"", "\"<...>\""); }*/ return str; } @Override public Point getSelection(IDocument document) { final int off = offset+versioned.length()-prefix.length()-len; if (withBody) { final int verlen = version.getVersion().length(); return new Point(off-verlen-2, verlen); } else { return new Point(off, 0); } } @Override public void apply(IDocument document) { super.apply(document); if (withBody && //module.getVersions().size()>1 && //TODO: put this back in when sure it works EditorsUI.getPreferenceStore() .getBoolean(LINKED_MODE)) { final LinkedModeModel linkedModeModel = new LinkedModeModel(); final Point selection = getSelection(document); List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(); for (final ModuleVersionDetails d: module.getVersions()) { proposals.add(new ICompletionProposal() { @Override public Point getSelection(IDocument document) { return null; } @Override public Image getImage() { return CeylonResources.VERSION; } @Override public String getDisplayString() { return d.getVersion(); } @Override public IContextInformation getContextInformation() { return null; } @Override public String getAdditionalProposalInfo() { return "Repository: " + d.getOrigin(); } @Override public void apply(IDocument document) { try { document.replace(selection.x, selection.y, d.getVersion()); } catch (BadLocationException e) { e.printStackTrace(); } linkedModeModel.exit(ILinkedModeListener.UPDATE_CARET); } }); } ProposalPosition linkedPosition = new ProposalPosition(document, selection.x, selection.y, 0, proposals.toArray(NO_COMPLETIONS)); try { LinkedMode.addLinkedPosition(linkedModeModel, linkedPosition); LinkedMode.installLinkedMode((CeylonEditor) EditorUtil.getCurrentEditor(), document, linkedModeModel, this, new LinkedMode.NullExitPolicy(), 1, selection.x+selection.y+2); } catch (BadLocationException ble) { ble.printStackTrace(); } } } @Override public String getAdditionalProposalInfo() { Scope scope = node.getScope(); Unit unit = node.getUnit(); return JDKUtils.isJDKModule(name) ? getDocumentationForModule(name, JDKUtils.jdk.version, "This module forms part of the Java SDK.", scope, unit) : getDocumentationFor(module, version.getVersion(), scope, unit); } @Override protected boolean qualifiedNameIsPath() { return true; } } static final class JDKModuleProposal extends CompletionProposal { private final String name; JDKModuleProposal(int offset, String prefix, int len, String versioned, String name) { super(offset, prefix, MODULE, versioned, versioned.substring(len)); this.name = name; } @Override public String getAdditionalProposalInfo() { return getDocumentationForModule(name, JDKUtils.jdk.version, "This module forms part of the Java SDK.", null, null); } @Override protected boolean qualifiedNameIsPath() { return true; } } private static final SortedSet<String> JDK_MODULE_VERSION_SET = new TreeSet<String>(); { JDK_MODULE_VERSION_SET.add(JDKUtils.jdk.version); } static void addModuleCompletions(CeylonParseController cpc, int offset, String prefix, Tree.ImportPath path, Node node, List<ICompletionProposal> result, boolean withBody) { String fullPath = fullPath(offset, prefix, path); addModuleCompletions(offset, prefix, node, result, fullPath.length(), fullPath+prefix, cpc, withBody); } private static void addModuleCompletions(int offset, String prefix, Node node, List<ICompletionProposal> result, final int len, String pfp, final CeylonParseController cpc, final boolean withBody) { if (pfp.startsWith("java.")) { for (String name: new TreeSet<String>(JDKUtils.getJDKModuleNames())) { if (name.startsWith(pfp) && !moduleAlreadyImported(cpc, name)) { result.add(new JDKModuleProposal(offset, prefix, len, getModuleString(withBody, name, JDKUtils.jdk.version), name)); } } } else { final TypeChecker tc = cpc.getTypeChecker(); if (tc!=null) { IProject project = cpc.getProject(); for (ModuleDetails module: getModuleSearchResults(pfp, tc,project).getResults()) { final String name = module.getName(); if (!name.equals(Module.DEFAULT_MODULE_NAME) && !moduleAlreadyImported(cpc, name)) { if (EditorsUI.getPreferenceStore() .getBoolean(LINKED_MODE)) { result.add(new ModuleProposal(offset, prefix, len, getModuleString(withBody, name, module.getLastVersion().getVersion()), module, withBody, module.getLastVersion(), name, node)); } else { for (final ModuleVersionDetails version: module.getVersions().descendingSet()) { result.add(new ModuleProposal(offset, prefix, len, getModuleString(withBody, name, version.getVersion()), module, withBody, version, name, node)); } } } } } } } private static boolean moduleAlreadyImported(CeylonParseController cpc, final String mod) { if (mod.equals(Module.LANGUAGE_MODULE_NAME)) { return true; } List<Tree.ModuleDescriptor> md = cpc.getRootNode().getModuleDescriptors(); if (!md.isEmpty()) { Tree.ImportModuleList iml = md.get(0).getImportModuleList(); if (iml!=null) { for (Tree.ImportModule im: iml.getImportModules()) { if (im.getImportPath()!=null) { if (formatPath(im.getImportPath().getIdentifiers()).equals(mod)) { return true; } } } } } //Disabled, because once the module is imported, it hangs around! // for (ModuleImport mi: node.getUnit().getPackage().getModule().getImports()) { // if (mi.getModule().getNameAsString().equals(mod)) { // return true; // } // } return false; } private static String getModuleString(boolean withBody, String name, String version) { if (!name.matches("^[a-z_]\\w*(\\.[a-z_]\\w*)*$")) { name = '"' + name + '"'; } return withBody ? name + " \"" + version + "\";" : name; } static void addModuleDescriptorCompletion(CeylonParseController cpc, int offset, String prefix, List<ICompletionProposal> result) { if (!"module".startsWith(prefix)) return; IFile file = cpc.getProject().getFile(cpc.getPath()); String moduleName = getPackageName(file); if (moduleName!=null) { result.add(new ModuleDescriptorProposal(offset, prefix, moduleName)); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ModuleCompletions.java
1,527
public class ShardVersioningTests extends ElasticsearchAllocationTestCase { private final ESLogger logger = Loggers.getLogger(ShardVersioningTests.class); @Test public void simple() { AllocationService strategy = createAllocationService(settingsBuilder().put("cluster.routing.allocation.allow_rebalance", ClusterRebalanceAllocationDecider.ClusterRebalanceType.ALWAYS.toString()).build()); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test1").numberOfShards(1).numberOfReplicas(1)) .put(IndexMetaData.builder("test2").numberOfShards(1).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test1")) .addAsNew(metaData.index("test2")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("start two nodes"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2"))).build(); RoutingTable prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); for (int i = 0; i < routingTable.index("test1").shards().size(); i++) { assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test1").shard(i).primaryShard().state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test1").shard(i).primaryShard().version(), equalTo(1l)); assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED)); } for (int i = 0; i < routingTable.index("test2").shards().size(); i++) { assertThat(routingTable.index("test2").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test2").shard(i).primaryShard().state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test2").shard(i).primaryShard().version(), equalTo(1l)); assertThat(routingTable.index("test2").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED)); } logger.info("start all the primary shards for test1, replicas will start initializing"); RoutingNodes routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState("test1", INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); for (int i = 0; i < routingTable.index("test1").shards().size(); i++) { assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test1").shard(i).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test1").shard(i).primaryShard().version(), equalTo(2l)); assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).version(), equalTo(2l)); } for (int i = 0; i < routingTable.index("test2").shards().size(); i++) { assertThat(routingTable.index("test2").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test2").shard(i).primaryShard().state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test2").shard(i).primaryShard().version(), equalTo(1l)); assertThat(routingTable.index("test2").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED)); assertThat(routingTable.index("test2").shard(i).replicaShards().get(0).version(), equalTo(1l)); } } }
0true
src_test_java_org_elasticsearch_cluster_routing_allocation_ShardVersioningTests.java
5,352
public class InternalAvg extends MetricsAggregation.SingleValue implements Avg { public final static Type TYPE = new Type("avg"); public final static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() { @Override public InternalAvg readResult(StreamInput in) throws IOException { InternalAvg result = new InternalAvg(); result.readFrom(in); return result; } }; public static void registerStreams() { AggregationStreams.registerStream(STREAM, TYPE.stream()); } private double sum; private long count; InternalAvg() {} // for serialization public InternalAvg(String name, double sum, long count) { super(name); this.sum = sum; this.count = count; } @Override public double value() { return getValue(); } public double getValue() { return sum / count; } @Override public Type type() { return TYPE; } @Override public InternalAvg reduce(ReduceContext reduceContext) { List<InternalAggregation> aggregations = reduceContext.aggregations(); if (aggregations.size() == 1) { return (InternalAvg) aggregations.get(0); } InternalAvg reduced = null; for (InternalAggregation aggregation : aggregations) { if (reduced == null) { reduced = (InternalAvg) aggregation; } else { reduced.count += ((InternalAvg) aggregation).count; reduced.sum += ((InternalAvg) aggregation).sum; } } return reduced; } @Override public void readFrom(StreamInput in) throws IOException { name = in.readString(); valueFormatter = ValueFormatterStreams.readOptional(in); sum = in.readDouble(); count = in.readVLong(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(name); ValueFormatterStreams.writeOptional(valueFormatter, out); out.writeDouble(sum); out.writeVLong(count); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(name); builder.field(CommonFields.VALUE, count != 0 ? getValue() : null); if (count != 0 && valueFormatter != null) { builder.field(CommonFields.VALUE_AS_STRING, valueFormatter.format(getValue())); } builder.endObject(); return builder; } }
1no label
src_main_java_org_elasticsearch_search_aggregations_metrics_avg_InternalAvg.java
1,315
public final class ExecutionCallbackAdapter implements Callback<Object> { private final ExecutionCallback executionCallback; public ExecutionCallbackAdapter(ExecutionCallback executionCallback) { this.executionCallback = executionCallback; } @Override public void notify(Object response) { if (response instanceof Throwable) { executionCallback.onFailure((Throwable) response); } else { //noinspection unchecked executionCallback.onResponse(response); } } }
0true
hazelcast_src_main_java_com_hazelcast_executor_ExecutionCallbackAdapter.java
1,530
public interface HazelcastConnectionFactory extends ConnectionFactory { /** @return access to the real bridging object to access Hazelcast's infrastructure * @see HazelcastConnection */ HazelcastConnection getConnection() throws ResourceException; /** @return access to the real bridging object to access Hazelcast's infrastructure * @see HazelcastConnection */ HazelcastConnection getConnection(ConnectionSpec connSpec) throws ResourceException; }
0true
hazelcast-ra_hazelcast-jca_src_main_java_com_hazelcast_jca_HazelcastConnectionFactory.java
1,036
protected static class TestDoc { final public String id; final public TestFieldSetting[] fieldSettings; final public String[] fieldContent; public String index = "test"; public String type = "type1"; public TestDoc(String id, TestFieldSetting[] fieldSettings, String[] fieldContent) { this.id = id; assertEquals(fieldSettings.length, fieldContent.length); this.fieldSettings = fieldSettings; this.fieldContent = fieldContent; } public TestDoc index(String index) { this.index = index; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder("index:").append(index).append(" type:").append(type).append(" id:").append(id); for (int i = 0; i < fieldSettings.length; i++) { TestFieldSetting f = fieldSettings[i]; sb.append("\n").append("Field: ").append(f).append("\n content:").append(fieldContent[i]); } sb.append("\n"); return sb.toString(); } }
0true
src_test_java_org_elasticsearch_action_termvector_AbstractTermVectorTests.java
733
public class DeleteByQueryRequestBuilder extends IndicesReplicationOperationRequestBuilder<DeleteByQueryRequest, DeleteByQueryResponse, DeleteByQueryRequestBuilder> { private QuerySourceBuilder sourceBuilder; public DeleteByQueryRequestBuilder(Client client) { super((InternalClient) client, new DeleteByQueryRequest()); } /** * The types of documents the query will run against. Defaults to all types. */ public DeleteByQueryRequestBuilder setTypes(String... types) { request.types(types); return this; } /** * A comma separated list of routing values to control the shards the action will be executed on. */ public DeleteByQueryRequestBuilder setRouting(String routing) { request.routing(routing); return this; } /** * The routing values to control the shards that the action will be executed on. */ public DeleteByQueryRequestBuilder setRouting(String... routing) { request.routing(routing); return this; } /** * The query to delete documents for. * * @see org.elasticsearch.index.query.QueryBuilders */ public DeleteByQueryRequestBuilder setQuery(QueryBuilder queryBuilder) { sourceBuilder().setQuery(queryBuilder); return this; } /** * The source to execute. It is preferable to use either {@link #setSource(byte[])} * or {@link #setQuery(QueryBuilder)}. */ public DeleteByQueryRequestBuilder setSource(String source) { request().source(source); return this; } /** * The source to execute in the form of a map. */ public DeleteByQueryRequestBuilder setSource(Map<String, Object> source) { request().source(source); return this; } /** * The source to execute in the form of a builder. */ public DeleteByQueryRequestBuilder setSource(XContentBuilder builder) { request().source(builder); return this; } /** * The source to execute. */ public DeleteByQueryRequestBuilder setSource(byte[] source) { request().source(source); return this; } /** * The source to execute. */ public DeleteByQueryRequestBuilder setSource(BytesReference source) { request().source(source, false); return this; } /** * The source to execute. */ public DeleteByQueryRequestBuilder setSource(BytesReference source, boolean unsafe) { request().source(source, unsafe); return this; } /** * The source to execute. */ public DeleteByQueryRequestBuilder setSource(byte[] source, int offset, int length, boolean unsafe) { request().source(source, offset, length, unsafe); return this; } /** * The replication type to use with this operation. */ public DeleteByQueryRequestBuilder setReplicationType(ReplicationType replicationType) { request.replicationType(replicationType); return this; } /** * The replication type to use with this operation. */ public DeleteByQueryRequestBuilder setReplicationType(String replicationType) { request.replicationType(replicationType); return this; } public DeleteByQueryRequestBuilder setConsistencyLevel(WriteConsistencyLevel consistencyLevel) { request.consistencyLevel(consistencyLevel); return this; } @Override protected void doExecute(ActionListener<DeleteByQueryResponse> listener) { if (sourceBuilder != null) { request.source(sourceBuilder); } ((Client) client).deleteByQuery(request, listener); } private QuerySourceBuilder sourceBuilder() { if (sourceBuilder == null) { sourceBuilder = new QuerySourceBuilder(); } return sourceBuilder; } }
0true
src_main_java_org_elasticsearch_action_deletebyquery_DeleteByQueryRequestBuilder.java
1,517
final class NodeShutdownLatch { private final Map<String, HazelcastInstanceImpl> registrations; private final Semaphore latch; private final MemberImpl localMember; NodeShutdownLatch(final Node node) { localMember = node.localMember; Collection<MemberImpl> memberList = node.clusterService.getMemberList(); registrations = new HashMap<String, HazelcastInstanceImpl>(3); Set<MemberImpl> members = new HashSet<MemberImpl>(memberList); members.remove(localMember); if (!members.isEmpty()) { final Map<MemberImpl, HazelcastInstanceImpl> map = HazelcastInstanceFactory.getInstanceImplMap(); for (Map.Entry<MemberImpl, HazelcastInstanceImpl> entry : map.entrySet()) { final MemberImpl member = entry.getKey(); if (members.contains(member)) { HazelcastInstanceImpl instance = entry.getValue(); if (instance.node.isActive()) { try { ClusterServiceImpl clusterService = instance.node.clusterService; final String id = clusterService.addMembershipListener(new ShutdownMembershipListener()); registrations.put(id, instance); } catch (Throwable ignored) { } } } } } latch = new Semaphore(0); } void await(long time, TimeUnit unit) { if (registrations.isEmpty()) { return; } int permits = registrations.size(); for (HazelcastInstanceImpl instance : registrations.values()) { if (!instance.node.isActive()) { permits--; } } try { latch.tryAcquire(permits, time, unit); } catch (InterruptedException ignored) { } for (Map.Entry<String, HazelcastInstanceImpl> entry : registrations.entrySet()) { final HazelcastInstanceImpl instance = entry.getValue(); try { instance.node.clusterService.removeMembershipListener(entry.getKey()); } catch (Throwable ignored) { } } registrations.clear(); } private class ShutdownMembershipListener implements MembershipListener { @Override public void memberAdded(MembershipEvent membershipEvent) { } @Override public void memberRemoved(MembershipEvent event) { if (localMember.equals(event.getMember())) { latch.release(); } } @Override public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) { } } }
0true
hazelcast_src_main_java_com_hazelcast_instance_NodeShutdownLatch.java
1,342
completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference2.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference2.set(t); latch2.countDown(); } });
0true
hazelcast_src_test_java_com_hazelcast_executor_ExecutorServiceTest.java
137
public class NoOpLogicalLog extends XaLogicalLog { public NoOpLogicalLog( Logging logging ) { super( null, null, null, null, null, new Monitors(), logging, null, null, null, 10000l, null ); } @Override synchronized void open() throws IOException { super.open(); //To change body of overridden methods use File | Settings | File Templates. } @Override public boolean scanIsComplete() { return true; } @Override public synchronized int start( Xid xid, int masterId, int myId, long highestKnownCommittedTx ) { return 0; } @Override public synchronized void writeStartEntry( int identifier ) throws XAException { } @Override synchronized LogEntry.Start getStartEntry( int identifier ) { return null; } @Override public synchronized void prepare( int identifier ) throws XAException { } @Override public synchronized void commitOnePhase( int identifier, long txId, ForceMode forceMode ) throws XAException { } @Override public synchronized void done( int identifier ) throws XAException { } @Override synchronized void doneInternal( int identifier ) throws IOException { } @Override public synchronized void commitTwoPhase( int identifier, long txId, ForceMode forceMode ) throws XAException { } @Override public synchronized void writeCommand( XaCommand command, int identifier ) throws IOException { } @Override public synchronized void close() throws IOException { } @Override void reset() { super.reset(); //To change body of overridden methods use File | Settings | File Templates. } @Override void registerTxIdentifier( int identifier ) { } @Override void unregisterTxIdentifier() { } @Override public int getCurrentTxIdentifier() { return 0; } @Override public ReadableByteChannel getLogicalLog( long version ) throws IOException { return null; } @Override public ReadableByteChannel getLogicalLog( long version, long position ) throws IOException { return null; } @Override public synchronized ReadableByteChannel getPreparedTransaction( int identifier ) throws IOException { return null; } @Override public synchronized void getPreparedTransaction( int identifier, LogBuffer targetBuffer ) throws IOException { } @Override public LogExtractor getLogExtractor( long startTxId, long endTxIdHint ) throws IOException { return null; } @Override public synchronized Pair<Integer, Long> getMasterForCommittedTransaction( long txId ) throws IOException { return null; } @Override public ReadableByteChannel getLogicalLogOrMyselfCommitted( long version, long position ) throws IOException { return null; } @Override public long getLogicalLogLength( long version ) { return 0l; } @Override public boolean hasLogicalLog( long version ) { return false; } @Override public boolean deleteLogicalLog( long version ) { return false; } @Override protected LogDeserializer getLogDeserializer( ReadableByteChannel byteChannel ) { return null; } @Override public synchronized void applyTransactionWithoutTxId( ReadableByteChannel byteChannel, long nextTxId, ForceMode forceMode ) throws IOException { } @Override public synchronized void applyTransaction( ReadableByteChannel byteChannel ) throws IOException { } @Override public synchronized long rotate() throws IOException { return 0l; } @Override public void setAutoRotateLogs( boolean autoRotate ) { } @Override public boolean isLogsAutoRotated() { return false; } @Override public void setLogicalLogTargetSize( long size ) { } @Override public long getLogicalLogTargetSize() { return 0l; } @Override public File getFileName( long version ) { return null; } @Override public File getBaseFileName() { return null; } @Override public Pattern getHistoryFileNamePattern() { return null; } @Override public boolean wasNonClean() { return false; } @Override public long getHighestLogVersion() { return 0l; } @Override public Long getFirstCommittedTxId( long version ) { return 0l; } @Override public long getLastCommittedTxId() { return 0l; } @Override public Long getFirstStartRecordTimestamp( long version ) throws IOException { return 0l; } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_NoOpLogicalLog.java
1,908
public class DataDTOToMVELTranslator { public String createMVEL(String entityKey, DataDTO dataDTO, RuleBuilderFieldService fieldService) throws MVELTranslationException { StringBuffer sb = new StringBuffer(); buildMVEL(dataDTO, sb, entityKey, null, fieldService); String response = sb.toString().trim(); if (response.length() == 0) { response = null; } return response; } protected void buildMVEL(DataDTO dataDTO, StringBuffer sb, String entityKey, String groupOperator, RuleBuilderFieldService fieldService) throws MVELTranslationException { BLCOperator operator = null; if (dataDTO instanceof ExpressionDTO) { operator = BLCOperator.valueOf(((ExpressionDTO) dataDTO).getOperator()); } else { operator = BLCOperator.valueOf(dataDTO.getGroupOperator()); } ArrayList<DataDTO> groups = dataDTO.getGroups(); if (sb.length() != 0 && sb.charAt(sb.length() - 1) != '(' && groupOperator != null) { BLCOperator groupOp = BLCOperator.valueOf(groupOperator); switch(groupOp) { default: sb.append("&&"); break; case OR: sb.append("||"); } } if (dataDTO instanceof ExpressionDTO) { buildExpression((ExpressionDTO)dataDTO, sb, entityKey, operator, fieldService); } else { boolean includeTopLevelParenthesis = false; if (sb.length() != 0 || BLCOperator.NOT.equals(operator) || (sb.length() == 0 && groupOperator != null)) { includeTopLevelParenthesis = true; } if (BLCOperator.NOT.equals(operator)) { sb.append("!"); } if (includeTopLevelParenthesis) sb.append("("); for (DataDTO dto : groups) { buildMVEL(dto, sb, entityKey, dataDTO.getGroupOperator(), fieldService); } if (includeTopLevelParenthesis) sb.append(")"); } } protected void buildExpression(ExpressionDTO expressionDTO, StringBuffer sb, String entityKey, BLCOperator operator, RuleBuilderFieldService fieldService) throws MVELTranslationException { String field = expressionDTO.getName(); SupportedFieldType type = fieldService.getSupportedFieldType(field); SupportedFieldType secondaryType = fieldService.getSecondaryFieldType(field); Object[] value; if (type == null) { throw new MVELTranslationException(MVELTranslationException.SPECIFIED_FIELD_NOT_FOUND, "The DataDTO is not compatible with the RuleBuilderFieldService " + "associated with the current rules builder. Unable to find the field " + "specified: ("+field+")"); } if ( SupportedFieldType.DATE.toString().equals(type.toString()) && !BLCOperator.CONTAINS_FIELD.equals(operator) && !BLCOperator.ENDS_WITH_FIELD.equals(operator) && !BLCOperator.EQUALS_FIELD.equals(operator) && !BLCOperator.GREATER_OR_EQUAL_FIELD.equals(operator) && !BLCOperator.GREATER_THAN_FIELD.equals(operator) && !BLCOperator.LESS_OR_EQUAL_FIELD.equals(operator) && !BLCOperator.LESS_THAN_FIELD.equals(operator) && !BLCOperator.NOT_EQUAL_FIELD.equals(operator) && !BLCOperator.STARTS_WITH_FIELD.equals(operator) && !BLCOperator.BETWEEN.equals(operator) && !BLCOperator.BETWEEN_INCLUSIVE.equals(operator) ) { value = extractDate(expressionDTO, operator, "value"); } else { value = extractBasicValues(expressionDTO.getValue()); } switch(operator) { case CONTAINS: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".contains", true, false, false, false, false); break; } case CONTAINS_FIELD: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".contains", true, true, false, false, false); break; } case ENDS_WITH: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".endsWith", true, false, false, false, false); break; } case ENDS_WITH_FIELD: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".endsWith", true, true, false, false, false); break; } case EQUALS: { buildExpression(sb, entityKey, field, value, type, secondaryType, "==", false, false, false, false, false); break; } case EQUALS_FIELD: { buildExpression(sb, entityKey, field, value, type, secondaryType, "==", false, true, false, false, false); break; } case GREATER_OR_EQUAL: { buildExpression(sb, entityKey, field, value, type, secondaryType, ">=", false, false, false, false, false); break; } case GREATER_OR_EQUAL_FIELD: { buildExpression(sb, entityKey, field, value, type, secondaryType, ">=", false, true, false, false, false); break; } case GREATER_THAN: { buildExpression(sb, entityKey, field, value, type, secondaryType, ">", false, false, false, false, false); break; } case GREATER_THAN_FIELD: { buildExpression(sb, entityKey, field, value, type, secondaryType, ">", false, true, false, false, false); break; } case ICONTAINS: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".contains", true, false, true, false, false); break; } case IENDS_WITH: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".endsWith", true, false, true, false, false); break; } case IEQUALS: { buildExpression(sb, entityKey, field, value, type, secondaryType, "==", false, false, true, false, false); break; } case INOT_CONTAINS: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".contains", true, false, true, true, false); break; } case INOT_ENDS_WITH: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".endsWith", true, false, true, true, false); break; } case INOT_EQUAL: { buildExpression(sb, entityKey, field, value, type, secondaryType, "!=", false, false, true, false, false); break; } case INOT_STARTS_WITH: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".startsWith", true, false, true, true, false); break; } case IS_NULL: { buildExpression(sb, entityKey, field, new Object[]{"null"}, type, secondaryType, "==", false, false, false, false, true); break; } case ISTARTS_WITH: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".startsWith", true, false, true, false, false); break; } case LESS_OR_EQUAL: { buildExpression(sb, entityKey, field, value, type, secondaryType, "<=", false, false, false, false, false); break; } case LESS_OR_EQUAL_FIELD: { buildExpression(sb, entityKey, field, value, type, secondaryType, "<=", false, true, false, false, false); break; } case LESS_THAN: { buildExpression(sb, entityKey, field, value, type, secondaryType, "<", false, false, false, false, false); break; } case LESS_THAN_FIELD: { buildExpression(sb, entityKey, field, value, type, secondaryType, "<", false, true, false, false, false); break; } case NOT_CONTAINS: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".contains", true, false, false, true, false); break; } case NOT_ENDS_WITH: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".endsWith", true, false, false, true, false); break; } case NOT_EQUAL: { buildExpression(sb, entityKey, field, value, type, secondaryType, "!=", false, false, false, false, false); break; } case NOT_EQUAL_FIELD: { buildExpression(sb, entityKey, field, value, type, secondaryType, "!=", false, true, false, false, false); break; } case NOT_NULL: { buildExpression(sb, entityKey, field, new Object[]{"null"}, type, secondaryType, "!=", false, false, false, false, true); break; } case NOT_STARTS_WITH: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".startsWith", true, false, false, true, false); break; } case STARTS_WITH: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".startsWith", true, false, false, false, false); break; } case STARTS_WITH_FIELD: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".startsWith", true, true, false, false, false); break; } case COUNT_GREATER_THAN: { buildExpression(sb, entityKey, field, value, type, secondaryType, ".size()>", false, false, false, false, true); break; } case COUNT_GREATER_OR_EQUAL:{ buildExpression(sb, entityKey, field, value, type, secondaryType, ".size()>=", false, false, false, false, true); break; } case COUNT_LESS_THAN:{ buildExpression(sb, entityKey, field, value, type, secondaryType, ".size()<", false, false, false, false, true); break; } case COUNT_LESS_OR_EQUAL:{ buildExpression(sb, entityKey, field, value, type, secondaryType, ".size()<=", false, false, false, false, true); break; } case COUNT_EQUALS:{ buildExpression(sb, entityKey, field, value, type, secondaryType, ".size()==", false, false, false, false, true); break; } case BETWEEN: { if (SupportedFieldType.DATE.toString().equals(type.toString())) { sb.append("("); buildExpression(sb, entityKey, field, extractDate(expressionDTO, BLCOperator.GREATER_THAN, "start"), type, secondaryType, ">", false, false, false, false, false); sb.append("&&"); buildExpression(sb, entityKey, field, extractDate(expressionDTO, BLCOperator.LESS_THAN, "end"), type, secondaryType, "<", false, false, false, false, false); sb.append(")"); } else { sb.append("("); buildExpression(sb, entityKey, field, new Object[]{expressionDTO.getStart()}, type, secondaryType, ">", false, false, false, false, false); sb.append("&&"); buildExpression(sb, entityKey, field, new Object[]{expressionDTO.getEnd()}, type, secondaryType, "<", false, false, false, false, false); sb.append(")"); } break; } case BETWEEN_INCLUSIVE: { if ( SupportedFieldType.DATE.toString().equals(type.toString()) ) { sb.append("("); buildExpression(sb, entityKey, field, extractDate(expressionDTO, BLCOperator.GREATER_OR_EQUAL, "start"), type, secondaryType, ">=", false, false, false, false, false); sb.append("&&"); buildExpression(sb, entityKey, field, extractDate(expressionDTO, BLCOperator.LESS_OR_EQUAL, "end"), type, secondaryType, "<=", false, false, false, false, false); sb.append(")"); } else { sb.append("("); buildExpression(sb, entityKey, field, new Object[]{expressionDTO.getStart()}, type, secondaryType, ">=", false, false, false, false, false); sb.append("&&"); buildExpression(sb, entityKey, field, new Object[]{expressionDTO.getEnd()}, type, secondaryType, "<=", false, false, false, false, false); sb.append(")"); } break; } } } @SuppressWarnings({ "rawtypes", "deprecation", "unchecked" }) protected Object[] extractDate(ExpressionDTO expressionDTO, BLCOperator operator, String key) { String value; if ("start".equals(key)) { value = expressionDTO.getStart(); } else if ("end".equals(key)) { value = expressionDTO.getEnd(); } else { value = expressionDTO.getValue(); } //TODO handle Date Time Format // if (BLCOperator.GREATER_THAN.equals(operator) || BLCOperator.LESS_OR_EQUAL.equals(operator)) { // ((Date) value).setHours(23); // ((Date) value).setMinutes(59); // } else { // ((Date) value).setHours(0); // ((Date) value).setMinutes(0); // } return new Object[]{value}; } protected Object[] extractBasicValues(Object value) { if (value == null) { return null; } String stringValue = value.toString().trim(); Object[] response = new Object[]{}; if (isProjection(value)) { List<String> temp = new ArrayList<String>(); int initial = 1; //assume this is a multi-value phrase boolean eof = false; while (!eof) { int end = stringValue.indexOf(",", initial); if (end == -1) { eof = true; end = stringValue.length() - 1; } temp.add(stringValue.substring(initial, end)); initial = end + 1; } response = temp.toArray(response); } else { response = new Object[]{value}; } return response; } public boolean isProjection(Object value) { String stringValue = value.toString().trim(); return stringValue.startsWith("[") && stringValue.endsWith("]") && stringValue.indexOf(",") > 0; } protected void buildExpression(StringBuffer sb, String entityKey, String field, Object[] value, SupportedFieldType type, SupportedFieldType secondaryType, String operator, boolean includeParenthesis, boolean isFieldComparison, boolean ignoreCase, boolean isNegation, boolean ignoreQuotes) throws MVELTranslationException { if (operator.equals("==") && !isFieldComparison && value.length > 1) { sb.append("("); sb.append("["); sb.append(formatValue(field, entityKey, type, secondaryType, value, isFieldComparison, ignoreCase, ignoreQuotes)); sb.append("] contains "); sb.append(formatField(entityKey, type, field, ignoreCase, isNegation)); if ((type.equals(SupportedFieldType.ID) && secondaryType != null && secondaryType.equals(SupportedFieldType.INTEGER)) || type.equals(SupportedFieldType.INTEGER)) { sb.append(".intValue()"); } sb.append(")"); } else { sb.append(formatField(entityKey, type, field, ignoreCase, isNegation)); sb.append(operator); if (includeParenthesis) { sb.append("("); } sb.append(formatValue(field, entityKey, type, secondaryType, value, isFieldComparison, ignoreCase, ignoreQuotes)); if (includeParenthesis) { sb.append(")"); } } } protected String buildFieldName(String entityKey, String fieldName) { String response = entityKey + "." + fieldName; response = response.replaceAll("\\.", ".?"); return response; } protected String formatField(String entityKey, SupportedFieldType type, String field, boolean ignoreCase, boolean isNegation) { StringBuilder response = new StringBuilder(); if (isNegation) { response.append("!"); } String convertedField = field; boolean isMapField = false; if (convertedField.contains(FieldManager.MAPFIELDSEPARATOR)) { //This must be a map field, convert the field name to syntax MVEL can understand for map access convertedField = convertedField.substring(0, convertedField.indexOf(FieldManager.MAPFIELDSEPARATOR)) + "[\"" + convertedField.substring(convertedField.indexOf(FieldManager.MAPFIELDSEPARATOR) + FieldManager.MAPFIELDSEPARATOR.length(), convertedField.length()) + "\"]"; isMapField = true; } if (isMapField) { switch(type) { case BOOLEAN: response.append("MvelHelper.convertField(\"BOOLEAN\","); response.append(buildFieldName(entityKey, convertedField)); response.append(")"); break; case INTEGER: response.append("MvelHelper.convertField(\"INTEGER\","); response.append(buildFieldName(entityKey, convertedField)); response.append(")"); break; case DECIMAL: case MONEY: response.append("MvelHelper.convertField(\"DECIMAL\","); response.append(buildFieldName(entityKey, convertedField)); response.append(")"); break; case DATE: response.append("MvelHelper.convertField(\"DATE\","); response.append(buildFieldName(entityKey, convertedField)); response.append(")"); break; case STRING: if (ignoreCase) { response.append("MvelHelper.toUpperCase("); } response.append(buildFieldName(entityKey, convertedField)); if (ignoreCase) { response.append(")"); } break; case STRING_LIST: response.append(buildFieldName(entityKey, convertedField)); break; default: throw new UnsupportedOperationException(type.toString() + " is not supported for map fields in the rule builder."); } } else { switch(type) { case BROADLEAF_ENUMERATION: if (isMapField) { throw new UnsupportedOperationException("Enumerations are not supported for map fields in the rule builder."); } else { response.append(buildFieldName(entityKey, convertedField)); response.append(".getType()"); } break; case MONEY: response.append(buildFieldName(entityKey, convertedField)); response.append(".getAmount()"); break; case STRING: if (ignoreCase) { response.append("MvelHelper.toUpperCase("); } response.append(buildFieldName(entityKey, convertedField)); if (ignoreCase) { response.append(")"); } break; default: response.append(buildFieldName(entityKey, convertedField)); break; } } return response.toString(); } protected String formatValue(String fieldName, String entityKey, SupportedFieldType type, SupportedFieldType secondaryType, Object[] value, boolean isFieldComparison, boolean ignoreCase, boolean ignoreQuotes) throws MVELTranslationException { StringBuilder response = new StringBuilder(); if (isFieldComparison) { switch(type) { case MONEY: response.append(entityKey); response.append("."); response.append(value[0]); response.append(".getAmount()"); break; case STRING: if (ignoreCase) { response.append("MvelHelper.toUpperCase("); } response.append(entityKey); response.append("."); response.append(value[0]); if (ignoreCase) { response.append(")"); } break; default: response.append(entityKey); response.append("."); response.append(value[0]); break; } } else { for (int j=0;j<value.length;j++){ switch(type) { case BOOLEAN: response.append(value[j]); break; case DECIMAL: try { Double.parseDouble(value[j].toString()); } catch (Exception e) { throw new MVELTranslationException(MVELTranslationException.INCOMPATIBLE_DECIMAL_VALUE, "Cannot format value for the field (" + fieldName + ") based on field type. The type of field is Decimal, " + "and you entered: (" + value[j] +")"); } response.append(value[j]); break; case ID: if (secondaryType != null && secondaryType.toString().equals( SupportedFieldType.STRING.toString())) { if (ignoreCase) { response.append("MvelHelper.toUpperCase("); } if (!ignoreQuotes) { response.append("\""); } response.append(value[j]); if (!ignoreQuotes) { response.append("\""); } if (ignoreCase) { response.append(")"); } } else { try { Integer.parseInt(value[j].toString()); } catch (Exception e) { throw new MVELTranslationException(MVELTranslationException.INCOMPATIBLE_INTEGER_VALUE, "Cannot format value for the field (" + fieldName + ") based on field type. The type of field is Integer, " + "and you entered: (" + value[j] +")"); } response.append(value[j]); } break; case INTEGER: try { Integer.parseInt(value[j].toString()); } catch (Exception e) { throw new MVELTranslationException(MVELTranslationException.INCOMPATIBLE_INTEGER_VALUE, "Cannot format value for the field (" + fieldName + ") based on field type. The type of field is Integer, " + "and you entered: (" + value[j] +")"); } response.append(value[j]); break; case MONEY: try { Double.parseDouble(value[j].toString()); } catch (Exception e) { throw new MVELTranslationException(MVELTranslationException.INCOMPATIBLE_DECIMAL_VALUE, "Cannot format value for the field (" + fieldName + ") based on field type. The type of field is Money, " + "and you entered: (" + value[j] +")"); } response.append(value[j]); break; case DATE: //convert the date to our standard date/time format Date temp = null; try { temp = RuleBuilderFormatUtil.parseDate(String.valueOf(value[j])); } catch (ParseException e) { throw new MVELTranslationException(MVELTranslationException.INCOMPATIBLE_DATE_VALUE, "Cannot format value for the field (" + fieldName + ") based on field type. The type of field is Date, " + "and you entered: (" + value[j] +"). Dates must be in the format MM/dd/yyyy HH:mm."); } String convertedDate = FormatUtil.getTimeZoneFormat().format(temp); response.append("MvelHelper.convertField(\"DATE\",\""); response.append(convertedDate); response.append("\")"); break; default: if (ignoreCase) { response.append("MvelHelper.toUpperCase("); } if (!ignoreQuotes) { response.append("\""); } response.append(value[j]); if (!ignoreQuotes) { response.append("\""); } if (ignoreCase) { response.append(")"); } break; } if (j < value.length - 1) { response.append(","); } } } return response.toString(); } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_web_rulebuilder_DataDTOToMVELTranslator.java
1,605
public class ClusterSerializationTests extends ElasticsearchAllocationTestCase { @Test public void testClusterStateSerialization() throws Exception { MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(10).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); DiscoveryNodes nodes = DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3")).localNodeId("node1").masterNodeId("node2").build(); ClusterState clusterState = ClusterState.builder().nodes(nodes).metaData(metaData).routingTable(routingTable).build(); AllocationService strategy = createAllocationService(); clusterState = ClusterState.builder(clusterState).routingTable(strategy.reroute(clusterState).routingTable()).build(); ClusterState serializedClusterState = ClusterState.Builder.fromBytes(ClusterState.Builder.toBytes(clusterState), newNode("node1")); assertThat(serializedClusterState.routingTable().prettyPrint(), equalTo(clusterState.routingTable().prettyPrint())); } @Test public void testRoutingTableSerialization() throws Exception { MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(10).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); DiscoveryNodes nodes = DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3")).build(); ClusterState clusterState = ClusterState.builder().nodes(nodes).metaData(metaData).routingTable(routingTable).build(); AllocationService strategy = createAllocationService(); RoutingTable source = strategy.reroute(clusterState).routingTable(); BytesStreamOutput outStream = new BytesStreamOutput(); RoutingTable.Builder.writeTo(source, outStream); BytesStreamInput inStream = new BytesStreamInput(outStream.bytes().toBytes(), false); RoutingTable target = RoutingTable.Builder.readFrom(inStream); assertThat(target.prettyPrint(), equalTo(source.prettyPrint())); } }
0true
src_test_java_org_elasticsearch_cluster_serialization_ClusterSerializationTests.java
1,808
interface ConstructionProxy<T> { /** * Constructs an instance of {@code T} for the given arguments. */ T newInstance(Object... arguments) throws InvocationTargetException; /** * Returns the injection point for this constructor. */ InjectionPoint getInjectionPoint(); /** * Returns the injected constructor. If the injected constructor is synthetic (such as generated * code for method interception), the natural constructor is returned. */ Constructor<T> getConstructor(); }
0true
src_main_java_org_elasticsearch_common_inject_ConstructionProxy.java
954
public interface OrderDao { Order readOrderById(Long orderId); List<Order> readOrdersForCustomer(Customer customer, OrderStatus orderStatus); List<Order> readOrdersForCustomer(Long id); Order readNamedOrderForCustomer(Customer customer, String name); Order readCartForCustomer(Customer customer); Order save(Order order); void delete(Order order); Order submitOrder(Order cartOrder); Order create(); Order createNewCartForCustomer(Customer customer); Order readOrderByOrderNumber(String orderNumber); Order updatePrices(Order order); // removed methods // List<Order> readNamedOrdersForcustomer(Customer customer); // // Order readOrderForCustomer(Long customerId, Long orderId); // // List<Order> readSubmittedOrdersForCustomer(Customer customer); // }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_dao_OrderDao.java
302
@Deprecated public class InstrumentationRuntimeFactory { private static final Log LOG = LogFactory.getLog(InstrumentationRuntimeFactory.class); private static final String IBM_VM_CLASS = "com.ibm.tools.attach.VirtualMachine"; private static final String SUN_VM_CLASS = "com.sun.tools.attach.VirtualMachine"; private static boolean isIBM = false; private static Instrumentation inst; /** * This method is called by the JVM to set the instrumentation. We can't synchronize this because it will cause * a deadlock with the thread calling the getInstrumentation() method when the instrumentation is installed. * * @param agentArgs * @param instrumentation */ public static void agentmain(String agentArgs, Instrumentation instrumentation) { inst = instrumentation; } /** * This method returns the Instrumentation object provided by the JVM. If the Instrumentation object is null, * it does its best to add an instrumentation agent to the JVM and then the instrumentation object. * @return Instrumentation */ public static synchronized Instrumentation getInstrumentation() { if (inst != null) { return inst; } if (System.getProperty("java.vendor").toUpperCase().contains("IBM")) { isIBM = true; } AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { try { if (!InstrumentationRuntimeFactory.class.getClassLoader().equals( ClassLoader.getSystemClassLoader())) { return null; } } catch (Throwable t) { return null; } File toolsJar = null; // When running on IBM, the attach api classes are packaged in vm.jar which is a part // of the default vm classpath. if (! isIBM) { // If we can't find the tools.jar and we're not on IBM we can't load the agent. toolsJar = findToolsJar(); if (toolsJar == null) { return null; } } Class<?> vmClass = loadVMClass(toolsJar); if (vmClass == null) { return null; } String agentPath = getAgentJar(); if (agentPath == null) { return null; } loadAgent(agentPath, vmClass); return null; } }); return inst; } private static File findToolsJar() { String javaHome = System.getProperty("java.home"); File javaHomeFile = new File(javaHome); File toolsJarFile = new File(javaHomeFile, "lib" + File.separator + "tools.jar"); if (!toolsJarFile.exists()) { // If we're on an IBM SDK, then remove /jre off of java.home and try again. if (javaHomeFile.getAbsolutePath().endsWith(File.separator + "jre")) { javaHomeFile = javaHomeFile.getParentFile(); toolsJarFile = new File(javaHomeFile, "lib" + File.separator + "tools.jar"); } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { // If we're on a Mac, then change the search path to use ../Classes/classes.jar. if (javaHomeFile.getAbsolutePath().endsWith(File.separator + "Home")) { javaHomeFile = javaHomeFile.getParentFile(); toolsJarFile = new File(javaHomeFile, "Classes" + File.separator + "classes.jar"); } } } if (! toolsJarFile.exists()) { return null; } else { return toolsJarFile; } } private static String createAgentJar() throws IOException { File file = File.createTempFile(InstrumentationRuntimeFactory.class.getName(), ".jar"); file.deleteOnExit(); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(file)); zout.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF")); PrintWriter writer = new PrintWriter(new OutputStreamWriter(zout)); writer.println("Agent-Class: " + InstrumentationRuntimeFactory.class.getName()); writer.println("Can-Redefine-Classes: true"); // IBM doesn't support retransform writer.println("Can-Retransform-Classes: " + Boolean.toString(!isIBM)); writer.close(); return file.getAbsolutePath(); } private static String getAgentJar() { File agentJarFile = null; // Find the name of the File that this class was loaded from. That // jar *should* be the same location as our agent. CodeSource cs = InstrumentationRuntimeFactory.class.getProtectionDomain().getCodeSource(); if (cs != null) { URL loc = cs.getLocation(); if (loc != null) { agentJarFile = new File(loc.getFile()); } } // Determine whether the File that this class was loaded from has this // class defined as the Agent-Class. boolean createJar = false; if (cs == null || agentJarFile == null || agentJarFile.isDirectory()) { createJar = true; } else if (!validateAgentJarManifest(agentJarFile, InstrumentationRuntimeFactory.class.getName())) { // We have an agentJarFile, but this class isn't the Agent-Class. createJar = true; } String agentJar; if (createJar) { try { agentJar = createAgentJar(); } catch (IOException ioe) { agentJar = null; } } else { agentJar = agentJarFile.getAbsolutePath(); } return agentJar; } private static void loadAgent(String agentJar, Class<?> vmClass) { try { // first obtain the PID of the currently-running process // ### this relies on the undocumented convention of the // RuntimeMXBean's // ### name starting with the PID, but there appears to be no other // ### way to obtain the current process' id, which we need for // ### the attach process RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String pid = runtime.getName(); if (pid.contains("@")) pid = pid.substring(0, pid.indexOf("@")); // JDK1.6: now attach to the current VM so we can deploy a new agent // ### this is a Sun JVM specific feature; other JVMs may offer // ### this feature, but in an implementation-dependent way Object vm = vmClass.getMethod("attach", new Class<?>[]{String.class}).invoke(null, pid); vmClass.getMethod("loadAgent", new Class[]{String.class}).invoke(vm, agentJar); vmClass.getMethod("detach", new Class[]{}).invoke(vm); } catch (Throwable t) { if (LOG.isTraceEnabled()) { LOG.trace("Problem loading the agent", t); } } } private static Class<?> loadVMClass(File toolsJar) { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); String cls = SUN_VM_CLASS; if (isIBM) { cls = IBM_VM_CLASS; } else { loader = new URLClassLoader(new URL[]{toolsJar.toURI().toURL()}, loader); } return loader.loadClass(cls); } catch (Exception e) { if (LOG.isTraceEnabled()) { LOG.trace("Failed to load the virtual machine class", e); } } return null; } private static boolean validateAgentJarManifest(File agentJarFile, String agentClassName) { try { JarFile jar = new JarFile(agentJarFile); Manifest manifest = jar.getManifest(); if (manifest == null) { return false; } Attributes attributes = manifest.getMainAttributes(); String ac = attributes.getValue("Agent-Class"); if (ac != null && ac.equals(agentClassName)) { return true; } } catch (Exception e) { if (LOG.isTraceEnabled()) { LOG.trace("Unexpected exception occured.", e); } } return false; } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_InstrumentationRuntimeFactory.java
1,004
public class SemaphorePortableHook implements PortableHook { static final int F_ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.SEMAPHORE_PORTABLE_FACTORY, -16); static final int ACQUIRE = 1; static final int AVAILABLE = 2; static final int DRAIN = 3; static final int INIT = 4; static final int REDUCE = 5; static final int RELEASE = 6; @Override public int getFactoryId() { return F_ID; } @Override public PortableFactory createFactory() { return new PortableFactory() { @Override public Portable create(int classId) { switch (classId) { case ACQUIRE: return new AcquireRequest(); case AVAILABLE: return new AvailableRequest(); case DRAIN: return new DrainRequest(); case INIT: return new InitRequest(); case REDUCE: return new ReduceRequest(); case RELEASE: return new ReleaseRequest(); default: return null; } } }; } @Override public Collection<ClassDefinition> getBuiltinDefinitions() { return null; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_semaphore_client_SemaphorePortableHook.java