Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
3,213
SINGLE_VALUED_DENSE_ENUM { public int numValues(Random r) { return 1; } @Override public long nextValue(Random r) { return 1 + r.nextInt(16); } },
0true
src_test_java_org_elasticsearch_index_fielddata_LongFieldDataTests.java
57
public class OLockException extends OException { private static final long serialVersionUID = 2215169397325875189L; public OLockException(String iMessage) { super(iMessage); // OProfiler.getInstance().updateCounter("system.concurrency.OLockException", +1); } public OLockException(String iMessage, Exception iException) { super(iMessage, iException); // OProfiler.getInstance().updateCounter("system.concurrency.OLockException", +1); } }
0true
commons_src_main_java_com_orientechnologies_common_concur_lock_OLockException.java
2,455
public class EsRejectedExecutionException extends ElasticsearchException { public EsRejectedExecutionException(String message) { super(message); } public EsRejectedExecutionException() { super(null); } public EsRejectedExecutionException(Throwable e) { super(null, e); } @Override public RestStatus status() { return RestStatus.SERVICE_UNAVAILABLE; } }
0true
src_main_java_org_elasticsearch_common_util_concurrent_EsRejectedExecutionException.java
336
public class NodesRestartRequestBuilder extends NodesOperationRequestBuilder<NodesRestartRequest, NodesRestartResponse, NodesRestartRequestBuilder> { public NodesRestartRequestBuilder(ClusterAdminClient clusterClient) { super((InternalClusterAdminClient) clusterClient, new NodesRestartRequest()); } /** * The delay for the restart to occur. Defaults to <tt>1s</tt>. */ public NodesRestartRequestBuilder setDelay(TimeValue delay) { request.delay(delay); return this; } /** * The delay for the restart to occur. Defaults to <tt>1s</tt>. */ public NodesRestartRequestBuilder setDelay(String delay) { request.delay(delay); return this; } @Override protected void doExecute(ActionListener<NodesRestartResponse> listener) { ((ClusterAdminClient) client).nodesRestart(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_restart_NodesRestartRequestBuilder.java
1,253
addOperation(operations, new Runnable() { public void run() { ITopic topic = hazelcast.getTopic("myTopic"); topic.publish(String.valueOf(random.nextInt(100000000))); messagesSend.incrementAndGet(); } }, 10);
0true
hazelcast_src_main_java_com_hazelcast_examples_AllTest.java
3,459
static final class Fields { static final XContentBuilderString _INDEX = new XContentBuilderString("_index"); static final XContentBuilderString _TYPE = new XContentBuilderString("_type"); static final XContentBuilderString _ID = new XContentBuilderString("_id"); static final XContentBuilderString _VERSION = new XContentBuilderString("_version"); static final XContentBuilderString FOUND = new XContentBuilderString("found"); static final XContentBuilderString FIELDS = new XContentBuilderString("fields"); }
0true
src_main_java_org_elasticsearch_index_get_GetResult.java
2,123
private static class SystemErrStream extends OutputStream { public SystemErrStream() { } public void close() { } public void flush() { System.err.flush(); } public void write(final byte[] b) throws IOException { if (!Loggers.consoleLoggingEnabled()) { return; } System.err.write(b); } public void write(final byte[] b, final int off, final int len) throws IOException { if (!Loggers.consoleLoggingEnabled()) { return; } System.err.write(b, off, len); } public void write(final int b) throws IOException { if (!Loggers.consoleLoggingEnabled()) { return; } System.err.write(b); } }
0true
src_main_java_org_elasticsearch_common_logging_log4j_ConsoleAppender.java
2,472
static class AwaitingJob extends PrioritizedRunnable { private final CountDownLatch latch; private AwaitingJob(CountDownLatch latch) { super(Priority.URGENT); this.latch = latch; } @Override public void run() { try { latch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
0true
src_test_java_org_elasticsearch_common_util_concurrent_PrioritizedExecutorsTests.java
196
public interface MetaAnnotatable { public Object setMetaData(EntryMetaData key, Object value); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_MetaAnnotatable.java
516
public class IndicesExistsRequestBuilder extends MasterNodeReadOperationRequestBuilder<IndicesExistsRequest, IndicesExistsResponse, IndicesExistsRequestBuilder> { public IndicesExistsRequestBuilder(IndicesAdminClient indicesClient, String... indices) { super((InternalIndicesAdminClient) indicesClient, new IndicesExistsRequest(indices)); } public IndicesExistsRequestBuilder setIndices(String... indices) { request.indices(indices); return this; } /** * Specifies what type of requested indices to ignore and wildcard indices expressions. * * For example indices that don't exist. */ public IndicesExistsRequestBuilder setIndicesOptions(IndicesOptions options) { request.indicesOptions(options); return this; } @Override protected void doExecute(ActionListener<IndicesExistsResponse> listener) { ((IndicesAdminClient) client).exists(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_exists_indices_IndicesExistsRequestBuilder.java
147
public class OBinaryTypeSerializer implements OBinarySerializer<byte[]> { private static final OBinaryConverter CONVERTER = OBinaryConverterFactory.getConverter(); public static final OBinaryTypeSerializer INSTANCE = new OBinaryTypeSerializer(); public static final byte ID = 17; public int getObjectSize(int length) { return length + OIntegerSerializer.INT_SIZE; } public int getObjectSize(byte[] object, Object... hints) { return object.length + OIntegerSerializer.INT_SIZE; } public void serialize(byte[] object, byte[] stream, int startPosition, Object... hints) { int len = object.length; OIntegerSerializer.INSTANCE.serialize(len, stream, startPosition); System.arraycopy(object, 0, stream, startPosition + OIntegerSerializer.INT_SIZE, len); } public byte[] deserialize(byte[] stream, int startPosition) { int len = OIntegerSerializer.INSTANCE.deserialize(stream, startPosition); return Arrays.copyOfRange(stream, startPosition + OIntegerSerializer.INT_SIZE, startPosition + OIntegerSerializer.INT_SIZE + len); } public int getObjectSize(byte[] stream, int startPosition) { return OIntegerSerializer.INSTANCE.deserialize(stream, startPosition) + OIntegerSerializer.INT_SIZE; } public int getObjectSizeNative(byte[] stream, int startPosition) { return CONVERTER.getInt(stream, startPosition, ByteOrder.nativeOrder()) + OIntegerSerializer.INT_SIZE; } public void serializeNative(byte[] object, byte[] stream, int startPosition, Object... hints) { int len = object.length; CONVERTER.putInt(stream, startPosition, len, ByteOrder.nativeOrder()); System.arraycopy(object, 0, stream, startPosition + OIntegerSerializer.INT_SIZE, len); } public byte[] deserializeNative(byte[] stream, int startPosition) { int len = CONVERTER.getInt(stream, startPosition, ByteOrder.nativeOrder()); return Arrays.copyOfRange(stream, startPosition + OIntegerSerializer.INT_SIZE, startPosition + OIntegerSerializer.INT_SIZE + len); } @Override public void serializeInDirectMemory(byte[] object, ODirectMemoryPointer pointer, long offset, Object... hints) { int len = object.length; pointer.setInt(offset, len); offset += OIntegerSerializer.INT_SIZE; pointer.set(offset, object, 0, len); } @Override public byte[] deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) { int len = pointer.getInt(offset); offset += OIntegerSerializer.INT_SIZE; return pointer.get(offset, len); } @Override public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) { return pointer.getInt(offset) + OIntegerSerializer.INT_SIZE; } public byte getId() { return ID; } public boolean isFixedLength() { return false; } public int getFixedLength() { return 0; } @Override public byte[] preprocess(byte[] value, Object... hints) { return value; } }
0true
commons_src_main_java_com_orientechnologies_common_serialization_types_OBinaryTypeSerializer.java
1,145
public class UpdateFulfillmentGroupItemActivity extends BaseActivity<CartOperationContext> { @Resource(name = "blFulfillmentGroupItemStrategy") protected FulfillmentGroupItemStrategy fgItemStrategy; @Override public CartOperationContext execute(CartOperationContext context) throws Exception { CartOperationRequest request = context.getSeedData(); request = fgItemStrategy.onItemUpdated(request); context.setSeedData(request); return context; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_workflow_update_UpdateFulfillmentGroupItemActivity.java
1,525
public static class Map extends Mapper<NullWritable, FaunusVertex, WritableComparable, LongWritable> { private String property; private WritableHandler handler; private boolean isVertex; // making use of in-map aggregation/combiner private CounterMap<Object> map; private int mapSpillOver; private SafeMapperOutputs outputs; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.map = new CounterMap<Object>(); this.mapSpillOver = context.getConfiguration().getInt(Tokens.TITAN_HADOOP_PIPELINE_MAP_SPILL_OVER, Tokens.DEFAULT_MAP_SPILL_OVER); this.property = context.getConfiguration().get(PROPERTY); this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class); this.handler = new WritableHandler(context.getConfiguration().getClass(TYPE, Text.class, WritableComparable.class)); this.outputs = new SafeMapperOutputs(context); } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, WritableComparable, LongWritable>.Context context) throws IOException, InterruptedException { if (this.isVertex) { if (value.hasPaths()) { this.map.incr(ElementPicker.getProperty(value, this.property), value.pathCount()); DEFAULT_COMPAT.incrementContextCounter(context, Counters.PROPERTIES_COUNTED, 1L); } } else { for (final Edge e : value.getEdges(Direction.OUT)) { final StandardFaunusEdge edge = (StandardFaunusEdge) e; if (edge.hasPaths()) { this.map.incr(ElementPicker.getProperty(edge, this.property), edge.pathCount()); DEFAULT_COMPAT.incrementContextCounter(context, Counters.PROPERTIES_COUNTED, 1L); } } } // protected against memory explosion if (this.map.size() > this.mapSpillOver) { this.dischargeMap(context); } this.outputs.write(Tokens.GRAPH, NullWritable.get(), value); } private final LongWritable longWritable = new LongWritable(); public void dischargeMap(final Mapper<NullWritable, FaunusVertex, WritableComparable, LongWritable>.Context context) throws IOException, InterruptedException { for (final java.util.Map.Entry<Object, Long> entry : this.map.entrySet()) { this.longWritable.set(entry.getValue()); context.write(this.handler.set(entry.getKey()), this.longWritable); } this.map.clear(); } @Override public void cleanup(final Mapper<NullWritable, FaunusVertex, WritableComparable, LongWritable>.Context context) throws IOException, InterruptedException { this.dischargeMap(context); this.outputs.close(); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_ValueGroupCountMapReduce.java
1,848
private static class ConvertedConstantBindingImpl<T> extends BindingImpl<T> implements ConvertedConstantBinding<T> { final T value; final Provider<T> provider; final Binding<String> originalBinding; ConvertedConstantBindingImpl( Injector injector, Key<T> key, T value, Binding<String> originalBinding) { super(injector, key, originalBinding.getSource(), new ConstantFactory<T>(Initializables.of(value)), Scoping.UNSCOPED); this.value = value; provider = Providers.of(value); this.originalBinding = originalBinding; } @Override public Provider<T> getProvider() { return provider; } public <V> V acceptTargetVisitor(BindingTargetVisitor<? super T, V> visitor) { return visitor.visit(this); } public T getValue() { return value; } public Key<String> getSourceKey() { return originalBinding.getKey(); } public Set<Dependency<?>> getDependencies() { return ImmutableSet.<Dependency<?>>of(Dependency.get(getSourceKey())); } public void applyTo(Binder binder) { throw new UnsupportedOperationException("This element represents a synthetic binding."); } @Override public String toString() { return new ToStringBuilder(ConvertedConstantBinding.class) .add("key", getKey()) .add("sourceKey", getSourceKey()) .add("value", value) .toString(); } }
0true
src_main_java_org_elasticsearch_common_inject_InjectorImpl.java
39
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); }});
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
178
public class AnnotationCreator extends ErrorVisitor { private static class PositionedMessage { public final String message; public final Position pos; public final int code; public final int severity; public final boolean syntaxError; public final int line; private PositionedMessage(String msg, Position pos, int severity, int code, boolean syntaxError, int line) { this.message = msg; this.pos = pos; this.code = code; this.severity = severity; this.syntaxError = syntaxError; this.line = line; } @Override public String toString() { return pos.toString() + " - "+ message; } } private final CeylonEditor editor; private final List<PositionedMessage> messages= new LinkedList<PositionedMessage>(); private final List<Annotation> annotations= new LinkedList<Annotation>(); public AnnotationCreator(CeylonEditor editor) { this.editor = editor; } @Override public void handleMessage(int startOffset, int endOffset, int startCol, int startLine, Message error) { messages.add(new PositionedMessage(error.getMessage(), new Position(startOffset, endOffset-startOffset+1), getSeverity(error, warnForErrors), error.getCode(), error instanceof RecognitionError, error.getLine())); } public void clearMessages() { messages.clear(); } public void updateAnnotations() { IDocumentProvider docProvider = editor.getDocumentProvider(); if (docProvider!=null) { IAnnotationModel model = docProvider.getAnnotationModel(editor.getEditorInput()); if (model instanceof IAnnotationModelExtension) { IAnnotationModelExtension modelExt = (IAnnotationModelExtension) model; Annotation[] oldAnnotations = annotations.toArray(new Annotation[annotations.size()]); Map<Annotation,Position> newAnnotations = new HashMap<Annotation,Position>(messages.size()); for (PositionedMessage pm: messages) { if (!suppressAnnotation(pm)) { Annotation a = createAnnotation(pm); newAnnotations.put(a, pm.pos); annotations.add(a); } } modelExt.replaceAnnotations(oldAnnotations, newAnnotations); } else if (model != null) { // model could be null if, e.g., we're directly browsing a file version in a src repo for (@SuppressWarnings("unchecked") Iterator<Annotation> i = model.getAnnotationIterator(); i.hasNext();) { Annotation a = i.next(); if (isParseAnnotation(a)) { model.removeAnnotation(a); } } for (PositionedMessage pm: messages) { if (!suppressAnnotation(pm)) { Annotation a= createAnnotation(pm); model.addAnnotation(a, pm.pos); annotations.add(a); } } } } messages.clear(); } public boolean suppressAnnotation(PositionedMessage pm) { boolean suppress = false; if (!pm.syntaxError && pm.line>=0) { for (PositionedMessage m: messages) { if (m.syntaxError && m.line==pm.line) { suppress = true; break; } } } return suppress; } private Annotation createAnnotation(PositionedMessage pm) { return new CeylonAnnotation(getAnnotationType(pm), pm.message, pm.code, pm.severity); } private String getAnnotationType(PositionedMessage pm) { switch (pm.severity) { case SEVERITY_ERROR: return PARSE_ANNOTATION_TYPE_ERROR; case SEVERITY_WARNING: return PARSE_ANNOTATION_TYPE_WARNING; case SEVERITY_INFO: return PARSE_ANNOTATION_TYPE_INFO; default: return PARSE_ANNOTATION_TYPE; } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_AnnotationCreator.java
368
public class GetRepositoriesAction extends ClusterAction<GetRepositoriesRequest, GetRepositoriesResponse, GetRepositoriesRequestBuilder> { public static final GetRepositoriesAction INSTANCE = new GetRepositoriesAction(); public static final String NAME = "cluster/repository/get"; private GetRepositoriesAction() { super(NAME); } @Override public GetRepositoriesResponse newResponse() { return new GetRepositoriesResponse(); } @Override public GetRepositoriesRequestBuilder newRequestBuilder(ClusterAdminClient client) { return new GetRepositoriesRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_repositories_get_GetRepositoriesAction.java
2,894
public static class GreaterLessPredicate extends EqualPredicate { boolean equal; boolean less; public GreaterLessPredicate() { } public GreaterLessPredicate(String attribute, Comparable value, boolean equal, boolean less) { super(attribute, value); this.equal = equal; this.less = less; } @Override public boolean apply(Map.Entry mapEntry) { final Comparable entryValue = readAttribute(mapEntry); final Comparable attributeValue = convert(mapEntry, entryValue, value); final int result = entryValue.compareTo(attributeValue); return equal && result == 0 || (less ? (result < 0) : (result > 0)); } @Override public Set<QueryableEntry> filter(QueryContext queryContext) { Index index = getIndex(queryContext); final ComparisonType comparisonType; if (less) { comparisonType = equal ? ComparisonType.LESSER_EQUAL : ComparisonType.LESSER; } else { comparisonType = equal ? ComparisonType.GREATER_EQUAL : ComparisonType.GREATER; } return index.getSubRecords(comparisonType, value); } @Override public void readData(ObjectDataInput in) throws IOException { super.readData(in); equal = in.readBoolean(); less = in.readBoolean(); } @Override public void writeData(ObjectDataOutput out) throws IOException { super.writeData(out); out.writeBoolean(equal); out.writeBoolean(less); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(attribute); sb.append(less ? "<" : ">"); if (equal) { sb.append("="); } sb.append(value); return sb.toString(); } }
1no label
hazelcast_src_main_java_com_hazelcast_query_Predicates.java
520
public class TypesExistsAction extends IndicesAction<TypesExistsRequest, TypesExistsResponse, TypesExistsRequestBuilder> { public static final TypesExistsAction INSTANCE = new TypesExistsAction(); public static final String NAME = "indices/types/exists"; private TypesExistsAction() { super(NAME); } @Override public TypesExistsResponse newResponse() { return new TypesExistsResponse(); } @Override public TypesExistsRequestBuilder newRequestBuilder(IndicesAdminClient client) { return new TypesExistsRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_exists_types_TypesExistsAction.java
319
private static class GotoResourceDialog extends FilteredResourcesSelectionDialog { private IJavaModel fJavaModel; public GotoResourceDialog(Shell parentShell, IContainer container, StructuredViewer viewer) { super(parentShell, false, container, IResource.FILE | IResource.FOLDER | IResource.PROJECT); fJavaModel= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); setTitle(PackagesMessages.GotoResource_dialog_title); PlatformUI.getWorkbench().getHelpSystem().setHelp(parentShell, IJavaHelpContextIds.GOTO_RESOURCE_DIALOG); } @Override protected ItemsFilter createFilter() { return new GotoResourceFilter(); } private class GotoResourceFilter extends ResourceFilter { /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog.ResourceFilter#matchItem(java.lang.Object) */ @Override public boolean matchItem(Object item) { IResource resource = (IResource) item; return super.matchItem(item) && select(resource); } /** * This is the orignal <code>select</code> method. Since * <code>GotoResourceDialog</code> needs to extend * <code>FilteredResourcesSelectionDialog</code> result of this * method must be combined with the <code>matchItem</code> method * from super class (<code>ResourceFilter</code>). * * @param resource * A resource * @return <code>true</code> if item matches against given * conditions <code>false</code> otherwise */ private boolean select(IResource resource) { IProject project= resource.getProject(); try { if (project.getNature(JavaCore.NATURE_ID) != null) return fJavaModel.contains(resource); } catch (CoreException e) { // do nothing. Consider resource; } return true; } /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog.ResourceFilter#equalsFilter(org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter) */ @Override public boolean equalsFilter(ItemsFilter filter) { if (!super.equalsFilter(filter)) { return false; } if (!(filter instanceof GotoResourceFilter)) { return false; } return true; } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_GotoResourceAction.java
2,150
protected class AllTermSpanScorer extends SpanScorer { protected DocsAndPositionsEnum positions; protected float payloadScore; protected int payloadsSeen; public AllTermSpanScorer(TermSpans spans, Weight weight, Similarity.SimScorer docScorer) throws IOException { super(spans, weight, docScorer); positions = spans.getPostings(); } @Override protected boolean setFreqCurrentDoc() throws IOException { if (!more) { return false; } doc = spans.doc(); freq = 0.0f; numMatches = 0; payloadScore = 0; payloadsSeen = 0; do { int matchLength = spans.end() - spans.start(); freq += docScorer.computeSlopFactor(matchLength); numMatches++; processPayload(); more = spans.next();// this moves positions to the next match } while (more && (doc == spans.doc())); return true; } protected void processPayload() throws IOException { final BytesRef payload; if ((payload = positions.getPayload()) != null) { payloadScore += decodeFloat(payload.bytes, payload.offset); payloadsSeen++; } else { // zero out the payload? } } /** * @return {@link #getSpanScore()} * {@link #getPayloadScore()} * @throws IOException */ @Override public float score() throws IOException { return getSpanScore() * getPayloadScore(); } /** * Returns the SpanScorer score only. * <p/> * Should not be overridden without good cause! * * @return the score for just the Span part w/o the payload * @throws IOException * @see #score() */ protected float getSpanScore() throws IOException { return super.score(); } /** * The score for the payload */ protected float getPayloadScore() { return payloadsSeen > 0 ? (payloadScore / payloadsSeen) : 1; } }
0true
src_main_java_org_elasticsearch_common_lucene_all_AllTermQuery.java
143
static final class HashCode { static final Random rng = new Random(); int code; HashCode() { int h = rng.nextInt(); // Avoid zero to allow xorShift rehash code = (h == 0) ? 1 : h; } }
0true
src_main_java_jsr166e_Striped64.java
101
public class OException extends RuntimeException { private static final long serialVersionUID = 3882447822497861424L; public OException() { } public OException(final String message) { super(message); } public OException(final Throwable cause) { super(cause); } public OException(final String message, final Throwable cause) { super(message, cause); } }
0true
commons_src_main_java_com_orientechnologies_common_exception_OException.java
1,060
return new Fields() { @Override public Iterator<String> iterator() { return Iterators.emptyIterator(); } @Override public Terms terms(String field) throws IOException { return null; } @Override public int size() { return 0; } };
0true
src_main_java_org_elasticsearch_action_termvector_TermVectorResponse.java
786
public interface OfferCodeDao { public OfferCode readOfferCodeById(Long offerCode); public OfferCode readOfferCodeByCode(String code); public OfferCode save(OfferCode offerCode); public void delete(OfferCode offerCodeId); public OfferCode create(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_dao_OfferCodeDao.java
1,625
public class DynamicSettings { private ImmutableMap<String, Validator> dynamicSettings = ImmutableMap.of(); public boolean hasDynamicSetting(String key) { for (String dynamicSetting : dynamicSettings.keySet()) { if (Regex.simpleMatch(dynamicSetting, key)) { return true; } } return false; } public String validateDynamicSetting(String dynamicSetting, String value) { for (Map.Entry<String, Validator> setting : dynamicSettings.entrySet()) { if (Regex.simpleMatch(dynamicSetting, setting.getKey())) { return setting.getValue().validate(dynamicSetting, value); } } return null; } public synchronized void addDynamicSetting(String setting, Validator validator) { MapBuilder<String, Validator> updatedSettings = MapBuilder.newMapBuilder(dynamicSettings); updatedSettings.put(setting, validator); dynamicSettings = updatedSettings.immutableMap(); } public synchronized void addDynamicSetting(String setting) { addDynamicSetting(setting, Validator.EMPTY); } public synchronized void addDynamicSettings(String... settings) { MapBuilder<String, Validator> updatedSettings = MapBuilder.newMapBuilder(dynamicSettings); for (String setting : settings) { updatedSettings.put(setting, Validator.EMPTY); } dynamicSettings = updatedSettings.immutableMap(); } }
0true
src_main_java_org_elasticsearch_cluster_settings_DynamicSettings.java
1,379
@RunWith(HazelcastSerialClassRunner.class) @Category(SlowTest.class) public class CustomPropertiesTest extends HibernateTestSupport { @Test public void test() { Properties props = getDefaultProperties(); props.put(CacheEnvironment.SHUTDOWN_ON_STOP, "false"); SessionFactory sf = createSessionFactory(props); HazelcastInstance hz = HazelcastAccessor.getHazelcastInstance(sf); assertEquals(1, hz.getCluster().getMembers().size()); MapConfig cfg = hz.getConfig().getMapConfig("com.hazelcast.hibernate.entity.*"); assertNotNull(cfg); assertEquals(30, cfg.getTimeToLiveSeconds()); assertEquals(50, cfg.getMaxSizeConfig().getSize()); sf.close(); assertTrue(hz.getLifecycleService().isRunning()); hz.shutdown(); } @Test public void testNativeClient() throws Exception { HazelcastInstance main = Hazelcast.newHazelcastInstance(new ClasspathXmlConfig("hazelcast-custom.xml")); Properties props = getDefaultProperties(); props.remove(CacheEnvironment.CONFIG_FILE_PATH_LEGACY); props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName()); props.setProperty(CacheEnvironment.USE_NATIVE_CLIENT, "true"); props.setProperty(CacheEnvironment.NATIVE_CLIENT_GROUP, "dev-custom"); props.setProperty(CacheEnvironment.NATIVE_CLIENT_PASSWORD, "dev-pass"); props.setProperty(CacheEnvironment.NATIVE_CLIENT_ADDRESS, "localhost"); SessionFactory sf = createSessionFactory(props); HazelcastInstance hz = HazelcastAccessor.getHazelcastInstance(sf); assertTrue(hz instanceof HazelcastClientProxy); assertEquals(1, main.getCluster().getMembers().size()); HazelcastClientProxy client = (HazelcastClientProxy) hz; ClientConfig clientConfig = client.getClientConfig(); assertEquals("dev-custom", clientConfig.getGroupConfig().getName()); assertEquals("dev-pass", clientConfig.getGroupConfig().getPassword()); assertTrue(clientConfig.getNetworkConfig().isSmartRouting()); assertTrue(clientConfig.getNetworkConfig().isRedoOperation()); Hazelcast.newHazelcastInstance(new ClasspathXmlConfig("hazelcast-custom.xml")); assertEquals(2, hz.getCluster().getMembers().size()); main.shutdown(); Thread.sleep(1000 * 3); // let client to reconnect assertEquals(1, hz.getCluster().getMembers().size()); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); session.save(new DummyEntity(1L, "dummy", 0, new Date())); tx.commit(); session.close(); sf.close(); Hazelcast.shutdownAll(); } @Test public void testNamedInstance() { Config config = new Config(); config.setInstanceName("hibernate"); HazelcastInstance hz = Hazelcast.newHazelcastInstance(config); Properties props = getDefaultProperties(); props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName()); props.put(CacheEnvironment.HAZELCAST_INSTANCE_NAME, "hibernate"); props.put(CacheEnvironment.SHUTDOWN_ON_STOP, "false"); final SessionFactory sf = createSessionFactory(props); assertTrue(hz == HazelcastAccessor.getHazelcastInstance(sf)); sf.close(); assertTrue(hz.getLifecycleService().isRunning()); hz.shutdown(); } private Properties getDefaultProperties() { Properties props = new Properties(); props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName()); props.setProperty(CacheEnvironment.CONFIG_FILE_PATH_LEGACY, "hazelcast-custom.xml"); return props; } }
0true
hazelcast-hibernate_hazelcast-hibernate3_src_test_java_com_hazelcast_hibernate_CustomPropertiesTest.java
1,146
public class UpdateOrderItemActivity extends BaseActivity<CartOperationContext> { @Resource(name = "blOrderService") protected OrderService orderService; @Override public CartOperationContext execute(CartOperationContext context) throws Exception { CartOperationRequest request = context.getSeedData(); OrderItemRequestDTO orderItemRequestDTO = request.getItemRequest(); Order order = request.getOrder(); OrderItem orderItem = null; for (OrderItem oi : order.getOrderItems()) { if (oi.getId().equals(orderItemRequestDTO.getOrderItemId())) { orderItem = oi; } } if (orderItem == null || !order.getOrderItems().contains(orderItem)) { throw new ItemNotFoundException("Order Item (" + orderItem.getId() + ") not found in Order (" + order.getId() + ")"); } OrderItem itemFromOrder = order.getOrderItems().get(order.getOrderItems().indexOf(orderItem)); if (orderItemRequestDTO.getQuantity() >= 0) { request.setOrderItemQuantityDelta(orderItemRequestDTO.getQuantity() - itemFromOrder.getQuantity()); itemFromOrder.setQuantity(orderItemRequestDTO.getQuantity()); order = orderService.save(order, false); request.setAddedOrderItem(itemFromOrder); request.setOrder(order); } return context; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_workflow_update_UpdateOrderItemActivity.java
632
public class OIndexTxAwareDictionary extends OIndexTxAwareOneValue { public OIndexTxAwareDictionary(ODatabaseRecord iDatabase, OIndex<OIdentifiable> iDelegate) { super(iDatabase, iDelegate); } @Override public void checkEntry(final OIdentifiable iRecord, final Object iKey) { } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndexTxAwareDictionary.java
638
public class OPropertyIndexDefinition extends OAbstractIndexDefinition { protected String className; protected String field; protected OType keyType; public OPropertyIndexDefinition(final String iClassName, final String iField, final OType iType) { className = iClassName; field = iField; keyType = iType; } /** * Constructor used for index unmarshalling. */ public OPropertyIndexDefinition() { } public String getClassName() { return className; } public List<String> getFields() { return Collections.singletonList(field); } public List<String> getFieldsToIndex() { return Collections.singletonList(field); } public Object getDocumentValueToIndex(final ODocument iDocument) { if (OType.LINK.equals(keyType)) { final OIdentifiable identifiable = iDocument.field(field, OType.LINK); if (identifiable != null) return createValue(identifiable.getIdentity()); else return null; } return createValue(iDocument.field(field)); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final OPropertyIndexDefinition that = (OPropertyIndexDefinition) o; if (!className.equals(that.className)) return false; if (!field.equals(that.field)) return false; if (keyType != that.keyType) return false; return true; } @Override public int hashCode() { int result = className.hashCode(); result = 31 * result + field.hashCode(); result = 31 * result + keyType.hashCode(); return result; } @Override public String toString() { return "OPropertyIndexDefinition{" + "className='" + className + '\'' + ", field='" + field + '\'' + ", keyType=" + keyType + '}'; } public Object createValue(final List<?> params) { return OType.convert(params.get(0), keyType.getDefaultJavaType()); } /** * {@inheritDoc} */ public Object createValue(final Object... params) { return OType.convert(params[0], keyType.getDefaultJavaType()); } public int getParamCount() { return 1; } public OType[] getTypes() { return new OType[] { keyType }; } @Override protected final void fromStream() { serializeFromStream(); } @Override public final ODocument toStream() { document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); try { serializeToStream(); } finally { document.setInternalStatus(ORecordElement.STATUS.LOADED); } return document; } protected void serializeToStream() { document.field("className", className); document.field("field", field); document.field("keyType", keyType.toString()); document.field("collate", collate.getName()); } protected void serializeFromStream() { className = document.field("className"); field = document.field("field"); final String keyTypeStr = document.field("keyType"); keyType = OType.valueOf(keyTypeStr); setCollate((String) document.field("collate")); } /** * {@inheritDoc} * * @param indexName * @param indexType */ public String toCreateIndexDDL(final String indexName, final String indexType) { return createIndexDDLWithFieldType(indexName, indexType).toString(); } protected StringBuilder createIndexDDLWithFieldType(String indexName, String indexType) { final StringBuilder ddl = createIndexDDLWithoutFieldType(indexName, indexType); ddl.append(' ').append(keyType.name()); return ddl; } protected StringBuilder createIndexDDLWithoutFieldType(final String indexName, final String indexType) { final StringBuilder ddl = new StringBuilder("create index "); final String shortName = className + "." + field; if (indexName.equalsIgnoreCase(shortName)) { ddl.append(shortName).append(" "); } else { ddl.append(indexName).append(" on "); ddl.append(className).append(" ( ").append(field); if (!collate.getName().equals(ODefaultCollate.NAME)) ddl.append(" COLLATE ").append(collate.getName()); ddl.append(" ) "); } ddl.append(indexType); return ddl; } @Override public boolean isAutomatic() { return true; } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OPropertyIndexDefinition.java
427
@Test public class TrackedMapTest { public void testPutOne() { final ODocument doc = new ODocument(); final OTrackedMap<String> map = new OTrackedMap<String>(doc); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); map.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD); Assert.assertNull(event.getOldValue()); Assert.assertEquals(event.getKey(), "key1"); Assert.assertEquals(event.getValue(), "value1"); changed.value = true; } }); map.put("key1", "value1"); Assert.assertTrue(changed.value); Assert.assertTrue(doc.isDirty()); } public void testPutTwo() { final ODocument doc = new ODocument(); final OTrackedMap<String> map = new OTrackedMap<String>(doc); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); map.put("key1", "value1"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); map.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.UPDATE); Assert.assertEquals(event.getOldValue(), "value1"); Assert.assertEquals(event.getKey(), "key1"); Assert.assertEquals(event.getValue(), "value2"); changed.value = true; } }); map.put("key1", "value2"); Assert.assertTrue(changed.value); Assert.assertTrue(doc.isDirty()); } public void testPutThree() { final ODocument doc = new ODocument(); final OTrackedMap<String> map = new OTrackedMap<String>(doc); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); map.put("key1", "value1"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); map.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { changed.value = true; } }); map.put("key1", "value1"); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testPutFour() { final ODocument doc = new ODocument(); final OTrackedMap<String> map = new OTrackedMap<String>(doc); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); map.put("key1", "value1"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); map.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { changed.value = true; } }); map.put("key1", "value1"); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testPutFive() { final ODocument doc = new ODocument(); final OTrackedMap<String> map = new OTrackedMap<String>(doc); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); map.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); final ORef<Boolean> changed = new ORef<Boolean>(false); map.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { changed.value = true; } }); map.put("key1", "value1"); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testRemoveOne() { final ODocument doc = new ODocument(); final OTrackedMap<String> map = new OTrackedMap<String>(doc); map.put("key1", "value1"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); map.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.REMOVE); Assert.assertEquals(event.getOldValue(), "value1"); Assert.assertEquals(event.getKey(), "key1"); Assert.assertEquals(event.getValue(), null); changed.value = true; } }); map.remove("key1"); Assert.assertTrue(changed.value); Assert.assertTrue(doc.isDirty()); } public void testRemoveTwo() { final ODocument doc = new ODocument(); final OTrackedMap<String> map = new OTrackedMap<String>(doc); map.put("key1", "value1"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); map.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { changed.value = true; } }); map.remove("key2"); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testRemoveThree() { final ODocument doc = new ODocument(); final OTrackedMap<String> map = new OTrackedMap<String>(doc); map.put("key1", "value1"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); map.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); final ORef<Boolean> changed = new ORef<Boolean>(false); map.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { changed.value = true; } }); map.remove("key1"); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testClearOne() { final ODocument doc = new ODocument(); final OTrackedMap<String> trackedMap = new OTrackedMap<String>(doc); trackedMap.put("key1", "value1"); trackedMap.put("key2", "value2"); trackedMap.put("key3", "value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final Set<OMultiValueChangeEvent<Object, String>> firedEvents = new HashSet<OMultiValueChangeEvent<Object, String>>(); firedEvents.add(new OMultiValueChangeEvent<Object, String>(OMultiValueChangeEvent.OChangeType.REMOVE, "key1", null, "value1")); firedEvents.add(new OMultiValueChangeEvent<Object, String>(OMultiValueChangeEvent.OChangeType.REMOVE, "key2", null, "value2")); firedEvents.add(new OMultiValueChangeEvent<Object, String>(OMultiValueChangeEvent.OChangeType.REMOVE, "key3", null, "value3")); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { if (!firedEvents.remove(event)) Assert.fail(); changed.value = true; } }); trackedMap.clear(); Assert.assertEquals(firedEvents.size(), 0); Assert.assertTrue(changed.value); Assert.assertTrue(doc.isDirty()); } public void testClearTwo() { final ODocument doc = new ODocument(); final OTrackedMap<String> trackedMap = new OTrackedMap<String>(doc); trackedMap.put("key1", "value1"); trackedMap.put("key2", "value2"); trackedMap.put("key3", "value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedMap.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { changed.value = true; } }); trackedMap.clear(); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testClearThree() { final ODocument doc = new ODocument(); final OTrackedMap<String> trackedMap = new OTrackedMap<String>(doc); trackedMap.put("key1", "value1"); trackedMap.put("key2", "value2"); trackedMap.put("key3", "value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedMap.clear(); Assert.assertTrue(doc.isDirty()); } public void testReturnOriginalStateOne() { final ODocument doc = new ODocument(); final OTrackedMap<String> trackedMap = new OTrackedMap<String>(doc); trackedMap.put("key1", "value1"); trackedMap.put("key2", "value2"); trackedMap.put("key3", "value3"); trackedMap.put("key4", "value4"); trackedMap.put("key5", "value5"); trackedMap.put("key6", "value6"); trackedMap.put("key7", "value7"); final Map<Object, String> original = new HashMap<Object, String>(trackedMap); final List<OMultiValueChangeEvent<Object, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Object, String>>(); trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { firedEvents.add(event); } }); trackedMap.put("key8", "value8"); trackedMap.put("key9", "value9"); trackedMap.put("key2", "value10"); trackedMap.put("key11", "value11"); trackedMap.remove("key5"); trackedMap.remove("key5"); trackedMap.put("key3", "value12"); trackedMap.remove("key8"); trackedMap.remove("key3"); Assert.assertEquals(trackedMap.returnOriginalState(firedEvents), original); } public void testReturnOriginalStateTwo() { final ODocument doc = new ODocument(); final OTrackedMap<String> trackedMap = new OTrackedMap<String>(doc); trackedMap.put("key1", "value1"); trackedMap.put("key2", "value2"); trackedMap.put("key3", "value3"); trackedMap.put("key4", "value4"); trackedMap.put("key5", "value5"); trackedMap.put("key6", "value6"); trackedMap.put("key7", "value7"); final Map<Object, String> original = new HashMap<Object, String>(trackedMap); final List<OMultiValueChangeEvent<Object, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Object, String>>(); trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { firedEvents.add(event); } }); trackedMap.put("key8", "value8"); trackedMap.put("key9", "value9"); trackedMap.put("key2", "value10"); trackedMap.put("key11", "value11"); trackedMap.remove("key5"); trackedMap.remove("key5"); trackedMap.clear(); trackedMap.put("key3", "value12"); trackedMap.remove("key8"); trackedMap.remove("key3"); Assert.assertEquals(trackedMap.returnOriginalState(firedEvents), original); } /** * Test that {@link OTrackedMap} is serialised correctly. */ @Test public void testMapSerialization() throws Exception { class NotSerializableDocument extends ODocument { private static final long serialVersionUID = 1L; private void writeObject(ObjectOutputStream oos) throws IOException { throw new NotSerializableException(); } } final OTrackedMap<String> beforeSerialization = new OTrackedMap<String>(new NotSerializableDocument()); beforeSerialization.put(0, "firstVal"); beforeSerialization.put(1, "secondVal"); final OMemoryStream memoryStream = new OMemoryStream(); final ObjectOutputStream out = new ObjectOutputStream(memoryStream); out.writeObject(beforeSerialization); out.close(); final ObjectInputStream input = new ObjectInputStream(new OMemoryInputStream(memoryStream.copy())); @SuppressWarnings("unchecked") final Map<Object, String> afterSerialization = (Map<Object, String>) input.readObject(); Assert.assertEquals(afterSerialization.size(), beforeSerialization.size(), "Map size"); for (int i = 0; i < afterSerialization.size(); i++) { Assert.assertEquals(afterSerialization.get(i), beforeSerialization.get(i)); } } }
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedMapTest.java
254
private static class CommandCapturingVisitor implements Visitor<XaCommand,RuntimeException> { private final Collection<XaCommand> commands = new ArrayList<>(); @Override public boolean visit( XaCommand element ) throws RuntimeException { commands.add( element ); return true; } public void injectInto( NeoStoreTransaction tx ) { for ( XaCommand command : commands ) { tx.injectCommand( command ); } } public void visitCapturedCommands( Visitor<XaCommand, RuntimeException> visitor ) { for ( XaCommand command : commands ) { visitor.visit( command ); } } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_nioneo_xa_WriteTransactionTest.java
740
public class ProductBundlePricingModelType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, ProductBundlePricingModelType> TYPES = new LinkedHashMap<String, ProductBundlePricingModelType>(); public static final ProductBundlePricingModelType ITEM_SUM = new ProductBundlePricingModelType("ITEM_SUM","Item Sum"); public static final ProductBundlePricingModelType BUNDLE = new ProductBundlePricingModelType("BUNDLE","Bundle"); public static ProductBundlePricingModelType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public ProductBundlePricingModelType() { //do nothing } public ProductBundlePricingModelType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProductBundlePricingModelType other = (ProductBundlePricingModelType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_service_type_ProductBundlePricingModelType.java
310
private class PropertyBlockIterator extends PrefetchingIterator<PropertyBlock> { private final Iterator<PropertyRecord> records; private Iterator<PropertyBlock> blocks = IteratorUtil.emptyIterator(); PropertyBlockIterator( NodeRecord node ) { long firstPropertyId = node.getCommittedNextProp(); if ( firstPropertyId == Record.NO_NEXT_PROPERTY.intValue() ) { records = IteratorUtil.emptyIterator(); } else { records = propertyStore.getPropertyRecordChain( firstPropertyId ).iterator(); } } @Override protected PropertyBlock fetchNextOrNull() { for (; ; ) { if ( blocks.hasNext() ) { return blocks.next(); } if ( !records.hasNext() ) { return null; } blocks = records.next().getPropertyBlocks().iterator(); } } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreIndexStoreView.java
404
@SuppressWarnings("serial") public class OTrackedMap<T> extends LinkedHashMap<Object, T> implements ORecordElement, OTrackedMultiValue<Object, T>, Serializable { final protected ORecord<?> sourceRecord; private STATUS status = STATUS.NOT_LOADED; private Set<OMultiValueChangeListener<Object, T>> changeListeners = Collections .newSetFromMap(new WeakHashMap<OMultiValueChangeListener<Object, T>, Boolean>()); protected Class<?> genericClass; public OTrackedMap(final ORecord<?> iRecord, final Map<Object, T> iOrigin, final Class<?> cls) { this(iRecord); genericClass = cls; if (iOrigin != null && !iOrigin.isEmpty()) putAll(iOrigin); } public OTrackedMap(final ORecord<?> iSourceRecord) { this.sourceRecord = iSourceRecord; } @Override public T put(final Object iKey, final T iValue) { boolean containsKey = containsKey(iKey); T oldValue = super.put(iKey, iValue); if (containsKey && oldValue == iValue) return oldValue; if (containsKey) fireCollectionChangedEvent(new OMultiValueChangeEvent<Object, T>(OMultiValueChangeEvent.OChangeType.UPDATE, iKey, iValue, oldValue)); else fireCollectionChangedEvent(new OMultiValueChangeEvent<Object, T>(OMultiValueChangeEvent.OChangeType.ADD, iKey, iValue)); return oldValue; } @Override public T remove(final Object iKey) { boolean containsKey = containsKey(iKey); final T oldValue = super.remove(iKey); if (containsKey) fireCollectionChangedEvent(new OMultiValueChangeEvent<Object, T>(OMultiValueChangeEvent.OChangeType.REMOVE, iKey, null, oldValue)); return oldValue; } @Override public void clear() { final Map<Object, T> origValues; if (changeListeners.isEmpty()) origValues = null; else origValues = new HashMap<Object, T>(this); super.clear(); if (origValues != null) { for (Map.Entry<Object, T> entry : origValues.entrySet()) fireCollectionChangedEvent(new OMultiValueChangeEvent<Object, T>(OMultiValueChangeEvent.OChangeType.REMOVE, entry.getKey(), null, entry.getValue())); } else setDirty(); } @Override public void putAll(Map<? extends Object, ? extends T> m) { super.putAll(m); } @SuppressWarnings({ "unchecked" }) public OTrackedMap<T> setDirty() { if (status != STATUS.UNMARSHALLING && sourceRecord != null && !sourceRecord.isDirty()) sourceRecord.setDirty(); return this; } public void onBeforeIdentityChanged(final ORID iRID) { remove(iRID); } @SuppressWarnings("unchecked") public void onAfterIdentityChanged(final ORecord<?> iRecord) { super.put(iRecord.getIdentity(), (T) iRecord); } public STATUS getInternalStatus() { return status; } public void setInternalStatus(final STATUS iStatus) { status = iStatus; } public void addChangeListener(OMultiValueChangeListener<Object, T> changeListener) { changeListeners.add(changeListener); } public void removeRecordChangeListener(OMultiValueChangeListener<Object, T> changeListener) { changeListeners.remove(changeListener); } public Map<Object, T> returnOriginalState(final List<OMultiValueChangeEvent<Object, T>> multiValueChangeEvents) { final Map<Object, T> reverted = new HashMap<Object, T>(this); final ListIterator<OMultiValueChangeEvent<Object, T>> listIterator = multiValueChangeEvents.listIterator(multiValueChangeEvents .size()); while (listIterator.hasPrevious()) { final OMultiValueChangeEvent<Object, T> event = listIterator.previous(); switch (event.getChangeType()) { case ADD: reverted.remove(event.getKey()); break; case REMOVE: reverted.put(event.getKey(), event.getOldValue()); break; case UPDATE: reverted.put(event.getKey(), event.getOldValue()); break; default: throw new IllegalArgumentException("Invalid change type : " + event.getChangeType()); } } return reverted; } protected void fireCollectionChangedEvent(final OMultiValueChangeEvent<Object, T> event) { if (status == STATUS.UNMARSHALLING) return; setDirty(); for (final OMultiValueChangeListener<Object, T> changeListener : changeListeners) { if (changeListener != null) changeListener.onAfterRecordChanged(event); } } public Class<?> getGenericClass() { return genericClass; } public void setGenericClass(Class<?> genericClass) { this.genericClass = genericClass; } private Object writeReplace() { return new LinkedHashMap<Object, T>(this); } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_record_OTrackedMap.java
1,816
constructors[QUERY_RESULT_ENTRY] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new QueryResultEntryImpl(); } };
0true
hazelcast_src_main_java_com_hazelcast_map_MapDataSerializerHook.java
191
public abstract class KeyValueStoreTest extends AbstractKCVSTest { private Logger log = LoggerFactory.getLogger(KeyValueStoreTest.class); private int numKeys = 2000; private String storeName = "testStore1"; protected OrderedKeyValueStoreManager manager; protected StoreTransaction tx; protected OrderedKeyValueStore store; @Before public void setUp() throws Exception { StoreManager m = openStorageManager(); m.clearStorage(); m.close(); open(); } public void open() throws BackendException { manager = openStorageManager(); store = manager.openDatabase(storeName); tx = manager.beginTransaction(getTxConfig()); } public abstract OrderedKeyValueStoreManager openStorageManager() throws BackendException; @After public void tearDown() throws Exception { close(); } public void close() throws BackendException { if (tx != null) tx.commit(); store.close(); manager.close(); } public void clopen() throws BackendException { close(); open(); } @Test public void createDatabase() { //Just setup and shutdown } public String[] generateValues() { return KeyValueStoreUtil.generateData(numKeys); } public void loadValues(String[] values) throws BackendException { for (int i = 0; i < numKeys; i++) { store.insert(KeyValueStoreUtil.getBuffer(i), KeyValueStoreUtil.getBuffer(values[i]), tx); } } public Set<Integer> deleteValues(int start, int every) throws BackendException { Set<Integer> removed = new HashSet<Integer>(); for (int i = start; i < numKeys; i = i + every) { removed.add(i); store.delete(KeyValueStoreUtil.getBuffer(i), tx); } return removed; } public void checkValueExistence(String[] values) throws BackendException { checkValueExistence(values, new HashSet<Integer>()); } public void checkValueExistence(String[] values, Set<Integer> removed) throws BackendException { for (int i = 0; i < numKeys; i++) { boolean result = store.containsKey(KeyValueStoreUtil.getBuffer(i), tx); if (removed.contains(i)) { Assert.assertFalse(result); } else { Assert.assertTrue(result); } } } public void checkValues(String[] values) throws BackendException { checkValues(values, new HashSet<Integer>()); } public void checkValues(String[] values, Set<Integer> removed) throws BackendException { //1. Check one-by-one for (int i = 0; i < numKeys; i++) { StaticBuffer result = store.get(KeyValueStoreUtil.getBuffer(i), tx); if (removed.contains(i)) { Assert.assertNull(result); } else { Assert.assertEquals(values[i], KeyValueStoreUtil.getString(result)); } } //2. Check all at once (if supported) if (manager.getFeatures().hasMultiQuery()) { List<KVQuery> queries = Lists.newArrayList(); for (int i = 0; i < numKeys; i++) { StaticBuffer key = KeyValueStoreUtil.getBuffer(i); queries.add(new KVQuery(key, BufferUtil.nextBiggerBuffer(key),2)); } Map<KVQuery,RecordIterator<KeyValueEntry>> results = store.getSlices(queries,tx); for (int i = 0; i < numKeys; i++) { RecordIterator<KeyValueEntry> result = results.get(queries.get(i)); Assert.assertNotNull(result); StaticBuffer value; if (result.hasNext()) { value = result.next().getValue(); Assert.assertFalse(result.hasNext()); } else value=null; if (removed.contains(i)) { Assert.assertNull(value); } else { Assert.assertEquals(values[i], KeyValueStoreUtil.getString(value)); } } } } @Test public void storeAndRetrieve() throws BackendException { String[] values = generateValues(); log.debug("Loading values..."); loadValues(values); log.debug("Checking values..."); checkValueExistence(values); checkValues(values); } @Test public void storeAndRetrieveWithClosing() throws BackendException { String[] values = generateValues(); log.debug("Loading values..."); loadValues(values); clopen(); log.debug("Checking values..."); checkValueExistence(values); checkValues(values); } @Test public void deletionTest1() throws BackendException { String[] values = generateValues(); log.debug("Loading values..."); loadValues(values); clopen(); Set<Integer> deleted = deleteValues(0, 10); log.debug("Checking values..."); checkValueExistence(values, deleted); checkValues(values, deleted); } @Test public void deletionTest2() throws BackendException { String[] values = generateValues(); log.debug("Loading values..."); loadValues(values); Set<Integer> deleted = deleteValues(0, 10); clopen(); log.debug("Checking values..."); checkValueExistence(values, deleted); checkValues(values, deleted); } @Test public void scanTest() throws BackendException { if (manager.getFeatures().hasScan()) { String[] values = generateValues(); loadValues(values); RecordIterator<KeyValueEntry> iterator0 = getAllData(tx); Assert.assertEquals(numKeys, KeyValueStoreUtil.count(iterator0)); clopen(); RecordIterator<KeyValueEntry> iterator1 = getAllData(tx); RecordIterator<KeyValueEntry> iterator2 = getAllData(tx); // The idea is to open an iterator without using it // to make sure that closing a transaction will clean it up. // (important for BerkeleyJE where leaving cursors open causes exceptions) @SuppressWarnings("unused") RecordIterator<KeyValueEntry> iterator3 = getAllData(tx); Assert.assertEquals(numKeys, KeyValueStoreUtil.count(iterator1)); Assert.assertEquals(numKeys, KeyValueStoreUtil.count(iterator2)); } } private RecordIterator<KeyValueEntry> getAllData(StoreTransaction tx) throws BackendException { return store.getSlice(new KVQuery(BackendTransaction.EDGESTORE_MIN_KEY, BackendTransaction.EDGESTORE_MAX_KEY), tx); } public void checkSlice(String[] values, Set<Integer> removed, int start, int end, int limit) throws BackendException { EntryList entries; if (limit <= 0) entries = KVUtil.getSlice(store, KeyValueStoreUtil.getBuffer(start), KeyValueStoreUtil.getBuffer(end), tx); else entries = KVUtil.getSlice(store, KeyValueStoreUtil.getBuffer(start), KeyValueStoreUtil.getBuffer(end), limit, tx); int pos = 0; for (int i = start; i < end; i++) { if (removed.contains(i)) continue; if (pos < limit) { Entry entry = entries.get(pos); int id = KeyValueStoreUtil.getID(entry.getColumn()); String str = KeyValueStoreUtil.getString(entry.getValueAs(StaticBuffer.STATIC_FACTORY)); Assert.assertEquals(i, id); Assert.assertEquals(values[i], str); } pos++; } if (limit > 0 && pos >= limit) Assert.assertEquals(limit, entries.size()); else { Assert.assertNotNull(entries); Assert.assertEquals(pos, entries.size()); } } @Test public void intervalTest1() throws BackendException { String[] values = generateValues(); log.debug("Loading values..."); loadValues(values); Set<Integer> deleted = deleteValues(0, 10); clopen(); checkSlice(values, deleted, 5, 25, -1); checkSlice(values, deleted, 5, 250, 10); checkSlice(values, deleted, 500, 1250, -1); checkSlice(values, deleted, 500, 1250, 1000); checkSlice(values, deleted, 500, 1250, 100); checkSlice(values, deleted, 50, 20, 10); checkSlice(values, deleted, 50, 20, -1); } }
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_KeyValueStoreTest.java
775
public class SkuAvailabilityDataProvider { @DataProvider(name = "setupSkuAvailability") public static Object[][] createSkuAvailabilityRecords() { Object[][] paramArray = new Object[10][1]; Date AVAILABLE_TODAY = SystemTime.asDate(); Date AVAILABLE_NULL = null; Long LOCATION_NULL = null; Long LOCATION_ONE = 1L; Long SKU_ID_1 = 1L; Long SKU_ID_2 = 2L; Long SKU_ID_3 = 3L; Long SKU_ID_4 = 4L; Long SKU_ID_5 = 5L; long recordCount = 0; paramArray[0][0] = createSkuForSkuIdAndLocation(recordCount++, SKU_ID_1, LOCATION_NULL, AVAILABLE_TODAY, "AVAILABLE", null, new Integer(1)); paramArray[1][0] = createSkuForSkuIdAndLocation(recordCount++, SKU_ID_1, LOCATION_ONE, AVAILABLE_TODAY, "AVAILABLE", null, new Integer(1)); paramArray[2][0] = createSkuForSkuIdAndLocation(recordCount++, SKU_ID_2, LOCATION_NULL, AVAILABLE_TODAY, null, new Integer(5), new Integer(1)); paramArray[3][0] = createSkuForSkuIdAndLocation(recordCount++, SKU_ID_2, LOCATION_ONE, AVAILABLE_TODAY, null, new Integer(5), new Integer(1)); paramArray[4][0] = createSkuForSkuIdAndLocation(recordCount++, SKU_ID_3, LOCATION_NULL, AVAILABLE_TODAY, null, new Integer(0), new Integer(1)); paramArray[5][0] = createSkuForSkuIdAndLocation(recordCount++, SKU_ID_3, LOCATION_ONE, AVAILABLE_TODAY, null, new Integer(0), new Integer(1)); paramArray[6][0] = createSkuForSkuIdAndLocation(recordCount++, SKU_ID_4, LOCATION_NULL, AVAILABLE_NULL, "BACKORDERED", new Integer(0), new Integer(1)); paramArray[7][0] = createSkuForSkuIdAndLocation(recordCount++, SKU_ID_4, LOCATION_ONE, AVAILABLE_NULL, "BACKORDERED", new Integer(0), new Integer(1)); paramArray[8][0] = createSkuForSkuIdAndLocation(recordCount++, SKU_ID_5, LOCATION_NULL, AVAILABLE_NULL, null, new Integer(5), null); paramArray[9][0] = createSkuForSkuIdAndLocation(recordCount++, SKU_ID_5, LOCATION_ONE, AVAILABLE_NULL, null, new Integer(5), null); return paramArray; } public static SkuAvailability createSkuForSkuIdAndLocation(Long id, Long skuId, Long locationId, Date availabilityDate, String availStatus, Integer qoh, Integer reserveQuantity) { SkuAvailability skuAvailability = new SkuAvailabilityImpl(); skuAvailability.setId(null); skuAvailability.setSkuId(skuId); skuAvailability.setLocationId(locationId); skuAvailability.setAvailabilityDate(availabilityDate); skuAvailability.setAvailabilityStatus(availStatus==null?null:AvailabilityStatusType.getInstance(availStatus)); skuAvailability.setQuantityOnHand(qoh); skuAvailability.setReserveQuantity(reserveQuantity); return skuAvailability; } }
0true
integration_src_test_java_org_broadleafcommerce_core_inventory_service_dataprovider_SkuAvailabilityDataProvider.java
3,669
public class IndexFieldMapper extends AbstractFieldMapper<String> implements InternalMapper, RootMapper { public static final String NAME = "_index"; public static final String CONTENT_TYPE = "_index"; public static class Defaults extends AbstractFieldMapper.Defaults { public static final String NAME = IndexFieldMapper.NAME; public static final String INDEX_NAME = IndexFieldMapper.NAME; public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.setIndexed(true); FIELD_TYPE.setTokenized(false); FIELD_TYPE.setStored(false); FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_ONLY); FIELD_TYPE.freeze(); } public static final EnabledAttributeMapper ENABLED_STATE = EnabledAttributeMapper.DISABLED; } public static class Builder extends AbstractFieldMapper.Builder<Builder, IndexFieldMapper> { private EnabledAttributeMapper enabledState = EnabledAttributeMapper.UNSET_DISABLED; public Builder() { super(Defaults.NAME, new FieldType(Defaults.FIELD_TYPE)); indexName = Defaults.INDEX_NAME; } public Builder enabled(EnabledAttributeMapper enabledState) { this.enabledState = enabledState; return this; } @Override public IndexFieldMapper build(BuilderContext context) { return new IndexFieldMapper(name, indexName, boost, fieldType, docValues, enabledState, postingsProvider, docValuesProvider, fieldDataSettings, context.indexSettings()); } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { IndexFieldMapper.Builder builder = MapperBuilders.index(); parseField(builder, builder.name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("enabled")) { EnabledAttributeMapper mapper = nodeBooleanValue(fieldNode) ? EnabledAttributeMapper.ENABLED : EnabledAttributeMapper.DISABLED; builder.enabled(mapper); } } return builder; } } private EnabledAttributeMapper enabledState; public IndexFieldMapper() { this(Defaults.NAME, Defaults.INDEX_NAME); } protected IndexFieldMapper(String name, String indexName) { this(name, indexName, Defaults.BOOST, new FieldType(Defaults.FIELD_TYPE), null, Defaults.ENABLED_STATE, null, null, null, ImmutableSettings.EMPTY); } public IndexFieldMapper(String name, String indexName, float boost, FieldType fieldType, Boolean docValues, EnabledAttributeMapper enabledState, PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider, @Nullable Settings fieldDataSettings, Settings indexSettings) { super(new Names(name, indexName, indexName, name), boost, fieldType, docValues, Lucene.KEYWORD_ANALYZER, Lucene.KEYWORD_ANALYZER, postingsProvider, docValuesProvider, null, null, fieldDataSettings, indexSettings); this.enabledState = enabledState; } public boolean enabled() { return this.enabledState.enabled; } @Override public FieldType defaultFieldType() { return Defaults.FIELD_TYPE; } @Override public FieldDataType defaultFieldDataType() { return new FieldDataType("string"); } @Override public boolean hasDocValues() { return false; } public String value(Document document) { Field field = (Field) document.getField(names.indexName()); return field == null ? null : value(field); } @Override public String value(Object value) { if (value == null) { return null; } return value.toString(); } @Override public void preParse(ParseContext context) throws IOException { // we pre parse it and not in parse, since its not part of the root object super.parse(context); } @Override public void postParse(ParseContext context) throws IOException { } @Override public void parse(ParseContext context) throws IOException { } @Override public void validate(ParseContext context) throws MapperParsingException { } @Override public boolean includeInObject() { return false; } @Override protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException { if (!enabledState.enabled) { return; } fields.add(new Field(names.indexName(), context.index(), fieldType)); } @Override protected String contentType() { return CONTENT_TYPE; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { boolean includeDefaults = params.paramAsBoolean("include_defaults", false); // if all defaults, no need to write it at all if (!includeDefaults && fieldType().stored() == Defaults.FIELD_TYPE.stored() && enabledState == Defaults.ENABLED_STATE) { return builder; } builder.startObject(CONTENT_TYPE); if (includeDefaults || fieldType().stored() != Defaults.FIELD_TYPE.stored() && enabledState.enabled) { builder.field("store", fieldType().stored()); } if (includeDefaults || enabledState != Defaults.ENABLED_STATE) { builder.field("enabled", enabledState.enabled); } if (customFieldDataSettings != null) { builder.field("fielddata", (Map) customFieldDataSettings.getAsMap()); } else if (includeDefaults) { builder.field("fielddata", (Map) fieldDataType.getSettings().getAsMap()); } builder.endObject(); return builder; } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { IndexFieldMapper indexFieldMapperMergeWith = (IndexFieldMapper) mergeWith; if (!mergeContext.mergeFlags().simulate()) { if (indexFieldMapperMergeWith.enabledState != enabledState && !indexFieldMapperMergeWith.enabledState.unset()) { this.enabledState = indexFieldMapperMergeWith.enabledState; } } } }
1no label
src_main_java_org_elasticsearch_index_mapper_internal_IndexFieldMapper.java
2,877
public class KeywordAnalyzerProvider extends AbstractIndexAnalyzerProvider<KeywordAnalyzer> { private final KeywordAnalyzer keywordAnalyzer; @Inject public KeywordAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); this.keywordAnalyzer = new KeywordAnalyzer(); } @Override public KeywordAnalyzer get() { return this.keywordAnalyzer; } }
0true
src_main_java_org_elasticsearch_index_analysis_KeywordAnalyzerProvider.java
123
static final class AdaptedRunnable<T> extends ForkJoinTask<T> implements RunnableFuture<T> { final Runnable runnable; T result; AdaptedRunnable(Runnable runnable, T result) { if (runnable == null) throw new NullPointerException(); this.runnable = runnable; this.result = result; // OK to set this even before completion } public final T getRawResult() { return result; } public final void setRawResult(T v) { result = v; } public final boolean exec() { runnable.run(); return true; } public final void run() { invoke(); } private static final long serialVersionUID = 5232453952276885070L; }
0true
src_main_java_jsr166e_ForkJoinTask.java
4,522
private class ExpiredDocsCollector extends Collector { private final MapperService mapperService; private AtomicReaderContext context; private List<DocToPurge> docsToPurge = new ArrayList<DocToPurge>(); public ExpiredDocsCollector(String index) { mapperService = indicesService.indexService(index).mapperService(); } public void setScorer(Scorer scorer) { } public boolean acceptsDocsOutOfOrder() { return true; } public void collect(int doc) { try { UidAndRoutingFieldsVisitor fieldsVisitor = new UidAndRoutingFieldsVisitor(); context.reader().document(doc, fieldsVisitor); Uid uid = fieldsVisitor.uid(); final long version = Versions.loadVersion(context.reader(), new Term(UidFieldMapper.NAME, uid.toBytesRef())); docsToPurge.add(new DocToPurge(uid.type(), uid.id(), version, fieldsVisitor.routing())); } catch (Exception e) { logger.trace("failed to collect doc", e); } } public void setNextReader(AtomicReaderContext context) throws IOException { this.context = context; } public List<DocToPurge> getDocsToPurge() { return this.docsToPurge; } }
1no label
src_main_java_org_elasticsearch_indices_ttl_IndicesTTLService.java
1,082
public class OSQLFilterItemField extends OSQLFilterItemAbstract { protected Set<String> preLoadedFields; protected String[] preLoadedFieldsArray; protected String name; protected OCollate collate; public OSQLFilterItemField(final OBaseParser iQueryToParse, final String iName) { super(iQueryToParse, iName); } public Object getValue(final OIdentifiable iRecord, OCommandContext iContext) { if (iRecord == null) throw new OCommandExecutionException("expression item '" + name + "' cannot be resolved"); final ODocument doc = (ODocument) iRecord.getRecord(); if (preLoadedFieldsArray == null && preLoadedFields != null && preLoadedFields.size() > 0 && preLoadedFields.size() < 5) { // TRANSFORM THE SET IN ARRAY ONLY THE FIRST TIME AND IF FIELDS ARE MORE THAN ONE, OTHERWISE GO WITH THE DEFAULT BEHAVIOR preLoadedFieldsArray = new String[preLoadedFields.size()]; preLoadedFields.toArray(preLoadedFieldsArray); } // UNMARSHALL THE SINGLE FIELD if (doc.deserializeFields(preLoadedFieldsArray)) { // FIELD FOUND Object v = ODocumentHelper.getFieldValue(doc, name); collate = getCollateForField(doc, name); return transformValue(iRecord, iContext, v); } return null; } public String getRoot() { return name; } public void setRoot(final OBaseParser iQueryToParse, final String iRoot) { this.name = iRoot; } /** * Check whether or not this filter item is chain of fields (e.g. "field1.field2.field3"). Return true if filter item contains * only field projections operators, if field item contains any other projection operator the method returns false. When filter * item does not contains any chain operator, it is also field chain consist of one field. * * @return whether or not this filter item can be represented as chain of fields. */ public boolean isFieldChain() { if (operationsChain == null) { return true; } for (OPair<OSQLMethod, Object[]> pair : operationsChain) { if (!pair.getKey().getName().equals(OSQLMethodField.NAME)) { return false; } } return true; } /** * Creates {@code FieldChain} in case when filter item can have such representation. * * @return {@code FieldChain} representation of this filter item. * @throws IllegalStateException * if this filter item cannot be represented as {@code FieldChain}. */ public FieldChain getFieldChain() { if (!isFieldChain()) { throw new IllegalStateException("Filter item field contains not only field operators"); } return new FieldChain(); } /** * Represents filter item as chain of fields. Provide interface to work with this chain like with sequence of field names. */ public class FieldChain { private FieldChain() { } public String getItemName(int fieldIndex) { if (fieldIndex == 0) { return name; } else { return operationsChain.get(fieldIndex - 1).getValue()[0].toString(); } } public int getItemCount() { if (operationsChain == null) { return 1; } else { return operationsChain.size() + 1; } } /** * Field chain is considered as long chain if it contains more than one item. * * @return true if this chain is long and false in another case. */ public boolean isLong() { return operationsChain != null && operationsChain.size() > 0; } } public void setPreLoadedFields(final Set<String> iPrefetchedFieldList) { this.preLoadedFields = iPrefetchedFieldList; } public OCollate getCollate() { return collate; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_filter_OSQLFilterItemField.java
685
public class OHashTreeNodeMetadata { private byte maxLeftChildDepth; private byte maxRightChildDepth; private byte nodeLocalDepth; public OHashTreeNodeMetadata(byte maxLeftChildDepth, byte maxRightChildDepth, byte nodeLocalDepth) { this.maxLeftChildDepth = maxLeftChildDepth; this.maxRightChildDepth = maxRightChildDepth; this.nodeLocalDepth = nodeLocalDepth; } public int getMaxLeftChildDepth() { return maxLeftChildDepth & 0xFF; } public void setMaxLeftChildDepth(int maxLeftChildDepth) { this.maxLeftChildDepth = (byte) maxLeftChildDepth; } public int getMaxRightChildDepth() { return maxRightChildDepth & 0xFF; } public void setMaxRightChildDepth(int maxRightChildDepth) { this.maxRightChildDepth = (byte) maxRightChildDepth; } public int getNodeLocalDepth() { return nodeLocalDepth & 0xFF; } public void setNodeLocalDepth(int nodeLocalDepth) { this.nodeLocalDepth = (byte) nodeLocalDepth; } public void incrementLocalNodeDepth() { nodeLocalDepth++; } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_OHashTreeNodeMetadata.java
1,147
public enum EntryEventType { ADDED(1), REMOVED(2), UPDATED(3), EVICTED(4); private int type; private EntryEventType(final int type) { this.type = type; } public int getType() { return type; } public static EntryEventType getByType(final int eventType) { for (EntryEventType entryEventType : values()) { if (entryEventType.type == eventType) { return entryEventType; } } return null; } }
0true
hazelcast_src_main_java_com_hazelcast_core_EntryEventType.java
5,361
public class InternalMin extends MetricsAggregation.SingleValue implements Min { public final static Type TYPE = new Type("min"); public final static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() { @Override public InternalMin readResult(StreamInput in) throws IOException { InternalMin result = new InternalMin(); result.readFrom(in); return result; } }; public static void registerStreams() { AggregationStreams.registerStream(STREAM, TYPE.stream()); } private double min; InternalMin() {} // for serialization public InternalMin(String name, double min) { super(name); this.min = min; } @Override public double value() { return min; } public double getValue() { return min; } @Override public Type type() { return TYPE; } @Override public InternalMin reduce(ReduceContext reduceContext) { List<InternalAggregation> aggregations = reduceContext.aggregations(); if (aggregations.size() == 1) { return (InternalMin) aggregations.get(0); } InternalMin reduced = null; for (InternalAggregation aggregation : aggregations) { if (reduced == null) { reduced = (InternalMin) aggregation; } else { reduced.min = Math.min(reduced.min, ((InternalMin) aggregation).min); } } if (reduced != null) { return reduced; } return (InternalMin) aggregations.get(0); } @Override public void readFrom(StreamInput in) throws IOException { name = in.readString(); valueFormatter = ValueFormatterStreams.readOptional(in); min = in.readDouble(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(name); ValueFormatterStreams.writeOptional(valueFormatter, out); out.writeDouble(min); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(name); boolean hasValue = !Double.isInfinite(min); builder.field(CommonFields.VALUE, hasValue ? min : null); if (hasValue && valueFormatter != null) { builder.field(CommonFields.VALUE_AS_STRING, valueFormatter.format(min)); } builder.endObject(); return builder; } }
1no label
src_main_java_org_elasticsearch_search_aggregations_metrics_min_InternalMin.java
25
public class DataDTOToMVELTranslatorTest extends TestCase { private OrderItemFieldServiceImpl orderItemFieldService; private CustomerFieldServiceImpl customerFieldService; private OrderFieldServiceImpl orderFieldService; private FulfillmentGroupFieldServiceImpl fulfillmentGroupFieldService; @Override protected void setUp() { orderItemFieldService = new OrderItemFieldServiceImpl(); orderItemFieldService.init(); customerFieldService = new CustomerFieldServiceImpl(); customerFieldService.init(); orderFieldService = new OrderFieldServiceImpl(); orderFieldService.init(); fulfillmentGroupFieldService = new FulfillmentGroupFieldServiceImpl(); fulfillmentGroupFieldService.init(); } /** * Tests the creation of an MVEL expression from a DataDTO * @throws MVELTranslationException * * Here's an example of a DataWrapper with a single DataDTO * * [{"id":"100", * "quantity":"1", * "groupOperator":"AND", * "groups":[ * {"id":null, * "quantity":null, * "groupOperator":null, * "groups":null, * "name":"category.name", * "operator":"IEQUALS", * "value":"merchandise"}] * }] */ public void testCreateMVEL() throws MVELTranslationException { DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator(); ExpressionDTO expressionDTO = new ExpressionDTO(); expressionDTO.setName("category.name"); expressionDTO.setOperator(BLCOperator.IEQUALS.name()); expressionDTO.setValue("merchandise"); String translated = translator.createMVEL("discreteOrderItem", expressionDTO, orderItemFieldService); String mvel = "MvelHelper.toUpperCase(discreteOrderItem.?category.?name)==MvelHelper.toUpperCase(\"merchandise\")"; assert(mvel.equals(translated)); } /** * Tests the creation of a Customer Qualification MVEL expression from a DataDTO * @throws MVELTranslationException * * [{"id":null, * "quantity":null, * "groupOperator":"AND", * "groups":[ * {"id":null, * "quantity":null, * "groupOperator":null, * "groups":null, * "name":"emailAddress", * "operator":"NOT_EQUAL_FIELD", * "value":"username"}, * {"id":null, * "quantity":null, * "groupOperator":null, * "groups":null, * "name":"deactivated", * "operator":"EQUALS", * "value":"true"}] * }] */ public void testCustomerQualificationMVEL() throws MVELTranslationException { DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator(); DataDTO dataDTO = new DataDTO(); dataDTO.setGroupOperator(BLCOperator.AND.name()); //not currently supported // ExpressionDTO e1 = new ExpressionDTO(); // e1.setName("emailAddress"); // e1.setOperator(BLCOperator.NOT_EQUAL_FIELD.name()); // e1.setValue("username"); ExpressionDTO e2 = new ExpressionDTO(); e2.setName("deactivated"); e2.setOperator(BLCOperator.EQUALS.name()); e2.setValue("true"); //dataDTO.getGroups().add(e1); dataDTO.getGroups().add(e2); String translated = translator.createMVEL("customer", dataDTO, customerFieldService); String mvel = "customer.?deactivated==true"; assert (mvel.equals(translated)); } /** * Tests the creation of an Order Qualification MVEL expression from a DataDTO * @throws MVELTranslationException * * [{"id":null, * "quantity":null, * "groupOperator":"AND", * "groups":[ * {"id":null, * "quantity":null, * "groupOperator":null, * "groups":null, * "name":"subTotal", * "operator":"GREATER_OR_EQUAL", * "value":"100"}, * {"id":null, * "quantity":null, * "groupOperator":"OR", * "groups":[ * {"id":null, * "quantity":null, * "groupOperator":null, * "groups":null, * "name":"currency.defaultFlag", * "operator":"EQUALS", * "value":"true"}, * {"id":null, * "quantity":null, * "groupOperator":"null", * "groups":null, * "name":"locale.localeCode", * "operator":"EQUALS", * "value":"my"}] * }] * }] */ public void testOrderQualificationMVEL() throws MVELTranslationException { DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator(); DataDTO dataDTO = new DataDTO(); dataDTO.setGroupOperator(BLCOperator.AND.name()); ExpressionDTO expressionDTO = new ExpressionDTO(); expressionDTO.setName("subTotal"); expressionDTO.setOperator(BLCOperator.GREATER_OR_EQUAL.name()); expressionDTO.setValue("100"); dataDTO.getGroups().add(expressionDTO); DataDTO d1 = new DataDTO(); d1.setGroupOperator(BLCOperator.OR.name()); ExpressionDTO e1 = new ExpressionDTO(); e1.setName("currency.defaultFlag"); e1.setOperator(BLCOperator.EQUALS.name()); e1.setValue("true"); ExpressionDTO e2 = new ExpressionDTO(); e2.setName("locale.localeCode"); e2.setOperator(BLCOperator.EQUALS.name()); e2.setValue("my"); d1.getGroups().add(e1); d1.getGroups().add(e2); dataDTO.getGroups().add(d1); String translated = translator.createMVEL("order", dataDTO, orderFieldService); String mvel = "order.?subTotal.getAmount()>=100&&(order.?currency.?defaultFlag==true||order.?locale.?localeCode==\"my\")"; assert (mvel.equals(translated)); } /** * Tests the creation of an Item Qualification MVEL expression from a DataDTO * @throws MVELTranslationException * * [{"id":100, * "quantity":1, * "groupOperator":"AND", * "groups":[ * {"id":null, * "quantity":null, * "groupOperator":null, * "groups":null, * "name":"category.name", * "operator":"EQUALS", * "value":"test category" * }] * }, * {"id":"200", * "quantity":2, * "groupOperator":"NOT", * "groups":[ * {"id":null, * "quantity":null, * "groupOperator":null, * "groups":null, * "name":"product.manufacturer", * "operator":"EQUALS", * "value":"test manufacturer"}, * {"id":null, * "quantity":null, * "groupOperator":null, * "groups":null, * "name":"product.model", * "operator":"EQUALS", * "value":"test model" * }] * }] */ public void testItemQualificationMVEL() throws MVELTranslationException { DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator(); DataDTO d1 = new DataDTO(); d1.setQuantity(1); d1.setGroupOperator(BLCOperator.AND.name()); ExpressionDTO d1e1 = new ExpressionDTO(); d1e1.setName("category.name"); d1e1.setOperator(BLCOperator.EQUALS.name()); d1e1.setValue("test category"); d1.getGroups().add(d1e1); String d1Translated = translator.createMVEL("discreteOrderItem", d1, orderItemFieldService); String d1Mvel = "discreteOrderItem.?category.?name==\"test category\""; assert(d1Mvel.equals(d1Translated)); DataDTO d2 = new DataDTO(); d2.setQuantity(2); d2.setGroupOperator(BLCOperator.NOT.name()); ExpressionDTO d2e1 = new ExpressionDTO(); d2e1.setName("product.manufacturer"); d2e1.setOperator(BLCOperator.EQUALS.name()); d2e1.setValue("test manufacturer"); ExpressionDTO d2e2 = new ExpressionDTO(); d2e2.setName("product.model"); d2e2.setOperator(BLCOperator.EQUALS.name()); d2e2.setValue("test model"); d2.getGroups().add(d2e1); d2.getGroups().add(d2e2); String d2Translated = translator.createMVEL("discreteOrderItem", d2, orderItemFieldService); String d2Mvel = "!(discreteOrderItem.?product.?manufacturer==\"test manufacturer\"&&discreteOrderItem.?product.?model==\"test model\")"; assert (d2Mvel.equals(d2Translated)); } /** * Tests the creation of a Fulfillment Group Qualification MVEL expression from a DataDTO * @throws MVELTranslationException * * [{"id":null, * "quantity":null, * "groupOperator":"AND", * "groups":[ * {"id":null, * "quantity":null, * "groupOperator":null, * "groups":null, * "name":"address.state.name", * "operator":"EQUALS", * "value":"Texas"}, * {"id":null, * "quantity":null, * "groupOperator":null, * "groups":null, * "name":"retailShippingPrice", * "operator":"BETWEEN_INCLUSIVE", * "start":"99", * "end":"199"}] * }] */ public void testFulfillmentQualificationMVEL() throws MVELTranslationException { DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator(); DataDTO dataDTO = new DataDTO(); dataDTO.setGroupOperator(BLCOperator.AND.name()); ExpressionDTO e1 = new ExpressionDTO(); e1.setName("address.state.name"); e1.setOperator(BLCOperator.EQUALS.name()); e1.setValue("Texas"); ExpressionDTO e2 = new ExpressionDTO(); e2.setName("retailFulfillmentPrice"); e2.setOperator(BLCOperator.BETWEEN_INCLUSIVE.name()); e2.setStart("99"); e2.setEnd("199"); dataDTO.getGroups().add(e1); dataDTO.getGroups().add(e2); String translated = translator.createMVEL("fulfillmentGroup", dataDTO, fulfillmentGroupFieldService); String mvel = "fulfillmentGroup.?address.?state.?name==\"Texas\"&&(fulfillmentGroup.?retailFulfillmentPrice.getAmount()>=99&&fulfillmentGroup.?retailFulfillmentPrice.getAmount()<=199)"; assert (mvel.equals(translated)); } }
0true
admin_broadleaf-admin-module_src_test_java_org_broadleafcommerce_admin_web_rulebuilder_DataDTOToMVELTranslatorTest.java
2,559
public class MasterNotDiscoveredException extends ElasticsearchException { public MasterNotDiscoveredException() { super(""); } public MasterNotDiscoveredException(String message) { super(message); } @Override public RestStatus status() { return RestStatus.SERVICE_UNAVAILABLE; } }
0true
src_main_java_org_elasticsearch_discovery_MasterNotDiscoveredException.java
5,826
public class PostingsHighlighter implements Highlighter { private static final String CACHE_KEY = "highlight-postings"; @Override public String[] names() { return new String[]{"postings", "postings-highlighter"}; } @Override public HighlightField highlight(HighlighterContext highlighterContext) { FieldMapper<?> fieldMapper = highlighterContext.mapper; SearchContextHighlight.Field field = highlighterContext.field; if (fieldMapper.fieldType().indexOptions() != FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) { throw new ElasticsearchIllegalArgumentException("the field [" + field.field() + "] should be indexed with positions and offsets in the postings list to be used with postings highlighter"); } SearchContext context = highlighterContext.context; FetchSubPhase.HitContext hitContext = highlighterContext.hitContext; if (!hitContext.cache().containsKey(CACHE_KEY)) { //get the non rewritten query and rewrite it Query query; try { query = rewrite(highlighterContext, hitContext.topLevelReader()); } catch (IOException e) { throw new FetchPhaseExecutionException(context, "Failed to highlight field [" + highlighterContext.fieldName + "]", e); } SortedSet<Term> queryTerms = extractTerms(query); hitContext.cache().put(CACHE_KEY, new HighlighterEntry(queryTerms)); } HighlighterEntry highlighterEntry = (HighlighterEntry) hitContext.cache().get(CACHE_KEY); MapperHighlighterEntry mapperHighlighterEntry = highlighterEntry.mappers.get(fieldMapper); if (mapperHighlighterEntry == null) { Encoder encoder = field.encoder().equals("html") ? HighlightUtils.Encoders.HTML : HighlightUtils.Encoders.DEFAULT; CustomPassageFormatter passageFormatter = new CustomPassageFormatter(field.preTags()[0], field.postTags()[0], encoder); BytesRef[] filteredQueryTerms = filterTerms(highlighterEntry.queryTerms, fieldMapper.names().indexName(), field.requireFieldMatch()); mapperHighlighterEntry = new MapperHighlighterEntry(passageFormatter, filteredQueryTerms); } //we merge back multiple values into a single value using the paragraph separator, unless we have to highlight every single value separately (number_of_fragments=0). boolean mergeValues = field.numberOfFragments() != 0; List<Snippet> snippets = new ArrayList<Snippet>(); int numberOfFragments; try { //we manually load the field values (from source if needed) List<Object> textsToHighlight = HighlightUtils.loadFieldValues(fieldMapper, context, hitContext, field.forceSource()); CustomPostingsHighlighter highlighter = new CustomPostingsHighlighter(mapperHighlighterEntry.passageFormatter, textsToHighlight, mergeValues, Integer.MAX_VALUE-1, field.noMatchSize()); if (field.numberOfFragments() == 0) { highlighter.setBreakIterator(new WholeBreakIterator()); numberOfFragments = 1; //1 per value since we highlight per value } else { numberOfFragments = field.numberOfFragments(); } //we highlight every value separately calling the highlight method multiple times, only if we need to have back a snippet per value (whole value) int values = mergeValues ? 1 : textsToHighlight.size(); for (int i = 0; i < values; i++) { Snippet[] fieldSnippets = highlighter.highlightDoc(fieldMapper.names().indexName(), mapperHighlighterEntry.filteredQueryTerms, hitContext.searcher(), hitContext.docId(), numberOfFragments); if (fieldSnippets != null) { for (Snippet fieldSnippet : fieldSnippets) { if (Strings.hasText(fieldSnippet.getText())) { snippets.add(fieldSnippet); } } } } } catch(IOException e) { throw new FetchPhaseExecutionException(context, "Failed to highlight field [" + highlighterContext.fieldName + "]", e); } snippets = filterSnippets(snippets, field.numberOfFragments()); if (field.scoreOrdered()) { //let's sort the snippets by score if needed CollectionUtil.introSort(snippets, new Comparator<Snippet>() { public int compare(Snippet o1, Snippet o2) { return (int) Math.signum(o2.getScore() - o1.getScore()); } }); } String[] fragments = new String[snippets.size()]; for (int i = 0; i < fragments.length; i++) { fragments[i] = snippets.get(i).getText(); } if (fragments.length > 0) { return new HighlightField(highlighterContext.fieldName, StringText.convertFromStringArray(fragments)); } return null; } private static Query rewrite(HighlighterContext highlighterContext, IndexReader reader) throws IOException { //rewrite is expensive: if the query was already rewritten we try not to rewrite boolean mustRewrite = !highlighterContext.query.queryRewritten(); Query original = highlighterContext.query.originalQuery(); MultiTermQuery originalMultiTermQuery = null; MultiTermQuery.RewriteMethod originalRewriteMethod = null; if (original instanceof MultiTermQuery) { originalMultiTermQuery = (MultiTermQuery) original; if (!allowsForTermExtraction(originalMultiTermQuery.getRewriteMethod())) { originalRewriteMethod = originalMultiTermQuery.getRewriteMethod(); originalMultiTermQuery.setRewriteMethod(new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(50)); //we need to rewrite anyway if it is a multi term query which was rewritten with the wrong rewrite method mustRewrite = true; } } if (!mustRewrite) { //return the rewritten query return highlighterContext.query.query(); } Query query = original; for (Query rewrittenQuery = query.rewrite(reader); rewrittenQuery != query; rewrittenQuery = query.rewrite(reader)) { query = rewrittenQuery; } if (originalMultiTermQuery != null) { if (originalRewriteMethod != null) { //set back the original rewrite method after the rewrite is done originalMultiTermQuery.setRewriteMethod(originalRewriteMethod); } } return query; } private static boolean allowsForTermExtraction(MultiTermQuery.RewriteMethod rewriteMethod) { return rewriteMethod instanceof TopTermsRewrite || rewriteMethod instanceof ScoringRewrite; } private static SortedSet<Term> extractTerms(Query query) { SortedSet<Term> queryTerms = new TreeSet<Term>(); query.extractTerms(queryTerms); return queryTerms; } private static BytesRef[] filterTerms(SortedSet<Term> queryTerms, String field, boolean requireFieldMatch) { SortedSet<Term> fieldTerms; if (requireFieldMatch) { Term floor = new Term(field, ""); Term ceiling = new Term(field, UnicodeUtil.BIG_TERM); fieldTerms = queryTerms.subSet(floor, ceiling); } else { fieldTerms = queryTerms; } BytesRef terms[] = new BytesRef[fieldTerms.size()]; int termUpto = 0; for(Term term : fieldTerms) { terms[termUpto++] = term.bytes(); } return terms; } private static List<Snippet> filterSnippets(List<Snippet> snippets, int numberOfFragments) { //We need to filter the snippets as due to no_match_size we could have //either highlighted snippets together non highlighted ones //We don't want to mix those up List<Snippet> filteredSnippets = new ArrayList<Snippet>(snippets.size()); for (Snippet snippet : snippets) { if (snippet.isHighlighted()) { filteredSnippets.add(snippet); } } //if there's at least one highlighted snippet, we return all the highlighted ones //otherwise we return the first non highlighted one if available if (filteredSnippets.size() == 0) { if (snippets.size() > 0) { Snippet snippet = snippets.get(0); //if we did discrete per value highlighting using whole break iterator (as number_of_fragments was 0) //we need to obtain the first sentence of the first value if (numberOfFragments == 0) { BreakIterator bi = BreakIterator.getSentenceInstance(Locale.ROOT); String text = snippet.getText(); bi.setText(text); int next = bi.next(); if (next != BreakIterator.DONE) { String newText = text.substring(0, next).trim(); snippet = new Snippet(newText, snippet.getScore(), snippet.isHighlighted()); } } filteredSnippets.add(snippet); } } return filteredSnippets; } private static class HighlighterEntry { final SortedSet<Term> queryTerms; Map<FieldMapper<?>, MapperHighlighterEntry> mappers = Maps.newHashMap(); private HighlighterEntry(SortedSet<Term> queryTerms) { this.queryTerms = queryTerms; } } private static class MapperHighlighterEntry { final CustomPassageFormatter passageFormatter; final BytesRef[] filteredQueryTerms; private MapperHighlighterEntry(CustomPassageFormatter passageFormatter, BytesRef[] filteredQueryTerms) { this.passageFormatter = passageFormatter; this.filteredQueryTerms = filteredQueryTerms; } } }
1no label
src_main_java_org_elasticsearch_search_highlight_PostingsHighlighter.java
1,540
@Service("blUpdateCartService") public class UpdateCartServiceImpl implements UpdateCartService { protected static final Log LOG = LogFactory.getLog(UpdateCartServiceImpl.class); protected static BroadleafCurrency savedCurrency; @Resource(name="blOrderService") protected OrderService orderService; @Resource(name = "blUpdateCartServiceExtensionManager") protected UpdateCartServiceExtensionManager extensionManager; @Override public boolean currencyHasChanged() { BroadleafCurrency currency = findActiveCurrency(); if (getSavedCurrency() == null) { setSavedCurrency(currency); } else if (getSavedCurrency() != currency){ return true; } return false; } @Override public UpdateCartResponse copyCartToCurrentContext(Order currentCart) { if(currentCart.getOrderItems() == null){ return null; } BroadleafCurrency currency = findActiveCurrency(); if(currency == null){ return null; } //Reprice order logic List<AddToCartItem> itemsToReprice = new ArrayList<AddToCartItem>(); List<OrderItem> itemsToRemove = new ArrayList<OrderItem>(); List<OrderItem> itemsToReset = new ArrayList<OrderItem>(); boolean repriceOrder = true; for(OrderItem orderItem: currentCart.getOrderItems()){ //Lookup price in price list, if null, then add to itemsToRemove if (orderItem instanceof DiscreteOrderItem){ DiscreteOrderItem doi = (DiscreteOrderItem) orderItem; if(checkAvailabilityInLocale(doi, currency)){ AddToCartItem itemRequest = new AddToCartItem(); itemRequest.setProductId(doi.getProduct().getId()); itemRequest.setQuantity(doi.getQuantity()); itemsToReprice.add(itemRequest); itemsToReset.add(orderItem); } else { itemsToRemove.add(orderItem); } } else if (orderItem instanceof BundleOrderItem) { BundleOrderItem boi = (BundleOrderItem) orderItem; for (DiscreteOrderItem doi : boi.getDiscreteOrderItems()) { if(checkAvailabilityInLocale(doi, currency)){ AddToCartItem itemRequest = new AddToCartItem(); itemRequest.setProductId(doi.getProduct().getId()); itemRequest.setQuantity(doi.getQuantity()); itemsToReprice.add(itemRequest); itemsToReset.add(orderItem); } else { itemsToRemove.add(orderItem); } } } } for(OrderItem orderItem: itemsToReset){ try { currentCart = orderService.removeItem(currentCart.getId(), orderItem.getId(), false); } catch (RemoveFromCartException e) { e.printStackTrace(); } } for(AddToCartItem itemRequest: itemsToReprice){ try { currentCart = orderService.addItem(currentCart.getId(), itemRequest, false); } catch (AddToCartException e) { e.printStackTrace(); } } // Reprice and save the cart try { currentCart = orderService.save(currentCart, repriceOrder); } catch (PricingException e) { e.printStackTrace(); } setSavedCurrency(currency); UpdateCartResponse updateCartResponse = new UpdateCartResponse(); updateCartResponse.setRemovedItems(itemsToRemove); updateCartResponse.setOrder(currentCart); return updateCartResponse; } @Override public void validateCart(Order cart) { // hook to allow override } @Override public void updateAndValidateCart(Order cart) { if (extensionManager != null) { ExtensionResultHolder erh = new ExtensionResultHolder(); extensionManager.getProxy().updateAndValidateCart(cart, erh); Boolean clearCart = (Boolean) erh.getContextMap().get("clearCart"); Boolean repriceCart = (Boolean) erh.getContextMap().get("repriceCart"); Boolean saveCart = (Boolean) erh.getContextMap().get("saveCart"); if (clearCart != null && clearCart.booleanValue()) { orderService.cancelOrder(cart); cart = orderService.createNewCartForCustomer(cart.getCustomer()); } else { try { if (repriceCart != null && repriceCart.booleanValue()) { cart.updatePrices(); orderService.save(cart, true); } else if (saveCart != null && saveCart.booleanValue()) { orderService.save(cart, false); } } catch (PricingException pe) { LOG.error("Pricing Exception while validating cart. Clearing cart.", pe); orderService.cancelOrder(cart); cart = orderService.createNewCartForCustomer(cart.getCustomer()); } } } } protected BroadleafCurrency findActiveCurrency(){ if(BroadleafRequestContext.hasLocale()){ return BroadleafRequestContext.getBroadleafRequestContext().getBroadleafCurrency(); } return null; } protected boolean checkAvailabilityInLocale(DiscreteOrderItem doi, BroadleafCurrency currency) { if (doi.getSku() != null && extensionManager != null) { Sku sku = doi.getSku(); return sku.isAvailable(); } return false; } @Override public void setSavedCurrency(BroadleafCurrency savedCurrency) { this.savedCurrency = savedCurrency; } @Override public BroadleafCurrency getSavedCurrency() { return savedCurrency; } }
1no label
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_service_UpdateCartServiceImpl.java
1,167
public abstract class OQueryOperator { public static enum ORDER { /** * Used when order compared to other operator can not be evaluated or has no consequences. */ UNKNOWNED, /** * Used when this operator must be before the other one */ BEFORE, /** * Used when this operator must be after the other one */ AFTER, /** * Used when this operator is equal the other one */ EQUAL } public static enum INDEX_OPERATION_TYPE { GET, COUNT } /** * Default operator order. can be used by additional operator to locate themself relatively to default ones. * <p/> * WARNING: ORDER IS IMPORTANT TO AVOID SUB-STRING LIKE "IS" and AND "INSTANCEOF": INSTANCEOF MUST BE PLACED BEFORE! AND ALSO FOR * PERFORMANCE (MOST USED BEFORE) */ protected static final Class<?>[] DEFAULT_OPERATORS_ORDER = { OQueryOperatorEquals.class, OQueryOperatorAnd.class, OQueryOperatorOr.class, OQueryOperatorNotEquals.class, OQueryOperatorNot.class, OQueryOperatorMinorEquals.class, OQueryOperatorMinor.class, OQueryOperatorMajorEquals.class, OQueryOperatorContainsAll.class, OQueryOperatorMajor.class, OQueryOperatorLike.class, OQueryOperatorMatches.class, OQueryOperatorInstanceof.class, OQueryOperatorIs.class, OQueryOperatorIn.class, OQueryOperatorContainsKey.class, OQueryOperatorContainsValue.class, OQueryOperatorContainsText.class, OQueryOperatorContains.class, OQueryOperatorTraverse.class, OQueryOperatorBetween.class, OQueryOperatorPlus.class, OQueryOperatorMinus.class, OQueryOperatorMultiply.class, OQueryOperatorDivide.class, OQueryOperatorMod.class }; public final String keyword; public final int precedence; public final int expectedRightWords; public final boolean unary; public final boolean expectsParameters; protected OQueryOperator(final String iKeyword, final int iPrecedence, final boolean iUnary) { this(iKeyword, iPrecedence, iUnary, 1, false); } protected OQueryOperator(final String iKeyword, final int iPrecedence, final boolean iUnary, final int iExpectedRightWords) { this(iKeyword, iPrecedence, iUnary, iExpectedRightWords, false); } protected OQueryOperator(final String iKeyword, final int iPrecedence, final boolean iUnary, final int iExpectedRightWords, final boolean iExpectsParameters) { keyword = iKeyword; precedence = iPrecedence; unary = iUnary; expectedRightWords = iExpectedRightWords; expectsParameters = iExpectsParameters; } public abstract Object evaluateRecord(final OIdentifiable iRecord, ODocument iCurrentResult, final OSQLFilterCondition iCondition, final Object iLeft, final Object iRight, OCommandContext iContext); /** * Returns hint how index can be used to calculate result of operator execution. * * @param iLeft * Value of left query parameter. * @param iRight * Value of right query parameter. * @return Hint how index can be used to calculate result of operator execution. */ public abstract OIndexReuseType getIndexReuseType(Object iLeft, Object iRight); /** * Performs index query to calculate result of execution of given operator. * <p/> * Query that should be executed can be presented like: [[property0 = keyParam0] and [property1 = keyParam1] and] propertyN * operator keyParamN. * <p/> * It is supped that index which passed in as parameter is used to index properties listed above and responsibility of given * method execute query using given parameters. * <p/> * Multiple parameters are passed in to implement composite indexes support. * * * * * @param iContext * TODO * @param index * Instance of index that will be used to calculate result of operator execution. * @param iOperationType * TODO * @param keyParams * Parameters of query is used to calculate query result. * @param resultListener * @param fetchLimit * @return Result of execution of given operator or {@code null} if given index can not be used to calculate operator result. */ public Object executeIndexQuery(OCommandContext iContext, OIndex<?> index, INDEX_OPERATION_TYPE iOperationType, final List<Object> keyParams, final IndexResultListener resultListener, int fetchLimit) { return null; } @Override public String toString() { return keyword; } /** * Default State-less implementation: does not save parameters and just return itself * * @param iParams * @return */ public OQueryOperator configure(final List<String> iParams) { return this; } public String getSyntax() { return "<left> " + keyword + " <right>"; } public abstract ORID getBeginRidRange(final Object iLeft, final Object iRight); public abstract ORID getEndRidRange(final Object iLeft, final Object iRight); public boolean isUnary() { return unary; } /** * Check priority of this operator compare to given operator. * * @param other * @return ORDER place of this operator compared to given operator */ public ORDER compare(OQueryOperator other) { final Class<?> thisClass = this.getClass(); final Class<?> otherClass = other.getClass(); int thisPosition = -1; int otherPosition = -1; for (int i = 0; i < DEFAULT_OPERATORS_ORDER.length; i++) { // subclass of default operators inherit their parent ordering final Class<?> clazz = DEFAULT_OPERATORS_ORDER[i]; if (clazz.isAssignableFrom(thisClass)) { thisPosition = i; } if (clazz.isAssignableFrom(otherClass)) { otherPosition = i; } } if (thisPosition == -1 || otherPosition == -1) { // can not decide which comes first return ORDER.UNKNOWNED; } if (thisPosition > otherPosition) { return ORDER.AFTER; } else if (thisPosition < otherPosition) { return ORDER.BEFORE; } return ORDER.EQUAL; } protected void updateProfiler(final OCommandContext iContext, final OIndex<?> index, final List<Object> keyParams, final OIndexDefinition indexDefinition) { if (iContext.isRecordingMetrics()) iContext.updateMetric("compositeIndexUsed", +1); final OProfilerMBean profiler = Orient.instance().getProfiler(); if (profiler.isRecording()) { profiler.updateCounter(profiler.getDatabaseMetric(index.getDatabaseName(), "query.indexUsed"), "Used index in query", +1); int params = indexDefinition.getParamCount(); if (params > 1) { final String profiler_prefix = profiler.getDatabaseMetric(index.getDatabaseName(), "query.compositeIndexUsed"); profiler.updateCounter(profiler_prefix, "Used composite index in query", +1); profiler.updateCounter(profiler_prefix + "." + params, "Used composite index in query with " + params + " params", +1); profiler.updateCounter(profiler_prefix + "." + params + '.' + keyParams.size(), "Used composite index in query with " + params + " params and " + keyParams.size() + " keys", +1); } } } public interface IndexResultListener extends OIndex.IndexValuesResultListener { Object getResult(); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperator.java
153
static final class SnapshotIterator<E> implements Iterator<E> { private final Object[] items; private int cursor; SnapshotIterator(ReadMostlyVector<E> v) { items = v.toArray(); } public boolean hasNext() { return cursor < items.length; } @SuppressWarnings("unchecked") public E next() { if (cursor < items.length) return (E) items[cursor++]; throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException() ; } }
0true
src_main_java_jsr166e_extra_ReadMostlyVector.java
372
@SuppressWarnings("unchecked") public class ODatabaseRaw extends OListenerManger<ODatabaseListener> implements ODatabase { protected String url; protected OStorage storage; protected STATUS status; protected OIntent currentIntent; private ODatabaseRecord databaseOwner; private final Map<String, Object> properties = new HashMap<String, Object>(); public ODatabaseRaw(final String iURL) { super(Collections.newSetFromMap(new IdentityHashMap<ODatabaseListener, Boolean>(64)), new ONoLock()); if (iURL == null) throw new IllegalArgumentException("URL parameter is null"); try { url = iURL.replace('\\', '/'); status = STATUS.CLOSED; // SET DEFAULT PROPERTIES setProperty("fetch-max", 50); } catch (Throwable t) { throw new ODatabaseException("Error on opening database '" + iURL + "'", t); } } public <DB extends ODatabase> DB open(final String iUserName, final String iUserPassword) { try { if (status == STATUS.OPEN) throw new IllegalStateException("Database " + getName() + " is already open"); if (storage == null) storage = Orient.instance().loadStorage(url); storage.open(iUserName, iUserPassword, properties); status = STATUS.OPEN; // WAKE UP LISTENERS callOnOpenListeners(); } catch (OException e) { // PASS THROUGH throw e; } catch (Exception e) { throw new ODatabaseException("Cannot open database", e); } return (DB) this; } public <DB extends ODatabase> DB create() { try { if (status == STATUS.OPEN) throw new IllegalStateException("Database " + getName() + " is already open"); if (storage == null) storage = Orient.instance().loadStorage(url); storage.create(properties); status = STATUS.OPEN; } catch (Exception e) { throw new ODatabaseException("Cannot create database", e); } return (DB) this; } public void drop() { final Iterable<ODatabaseListener> tmpListeners = getListenersCopy(); close(); try { if (storage == null) storage = Orient.instance().loadStorage(url); storage.delete(); storage = null; // WAKE UP LISTENERS for (ODatabaseListener listener : tmpListeners) try { listener.onDelete(this); } catch (Throwable t) { } status = STATUS.CLOSED; ODatabaseRecordThreadLocal.INSTANCE.set(null); } catch (OException e) { // PASS THROUGH throw e; } catch (Exception e) { throw new ODatabaseException("Cannot delete database", e); } } @Override public void backup(OutputStream out, Map<String, Object> options, Callable<Object> callable) throws IOException { getStorage().backup(out, options, callable); } @Override public void restore(InputStream in, Map<String, Object> options, Callable<Object> callable) throws IOException { if (storage == null) storage = Orient.instance().loadStorage(url); getStorage().restore(in, options, callable); } public void reload() { storage.reload(); } public STATUS getStatus() { return status; } public <DB extends ODatabase> DB setStatus(final STATUS status) { this.status = status; return (DB) this; } public <DB extends ODatabase> DB setDefaultClusterId(final int iDefClusterId) { storage.setDefaultClusterId(iDefClusterId); return (DB) this; } public boolean exists() { if (status == STATUS.OPEN) return true; if (storage == null) storage = Orient.instance().loadStorage(url); return storage.exists(); } public long countClusterElements(final String iClusterName) { final int clusterId = getClusterIdByName(iClusterName); if (clusterId < 0) throw new IllegalArgumentException("Cluster '" + iClusterName + "' was not found"); return storage.count(clusterId); } public long countClusterElements(final int iClusterId) { return storage.count(iClusterId); } public long countClusterElements(final int[] iClusterIds) { return storage.count(iClusterIds); } @Override public long countClusterElements(int iCurrentClusterId, boolean countTombstones) { return storage.count(iCurrentClusterId, countTombstones); } @Override public long countClusterElements(int[] iClusterIds, boolean countTombstones) { return storage.count(iClusterIds, countTombstones); } public OStorageOperationResult<ORawBuffer> read(final ORecordId iRid, final String iFetchPlan, final boolean iIgnoreCache, boolean loadTombstones) { if (!iRid.isValid()) return new OStorageOperationResult<ORawBuffer>(null); OFetchHelper.checkFetchPlanValid(iFetchPlan); try { return storage.readRecord(iRid, iFetchPlan, iIgnoreCache, null, loadTombstones); } catch (Throwable t) { if (iRid.isTemporary()) throw new ODatabaseException("Error on retrieving record using temporary RecordId: " + iRid, t); else throw new ODatabaseException("Error on retrieving record " + iRid + " (cluster: " + storage.getPhysicalClusterNameById(iRid.clusterId) + ")", t); } } public OStorageOperationResult<ORecordVersion> save(final int iDataSegmentId, final ORecordId iRid, final byte[] iContent, final ORecordVersion iVersion, final byte iRecordType, final int iMode, boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback, final ORecordCallback<ORecordVersion> iRecordUpdatedCallback) { // CHECK IF RECORD TYPE IS SUPPORTED Orient.instance().getRecordFactoryManager().getRecordTypeClass(iRecordType); try { if (iForceCreate || iRid.clusterPosition.isNew()) { // CREATE final OStorageOperationResult<OPhysicalPosition> ppos = storage.createRecord(iDataSegmentId, iRid, iContent, iVersion, iRecordType, iMode, (ORecordCallback<OClusterPosition>) iRecordCreatedCallback); return new OStorageOperationResult<ORecordVersion>(ppos.getResult().recordVersion, ppos.isMoved()); } else { // UPDATE return storage.updateRecord(iRid, iContent, iVersion, iRecordType, iMode, iRecordUpdatedCallback); } } catch (OException e) { // PASS THROUGH throw e; } catch (Throwable t) { throw new ODatabaseException("Error on saving record " + iRid, t); } } public boolean updateReplica(final int dataSegmentId, final ORecordId rid, final byte[] content, final ORecordVersion version, final byte recordType) { // CHECK IF RECORD TYPE IS SUPPORTED Orient.instance().getRecordFactoryManager().getRecordTypeClass(recordType); try { if (rid.clusterPosition.isNew()) { throw new ODatabaseException("Passed in record was not stored and can not be treated as replica."); } else { // UPDATE REPLICA return storage.updateReplica(dataSegmentId, rid, content, version, recordType); } } catch (OException e) { // PASS THROUGH throw e; } catch (Throwable t) { throw new ODatabaseException("Error on replica update " + rid, t); } } public OStorageOperationResult<Boolean> delete(final ORecordId iRid, final ORecordVersion iVersion, final boolean iRequired, final int iMode) { try { final OStorageOperationResult<Boolean> result = storage.deleteRecord(iRid, iVersion, iMode, null); if (!result.getResult() && iRequired) throw new ORecordNotFoundException("The record with id " + iRid + " was not found"); return result; } catch (OException e) { // PASS THROUGH throw e; } catch (Exception e) { OLogManager.instance().exception("Error on deleting record " + iRid, e, ODatabaseException.class); return new OStorageOperationResult<Boolean>(Boolean.FALSE); } } public boolean cleanOutRecord(final ORecordId iRid, final ORecordVersion iVersion, final boolean iRequired, final int iMode) { try { final boolean result = storage.cleanOutRecord(iRid, iVersion, iMode, null); if (!result && iRequired) throw new ORecordNotFoundException("The record with id " + iRid + " was not found"); return result; } catch (OException e) { // PASS THROUGH throw e; } catch (Exception e) { OLogManager.instance().exception("Error on deleting record " + iRid, e, ODatabaseException.class); return false; } } public OStorage getStorage() { return storage; } public void replaceStorage(final OStorage iNewStorage) { storage = iNewStorage; } public boolean isClosed() { return status == STATUS.CLOSED || storage.isClosed(); } public String getName() { return storage != null ? storage.getName() : url; } public String getURL() { return url != null ? url : storage.getURL(); } public int getDataSegmentIdByName(final String iDataSegmentName) { return storage.getDataSegmentIdByName(iDataSegmentName); } public String getDataSegmentNameById(final int dataSegmentId) { return storage.getDataSegmentById(dataSegmentId).getName(); } public int getClusters() { return storage.getClusters(); } public boolean existsCluster(final String iClusterName) { return storage.getClusterNames().contains(iClusterName); } public String getClusterType(final String iClusterName) { return storage.getClusterTypeByName(iClusterName); } public int getClusterIdByName(final String iClusterName) { return storage.getClusterIdByName(iClusterName); } public String getClusterNameById(final int iClusterId) { if (iClusterId == -1) return null; // PHIYSICAL CLUSTER return storage.getPhysicalClusterNameById(iClusterId); } public long getClusterRecordSizeById(final int iClusterId) { try { return storage.getClusterById(iClusterId).getRecordsSize(); } catch (Exception e) { OLogManager.instance().exception("Error on reading records size for cluster with id '" + iClusterId + "'", e, ODatabaseException.class); } return 0l; } public long getClusterRecordSizeByName(final String iClusterName) { try { return storage.getClusterById(getClusterIdByName(iClusterName)).getRecordsSize(); } catch (Exception e) { OLogManager.instance().exception("Error on reading records size for cluster '" + iClusterName + "'", e, ODatabaseException.class); } return 0l; } public int addCluster(String iClusterName, CLUSTER_TYPE iType, Object... iParameters) { return addCluster(iType.toString(), iClusterName, null, null, iParameters); } public int addCluster(final String iType, final String iClusterName, final String iLocation, final String iDataSegmentName, final Object... iParameters) { return storage.addCluster(iType, iClusterName, iLocation, iDataSegmentName, false, iParameters); } public int addCluster(String iType, String iClusterName, int iRequestedId, String iLocation, String iDataSegmentName, Object... iParameters) { return storage.addCluster(iType, iClusterName, iRequestedId, iLocation, iDataSegmentName, false, iParameters); } public boolean dropCluster(final String iClusterName, final boolean iTruncate) { return storage.dropCluster(iClusterName, iTruncate); } public boolean dropCluster(int iClusterId, final boolean iTruncate) { return storage.dropCluster(iClusterId, iTruncate); } public int addDataSegment(final String iSegmentName, final String iLocation) { return storage.addDataSegment(iSegmentName, iLocation); } public boolean dropDataSegment(final String iName) { return storage.dropDataSegment(iName); } public Collection<String> getClusterNames() { return storage.getClusterNames(); } /** * Returns always null * * @return */ public OLevel1RecordCache getLevel1Cache() { return null; } public int getDefaultClusterId() { return storage.getDefaultClusterId(); } public boolean declareIntent(final OIntent iIntent) { if (currentIntent != null) { if (iIntent != null && iIntent.getClass().equals(currentIntent.getClass())) // SAME INTENT: JUMP IT return false; // END CURRENT INTENT currentIntent.end(this); } currentIntent = iIntent; if (iIntent != null) iIntent.begin(this); return true; } public ODatabaseRecord getDatabaseOwner() { return databaseOwner; } public ODatabaseRaw setOwner(final ODatabaseRecord iOwner) { databaseOwner = iOwner; return this; } public Object setProperty(final String iName, final Object iValue) { if (iValue == null) return properties.remove(iName.toLowerCase()); else return properties.put(iName.toLowerCase(), iValue); } public Object getProperty(final String iName) { return properties.get(iName.toLowerCase()); } public Iterator<Entry<String, Object>> getProperties() { return properties.entrySet().iterator(); } public OLevel2RecordCache getLevel2Cache() { return storage.getLevel2Cache(); } public void close() { if (status != STATUS.OPEN) return; if (currentIntent != null) { currentIntent.end(this); currentIntent = null; } resetListeners(); if (storage != null) storage.close(); storage = null; status = STATUS.CLOSED; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append("OrientDB["); buffer.append(url != null ? url : "?"); buffer.append(']'); if (getStorage() != null) { buffer.append(" (users: "); buffer.append(getStorage().getUsers()); buffer.append(')'); } return buffer.toString(); } public Object get(final ATTRIBUTES iAttribute) { if (iAttribute == null) throw new IllegalArgumentException("attribute is null"); switch (iAttribute) { case STATUS: return getStatus(); case DEFAULTCLUSTERID: return getDefaultClusterId(); case TYPE: ODatabaseRecord db; if (getDatabaseOwner() instanceof ODatabaseRecord) db = ((ODatabaseRecord) getDatabaseOwner()); else db = new OGraphDatabase(url); return db.getMetadata().getSchema().existsClass("V") ? "graph" : "document"; case DATEFORMAT: return storage.getConfiguration().dateFormat; case DATETIMEFORMAT: return storage.getConfiguration().dateTimeFormat; case TIMEZONE: return storage.getConfiguration().getTimeZone().getID(); case LOCALECOUNTRY: return storage.getConfiguration().getLocaleCountry(); case LOCALELANGUAGE: return storage.getConfiguration().getLocaleLanguage(); case CHARSET: return storage.getConfiguration().getCharset(); case CUSTOM: return storage.getConfiguration().properties; } return null; } public <DB extends ODatabase> DB set(final ATTRIBUTES iAttribute, final Object iValue) { if (iAttribute == null) throw new IllegalArgumentException("attribute is null"); final String stringValue = iValue != null ? iValue.toString() : null; switch (iAttribute) { case STATUS: setStatus(STATUS.valueOf(stringValue.toUpperCase(Locale.ENGLISH))); break; case DEFAULTCLUSTERID: if (iValue != null) { if (iValue instanceof Number) storage.setDefaultClusterId(((Number) iValue).intValue()); else storage.setDefaultClusterId(storage.getClusterIdByName(iValue.toString())); } break; case TYPE: if (stringValue.equalsIgnoreCase("graph")) { if (getDatabaseOwner() instanceof OGraphDatabase) ((OGraphDatabase) getDatabaseOwner()).checkForGraphSchema(); else if (getDatabaseOwner() instanceof ODatabaseRecordTx) new OGraphDatabase((ODatabaseRecordTx) getDatabaseOwner()).checkForGraphSchema(); else new OGraphDatabase(url).checkForGraphSchema(); } else throw new IllegalArgumentException("Database type '" + stringValue + "' is not supported"); break; case DATEFORMAT: storage.getConfiguration().dateFormat = stringValue; storage.getConfiguration().update(); break; case DATETIMEFORMAT: storage.getConfiguration().dateTimeFormat = stringValue; storage.getConfiguration().update(); break; case TIMEZONE: storage.getConfiguration().setTimeZone(TimeZone.getTimeZone(stringValue.toUpperCase())); storage.getConfiguration().update(); break; case LOCALECOUNTRY: storage.getConfiguration().setLocaleCountry(stringValue); storage.getConfiguration().update(); break; case LOCALELANGUAGE: storage.getConfiguration().setLocaleLanguage(stringValue); storage.getConfiguration().update(); break; case CHARSET: storage.getConfiguration().setCharset(stringValue); storage.getConfiguration().update(); break; case CUSTOM: if (iValue.toString().indexOf("=") == -1) { if (iValue.toString().equalsIgnoreCase("clear")) { clearCustomInternal(); } else throw new IllegalArgumentException("Syntax error: expected <name> = <value> or clear, instead found: " + iValue); } else { final List<String> words = OStringSerializerHelper.smartSplit(iValue.toString(), '='); setCustomInternal(words.get(0).trim(), words.get(1).trim()); } break; default: throw new IllegalArgumentException("Option '" + iAttribute + "' not supported on alter database"); } return (DB) this; } public String getCustom(final String iName) { if (storage.getConfiguration().properties == null) return null; for (OStorageEntryConfiguration e : storage.getConfiguration().properties) { if (e.name.equals(iName)) return e.value; } return null; } public void setCustomInternal(final String iName, final String iValue) { if (iValue == null || "null".equalsIgnoreCase(iValue)) { // REMOVE if (storage.getConfiguration().properties != null) { for (Iterator<OStorageEntryConfiguration> it = storage.getConfiguration().properties.iterator(); it.hasNext();) { final OStorageEntryConfiguration e = it.next(); if (e.name.equals(iName)) { it.remove(); break; } } } } else { // SET if (storage.getConfiguration().properties == null) storage.getConfiguration().properties = new ArrayList<OStorageEntryConfiguration>(); boolean found = false; for (OStorageEntryConfiguration e : storage.getConfiguration().properties) { if (e.name.equals(iName)) { e.value = iValue; found = true; break; } } if (!found) // CREATE A NEW ONE storage.getConfiguration().properties.add(new OStorageEntryConfiguration(iName, iValue)); } storage.getConfiguration().update(); } public void clearCustomInternal() { storage.getConfiguration().properties = null; } public <V> V callInLock(final Callable<V> iCallable, final boolean iExclusiveLock) { return storage.callInLock(iCallable, iExclusiveLock); } @Override public <V> V callInRecordLock(final Callable<V> iCallable, final ORID rid, final boolean iExclusiveLock) { return storage.callInRecordLock(iCallable, rid, iExclusiveLock); } @Override public ORecordMetadata getRecordMetadata(final ORID rid) { return storage.getRecordMetadata(rid); } public void callOnOpenListeners() { // WAKE UP DB LIFECYCLE LISTENER for (Iterator<ODatabaseLifecycleListener> it = Orient.instance().getDbLifecycleListeners(); it.hasNext();) it.next().onOpen(getDatabaseOwner()); // WAKE UP LISTENERS for (ODatabaseListener listener : getListenersCopy()) try { listener.onOpen(getDatabaseOwner()); } catch (Throwable t) { t.printStackTrace(); } } public void callOnCloseListeners() { // WAKE UP DB LIFECYCLE LISTENER for (Iterator<ODatabaseLifecycleListener> it = Orient.instance().getDbLifecycleListeners(); it.hasNext();) it.next().onClose(getDatabaseOwner()); // WAKE UP LISTENERS for (ODatabaseListener listener : getListenersCopy()) try { listener.onClose(getDatabaseOwner()); } catch (Throwable t) { t.printStackTrace(); } } protected boolean isClusterBoundedToClass(final int iClusterId) { return false; } public long getSize() { return storage.getSize(); } public void freeze() { final OFreezableStorage storage = getFreezableStorage(); if (storage != null) { storage.freeze(false); } } public void freeze(final boolean throwException) { final OFreezableStorage storage = getFreezableStorage(); if (storage != null) { storage.freeze(throwException); } } public void release() { final OFreezableStorage storage = getFreezableStorage(); if (storage != null) { storage.release(); } } private OFreezableStorage getFreezableStorage() { OStorage s = getStorage(); if (s instanceof OFreezableStorage) return (OFreezableStorage) s; else { OLogManager.instance().error(this, "Storage of type " + s.getType() + " does not support freeze operation."); return null; } } @Override public void freezeCluster(final int iClusterId) { freezeCluster(iClusterId, false); } @Override public void releaseCluster(final int iClusterId) { final OLocalPaginatedStorage storage; if (getStorage() instanceof OLocalPaginatedStorage) storage = ((OLocalPaginatedStorage) getStorage()); else { OLogManager.instance().error(this, "We can not freeze non local storage."); return; } storage.release(iClusterId); } @Override public void freezeCluster(final int iClusterId, final boolean throwException) { if (getStorage() instanceof OLocalPaginatedStorage) { final OLocalPaginatedStorage paginatedStorage = ((OLocalPaginatedStorage) getStorage()); paginatedStorage.freeze(throwException, iClusterId); } else { OLogManager.instance().error(this, "Only local paginated storage supports cluster freeze."); } } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_raw_ODatabaseRaw.java
1,253
new OProfilerHookValue() { public Object getValue() { return lastStrategy; } });
0true
core_src_main_java_com_orientechnologies_orient_core_storage_fs_OMMapManagerOld.java
105
public static class Name { public static final String Basic = "PageImpl_Basic"; public static final String Page = "PageImpl_Page"; public static final String Rules = "PageImpl_Rules"; }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageImpl.java
738
public class ShardDeleteByQueryResponse extends ActionResponse { @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); } }
0true
src_main_java_org_elasticsearch_action_deletebyquery_ShardDeleteByQueryResponse.java
1,148
public interface EntryListener<K, V> extends EventListener { /** * Invoked when an entry is added. * * @param event entry event */ void entryAdded(EntryEvent<K, V> event); /** * Invoked when an entry is removed. * * @param event entry event */ void entryRemoved(EntryEvent<K, V> event); /** * Invoked when an entry is updated. * * @param event entry event */ void entryUpdated(EntryEvent<K, V> event); /** * Invoked when an entry is evicted. * * @param event entry event */ void entryEvicted(EntryEvent<K, V> event); }
0true
hazelcast_src_main_java_com_hazelcast_core_EntryListener.java
633
public class PropertiesVariableExpression implements BroadleafVariableExpression { @Autowired protected RuntimeEnvironmentPropertiesManager propMgr; @Override public String getName() { return "props"; } public String get(String propertyName) { return propMgr.getProperty(propertyName); } public int getAsInt(String propertyName) { return Integer.parseInt(propMgr.getProperty(propertyName)); } }
0true
common_src_main_java_org_broadleafcommerce_common_web_expression_PropertiesVariableExpression.java
112
public interface PageRule extends SimpleRule { /** * Gets the primary key. * * @return the primary key */ @Nullable public Long getId(); /** * Sets the primary key. * * @param id the new primary key */ public void setId(@Nullable Long id); /** * Builds a copy of this content rule. Used by the content management system when an * item is edited. * * @return a copy of this rule */ @Nonnull public PageRule cloneEntity(); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageRule.java
3,208
LONG(64, false, SortField.Type.LONG, Long.MIN_VALUE, Long.MAX_VALUE) { @Override public long toLong(BytesRef indexForm) { return NumericUtils.prefixCodedToLong(indexForm); } @Override public void toIndexForm(Number number, BytesRef bytes) { NumericUtils.longToPrefixCodedBytes(number.longValue(), 0, bytes); } @Override public Number toNumber(BytesRef indexForm) { return NumericUtils.prefixCodedToLong(indexForm); } },
0true
src_main_java_org_elasticsearch_index_fielddata_IndexNumericFieldData.java
435
public class StandardKeyInformation implements KeyInformation { private final Class<?> dataType; private final Parameter[] parameters; private final Cardinality cardinality; public StandardKeyInformation(Class<?> dataType) { this(dataType,new Parameter[0]); } public StandardKeyInformation(Class<?> dataType, Parameter... parameters) { Preconditions.checkNotNull(dataType); Preconditions.checkNotNull(parameters); this.dataType = dataType; this.parameters = parameters; this.cardinality = Cardinality.SINGLE; } @Override public Class<?> getDataType() { return dataType; } public boolean hasParameters() { return parameters.length>0; } @Override public Parameter[] getParameters() { return parameters; } @Override public Cardinality getCardinality() { return cardinality; } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_StandardKeyInformation.java
129
public class TestApplyTransactions { @Test public void testCommittedTransactionReceivedAreForcedToLog() throws Exception { /* GIVEN * Create a tx on a db (as if the master), extract that, apply on dest (as if pullUpdate on slave). * Let slave crash uncleanly. */ File baseStoreDir = new File( "base" ); File originStoreDir = new File( baseStoreDir, "origin" ); File destStoreDir = new File( baseStoreDir, "destination" ); GraphDatabaseAPI origin = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( fs.get() ) .newImpermanentDatabase( originStoreDir.getPath() ); Transaction tx = origin.beginTx(); origin.createNode(); tx.success(); tx.finish(); XaDataSource originNeoDataSource = xaDs( origin ); int latestTxId = (int) originNeoDataSource.getLastCommittedTxId(); InMemoryLogBuffer theTx = new InMemoryLogBuffer(); originNeoDataSource.getLogExtractor( latestTxId, latestTxId ).extractNext( theTx ); final GraphDatabaseAPI dest = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( fs.get() ) .newImpermanentDatabase( destStoreDir.getPath() ); XaDataSource destNeoDataSource = xaDs( dest ); destNeoDataSource.applyCommittedTransaction( latestTxId, theTx ); origin.shutdown(); EphemeralFileSystemAbstraction snapshot = fs.snapshot( shutdownDb( dest ) ); /* * Open crashed db, try to extract the transaction it reports as latest. It should be there. */ GraphDatabaseAPI newDest = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( snapshot ) .newImpermanentDatabase( destStoreDir.getPath() ); destNeoDataSource = newDest.getDependencyResolver().resolveDependency( XaDataSourceManager.class ) .getXaDataSource( NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME ); latestTxId = (int) destNeoDataSource.getLastCommittedTxId(); theTx = new InMemoryLogBuffer(); long extractedTxId = destNeoDataSource.getLogExtractor( latestTxId, latestTxId ).extractNext( theTx ); assertEquals( latestTxId, extractedTxId ); } private XaDataSource xaDs( GraphDatabaseAPI origin ) { return origin.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).getXaDataSource( NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME ); } @Test public void verifyThatRecoveredTransactionsHaveTheirDoneRecordsWrittenInOrder() throws IOException { XaDataSource ds; File archivedLogFilename; File originStoreDir = new File( new File( "base" ), "origin" ); String logicalLogFilename = "logicallog"; final GraphDatabaseAPI db1 = (GraphDatabaseAPI) new TestGraphDatabaseFactory() .setFileSystem( fs.get() ) .newImpermanentDatabaseBuilder( originStoreDir.getPath() ) .setConfig( InternalAbstractGraphDatabase.Configuration.logical_log, logicalLogFilename ) .newGraphDatabase(); for ( int i = 0; i < 100; i++ ) { Transaction tx = db1.beginTx(); db1.createNode(); tx.success(); tx.finish(); } ds = xaDs( db1 ); archivedLogFilename = ds.getFileName( ds.getCurrentLogVersion() ); fs.snapshot( new Runnable() { @Override public void run() { db1.shutdown(); } } ); removeDoneEntriesFromLog( new File( archivedLogFilename.getParent(), logicalLogFilename + ".1" ) ); GraphDatabaseAPI db2 = (GraphDatabaseAPI) new TestGraphDatabaseFactory() .setFileSystem( fs.get() ) .newImpermanentDatabaseBuilder( originStoreDir.getPath() ) .setConfig( InternalAbstractGraphDatabase.Configuration.logical_log, logicalLogFilename ) .newGraphDatabase(); ds = xaDs( db2 ); archivedLogFilename = ds.getFileName( ds.getCurrentLogVersion() ); db2.shutdown(); List<LogEntry> logEntries = filterDoneEntries( logEntries( fs.get(), archivedLogFilename ) ); String errorMessage = "DONE entries should be in order: " + logEntries; int prev = 0; for ( LogEntry entry : logEntries ) { int current = entry.getIdentifier(); assertThat( errorMessage, current, greaterThan( prev ) ); prev = current; } } private void removeDoneEntriesFromLog( File archivedLogFilename ) throws IOException { LogTestUtils.LogHook<LogEntry> doneEntryFilter = new LogTestUtils.LogHookAdapter<LogEntry>() { @Override public boolean accept( LogEntry item ) { return !(item instanceof LogEntry.Done); } }; EphemeralFileSystemAbstraction fsa = fs.get(); File tempFile = filterNeostoreLogicalLog( fsa, archivedLogFilename, doneEntryFilter ); fsa.deleteFile( archivedLogFilename ); fsa.renameFile( tempFile, archivedLogFilename ); } private List<LogEntry> filterDoneEntries( List<LogEntry> logEntries ) { Predicate<? super LogEntry> doneEntryPredicate = new Predicate<LogEntry>() { @Override public boolean accept( LogEntry item ) { return item instanceof LogEntry.Done; } }; return Iterables.toList( Iterables.filter( doneEntryPredicate, logEntries ) ); } @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestApplyTransactions.java
1,595
public class MapMetadata extends CollectionMetadata { private String valueClassName; private String[][] keys; private boolean isSimpleValue; private String mediaField; private String mapKeyValueProperty; private String mapKeyOptionEntityClass; private String mapKeyOptionEntityDisplayField; private String mapKeyOptionEntityValueField; private Boolean forceFreeFormKeys; public String getValueClassName() { return valueClassName; } public void setValueClassName(String valueClassName) { this.valueClassName = valueClassName; } public boolean isSimpleValue() { return isSimpleValue; } public void setSimpleValue(boolean simpleValue) { isSimpleValue = simpleValue; } public String getMediaField() { return mediaField; } public void setMediaField(String mediaField) { this.mediaField = mediaField; } public String[][] getKeys() { return keys; } public void setKeys(String[][] keys) { this.keys = keys; } public String getMapKeyValueProperty() { return mapKeyValueProperty; } public void setMapKeyValueProperty(String mapKeyValueProperty) { this.mapKeyValueProperty = mapKeyValueProperty; } public String getMapKeyOptionEntityClass() { return mapKeyOptionEntityClass; } public void setMapKeyOptionEntityClass(String mapKeyOptionEntityClass) { this.mapKeyOptionEntityClass = mapKeyOptionEntityClass; } public String getMapKeyOptionEntityDisplayField() { return mapKeyOptionEntityDisplayField; } public void setMapKeyOptionEntityDisplayField(String mapKeyOptionEntityDisplayField) { this.mapKeyOptionEntityDisplayField = mapKeyOptionEntityDisplayField; } public String getMapKeyOptionEntityValueField() { return mapKeyOptionEntityValueField; } public void setMapKeyOptionEntityValueField(String mapKeyOptionEntityValueField) { this.mapKeyOptionEntityValueField = mapKeyOptionEntityValueField; } public Boolean getForceFreeFormKeys() { return forceFreeFormKeys; } public void setForceFreeFormKeys(Boolean forceFreeFormKeys) { this.forceFreeFormKeys = forceFreeFormKeys; } @Override public void accept(MetadataVisitor visitor) { visitor.visit(this); } @Override protected FieldMetadata populate(FieldMetadata metadata) { ((MapMetadata) metadata).valueClassName = valueClassName; ((MapMetadata) metadata).isSimpleValue = isSimpleValue; ((MapMetadata) metadata).mediaField = mediaField; ((MapMetadata) metadata).keys = keys; ((MapMetadata) metadata).mapKeyValueProperty = mapKeyValueProperty; ((MapMetadata) metadata).mapKeyOptionEntityClass = mapKeyOptionEntityClass; ((MapMetadata) metadata).mapKeyOptionEntityDisplayField = mapKeyOptionEntityDisplayField; ((MapMetadata) metadata).mapKeyOptionEntityValueField = mapKeyOptionEntityValueField; ((MapMetadata) metadata).forceFreeFormKeys = forceFreeFormKeys; return super.populate(metadata); } @Override public FieldMetadata cloneFieldMetadata() { MapMetadata metadata = new MapMetadata(); return populate(metadata); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MapMetadata)) return false; if (!super.equals(o)) return false; MapMetadata metadata = (MapMetadata) o; if (isSimpleValue != metadata.isSimpleValue) return false; if (mapKeyValueProperty != null ? !mapKeyValueProperty.equals(metadata.mapKeyValueProperty) : metadata.mapKeyValueProperty != null) return false; if (mapKeyOptionEntityClass != null ? !mapKeyOptionEntityClass.equals(metadata.mapKeyOptionEntityClass) : metadata.mapKeyOptionEntityClass != null) return false; if (mapKeyOptionEntityDisplayField != null ? !mapKeyOptionEntityDisplayField.equals(metadata.mapKeyOptionEntityDisplayField) : metadata.mapKeyOptionEntityDisplayField != null) return false; if (mapKeyOptionEntityValueField != null ? !mapKeyOptionEntityValueField.equals(metadata.mapKeyOptionEntityValueField) : metadata.mapKeyOptionEntityValueField != null) return false; if (mediaField != null ? !mediaField.equals(metadata.mediaField) : metadata.mediaField != null) return false; if (valueClassName != null ? !valueClassName.equals(metadata.valueClassName) : metadata.valueClassName != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (valueClassName != null ? valueClassName.hashCode() : 0); result = 31 * result + (isSimpleValue ? 1 : 0); result = 31 * result + (mediaField != null ? mediaField.hashCode() : 0); result = 31 * result + (mapKeyValueProperty != null ? mapKeyValueProperty.hashCode() : 0); result = 31 * result + (mapKeyOptionEntityClass != null ? mapKeyOptionEntityClass.hashCode() : 0); result = 31 * result + (mapKeyOptionEntityDisplayField != null ? mapKeyOptionEntityDisplayField.hashCode() : 0); result = 31 * result + (mapKeyOptionEntityValueField != null ? mapKeyOptionEntityValueField.hashCode() : 0); return result; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_MapMetadata.java
299
public class NoOpStoreTransaction extends AbstractStoreTransaction { public NoOpStoreTransaction(BaseTransactionConfig config) { super(config); } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_common_NoOpStoreTransaction.java
1,520
private static class DefaultOutOfMemoryHandler extends OutOfMemoryHandler { @Override public void onOutOfMemory(OutOfMemoryError oom, HazelcastInstance[] hazelcastInstances) { for (HazelcastInstance instance : hazelcastInstances) { if (instance instanceof HazelcastInstanceImpl) { Helper.tryCloseConnections(instance); Helper.tryStopThreads(instance); Helper.tryShutdown(instance); } } System.err.println(oom); } }
0true
hazelcast_src_main_java_com_hazelcast_instance_OutOfMemoryErrorDispatcher.java
3,517
public class MergeMappingException extends MapperException { private final String[] failures; public MergeMappingException(String[] failures) { super("Merge failed with failures {" + Arrays.toString(failures) + "}"); this.failures = failures; } public String[] failures() { return failures; } @Override public RestStatus status() { return RestStatus.BAD_REQUEST; } }
0true
src_main_java_org_elasticsearch_index_mapper_MergeMappingException.java
627
public class OIndexRebuildOutputListener implements OProgressListener { private final OIndex<?> idx; long startTime; long lastDump; long lastCounter = 0; public OIndexRebuildOutputListener(final OIndex<?> idx) { this.idx = idx; } @Override public void onBegin(final Object iTask, final long iTotal) { startTime = System.currentTimeMillis(); lastDump = startTime; OLogManager.instance().debug(this, "- Building index %s...", idx.getName()); } @Override public boolean onProgress(final Object iTask, final long iCounter, final float iPercent) { final long now = System.currentTimeMillis(); if (now - lastDump > 10000) { // DUMP EVERY 5 SECONDS FOR LARGE INDEXES OLogManager.instance().debug(this, "--> %3.2f%% progress, %,d indexed so far (%,d items/sec)", iPercent, iCounter, ((iCounter - lastCounter) / 10)); lastDump = now; lastCounter = iCounter; } return true; } @Override public void onCompletition(final Object iTask, final boolean iSucceed) { OLogManager.instance().debug(this, "--> OK, indexed %,d items in %,d ms", idx.getSize(), (System.currentTimeMillis() - startTime)); } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndexRebuildOutputListener.java
1,603
public class Imports { private static final List<String> imports = new ArrayList<String>(); private static final List<String> evaluates = new ArrayList<String>(); public static final String HDFS = "hdfs"; public static final String LOCAL = "local"; static { // hadoop imports.add("org.apache.hadoop.hdfs.*"); imports.add("org.apache.hadoop.conf.*"); imports.add("org.apache.hadoop.fs.*"); imports.add("org.apache.hadoop.util.*"); imports.add("org.apache.hadoop.io.*"); imports.add("org.apache.hadoop.io.compress.*"); imports.add("org.apache.hadoop.mapreduce.lib.input.*"); imports.add("org.apache.hadoop.mapreduce.lib.output.*"); // faunus imports.add("com.thinkaurelius.titan.hadoop.*"); imports.add("com.thinkaurelius.titan.hadoop.formats.*"); imports.add("com.thinkaurelius.titan.hadoop.formats.edgelist.*"); imports.add("com.thinkaurelius.titan.hadoop.formats.edgelist.rdf.*"); imports.add("com.thinkaurelius.titan.hadoop.formats.graphson.*"); imports.add("com.thinkaurelius.titan.hadoop.formats.noop.*"); imports.add("com.thinkaurelius.titan.hadoop.formats.rexster.*"); imports.add("com.thinkaurelius.titan.hadoop.formats.script.*"); imports.add("com.thinkaurelius.titan.hadoop.formats.util.*"); imports.add("com.thinkaurelius.titan.hadoop.formats.hbase.*"); imports.add("com.thinkaurelius.titan.hadoop.formats.cassandra.*"); imports.add("com.thinkaurelius.titan.hadoop.hdfs.*"); imports.add("com.thinkaurelius.titan.hadoop.tinkerpop.gremlin.*"); imports.add("com.tinkerpop.gremlin.Tokens.T"); imports.add("com.tinkerpop.gremlin.groovy.*"); imports.add("static " + TransformPipe.Order.class.getName() + ".*"); // titan imports.addAll(com.thinkaurelius.titan.tinkerpop.gremlin.Imports.getImports()); // tinkerpop (most likely inherited from Titan, but just to be safe) imports.addAll(com.tinkerpop.gremlin.Imports.getImports()); evaluates.add("hdfs = FileSystem.get(new Configuration())"); evaluates.add("local = FileSystem.getLocal(new Configuration())"); } public static List<String> getImports() { return Imports.imports; } public static List<String> getEvaluates() { return Imports.evaluates; } public static Bindings getEvaluateBindings() throws IOException { Bindings bindings = new SimpleBindings(); bindings.put(Imports.HDFS, FileSystem.get(new Configuration())); bindings.put(Imports.LOCAL, FileSystem.getLocal(new Configuration())); return bindings; } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_tinkerpop_gremlin_Imports.java
379
public class ODatabaseRecordTx extends ODatabaseRecordAbstract { public static final String TYPE = "record"; private OTransaction currentTx; public ODatabaseRecordTx(final String iURL, final byte iRecordType) { super(iURL, iRecordType); init(); } public ODatabaseRecord begin() { return begin(TXTYPE.OPTIMISTIC); } public ODatabaseRecord begin(final TXTYPE iType) { setCurrentDatabaseinThreadLocal(); if (currentTx.isActive()) currentTx.rollback(); // WAKE UP LISTENERS for (ODatabaseListener listener : underlying.browseListeners()) try { listener.onBeforeTxBegin(underlying); } catch (Throwable t) { OLogManager.instance().error(this, "Error before tx begin", t); } switch (iType) { case NOTX: setDefaultTransactionMode(); break; case OPTIMISTIC: currentTx = new OTransactionOptimistic(this); break; case PESSIMISTIC: throw new UnsupportedOperationException("Pessimistic transaction"); } currentTx.begin(); return this; } public ODatabaseRecord begin(final OTransaction iTx) { currentTx.rollback(); // WAKE UP LISTENERS for (ODatabaseListener listener : underlying.browseListeners()) try { listener.onBeforeTxBegin(underlying); } catch (Throwable t) { OLogManager.instance().error(this, "Error before the transaction begin", t, OTransactionBlockedException.class); } currentTx = iTx; currentTx.begin(); return this; } public ODatabaseRecord commit() { setCurrentDatabaseinThreadLocal(); // WAKE UP LISTENERS for (ODatabaseListener listener : underlying.browseListeners()) try { listener.onBeforeTxCommit(this); } catch (Throwable t) { try { rollback(); } catch (Exception e) { } OLogManager.instance().debug(this, "Cannot commit the transaction: caught exception on execution of %s.onBeforeTxCommit()", t, OTransactionBlockedException.class, listener.getClass()); } try { currentTx.commit(); } catch (RuntimeException e) { // WAKE UP ROLLBACK LISTENERS for (ODatabaseListener listener : underlying.browseListeners()) try { listener.onBeforeTxRollback(underlying); } catch (Throwable t) { OLogManager.instance().error(this, "Error before tx rollback", t); } // ROLLBACK TX AT DB LEVEL currentTx.rollback(); // WAKE UP ROLLBACK LISTENERS for (ODatabaseListener listener : underlying.browseListeners()) try { listener.onAfterTxRollback(underlying); } catch (Throwable t) { OLogManager.instance().error(this, "Error after tx rollback", t); } throw e; } // WAKE UP LISTENERS for (ODatabaseListener listener : underlying.browseListeners()) try { listener.onAfterTxCommit(underlying); } catch (Throwable t) { OLogManager .instance() .debug( this, "Error after the transaction has been committed. The transaction remains valid. The exception caught was on execution of %s.onAfterTxCommit()", t, OTransactionBlockedException.class, listener.getClass()); } return this; } public ODatabaseRecord rollback() { if (currentTx.isActive()) { // WAKE UP LISTENERS for (ODatabaseListener listener : underlying.browseListeners()) try { listener.onBeforeTxRollback(underlying); } catch (Throwable t) { OLogManager.instance().error(this, "Error before tx rollback", t); } currentTx.rollback(); // WAKE UP LISTENERS for (ODatabaseListener listener : underlying.browseListeners()) try { listener.onAfterTxRollback(underlying); } catch (Throwable t) { OLogManager.instance().error(this, "Error after tx rollback", t); } } return this; } public OTransaction getTransaction() { return currentTx; } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET load(final ORecordInternal<?> iRecord, final String iFetchPlan) { return (RET) currentTx.loadRecord(iRecord.getIdentity(), iRecord, iFetchPlan, false, false); } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET load(ORecordInternal<?> iRecord, String iFetchPlan, boolean iIgnoreCache, boolean loadTombstone) { return (RET) currentTx.loadRecord(iRecord.getIdentity(), iRecord, iFetchPlan, iIgnoreCache, loadTombstone); } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET load(final ORecordInternal<?> iRecord) { return (RET) currentTx.loadRecord(iRecord.getIdentity(), iRecord, null, false, false); } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET load(final ORID iRecordId) { return (RET) currentTx.loadRecord(iRecordId, null, null, false, false); } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET load(final ORID iRecordId, final String iFetchPlan) { return (RET) currentTx.loadRecord(iRecordId, null, iFetchPlan, false, false); } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET load(ORID iRecordId, String iFetchPlan, boolean iIgnoreCache, boolean loadTombstone) { return (RET) currentTx.loadRecord(iRecordId, null, iFetchPlan, iIgnoreCache, loadTombstone); } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET reload(ORecordInternal<?> iRecord) { return reload(iRecord, null, false); } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET reload(ORecordInternal<?> iRecord, String iFetchPlan) { return reload(iRecord, iFetchPlan, false); } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET reload(ORecordInternal<?> iRecord, String iFetchPlan, boolean iIgnoreCache) { ORecordInternal<?> record = currentTx.loadRecord(iRecord.getIdentity(), iRecord, iFetchPlan, iIgnoreCache, false); if (record != null && iRecord != record) { iRecord.fromStream(record.toStream()); iRecord.getRecordVersion().copyFrom(record.getRecordVersion()); } return (RET) record; } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iContent, final OPERATION_MODE iMode, boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<ORecordVersion> iRecordUpdatedCallback) { return (RET) save(iContent, (String) null, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback); } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iContent) { return (RET) save(iContent, (String) null, OPERATION_MODE.SYNCHRONOUS, false, null, null); } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iContent, final String iClusterName) { return (RET) save(iContent, iClusterName, OPERATION_MODE.SYNCHRONOUS, false, null, null); } @Override public boolean updatedReplica(ORecordInternal<?> iContent) { return currentTx.updateReplica(iContent); } @SuppressWarnings("unchecked") @Override public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iContent, final String iClusterName, final OPERATION_MODE iMode, boolean iForceCreate, ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<ORecordVersion> iRecordUpdatedCallback) { currentTx.saveRecord(iContent, iClusterName, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback); return (RET) iContent; } /** * Deletes the record without checking the version. */ public ODatabaseRecord delete(final ORID iRecord) { final ORecord<?> rec = iRecord.getRecord(); if (rec != null) rec.delete(); return this; } @Override public ODatabaseRecord delete(final ORecordInternal<?> iRecord) { currentTx.deleteRecord(iRecord, OPERATION_MODE.SYNCHRONOUS); return this; } @Override public ODatabaseRecord delete(final ORecordInternal<?> iRecord, final OPERATION_MODE iMode) { currentTx.deleteRecord(iRecord, iMode); return this; } public void executeRollback(final OTransaction iTransaction) { } protected void checkTransaction() { if (currentTx == null || currentTx.getStatus() == TXSTATUS.INVALID) throw new OTransactionException("Transaction not started"); } private void init() { currentTx = new OTransactionNoTx(this); } public ORecordInternal<?> getRecordByUserObject(final Object iUserObject, final boolean iCreateIfNotAvailable) { return (ORecordInternal<?>) iUserObject; } public void registerUserObject(final Object iObject, final ORecordInternal<?> iRecord) { } public void registerUserObjectAfterLinkSave(ORecordInternal<?> iRecord) { } public Object getUserObjectByRecord(final OIdentifiable record, final String iFetchPlan) { return record; } public boolean existsUserObjectByRID(final ORID iRID) { return true; } public String getType() { return TYPE; } public void setDefaultTransactionMode() { if (!(currentTx instanceof OTransactionNoTx)) currentTx = new OTransactionNoTx(this); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_db_record_ODatabaseRecordTx.java
1,591
public abstract class FieldMetadata implements Serializable { private static final long serialVersionUID = 1L; private String inheritedFromType; private String[] availableToTypes; private Boolean excluded; private String friendlyName; private String securityLevel; private Integer order; private String owningClassFriendlyName; private String tab; private Integer tabOrder; //temporary fields private Boolean childrenExcluded; private String targetClass; private String owningClass; private String prefix; private String fieldName; private String showIfProperty; private String currencyCodeField; //Additional metadata not supported as first class private Map<String, Object> additionalMetadata = new HashMap<String, Object>(); public String[] getAvailableToTypes() { return availableToTypes; } public void setAvailableToTypes(String[] availableToTypes) { Arrays.sort(availableToTypes); this.availableToTypes = availableToTypes; } public String getInheritedFromType() { return inheritedFromType; } public void setInheritedFromType(String inheritedFromType) { this.inheritedFromType = inheritedFromType; } public Boolean getExcluded() { return excluded; } public void setExcluded(Boolean excluded) { this.excluded = excluded; } public Map<String, Object> getAdditionalMetadata() { return additionalMetadata; } public void setAdditionalMetadata(Map<String, Object> additionalMetadata) { this.additionalMetadata = additionalMetadata; } protected FieldMetadata populate(FieldMetadata metadata) { metadata.inheritedFromType = inheritedFromType; if (availableToTypes != null) { metadata.availableToTypes = new String[availableToTypes.length]; System.arraycopy(availableToTypes, 0, metadata.availableToTypes, 0, availableToTypes.length); } metadata.excluded = excluded; metadata.friendlyName = friendlyName; metadata.owningClassFriendlyName = owningClassFriendlyName; metadata.securityLevel = securityLevel; metadata.order = order; metadata.targetClass = targetClass; metadata.owningClass = owningClass; metadata.prefix = prefix; metadata.childrenExcluded = childrenExcluded; metadata.fieldName = fieldName; metadata.showIfProperty = showIfProperty; metadata.currencyCodeField = currencyCodeField; for (Map.Entry<String, Object> entry : additionalMetadata.entrySet()) { metadata.additionalMetadata.put(entry.getKey(), entry.getValue()); } return metadata; } public String getShowIfProperty() { return showIfProperty; } public void setShowIfProperty(String showIfProperty) { this.showIfProperty = showIfProperty; } public String getCurrencyCodeField() { return currencyCodeField; } public void setCurrencyCodeField(String currencyCodeField) { this.currencyCodeField = currencyCodeField; } public String getFriendlyName() { return friendlyName; } public void setFriendlyName(String friendlyName) { this.friendlyName = friendlyName; } public String getSecurityLevel() { return securityLevel; } public void setSecurityLevel(String securityLevel) { this.securityLevel = securityLevel; } public Integer getOrder() { return order; } public void setOrder(Integer order) { this.order = order; } public String getTargetClass() { return targetClass; } public void setTargetClass(String targetClass) { this.targetClass = targetClass; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getOwningClassFriendlyName() { return owningClassFriendlyName; } public void setOwningClassFriendlyName(String owningClassFriendlyName) { this.owningClassFriendlyName = owningClassFriendlyName; } public String getOwningClass() { return owningClass; } public void setOwningClass(String owningClass) { this.owningClass = owningClass; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public Boolean getChildrenExcluded() { return childrenExcluded; } public void setChildrenExcluded(Boolean childrenExcluded) { this.childrenExcluded = childrenExcluded; } public String getTab() { return tab; } public void setTab(String tab) { this.tab = tab; } public Integer getTabOrder() { return tabOrder; } public void setTabOrder(Integer tabOrder) { this.tabOrder = tabOrder; } public abstract FieldMetadata cloneFieldMetadata(); public abstract void accept(MetadataVisitor visitor); @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof FieldMetadata)) return false; FieldMetadata that = (FieldMetadata) o; if (additionalMetadata != null ? !additionalMetadata.equals(that.additionalMetadata) : that .additionalMetadata != null) return false; if (!Arrays.equals(availableToTypes, that.availableToTypes)) return false; if (childrenExcluded != null ? !childrenExcluded.equals(that.childrenExcluded) : that.childrenExcluded != null) return false; if (currencyCodeField != null ? !currencyCodeField.equals(that.currencyCodeField) : that.currencyCodeField != null) return false; if (excluded != null ? !excluded.equals(that.excluded) : that.excluded != null) return false; if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) return false; if (friendlyName != null ? !friendlyName.equals(that.friendlyName) : that.friendlyName != null) return false; if (inheritedFromType != null ? !inheritedFromType.equals(that.inheritedFromType) : that.inheritedFromType != null) return false; if (order != null ? !order.equals(that.order) : that.order != null) return false; if (owningClass != null ? !owningClass.equals(that.owningClass) : that.owningClass != null) return false; if (owningClassFriendlyName != null ? !owningClassFriendlyName.equals(that.owningClassFriendlyName) : that .owningClassFriendlyName != null) return false; if (prefix != null ? !prefix.equals(that.prefix) : that.prefix != null) return false; if (securityLevel != null ? !securityLevel.equals(that.securityLevel) : that.securityLevel != null) return false; if (showIfProperty != null ? !showIfProperty.equals(that.showIfProperty) : that.showIfProperty != null) return false; if (tab != null ? !tab.equals(that.tab) : that.tab != null) return false; if (tabOrder != null ? !tabOrder.equals(that.tabOrder) : that.tabOrder != null) return false; if (targetClass != null ? !targetClass.equals(that.targetClass) : that.targetClass != null) return false; return true; } @Override public int hashCode() { int result = inheritedFromType != null ? inheritedFromType.hashCode() : 0; result = 31 * result + (availableToTypes != null ? Arrays.hashCode(availableToTypes) : 0); result = 31 * result + (excluded != null ? excluded.hashCode() : 0); result = 31 * result + (friendlyName != null ? friendlyName.hashCode() : 0); result = 31 * result + (securityLevel != null ? securityLevel.hashCode() : 0); result = 31 * result + (order != null ? order.hashCode() : 0); result = 31 * result + (owningClassFriendlyName != null ? owningClassFriendlyName.hashCode() : 0); result = 31 * result + (tab != null ? tab.hashCode() : 0); result = 31 * result + (tabOrder != null ? tabOrder.hashCode() : 0); result = 31 * result + (childrenExcluded != null ? childrenExcluded.hashCode() : 0); result = 31 * result + (targetClass != null ? targetClass.hashCode() : 0); result = 31 * result + (owningClass != null ? owningClass.hashCode() : 0); result = 31 * result + (prefix != null ? prefix.hashCode() : 0); result = 31 * result + (fieldName != null ? fieldName.hashCode() : 0); result = 31 * result + (showIfProperty != null ? showIfProperty.hashCode() : 0); result = 31 * result + (currencyCodeField != null ? currencyCodeField.hashCode() : 0); result = 31 * result + (additionalMetadata != null ? additionalMetadata.hashCode() : 0); return result; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_FieldMetadata.java
3,203
public interface IndexNumericFieldData<FD extends AtomicNumericFieldData> extends IndexFieldData<FD> { public static enum NumericType { BYTE(8, false, SortField.Type.INT, Byte.MIN_VALUE, Byte.MAX_VALUE) { @Override public long toLong(BytesRef indexForm) { return INT.toLong(indexForm); } @Override public void toIndexForm(Number number, BytesRef bytes) { INT.toIndexForm(number, bytes); } @Override public Number toNumber(BytesRef indexForm) { return INT.toNumber(indexForm); } }, SHORT(16, false, SortField.Type.INT, Short.MIN_VALUE, Short.MAX_VALUE) { @Override public long toLong(BytesRef indexForm) { return INT.toLong(indexForm); } @Override public void toIndexForm(Number number, BytesRef bytes) { INT.toIndexForm(number, bytes); } @Override public Number toNumber(BytesRef indexForm) { return INT.toNumber(indexForm); } }, INT(32, false, SortField.Type.INT, Integer.MIN_VALUE, Integer.MAX_VALUE) { @Override public long toLong(BytesRef indexForm) { return NumericUtils.prefixCodedToInt(indexForm); } @Override public void toIndexForm(Number number, BytesRef bytes) { NumericUtils.intToPrefixCodedBytes(number.intValue(), 0, bytes); } @Override public Number toNumber(BytesRef indexForm) { return NumericUtils.prefixCodedToInt(indexForm); } }, LONG(64, false, SortField.Type.LONG, Long.MIN_VALUE, Long.MAX_VALUE) { @Override public long toLong(BytesRef indexForm) { return NumericUtils.prefixCodedToLong(indexForm); } @Override public void toIndexForm(Number number, BytesRef bytes) { NumericUtils.longToPrefixCodedBytes(number.longValue(), 0, bytes); } @Override public Number toNumber(BytesRef indexForm) { return NumericUtils.prefixCodedToLong(indexForm); } }, FLOAT(32, true, SortField.Type.FLOAT, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) { @Override public double toDouble(BytesRef indexForm) { return NumericUtils.sortableIntToFloat(NumericUtils.prefixCodedToInt(indexForm)); } @Override public void toIndexForm(Number number, BytesRef bytes) { NumericUtils.intToPrefixCodedBytes(NumericUtils.floatToSortableInt(number.floatValue()), 0, bytes); } @Override public Number toNumber(BytesRef indexForm) { return NumericUtils.sortableIntToFloat(NumericUtils.prefixCodedToInt(indexForm)); } }, DOUBLE(64, true, SortField.Type.DOUBLE, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) { @Override public double toDouble(BytesRef indexForm) { return NumericUtils.sortableLongToDouble(NumericUtils.prefixCodedToLong(indexForm)); } @Override public void toIndexForm(Number number, BytesRef bytes) { NumericUtils.longToPrefixCodedBytes(NumericUtils.doubleToSortableLong(number.doubleValue()), 0, bytes); } @Override public Number toNumber(BytesRef indexForm) { return NumericUtils.sortableLongToDouble(NumericUtils.prefixCodedToLong(indexForm)); } }; private final int requiredBits; private final boolean floatingPoint; private final SortField.Type type; private final Number minValue, maxValue; private NumericType(int requiredBits, boolean floatingPoint, SortField.Type type, Number minValue, Number maxValue) { this.requiredBits = requiredBits; this.floatingPoint = floatingPoint; this.type = type; this.minValue = minValue; this.maxValue = maxValue; } public final SortField.Type sortFieldType() { return type; } public final Number minValue() { return minValue; } public final Number maxValue() { return maxValue; } public final boolean isFloatingPoint() { return floatingPoint; } public final int requiredBits() { return requiredBits; } public abstract void toIndexForm(Number number, BytesRef bytes); public long toLong(BytesRef indexForm) { return (long) toDouble(indexForm); } public double toDouble(BytesRef indexForm) { return (double) toLong(indexForm); } public abstract Number toNumber(BytesRef indexForm); public final TermsEnum wrapTermsEnum(TermsEnum termsEnum) { if (requiredBits() > 32) { return OrdinalsBuilder.wrapNumeric64Bit(termsEnum); } else { return OrdinalsBuilder.wrapNumeric32Bit(termsEnum); } } } NumericType getNumericType(); /** * Loads the atomic field data for the reader, possibly cached. */ FD load(AtomicReaderContext context); /** * Loads directly the atomic field data for the reader, ignoring any caching involved. */ FD loadDirect(AtomicReaderContext context) throws Exception; }
0true
src_main_java_org_elasticsearch_index_fielddata_IndexNumericFieldData.java
1,497
public class AbstractEntity { private boolean before1Called = false; private boolean before2Called = false; public void reset() { before1Called = false; before2Called = false; } @OBeforeSerialization public void before1() { before1Called = true; } @OBeforeSerialization public void before2() { before2Called = true; } public boolean callbackExecuted() { return before1Called && before2Called; } }
0true
object_src_test_java_com_orientechnologies_orient_object_enhancement_AbstractEntity.java
1,235
@Deprecated public interface ShippingRateService { public ShippingRate save(ShippingRate shippingRate); public ShippingRate readShippingRateById(Long id); public ShippingRate readShippingRateByFeeTypesUnityQty(String feeType, String feeSubType, BigDecimal unitQuantity); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_ShippingRateService.java
1,394
interface Factory<T extends Custom> { String type(); T readFrom(StreamInput in) throws IOException; void writeTo(T customIndexMetaData, StreamOutput out) throws IOException; T fromXContent(XContentParser parser) throws IOException; void toXContent(T customIndexMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException; /** * Returns true if this custom metadata should be persisted as part of global cluster state */ boolean isPersistent(); }
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaData.java
1,594
public class ForeignKey implements Serializable, PersistencePerspectiveItem { private static final long serialVersionUID = 1L; private String manyToField; private String originatingField; private String foreignKeyClass; private String currentValue; private String dataSourceName; private ForeignKeyRestrictionType restrictionType = ForeignKeyRestrictionType.ID_EQ; private String displayValueProperty = "name"; private Boolean mutable = true; public ForeignKey() { //do nothing } public ForeignKey(String manyToField, String foreignKeyClass) { this(manyToField, foreignKeyClass, null); } public ForeignKey(String manyToField, String foreignKeyClass, String dataSourceName) { this(manyToField, foreignKeyClass, dataSourceName, ForeignKeyRestrictionType.ID_EQ); } public ForeignKey(String manyToField, String foreignKeyClass, String dataSourceName, ForeignKeyRestrictionType restrictionType) { this(manyToField, foreignKeyClass, dataSourceName, restrictionType, "name"); } public ForeignKey(String manyToField, String foreignKeyClass, String dataSourceName, ForeignKeyRestrictionType restrictionType, String displayValueProperty) { this.manyToField = manyToField; this.foreignKeyClass = foreignKeyClass; this.dataSourceName = dataSourceName; this.restrictionType = restrictionType; this.displayValueProperty = displayValueProperty; } public String getManyToField() { return manyToField; } public void setManyToField(String manyToField) { this.manyToField = manyToField; } public String getForeignKeyClass() { return foreignKeyClass; } public void setForeignKeyClass(String foreignKeyClass) { this.foreignKeyClass = foreignKeyClass; } public String getCurrentValue() { return currentValue; } public void setCurrentValue(String currentValue) { this.currentValue = currentValue; } public String getDataSourceName() { return dataSourceName; } public void setDataSourceName(String dataSourceName) { this.dataSourceName = dataSourceName; } public ForeignKeyRestrictionType getRestrictionType() { return restrictionType; } public void setRestrictionType(ForeignKeyRestrictionType restrictionType) { this.restrictionType = restrictionType; } public String getDisplayValueProperty() { return displayValueProperty; } public void setDisplayValueProperty(String displayValueProperty) { this.displayValueProperty = displayValueProperty; } public Boolean getMutable() { return mutable; } public void setMutable(Boolean mutable) { this.mutable = mutable; } public String getOriginatingField() { return originatingField; } public void setOriginatingField(String originatingField) { this.originatingField = originatingField; } public void accept(PersistencePerspectiveItemVisitor visitor) { visitor.visit(this); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(manyToField); sb.append(foreignKeyClass); sb.append(currentValue); sb.append(dataSourceName); sb.append(restrictionType); sb.append(displayValueProperty); sb.append(originatingField); return sb.toString(); } public ForeignKey cloneForeignKey() { ForeignKey foreignKey = new ForeignKey(); foreignKey.manyToField = manyToField; foreignKey.foreignKeyClass = foreignKeyClass; foreignKey.currentValue = currentValue; foreignKey.dataSourceName = dataSourceName; foreignKey.restrictionType = restrictionType; foreignKey.displayValueProperty = displayValueProperty; foreignKey.mutable = mutable; foreignKey.originatingField = originatingField; return foreignKey; } @Override public PersistencePerspectiveItem clonePersistencePerspectiveItem() { return cloneForeignKey(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ForeignKey)) return false; ForeignKey that = (ForeignKey) o; if (currentValue != null ? !currentValue.equals(that.currentValue) : that.currentValue != null) return false; if (dataSourceName != null ? !dataSourceName.equals(that.dataSourceName) : that.dataSourceName != null) return false; if (displayValueProperty != null ? !displayValueProperty.equals(that.displayValueProperty) : that .displayValueProperty != null) return false; if (foreignKeyClass != null ? !foreignKeyClass.equals(that.foreignKeyClass) : that.foreignKeyClass != null) return false; if (manyToField != null ? !manyToField.equals(that.manyToField) : that.manyToField != null) return false; if (mutable != null ? !mutable.equals(that.mutable) : that.mutable != null) return false; if (originatingField != null ? !originatingField.equals(that.originatingField) : that.originatingField != null) return false; if (restrictionType != that.restrictionType) return false; return true; } @Override public int hashCode() { int result = manyToField != null ? manyToField.hashCode() : 0; result = 31 * result + (originatingField != null ? originatingField.hashCode() : 0); result = 31 * result + (foreignKeyClass != null ? foreignKeyClass.hashCode() : 0); result = 31 * result + (currentValue != null ? currentValue.hashCode() : 0); result = 31 * result + (dataSourceName != null ? dataSourceName.hashCode() : 0); result = 31 * result + (restrictionType != null ? restrictionType.hashCode() : 0); result = 31 * result + (displayValueProperty != null ? displayValueProperty.hashCode() : 0); result = 31 * result + (mutable != null ? mutable.hashCode() : 0); return result; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_ForeignKey.java
2,427
public class TestList extends SlicedObjectList<Double> { public TestList(int capactiy) { this(new Double[capactiy], 0, capactiy); } public TestList(Double[] values, int offset, int length) { super(values, offset, length); } public TestList(Double[] values) { super(values); } @Override public void grow(int newLength) { assertThat(offset, equalTo(0)); // NOTE: senseless if offset != 0 if (values.length >= newLength) { return; } final Double[] current = values; values = new Double[ArrayUtil.oversize(newLength, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; System.arraycopy(current, 0, values, 0, current.length); } }
0true
src_test_java_org_elasticsearch_common_util_SlicedObjectListTests.java
1,588
public enum DIRECTION { NONE, IN, OUT, BOTH }
0true
server_src_main_java_com_orientechnologies_orient_server_distributed_ODistributedServerLog.java
1,670
public interface BlobMetaData { String name(); long length(); }
0true
src_main_java_org_elasticsearch_common_blobstore_BlobMetaData.java
259
{ @Override public synchronized Object answer( InvocationOnMock invocation ) throws Throwable { Lock mock = mock( Lock.class ); lockMocks.add( mock ); return mock; } } );
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_nioneo_xa_WriteTransactionTest.java
1,189
public class BroadcastActionsTests extends ElasticsearchIntegrationTest { @Test public void testBroadcastOperations() throws IOException { prepareCreate("test", 1).execute().actionGet(5000); logger.info("Running Cluster Health"); ClusterHealthResponse clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForYellowStatus()).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.getStatus()); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW)); client().index(indexRequest("test").type("type1").id("1").source(source("1", "test"))).actionGet(); flush(); client().index(indexRequest("test").type("type1").id("2").source(source("2", "test"))).actionGet(); refresh(); logger.info("Count"); // check count for (int i = 0; i < 5; i++) { // test successful CountResponse countResponse = client().prepareCount("test") .setQuery(termQuery("_type", "type1")) .setOperationThreading(BroadcastOperationThreading.NO_THREADS).get(); assertThat(countResponse.getCount(), equalTo(2l)); assertThat(countResponse.getTotalShards(), equalTo(5)); assertThat(countResponse.getSuccessfulShards(), equalTo(5)); assertThat(countResponse.getFailedShards(), equalTo(0)); } for (int i = 0; i < 5; i++) { CountResponse countResponse = client().prepareCount("test") .setQuery(termQuery("_type", "type1")) .setOperationThreading(BroadcastOperationThreading.SINGLE_THREAD).get(); assertThat(countResponse.getCount(), equalTo(2l)); assertThat(countResponse.getTotalShards(), equalTo(5)); assertThat(countResponse.getSuccessfulShards(), equalTo(5)); assertThat(countResponse.getFailedShards(), equalTo(0)); } for (int i = 0; i < 5; i++) { CountResponse countResponse = client().prepareCount("test") .setQuery(termQuery("_type", "type1")) .setOperationThreading(BroadcastOperationThreading.THREAD_PER_SHARD).get(); assertThat(countResponse.getCount(), equalTo(2l)); assertThat(countResponse.getTotalShards(), equalTo(5)); assertThat(countResponse.getSuccessfulShards(), equalTo(5)); assertThat(countResponse.getFailedShards(), equalTo(0)); } for (int i = 0; i < 5; i++) { // test failed (simply query that can't be parsed) CountResponse countResponse = client().count(countRequest("test").source("{ term : { _type : \"type1 } }".getBytes(Charsets.UTF_8))).actionGet(); assertThat(countResponse.getCount(), equalTo(0l)); assertThat(countResponse.getTotalShards(), equalTo(5)); assertThat(countResponse.getSuccessfulShards(), equalTo(0)); assertThat(countResponse.getFailedShards(), equalTo(5)); for (ShardOperationFailedException exp : countResponse.getShardFailures()) { assertThat(exp.reason(), containsString("QueryParsingException")); } } } private XContentBuilder source(String id, String nameValue) throws IOException { return XContentFactory.jsonBuilder().startObject().field("id", id).field("name", nameValue).endObject(); } }
0true
src_test_java_org_elasticsearch_broadcast_BroadcastActionsTests.java
784
execute(request, new ActionListener<SearchResponse>() { @Override public void onResponse(SearchResponse result) { try { channel.sendResponse(result); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(e); } catch (Exception e1) { logger.warn("Failed to send response for get", e1); } } });
0true
src_main_java_org_elasticsearch_action_mlt_TransportMoreLikeThisAction.java
2,848
public class CzechAnalyzerProvider extends AbstractIndexAnalyzerProvider<CzechAnalyzer> { private final CzechAnalyzer analyzer; @Inject public CzechAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); analyzer = new CzechAnalyzer(version, Analysis.parseStopWords(env, settings, CzechAnalyzer.getDefaultStopSet(), version), Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET, version)); } @Override public CzechAnalyzer get() { return this.analyzer; } }
0true
src_main_java_org_elasticsearch_index_analysis_CzechAnalyzerProvider.java
1,874
.setEnabled(true).setImplementation(new MapStoreAdapter() { public void store(Object key, Object value) { throw new IllegalStateException("Map store intentionally failed :) "); } }));
0true
hazelcast_src_test_java_com_hazelcast_map_MapTransactionTest.java
309
Integer.class, 2, new OConfigurationChangeCallback() { public void change(final Object iCurrentValue, final Object iNewValue) { OMMapManagerOld.setOverlapStrategy((Integer) iNewValue); } }),
0true
core_src_main_java_com_orientechnologies_orient_core_config_OGlobalConfiguration.java
2,673
public class EnvironmentModule extends AbstractModule { private final Environment environment; public EnvironmentModule(Environment environment) { this.environment = environment; } @Override protected void configure() { bind(Environment.class).toInstance(environment); } }
0true
src_main_java_org_elasticsearch_env_EnvironmentModule.java
1,008
threadPool.executor(executor).execute(new Runnable() { @Override public void run() { try { Response response = shardOperation(request, shard.id()); listener.onResponse(response); } catch (Throwable e) { onFailure(shard, e); } } });
0true
src_main_java_org_elasticsearch_action_support_single_custom_TransportSingleCustomOperationAction.java
429
public class ClusterStateResponse extends ActionResponse { private ClusterName clusterName; private ClusterState clusterState; public ClusterStateResponse() { } ClusterStateResponse(ClusterName clusterName, ClusterState clusterState) { this.clusterName = clusterName; this.clusterState = clusterState; } public ClusterState getState() { return this.clusterState; } public ClusterName getClusterName() { return this.clusterName; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); clusterName = ClusterName.readClusterName(in); clusterState = ClusterState.Builder.readFrom(in, null); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); clusterName.writeTo(out); ClusterState.Builder.writeTo(clusterState, out); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_state_ClusterStateResponse.java
551
public class GetFieldMappingsResponse extends ActionResponse implements ToXContent { private ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappings = ImmutableMap.of(); GetFieldMappingsResponse(ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappings) { this.mappings = mappings; } GetFieldMappingsResponse() { } /** returns the retrieved field mapping. The return map keys are index, type, field (as specified in the request). */ public ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappings() { return mappings; } /** * Returns the mappings of a specific field. * * @param field field name as specified in the {@link GetFieldMappingsRequest} * @return FieldMappingMetaData for the requested field or null if not found. */ public FieldMappingMetaData fieldMappings(String index, String type, String field) { ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>> indexMapping = mappings.get(index); if (indexMapping == null) { return null; } ImmutableMap<String, FieldMappingMetaData> typeMapping = indexMapping.get(type); if (typeMapping == null) { return null; } return typeMapping.get(field); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { for (Map.Entry<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> indexEntry : mappings.entrySet()) { builder.startObject(indexEntry.getKey(), XContentBuilder.FieldCaseConversion.NONE); builder.startObject("mappings"); for (Map.Entry<String, ImmutableMap<String, FieldMappingMetaData>> typeEntry : indexEntry.getValue().entrySet()) { builder.startObject(typeEntry.getKey(), XContentBuilder.FieldCaseConversion.NONE); for (Map.Entry<String, FieldMappingMetaData> fieldEntry : typeEntry.getValue().entrySet()) { builder.startObject(fieldEntry.getKey()); fieldEntry.getValue().toXContent(builder, params); builder.endObject(); } builder.endObject(); } builder.endObject(); builder.endObject(); } return builder; } public static class FieldMappingMetaData implements ToXContent { public static final FieldMappingMetaData NULL = new FieldMappingMetaData("", BytesArray.EMPTY); private String fullName; private BytesReference source; public FieldMappingMetaData(String fullName, BytesReference source) { this.fullName = fullName; this.source = source; } public String fullName() { return fullName; } /** Returns the mappings as a map. Note that the returned map has a single key which is always the field's {@link Mapper#name}. */ public Map<String, Object> sourceAsMap() { return XContentHelper.convertToMap(source.array(), source.arrayOffset(), source.length(), true).v2(); } public boolean isNull() { return NULL.fullName().equals(fullName) && NULL.source.length() == source.length(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field("full_name", fullName); XContentHelper.writeRawField("mapping", source, builder, params); return builder; } } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); int size = in.readVInt(); ImmutableMap.Builder<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> indexMapBuilder = ImmutableMap.builder(); for (int i = 0; i < size; i++) { String index = in.readString(); int typesSize = in.readVInt(); ImmutableMap.Builder<String, ImmutableMap<String, FieldMappingMetaData>> typeMapBuilder = ImmutableMap.builder(); for (int j = 0; j < typesSize; j++) { String type = in.readString(); ImmutableMap.Builder<String, FieldMappingMetaData> fieldMapBuilder = ImmutableMap.builder(); int fieldSize = in.readVInt(); for (int k = 0; k < fieldSize; k++) { fieldMapBuilder.put(in.readString(), new FieldMappingMetaData(in.readString(), in.readBytesReference())); } typeMapBuilder.put(type, fieldMapBuilder.build()); } indexMapBuilder.put(index, typeMapBuilder.build()); } mappings = indexMapBuilder.build(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(mappings.size()); for (Map.Entry<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> indexEntry : mappings.entrySet()) { out.writeString(indexEntry.getKey()); out.writeVInt(indexEntry.getValue().size()); for (Map.Entry<String, ImmutableMap<String, FieldMappingMetaData>> typeEntry : indexEntry.getValue().entrySet()) { out.writeString(typeEntry.getKey()); out.writeVInt(typeEntry.getValue().size()); for (Map.Entry<String, FieldMappingMetaData> fieldEntry : typeEntry.getValue().entrySet()) { out.writeString(fieldEntry.getKey()); FieldMappingMetaData fieldMapping = fieldEntry.getValue(); out.writeString(fieldMapping.fullName()); out.writeBytesReference(fieldMapping.source); } } } } }
1no label
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_GetFieldMappingsResponse.java
348
Map<String, IndexEntry> uniq = new HashMap<String, IndexEntry>(additions.size()) {{ for (IndexEntry e : additions) put(e.field, e); }};
0true
titan-es_src_main_java_com_thinkaurelius_titan_diskstorage_es_ElasticSearchIndex.java
3,749
@SuppressWarnings("deprecation") public class WebFilter implements Filter { protected static final String HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR = "::hz::"; private static final ILogger LOGGER = Logger.getLogger(WebFilter.class); private static final LocalCacheEntry NULL_ENTRY = new LocalCacheEntry(); private static final String HAZELCAST_REQUEST = "*hazelcast-request"; private static final String HAZELCAST_SESSION_COOKIE_NAME = "hazelcast.sessionId"; private static final ConcurrentMap<String, String> MAP_ORIGINAL_SESSIONS = new ConcurrentHashMap<String, String>(1000); private static final ConcurrentMap<String, HazelcastHttpSession> MAP_SESSIONS = new ConcurrentHashMap<String, HazelcastHttpSession>(1000); protected ServletContext servletContext; protected FilterConfig filterConfig; private String sessionCookieName = HAZELCAST_SESSION_COOKIE_NAME; private HazelcastInstance hazelcastInstance; private String clusterMapName = "none"; private String sessionCookieDomain; private boolean sessionCookieSecure; private boolean sessionCookieHttpOnly; private boolean stickySession = true; private boolean shutdownOnDestroy = true; private boolean deferredWrite; private Properties properties; public WebFilter() { } public WebFilter(Properties properties) { this(); this.properties = properties; } static void destroyOriginalSession(HttpSession originalSession) { String hazelcastSessionId = MAP_ORIGINAL_SESSIONS.remove(originalSession.getId()); if (hazelcastSessionId != null) { HazelcastHttpSession hazelSession = MAP_SESSIONS.remove(hazelcastSessionId); if (hazelSession != null) { hazelSession.webFilter.destroySession(hazelSession, false); } } } private static synchronized String generateSessionId() { final String id = UuidUtil.buildRandomUuidString(); final StringBuilder sb = new StringBuilder("HZ"); final char[] chars = id.toCharArray(); for (final char c : chars) { if (c != '-') { if (Character.isLetter(c)) { sb.append(Character.toUpperCase(c)); } else { sb.append(c); } } } return sb.toString(); } public final void init(final FilterConfig config) throws ServletException { filterConfig = config; servletContext = config.getServletContext(); initInstance(); String mapName = getParam("map-name"); if (mapName != null) { clusterMapName = mapName; } else { clusterMapName = "_web_" + servletContext.getServletContextName(); } try { Config hzConfig = hazelcastInstance.getConfig(); String sessionTTL = getParam("session-ttl-seconds"); if (sessionTTL != null) { MapConfig mapConfig = hzConfig.getMapConfig(clusterMapName); mapConfig.setTimeToLiveSeconds(Integer.parseInt(sessionTTL)); hzConfig.addMapConfig(mapConfig); } } catch (UnsupportedOperationException ignored) { LOGGER.info("client cannot access Config."); } initCookieParams(); initParams(); if (!stickySession) { getClusterMap().addEntryListener(new EntryListener<String, Object>() { public void entryAdded(EntryEvent<String, Object> entryEvent) { } public void entryRemoved(EntryEvent<String, Object> entryEvent) { if (entryEvent.getMember() == null || !entryEvent.getMember().localMember()) { removeSessionLocally(entryEvent.getKey()); } } public void entryUpdated(EntryEvent<String, Object> entryEvent) { } public void entryEvicted(EntryEvent<String, Object> entryEvent) { entryRemoved(entryEvent); } }, false); } if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("sticky:" + stickySession + ", shutdown-on-destroy: " + shutdownOnDestroy + ", map-name: " + clusterMapName); } } private void initParams() { String stickySessionParam = getParam("sticky-session"); if (stickySessionParam != null) { stickySession = Boolean.valueOf(stickySessionParam); } String shutdownOnDestroyParam = getParam("shutdown-on-destroy"); if (shutdownOnDestroyParam != null) { shutdownOnDestroy = Boolean.valueOf(shutdownOnDestroyParam); } String deferredWriteParam = getParam("deferred-write"); if (deferredWriteParam != null) { deferredWrite = Boolean.parseBoolean(deferredWriteParam); } } private void initCookieParams() { String cookieName = getParam("cookie-name"); if (cookieName != null) { sessionCookieName = cookieName; } String cookieDomain = getParam("cookie-domain"); if (cookieDomain != null) { sessionCookieDomain = cookieDomain; } String cookieSecure = getParam("cookie-secure"); if (cookieSecure != null) { sessionCookieSecure = Boolean.valueOf(cookieSecure); } String cookieHttpOnly = getParam("cookie-http-only"); if (cookieHttpOnly != null) { sessionCookieHttpOnly = Boolean.valueOf(cookieHttpOnly); } } private void initInstance() throws ServletException { if (properties == null) { properties = new Properties(); } setProperty(HazelcastInstanceLoader.CONFIG_LOCATION); setProperty(HazelcastInstanceLoader.INSTANCE_NAME); setProperty(HazelcastInstanceLoader.USE_CLIENT); setProperty(HazelcastInstanceLoader.CLIENT_CONFIG_LOCATION); hazelcastInstance = getInstance(properties); } private void setProperty(String propertyName) { String value = getParam(propertyName); if (value != null) { properties.setProperty(propertyName, value); } } private void removeSessionLocally(String sessionId) { HazelcastHttpSession hazelSession = MAP_SESSIONS.remove(sessionId); if (hazelSession != null) { MAP_ORIGINAL_SESSIONS.remove(hazelSession.originalSession.getId()); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("Destroying session locally " + hazelSession); } hazelSession.destroy(); } } private String extractAttributeKey(String key) { return key.substring(key.indexOf(HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR) + HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR.length()); } private HazelcastHttpSession createNewSession(RequestWrapper requestWrapper, String existingSessionId) { String id = existingSessionId != null ? existingSessionId : generateSessionId(); if (requestWrapper.getOriginalSession(false) != null) { LOGGER.finest("Original session exists!!!"); } HttpSession originalSession = requestWrapper.getOriginalSession(true); HazelcastHttpSession hazelcastSession = new HazelcastHttpSession(WebFilter.this, id, originalSession, deferredWrite); MAP_SESSIONS.put(hazelcastSession.getId(), hazelcastSession); String oldHazelcastSessionId = MAP_ORIGINAL_SESSIONS.put(originalSession.getId(), hazelcastSession.getId()); if (oldHazelcastSessionId != null) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("!!! Overriding an existing hazelcastSessionId " + oldHazelcastSessionId); } } if (LOGGER.isFinestEnabled()) { LOGGER.finest("Created new session with id: " + id); LOGGER.finest(MAP_SESSIONS.size() + " is sessions.size and originalSessions.size: " + MAP_ORIGINAL_SESSIONS.size()); } addSessionCookie(requestWrapper, id); if (deferredWrite) { loadHazelcastSession(hazelcastSession); } return hazelcastSession; } private void loadHazelcastSession(HazelcastHttpSession hazelcastSession) { Set<Entry<String, Object>> entrySet = getClusterMap().entrySet(new SessionAttributePredicate(hazelcastSession.getId())); Map<String, LocalCacheEntry> cache = hazelcastSession.localCache; for (Entry<String, Object> entry : entrySet) { String attributeKey = extractAttributeKey(entry.getKey()); LocalCacheEntry cacheEntry = cache.get(attributeKey); if (cacheEntry == null) { cacheEntry = new LocalCacheEntry(); cache.put(attributeKey, cacheEntry); } if (LOGGER.isFinestEnabled()) { LOGGER.finest("Storing " + attributeKey + " on session " + hazelcastSession.getId()); } cacheEntry.value = entry.getValue(); cacheEntry.dirty = false; } } private void prepareReloadingSession(HazelcastHttpSession hazelcastSession) { if (deferredWrite && hazelcastSession != null) { Map<String, LocalCacheEntry> cache = hazelcastSession.localCache; for (LocalCacheEntry cacheEntry : cache.values()) { cacheEntry.reload = true; } } } /** * Destroys a session, determining if it should be destroyed clusterwide automatically or via expiry. * * @param session The session to be destroyed * @param removeGlobalSession boolean value - true if the session should be destroyed irrespective of active time */ private void destroySession(HazelcastHttpSession session, boolean removeGlobalSession) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("Destroying local session: " + session.getId()); } MAP_SESSIONS.remove(session.getId()); MAP_ORIGINAL_SESSIONS.remove(session.originalSession.getId()); session.destroy(); if (removeGlobalSession) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("Destroying cluster session: " + session.getId() + " => Ignore-timeout: true"); } IMap<String, Object> clusterMap = getClusterMap(); clusterMap.delete(session.getId()); clusterMap.executeOnEntries(new InvalidateEntryProcessor(session.getId())); } } private IMap<String, Object> getClusterMap() { return hazelcastInstance.getMap(clusterMapName); } private HazelcastHttpSession getSessionWithId(final String sessionId) { HazelcastHttpSession session = MAP_SESSIONS.get(sessionId); if (session != null && !session.isValid()) { destroySession(session, true); session = null; } return session; } private void addSessionCookie(final RequestWrapper req, final String sessionId) { final Cookie sessionCookie = new Cookie(sessionCookieName, sessionId); String path = req.getContextPath(); if ("".equals(path)) { path = "/"; } sessionCookie.setPath(path); sessionCookie.setMaxAge(-1); if (sessionCookieDomain != null) { sessionCookie.setDomain(sessionCookieDomain); } try { sessionCookie.setHttpOnly(sessionCookieHttpOnly); } catch (NoSuchMethodError e) { LOGGER.info("must be servlet spec before 3.0, don't worry about it!"); } sessionCookie.setSecure(sessionCookieSecure); req.res.addCookie(sessionCookie); } private String getSessionCookie(final RequestWrapper req) { final Cookie[] cookies = req.getCookies(); if (cookies != null) { for (final Cookie cookie : cookies) { final String name = cookie.getName(); final String value = cookie.getValue(); if (name.equalsIgnoreCase(sessionCookieName)) { return value; } } } return null; } public final void doFilter(ServletRequest req, ServletResponse res, final FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest)) { chain.doFilter(req, res); } else { if (req instanceof RequestWrapper) { LOGGER.finest("Request is instance of RequestWrapper! Continue..."); chain.doFilter(req, res); return; } HttpServletRequest httpReq = (HttpServletRequest) req; RequestWrapper existingReq = (RequestWrapper) req.getAttribute(HAZELCAST_REQUEST); final ResponseWrapper resWrapper = new ResponseWrapper((HttpServletResponse) res); final RequestWrapper reqWrapper = new RequestWrapper(httpReq, resWrapper); if (existingReq != null) { reqWrapper.setHazelcastSession(existingReq.hazelcastSession, existingReq.requestedSessionId); } chain.doFilter(reqWrapper, resWrapper); if (existingReq != null) { return; } HazelcastHttpSession session = reqWrapper.getSession(false); if (session != null && session.isValid() && (session.sessionChanged() || !deferredWrite)) { if (LOGGER.isFinestEnabled()) { LOGGER.finest("PUTTING SESSION " + session.getId()); } session.sessionDeferredWrite(); } } } public final void destroy() { MAP_SESSIONS.clear(); MAP_ORIGINAL_SESSIONS.clear(); shutdownInstance(); } protected HazelcastInstance getInstance(Properties properties) throws ServletException { return HazelcastInstanceLoader.createInstance(filterConfig, properties); } protected void shutdownInstance() { if (shutdownOnDestroy && hazelcastInstance != null) { hazelcastInstance.getLifecycleService().shutdown(); } } private String getParam(String name) { if (properties != null && properties.containsKey(name)) { return properties.getProperty(name); } else { return filterConfig.getInitParameter(name); } } private static class ResponseWrapper extends HttpServletResponseWrapper { public ResponseWrapper(final HttpServletResponse original) { super(original); } } private static class LocalCacheEntry { volatile boolean dirty; volatile boolean reload; boolean removed; private Object value; } private class RequestWrapper extends HttpServletRequestWrapper { final ResponseWrapper res; HazelcastHttpSession hazelcastSession; String requestedSessionId; public RequestWrapper(final HttpServletRequest req, final ResponseWrapper res) { super(req); this.res = res; req.setAttribute(HAZELCAST_REQUEST, this); } public void setHazelcastSession(HazelcastHttpSession hazelcastSession, String requestedSessionId) { this.hazelcastSession = hazelcastSession; this.requestedSessionId = requestedSessionId; } HttpSession getOriginalSession(boolean create) { return super.getSession(create); } @Override public RequestDispatcher getRequestDispatcher(final String path) { final ServletRequest original = getRequest(); return new RequestDispatcher() { public void forward(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { original.getRequestDispatcher(path).forward(servletRequest, servletResponse); } public void include(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { original.getRequestDispatcher(path).include(servletRequest, servletResponse); } }; } public HazelcastHttpSession fetchHazelcastSession() { if (requestedSessionId == null) { requestedSessionId = getSessionCookie(this); } if (requestedSessionId == null) { requestedSessionId = getParameter(HAZELCAST_SESSION_COOKIE_NAME); } if (requestedSessionId != null) { hazelcastSession = getSessionWithId(requestedSessionId); if (hazelcastSession == null) { final Boolean existing = (Boolean) getClusterMap().get(requestedSessionId); if (existing != null && existing) { // we already have the session in the cluster loading it... hazelcastSession = createNewSession(RequestWrapper.this, requestedSessionId); } } } return hazelcastSession; } @Override public HttpSession getSession() { return getSession(true); } @Override public HazelcastHttpSession getSession(final boolean create) { if (hazelcastSession != null && !hazelcastSession.isValid()) { LOGGER.finest("Session is invalid!"); destroySession(hazelcastSession, true); hazelcastSession = null; } else if (hazelcastSession != null) { return hazelcastSession; } HttpSession originalSession = getOriginalSession(false); if (originalSession != null) { String hazelcastSessionId = MAP_ORIGINAL_SESSIONS.get(originalSession.getId()); if (hazelcastSessionId != null) { hazelcastSession = MAP_SESSIONS.get(hazelcastSessionId); return hazelcastSession; } MAP_ORIGINAL_SESSIONS.remove(originalSession.getId()); originalSession.invalidate(); } hazelcastSession = fetchHazelcastSession(); if (hazelcastSession == null && create) { hazelcastSession = createNewSession(RequestWrapper.this, null); } if (deferredWrite) { prepareReloadingSession(hazelcastSession); } return hazelcastSession; } } // END of RequestWrapper private class HazelcastHttpSession implements HttpSession { volatile boolean valid = true; final String id; final HttpSession originalSession; final WebFilter webFilter; private final Map<String, LocalCacheEntry> localCache; private final boolean deferredWrite; public HazelcastHttpSession(WebFilter webFilter, final String sessionId, HttpSession originalSession, boolean deferredWrite) { this.webFilter = webFilter; this.id = sessionId; this.originalSession = originalSession; this.deferredWrite = deferredWrite; this.localCache = deferredWrite ? new ConcurrentHashMap<String, LocalCacheEntry>() : null; } public Object getAttribute(final String name) { IMap<String, Object> clusterMap = getClusterMap(); if (deferredWrite) { LocalCacheEntry cacheEntry = localCache.get(name); if (cacheEntry == null || cacheEntry.reload) { Object value = clusterMap.get(buildAttributeName(name)); if (value == null) { cacheEntry = NULL_ENTRY; } else { cacheEntry = new LocalCacheEntry(); cacheEntry.value = value; cacheEntry.reload = false; } localCache.put(name, cacheEntry); } return cacheEntry != NULL_ENTRY ? cacheEntry.value : null; } return clusterMap.get(buildAttributeName(name)); } public Enumeration<String> getAttributeNames() { final Set<String> keys = selectKeys(); return new Enumeration<String>() { private final String[] elements = keys.toArray(new String[keys.size()]); private int index; @Override public boolean hasMoreElements() { return index < elements.length; } @Override public String nextElement() { return elements[index++]; } }; } public String getId() { return id; } public ServletContext getServletContext() { return servletContext; } public HttpSessionContext getSessionContext() { return originalSession.getSessionContext(); } public Object getValue(final String name) { return getAttribute(name); } public String[] getValueNames() { final Set<String> keys = selectKeys(); return keys.toArray(new String[keys.size()]); } public void invalidate() { originalSession.invalidate(); destroySession(this, true); } public boolean isNew() { return originalSession.isNew(); } public void putValue(final String name, final Object value) { setAttribute(name, value); } public void removeAttribute(final String name) { if (deferredWrite) { LocalCacheEntry entry = localCache.get(name); if (entry != null && entry != NULL_ENTRY) { entry.value = null; entry.removed = true; // dirty needs to be set as last value for memory visibility reasons! entry.dirty = true; } } else { getClusterMap().delete(buildAttributeName(name)); } } public void setAttribute(final String name, final Object value) { if (name == null) { throw new NullPointerException("name must not be null"); } if (value == null) { throw new IllegalArgumentException("value must not be null"); } if (deferredWrite) { LocalCacheEntry entry = localCache.get(name); if (entry == null || entry == NULL_ENTRY) { entry = new LocalCacheEntry(); localCache.put(name, entry); } entry.value = value; entry.dirty = true; } else { getClusterMap().put(buildAttributeName(name), value); } } public void removeValue(final String name) { removeAttribute(name); } public boolean sessionChanged() { if (!deferredWrite) { return false; } for (Entry<String, LocalCacheEntry> entry : localCache.entrySet()) { if (entry.getValue().dirty) { return true; } } return false; } public long getCreationTime() { return originalSession.getCreationTime(); } public long getLastAccessedTime() { return originalSession.getLastAccessedTime(); } public int getMaxInactiveInterval() { return originalSession.getMaxInactiveInterval(); } public void setMaxInactiveInterval(int maxInactiveSeconds) { originalSession.setMaxInactiveInterval(maxInactiveSeconds); } void destroy() { valid = false; } public boolean isValid() { return valid; } private String buildAttributeName(String name) { return id + HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR + name; } private void sessionDeferredWrite() { IMap<String, Object> clusterMap = getClusterMap(); if (deferredWrite) { Iterator<Entry<String, LocalCacheEntry>> iterator = localCache.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, LocalCacheEntry> entry = iterator.next(); if (entry.getValue().dirty) { LocalCacheEntry cacheEntry = entry.getValue(); if (cacheEntry.removed) { clusterMap.delete(buildAttributeName(entry.getKey())); iterator.remove(); } else { clusterMap.put(buildAttributeName(entry.getKey()), cacheEntry.value); cacheEntry.dirty = false; } } } } if (!clusterMap.containsKey(id)) { clusterMap.put(id, Boolean.TRUE); } } private Set<String> selectKeys() { Set<String> keys = new HashSet<String>(); if (!deferredWrite) { for (String qualifiedAttributeKey : getClusterMap().keySet(new SessionAttributePredicate(id))) { keys.add(extractAttributeKey(qualifiedAttributeKey)); } } else { for (Entry<String, LocalCacheEntry> entry : localCache.entrySet()) { if (!entry.getValue().removed) { keys.add(entry.getKey()); } } } return keys; } } // END of HazelSession } // END of WebFilter
1no label
hazelcast-wm_src_main_java_com_hazelcast_web_WebFilter.java
3,037
public class BloomFilterLucenePostingsFormatProvider extends AbstractPostingsFormatProvider { public static final class Defaults { public static final float MAX_SATURATION = 0.1f; public static final float SATURATION_LIMIT = 0.9f; } private final float desiredMaxSaturation; private final float saturationLimit; private final PostingsFormatProvider delegate; private final BloomFilteringPostingsFormat postingsFormat; @Inject public BloomFilterLucenePostingsFormatProvider(@IndexSettings Settings indexSettings, @Nullable Map<String, Factory> postingFormatFactories, @Assisted String name, @Assisted Settings postingsFormatSettings) { super(name); this.desiredMaxSaturation = postingsFormatSettings.getAsFloat("desired_max_saturation", Defaults.MAX_SATURATION); this.saturationLimit = postingsFormatSettings.getAsFloat("saturation_limit", Defaults.SATURATION_LIMIT); this.delegate = Helper.lookup(indexSettings, postingsFormatSettings.get("delegate"), postingFormatFactories); this.postingsFormat = new BloomFilteringPostingsFormat( delegate.get(), new CustomBloomFilterFactory(desiredMaxSaturation, saturationLimit) ); } public float desiredMaxSaturation() { return desiredMaxSaturation; } public float saturationLimit() { return saturationLimit; } public PostingsFormatProvider delegate() { return delegate; } @Override public PostingsFormat get() { return postingsFormat; } public static class CustomBloomFilterFactory extends BloomFilterFactory { private final float desiredMaxSaturation; private final float saturationLimit; public CustomBloomFilterFactory() { this(Defaults.MAX_SATURATION, Defaults.SATURATION_LIMIT); } CustomBloomFilterFactory(float desiredMaxSaturation, float saturationLimit) { this.desiredMaxSaturation = desiredMaxSaturation; this.saturationLimit = saturationLimit; } @Override public FuzzySet getSetForField(SegmentWriteState state, FieldInfo info) { //Assume all of the docs have a unique term (e.g. a primary key) and we hope to maintain a set with desiredMaxSaturation% of bits set return FuzzySet.createSetBasedOnQuality(state.segmentInfo.getDocCount(), desiredMaxSaturation); } @Override public boolean isSaturated(FuzzySet bloomFilter, FieldInfo fieldInfo) { // Don't bother saving bitsets if > saturationLimit % of bits are set - we don't want to // throw any more memory at this problem. return bloomFilter.getSaturation() > saturationLimit; } } }
0true
src_main_java_org_elasticsearch_index_codec_postingsformat_BloomFilterLucenePostingsFormatProvider.java
1,464
public class BroadleafLoginController extends BroadleafAbstractController { @Resource(name="blCustomerService") protected CustomerService customerService; @Resource(name="blResetPasswordValidator") protected ResetPasswordValidator resetPasswordValidator; @Resource(name="blLoginService") protected LoginService loginService; protected static String loginView = "authentication/login"; protected static String forgotPasswordView = "authentication/forgotPassword"; protected static String forgotUsernameView = "authentication/forgotUsername"; protected static String forgotPasswordSuccessView = "authentication/forgotPasswordSuccess"; protected static String resetPasswordView = "authentication/resetPassword"; protected static String resetPasswordErrorView = "authentication/resetPasswordError"; protected static String resetPasswordSuccessView = "redirect:/"; protected static String resetPasswordFormView = "authentication/resetPasswordForm"; /** * Redirects to the login view. * * @param request * @param response * @param model * @return the return view */ public String login(HttpServletRequest request, HttpServletResponse response, Model model) { if (StringUtils.isNotBlank(request.getParameter("successUrl"))) { model.addAttribute("successUrl", request.getParameter("successUrl")); } return getLoginView(); } /** * Redirects to te forgot password view. * * @param request * @param response * @param model * @return the return view */ public String forgotPassword(HttpServletRequest request, HttpServletResponse response, Model model) { return getForgotPasswordView(); } /** * Looks up the passed in username and sends an email to the address on file with a * reset password token. * * Returns error codes for invalid username. * * @param username * @param request * @param model * @return the return view */ public String processForgotPassword(String username, HttpServletRequest request, Model model) { GenericResponse errorResponse = customerService.sendForgotPasswordNotification(username, getResetPasswordUrl(request)); if (errorResponse.getHasErrors()) { String errorCode = errorResponse.getErrorCodesList().get(0); model.addAttribute("errorCode", errorCode); return getForgotPasswordView(); } else { request.getSession(true).setAttribute("forgot_password_username", username); return getForgotPasswordSuccessView(); } } /** * Returns the forgot username view. * * @param request * @param response * @param model * @return the return view */ public String forgotUsername(HttpServletRequest request, HttpServletResponse response, Model model) { return getForgotUsernameView(); } /** * Looks up an account by email address and if found, sends an email with the * associated username. * * @param email * @param request * @param response * @param model * @return the return view */ public String processForgotUsername(String email, HttpServletRequest request, HttpServletResponse response, Model model) { GenericResponse errorResponse = customerService.sendForgotUsernameNotification(email); if (errorResponse.getHasErrors()) { String errorCode = errorResponse.getErrorCodesList().get(0); request.setAttribute("errorCode", errorCode); return getForgotUsernameView(); } else { return buildRedirectToLoginWithMessage("usernameSent"); } } /** * Displays the reset password view. Expects a valid resetPasswordToken to exist * that was generated by {@link processForgotPassword} or similar. Returns an error * view if the token is invalid or expired. * * @param request * @param response * @param model * @return the return view */ public String resetPassword(HttpServletRequest request, HttpServletResponse response, Model model) { ResetPasswordForm resetPasswordForm = initResetPasswordForm(request); model.addAttribute("resetPasswordForm", resetPasswordForm); GenericResponse errorResponse = customerService.checkPasswordResetToken(resetPasswordForm.getToken()); if (errorResponse.getHasErrors()) { String errorCode = errorResponse.getErrorCodesList().get(0); request.setAttribute("errorCode", errorCode); return getResetPasswordErrorView(); } else { return getResetPasswordView(); } } /** * Processes the reset password token and allows the user to change their password. * Ensures that the password and confirm password match, that the token is valid, * and that the token matches the provided email address. * * @param resetPasswordForm * @param request * @param response * @param model * @param errors * @return the return view * @throws ServiceException */ public String processResetPassword(ResetPasswordForm resetPasswordForm, HttpServletRequest request, HttpServletResponse response, Model model, BindingResult errors) throws ServiceException { GenericResponse errorResponse = new GenericResponse(); resetPasswordValidator.validate(resetPasswordForm.getUsername(), resetPasswordForm.getPassword(), resetPasswordForm.getPasswordConfirm(), errors); if (errorResponse.getHasErrors()) { return getResetPasswordView(); } errorResponse = customerService.resetPasswordUsingToken( resetPasswordForm.getUsername(), resetPasswordForm.getToken(), resetPasswordForm.getPassword(), resetPasswordForm.getPasswordConfirm()); if (errorResponse.getHasErrors()) { String errorCode = errorResponse.getErrorCodesList().get(0); request.setAttribute("errorCode", errorCode); return getResetPasswordView(); } else { // The reset password was successful, so log this customer in. loginService.loginCustomer(resetPasswordForm.getUsername(), resetPasswordForm.getPassword()); return getResetPasswordSuccessView(); } } /** * By default, redirects to the login page with a message. * * @param message * @return the return view */ protected String buildRedirectToLoginWithMessage(String message) { StringBuffer url = new StringBuffer("redirect:").append(getLoginView()).append("?messageCode=").append(message); return url.toString(); } /** * Initializes the reset password by ensuring that the passed in token URL * parameter initializes the hidden form field. * * Also, if the reset password request is in the same session as the * forgotPassword request, the username will auto-populate * * @param request * @return the return view */ public ResetPasswordForm initResetPasswordForm(HttpServletRequest request) { ResetPasswordForm resetPasswordForm = new ResetPasswordForm(); String username = (String) request.getSession(true).getAttribute("forgot_password_username"); String token = request.getParameter("token"); resetPasswordForm.setToken(token); resetPasswordForm.setUsername(username); return resetPasswordForm; } /** * @return the view representing the login page. */ public String getLoginView() { return loginView; } /** * @return the view displayed for the forgot username form. */ public String getForgotUsernameView() { return forgotUsernameView; } /** * @return the view displayed for the forgot password form. */ public String getForgotPasswordView() { return forgotPasswordView; } /** * @return the view displayed for the reset password form. */ public String getResetPasswordView() { return resetPasswordView; } /** * @return the view returned after a successful forgotPassword email has been sent. */ public String getForgotPasswordSuccessView() { return forgotPasswordSuccessView; } /** * @return the view name to use for the reset password model.. */ public String getResetPasswordFormView() { return resetPasswordFormView; } public String getResetPasswordScheme(HttpServletRequest request) { return request.getScheme(); } public String getResetPasswordPort(HttpServletRequest request, String scheme) { if ("http".equalsIgnoreCase(scheme) && request.getServerPort() != 80) { return ":" + request.getServerPort(); } else if ("https".equalsIgnoreCase(scheme) && request.getServerPort() != 443) { return ":" + request.getServerPort(); } return ""; // no port required } public String getResetPasswordUrl(HttpServletRequest request) { String url = request.getScheme() + "://" + request.getServerName() + getResetPasswordPort(request, request.getScheme() + "/"); if (request.getContextPath() != null && ! "".equals(request.getContextPath())) { url = url + request.getContextPath() + getResetPasswordView(); } else { url = url + getResetPasswordView(); } return url; } /** * View user is directed to if they try to access the resetPasswordForm with an * invalid token. * * @return the error view */ public String getResetPasswordErrorView() { return resetPasswordErrorView; } /** * View that a user is sent to after a successful reset password operations. * Should be a redirect (e.g. start with "redirect:" since * this will cause the entire SpringSecurity pipeline to be fulfilled. */ public String getResetPasswordSuccessView() { return resetPasswordSuccessView; } }
1no label
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_account_BroadleafLoginController.java
1,243
public class NodeAdminClient extends AbstractComponent implements AdminClient { private final NodeIndicesAdminClient indicesAdminClient; private final NodeClusterAdminClient clusterAdminClient; @Inject public NodeAdminClient(Settings settings, NodeClusterAdminClient clusterAdminClient, NodeIndicesAdminClient indicesAdminClient) { super(settings); this.indicesAdminClient = indicesAdminClient; this.clusterAdminClient = clusterAdminClient; } @Override public IndicesAdminClient indices() { return indicesAdminClient; } @Override public ClusterAdminClient cluster() { return this.clusterAdminClient; } }
0true
src_main_java_org_elasticsearch_client_node_NodeAdminClient.java
1,408
public class CeylonPlugin extends AbstractUIPlugin implements CeylonResources { public static final String PLUGIN_ID = "com.redhat.ceylon.eclipse.ui"; public static final String DIST_PLUGIN_ID = "com.redhat.ceylon.dist"; public static final String EMBEDDED_REPO_PLUGIN_ID = "com.redhat.ceylon.dist.repo"; public static final String LANGUAGE_ID = "ceylon"; public static final String EDITOR_ID = PLUGIN_ID + ".editor"; private static final String[] RUNTIME_LIBRARIES = new String[]{ "com.redhat.ceylon.compiler.java-"+Versions.CEYLON_VERSION_NUMBER+".jar", "com.redhat.ceylon.typechecker-"+Versions.CEYLON_VERSION_NUMBER+".jar", "com.redhat.ceylon.module-resolver-"+Versions.CEYLON_VERSION_NUMBER+".jar", "com.redhat.ceylon.common-"+Versions.CEYLON_VERSION_NUMBER+".jar", "org.jboss.modules-1.3.3.Final.jar", }; private static final String[] COMPILETIME_LIBRARIES = new String[]{ "com.redhat.ceylon.typechecker-"+Versions.CEYLON_VERSION_NUMBER+".jar", }; private FontRegistry fontRegistry; /** * The unique instance of this plugin class */ protected static CeylonPlugin pluginInstance; private File ceylonRepository = null; private BundleContext bundleContext; /** * - If the 'ceylon.repo' property exist, returns the corresponding file * <br> * - Else return the internal repo folder * * @return */ public File getCeylonRepository() { return ceylonRepository; } public static CeylonPlugin getInstance() { if (pluginInstance==null) new CeylonPlugin(); return pluginInstance; } public CeylonPlugin() { final String version = System.getProperty("java.version"); if (!version.startsWith("1.7") && !version.startsWith("1.8")) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { ErrorDialog.openError(getWorkbench().getActiveWorkbenchWindow().getShell(), "Ceylon IDE does not support this JVM", "Ceylon IDE requires Java 1.7 or 1.8.", new Status(IStatus.ERROR, PLUGIN_ID, "Eclipse is running on a Java " + version + " VM.", null)); }}); } pluginInstance = this; } @Override public void start(BundleContext context) throws Exception { String ceylonRepositoryProperty = System.getProperty("ceylon.repo", ""); ceylonRepository = getCeylonPluginRepository(ceylonRepositoryProperty); super.start(context); this.bundleContext = context; addResourceFilterPreference(); registerProjectOpenCloseListener(); CeylonEncodingSynchronizer.getInstance().install(); Job registerCeylonModules = new Job("Load the Ceylon Metamodel for plugin dependencies") { protected IStatus run(IProgressMonitor monitor) { Activator.loadBundleAsModule(bundleContext.getBundle()); return Status.OK_STATUS; }; }; registerCeylonModules.setRule(ResourcesPlugin.getWorkspace().getRoot()); registerCeylonModules.schedule(); } @Override public void stop(BundleContext context) throws Exception { super.stop(context); unregisterProjectOpenCloseListener(); CeylonEncodingSynchronizer.getInstance().uninstall(); } private void addResourceFilterPreference() throws BackingStoreException { new Job("Add Resource Filter for Ceylon projects") { @Override protected IStatus run(IProgressMonitor monitor) { IEclipsePreferences instancePreferences = InstanceScope.INSTANCE .getNode(JavaCore.PLUGIN_ID); /*IEclipsePreferences defaultPreferences = DefaultScope.INSTANCE .getNode(JavaCore.PLUGIN_ID);*/ String filter = instancePreferences.get(CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, ""); if (filter.isEmpty()) { filter = "*.launch, *.ceylon"; } else if (!filter.contains("*.ceylon")) { filter += ", *.ceylon"; } instancePreferences.put(CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, filter); try { instancePreferences.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } return Status.OK_STATUS; } }.schedule(); } /** * - If the property is not empty, return the corresponding file * <br> * - Else return the internal repo folder * * @param ceylonRepositoryProperty * @return * */ public static File getCeylonPluginRepository(String ceylonRepositoryProperty) { File ceylonRepository=null; if (!"".equals(ceylonRepositoryProperty)) { File ceylonRepositoryPath = new File(ceylonRepositoryProperty); if (ceylonRepositoryPath.exists()) { ceylonRepository = ceylonRepositoryPath; } } if (ceylonRepository == null) { try { Bundle bundle = Platform.getBundle(EMBEDDED_REPO_PLUGIN_ID); IPath path = new Path("repo"); if (bundle == null) { bundle = Platform.getBundle(DIST_PLUGIN_ID); path = new Path("embeddedRepository").append(path); } URL eclipseUrl = FileLocator.find(bundle, path, null); URL fileURL = FileLocator.resolve(eclipseUrl); String urlPath = fileURL.getPath(); URI fileURI = new URI("file", null, urlPath, null); ceylonRepository = new File(fileURI); } catch (Exception e) { e.printStackTrace(); } } return ceylonRepository; } /** * Returns the list of jars in the bundled system repo that are required by the ceylon.language module at runtime */ public static List<String> getRuntimeRequiredJars(){ return getRequiredJars(RUNTIME_LIBRARIES); } /** * Returns the list of jars in the bundled system repo that are required by the ceylon.language module at compiletime */ public static List<String> getCompiletimeRequiredJars(){ return getRequiredJars(COMPILETIME_LIBRARIES); } /** * Returns the list of jars in the bundled lib folder required to launch a module */ public static List<String> getModuleLauncherJars(){ try { Bundle bundle = Platform.getBundle(DIST_PLUGIN_ID); Path path = new Path("lib"); URL eclipseUrl = FileLocator.find(bundle, path, null); URL fileURL = FileLocator.resolve(eclipseUrl); File libDir = new File(fileURL.getPath()); List<String> jars = new ArrayList<String>(); jars.add(new File(libDir, "ceylon-bootstrap.jar").getAbsolutePath()); return jars; } catch (IOException x) { x.printStackTrace(); return Collections.emptyList(); } } private static List<String> getRequiredJars(String[] libraries){ File repoDir = getCeylonPluginRepository(System.getProperty("ceylon.repo", "")); try{ List<String> jars = new ArrayList<String>(libraries.length); for(String jar : libraries){ File libDir = new File(repoDir, getRepoFolder(jar)); if( !libDir.exists() ) { System.out.println("WARNING directory doesn't exist: " + libDir); } jars.add(new File(libDir, jar).getAbsolutePath()); } return jars; } catch (Exception x) { x.printStackTrace(); return Collections.emptyList(); } } private static String getRepoFolder(String jarName) { int lastDot = jarName.lastIndexOf('.'); int lastDash = jarName.lastIndexOf('-'); return jarName.substring(0, lastDash).replace('.', '/') + "/" + jarName.substring(lastDash + 1, lastDot); } public String getID() { return PLUGIN_ID; } public String getLanguageID() { return LANGUAGE_ID; } private static IPath iconsPath = new Path("icons/"); public ImageDescriptor image(String file) { URL url = FileLocator.find(getBundle(), iconsPath.append(file), null); if (url!=null) { return ImageDescriptor.createFromURL(url); } else { return null; } } @Override protected void initializeImageRegistry(ImageRegistry reg) { reg.put(JAVA_FILE, image("jcu_obj.gif")); reg.put(GENERIC_FILE, image("file_obj.gif")); reg.put(CEYLON_PROJECT, image("prj_obj.gif")); reg.put(CEYLON_FILE, image("unit.gif")); reg.put(CEYLON_MODULE_DESC, image("m_desc.gif")); reg.put(CEYLON_PACKAGE_DESC, image("p_desc.gif")); reg.put(CEYLON_FOLDER, image("fldr_obj.gif")); reg.put(CEYLON_SOURCE_FOLDER, image("packagefolder_obj.gif")); reg.put(CEYLON_MODULE, image("jar_l_obj.gif")); reg.put(CEYLON_BINARY_ARCHIVE, image("jar_obj.gif")); reg.put(CEYLON_SOURCE_ARCHIVE, image("jar_src_obj.gif")); reg.put(CEYLON_PACKAGE, image("package_obj.gif")); reg.put(CEYLON_IMPORT_LIST, image("impc_obj.gif")); reg.put(CEYLON_IMPORT, image("imp_obj.gif")); reg.put(CEYLON_ALIAS, image("types.gif")); reg.put(CEYLON_CLASS, image("class_obj.gif")); reg.put(CEYLON_INTERFACE, image("int_obj.gif")); reg.put(CEYLON_LOCAL_CLASS, image("innerclass_private_obj.gif")); reg.put(CEYLON_LOCAL_INTERFACE, image("innerinterface_private_obj.gif")); reg.put(CEYLON_METHOD, image("public_co.gif")); reg.put(CEYLON_ATTRIBUTE, image("field_public_obj.gif")); reg.put(CEYLON_LOCAL_METHOD, image("private_co.gif")); reg.put(CEYLON_LOCAL_ATTRIBUTE, image("field_private_obj.gif")); reg.put(CEYLON_PARAMETER_METHOD, image("methpro_obj.gif")); reg.put(CEYLON_PARAMETER, image("field_protected_obj.gif")); reg.put(CEYLON_TYPE_PARAMETER, image("typevariable_obj.gif")); reg.put(CEYLON_ARGUMENT, image("arg_co.gif")); reg.put(CEYLON_DEFAULT_REFINEMENT, image("over_co.gif")); reg.put(CEYLON_FORMAL_REFINEMENT, image("implm_co.gif")); reg.put(CEYLON_OPEN_DECLARATION, image("opentype.gif")); reg.put(CEYLON_SEARCH_RESULTS, image("search_ref_obj.gif")); reg.put(CEYLON_CORRECTION, image("correction_change.gif")); reg.put(CEYLON_DELETE_IMPORT, image("correction_delete_import.gif")); reg.put(CEYLON_CHANGE, image("change.png")); reg.put(CEYLON_COMPOSITE_CHANGE, image("composite_change.png")); reg.put(CEYLON_RENAME, image("correction_rename.png")); reg.put(CEYLON_DELETE, image("delete_edit.gif")); reg.put(CEYLON_MOVE, image("file_change.png")); reg.put(CEYLON_ADD, image("add_obj.gif")); reg.put(CEYLON_REORDER, image("order_obj.gif")); reg.put(CEYLON_REVEAL, image("reveal.gif")); reg.put(CEYLON_ADD_CORRECTION, image("add_correction.gif")); reg.put(CEYLON_REMOVE_CORRECTION, image("remove_correction.gif")); reg.put(CEYLON_NEW_PROJECT, image("newprj_wiz.png")); reg.put(CEYLON_NEW_FILE, image("newfile_wiz.png")); reg.put(CEYLON_NEW_MODULE, image("addlibrary_wiz.png")); reg.put(CEYLON_NEW_PACKAGE, image("newpack_wiz.png")); reg.put(CEYLON_NEW_FOLDER, image("newfolder_wiz.gif")); reg.put(CEYLON_EXPORT_CAR, image("jar_pack_wiz.png")); reg.put(CEYLON_REFS, image("search_ref_obj.png")); reg.put(CEYLON_DECS, image("search_decl_obj.png")); reg.put(CEYLON_INHERITED, image("inher_co.gif")); reg.put(CEYLON_HIER, image("hierarchy_co.gif")); reg.put(CEYLON_SUP, image("super_co.gif")); reg.put(CEYLON_SUB, image("sub_co.gif")); reg.put(CEYLON_OUTLINE, image("outline_co.gif")); reg.put(CEYLON_HIERARCHY, image("class_hi.gif")); reg.put(CEYLON_SOURCE, image("source.gif")); reg.put(ELE32, image("ceylon_icon_32px.png")); reg.put(CEYLON_ERR, image("error_co.gif")); reg.put(CEYLON_WARN, image("warning_co.gif")); reg.put(GOTO, image("goto_obj.gif")); reg.put(HIERARCHY, image("class_hi_view.gif")); reg.put(SHIFT_LEFT, image("shift_l_edit.gif")); reg.put(SHIFT_RIGHT, image("shift_r_edit.gif")); reg.put(QUICK_ASSIST, image("quickassist_obj.gif")); reg.put(BUILDER, image("builder.gif")); reg.put(CONFIG_ANN, image("configure_annotations.gif")); reg.put(CONFIG_ANN_DIS, image("configure_annotations_disabled.gif")); reg.put(MODULE_VERSION, image("module_version.gif")); reg.put(HIDE_PRIVATE, image("hideprivate.gif")); reg.put(EXPAND_ALL, image("expandall.gif")); reg.put(PAGING, image("paging.gif")); reg.put(SHOW_DOC, image("show_doc.gif")); reg.put(REPOSITORIES, image("repositories.gif")); reg.put(RUNTIME_OBJ, image("runtime_obj.gif")); reg.put(CEYLON_LOCAL_NAME, image("localvariable_obj.gif")); reg.put(MULTIPLE_TYPES, image("types.gif")); reg.put(CEYLON_ERROR, image("error_obj.gif")); reg.put(CEYLON_WARNING, image("warning_obj.gif")); reg.put(CEYLON_FUN, image("public_fun.gif")); reg.put(CEYLON_LOCAL_FUN, image("private_fun.gif")); reg.put(WARNING_IMAGE, image(WARNING_IMAGE)); reg.put(ERROR_IMAGE, image(ERROR_IMAGE)); reg.put(REFINES_IMAGE, image(REFINES_IMAGE)); reg.put(IMPLEMENTS_IMAGE, image(IMPLEMENTS_IMAGE)); reg.put(FINAL_IMAGE, image(FINAL_IMAGE)); reg.put(ABSTRACT_IMAGE, image(ABSTRACT_IMAGE)); reg.put(VARIABLE_IMAGE, image(VARIABLE_IMAGE)); reg.put(ANNOTATION_IMAGE, image(ANNOTATION_IMAGE)); reg.put(ENUM_IMAGE, image(ENUM_IMAGE)); reg.put(ALIAS_IMAGE, image(ALIAS_IMAGE)); reg.put(DEPRECATED_IMAGE, image(DEPRECATED_IMAGE)); reg.put(PROJECT_MODE, image("prj_mode.gif")); reg.put(PACKAGE_MODE, image("package_mode.gif")); reg.put(MODULE_MODE, image("module_mode.gif")); reg.put(FOLDER_MODE, image("folder_mode.gif")); reg.put(UNIT_MODE, image("unit_mode.gif")); reg.put(TYPE_MODE, image("type_mode.gif")); reg.put(FLAT_MODE, image("flatLayout.gif")); reg.put(TREE_MODE, image("hierarchicalLayout.gif")); reg.put(TERMINATE_STATEMENT, image("correction_cast.gif")); reg.put(FORMAT_BLOCK, image("format_block.gif")); reg.put(REMOVE_COMMENT, image("remove_comment_edit.gif")); reg.put(ADD_COMMENT, image("comment_edit.gif")); reg.put(TOGGLE_COMMENT, image("url.gif")); reg.put(CORRECT_INDENT, image("correctindent.gif")); reg.put(LAST_EDIT, image("last_edit_pos.gif")); reg.put(NEXT_ANN, image("next_nav.gif")); reg.put(PREV_ANN, image("prev_nav.gif")); reg.put(SORT_ALPHA, image("alphab_sort_co.gif")); reg.put(CEYLON_LITERAL, image("correction_change.gif")); } private void registerProjectOpenCloseListener() { getWorkspace().addResourceChangeListener(projectOpenCloseListener, IResourceChangeEvent.POST_CHANGE); } private void unregisterProjectOpenCloseListener() { getWorkspace().removeResourceChangeListener(projectOpenCloseListener); } IResourceChangeListener projectOpenCloseListener = new ProjectChangeListener(); public BundleContext getBundleContext() { return this.bundleContext; } /** * Utility class that tries to adapt a non null object to the specified type * * @param object * the object to adapt * @param type * the class to adapt to * @return the adapted object */ public static Object adapt(Object object, Class<?> type) { if (type.isInstance(object)) { return object; } else if (object instanceof IAdaptable) { return ((IAdaptable) object).getAdapter(type); } return Platform.getAdapterManager().getAdapter(object, type); } public FontRegistry getFontRegistry() { // Hopefully this gets called late enough, i.e., after a Display has been // created on the current thread (see FontRegistry constructor). if (fontRegistry == null) { fontRegistry= new FontRegistry(); } return fontRegistry; } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_ui_CeylonPlugin.java
276
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientIdGeneratorTest { static final String name = "test"; static HazelcastInstance hz; static IdGenerator i; @BeforeClass public static void init() { Hazelcast.newHazelcastInstance(); hz = HazelcastClient.newHazelcastClient(null); i = hz.getIdGenerator(name); } @AfterClass public static void destroy() { hz.shutdown(); Hazelcast.shutdownAll(); } @Test public void testGenerator() throws Exception { assertTrue(i.init(3569)); assertFalse(i.init(4569)); assertEquals(3570, i.newId()); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_idgenerator_ClientIdGeneratorTest.java
434
public enum PersistencePerspectiveItemType { FOREIGNKEY, ADORNEDTARGETLIST, MAPSTRUCTURE }
0true
common_src_main_java_org_broadleafcommerce_common_presentation_client_PersistencePerspectiveItemType.java
1,896
interface SingleMemberInjector { void inject(Errors errors, InternalContext context, Object o); InjectionPoint getInjectionPoint(); }
0true
src_main_java_org_elasticsearch_common_inject_SingleMemberInjector.java
674
CollectionUtils.filter(parentFacets, new Predicate() { @Override public boolean evaluate(Object arg) { CategorySearchFacet csf = (CategorySearchFacet) arg; return !getExcludedSearchFacets().contains(csf.getSearchFacet()) && !returnFacets.contains(csf.getSearchFacet()); } });
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_CategoryImpl.java
124
client.getLifecycleService().addLifecycleListener(new LifecycleListener() { @Override public void stateChanged(LifecycleEvent event) { connectedLatch.countDown(); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientReconnectTest.java
2,910
@AnalysisSettingsRequired public class PatternCaptureGroupTokenFilterFactory extends AbstractTokenFilterFactory { private final Pattern[] patterns; private final boolean preserveOriginal; private static final String PATTERNS_KEY = "patterns"; private static final String PRESERVE_ORIG_KEY = "preserve_original"; @Inject public PatternCaptureGroupTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); String[] regexes = settings.getAsArray(PATTERNS_KEY, null, false); if (regexes == null) { throw new ElasticsearchIllegalArgumentException("required setting '" + PATTERNS_KEY + "' is missing for token filter [" + name + "]"); } patterns = new Pattern[regexes.length]; for (int i = 0; i < regexes.length; i++) { patterns[i] = Pattern.compile(regexes[i]); } preserveOriginal = settings.getAsBoolean(PRESERVE_ORIG_KEY, true); } @Override public TokenFilter create(TokenStream tokenStream) { return new PatternCaptureGroupTokenFilter(tokenStream, preserveOriginal, patterns); } }
0true
src_main_java_org_elasticsearch_index_analysis_PatternCaptureGroupTokenFilterFactory.java