Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
3,458 | public class GetResult implements Streamable, Iterable<GetField>, ToXContent {
private String index;
private String type;
private String id;
private long version;
private boolean exists;
private Map<String, GetField> fields;
private Map<String, Object> sourceAsMap;
private BytesReference source;
private byte[] sourceAsBytes;
GetResult() {
}
public GetResult(String index, String type, String id, long version, boolean exists, BytesReference source, Map<String, GetField> fields) {
this.index = index;
this.type = type;
this.id = id;
this.version = version;
this.exists = exists;
this.source = source;
this.fields = fields;
if (this.fields == null) {
this.fields = ImmutableMap.of();
}
}
/**
* Does the document exists.
*/
public boolean isExists() {
return exists;
}
/**
* The index the document was fetched from.
*/
public String getIndex() {
return index;
}
/**
* The type of the document.
*/
public String getType() {
return type;
}
/**
* The id of the document.
*/
public String getId() {
return id;
}
/**
* The version of the doc.
*/
public long getVersion() {
return version;
}
/**
* The source of the document if exists.
*/
public byte[] source() {
if (source == null) {
return null;
}
if (sourceAsBytes != null) {
return sourceAsBytes;
}
this.sourceAsBytes = sourceRef().toBytes();
return this.sourceAsBytes;
}
/**
* Returns bytes reference, also un compress the source if needed.
*/
public BytesReference sourceRef() {
try {
this.source = CompressorFactory.uncompressIfNeeded(this.source);
return this.source;
} catch (IOException e) {
throw new ElasticsearchParseException("failed to decompress source", e);
}
}
/**
* Internal source representation, might be compressed....
*/
public BytesReference internalSourceRef() {
return source;
}
/**
* Is the source empty (not available) or not.
*/
public boolean isSourceEmpty() {
return source == null;
}
/**
* The source of the document (as a string).
*/
public String sourceAsString() {
if (source == null) {
return null;
}
BytesReference source = sourceRef();
try {
return XContentHelper.convertToJson(source, false);
} catch (IOException e) {
throw new ElasticsearchParseException("failed to convert source to a json string");
}
}
/**
* The source of the document (As a map).
*/
@SuppressWarnings({"unchecked"})
public Map<String, Object> sourceAsMap() throws ElasticsearchParseException {
if (source == null) {
return null;
}
if (sourceAsMap != null) {
return sourceAsMap;
}
sourceAsMap = SourceLookup.sourceAsMap(source);
return sourceAsMap;
}
public Map<String, Object> getSource() {
return sourceAsMap();
}
public Map<String, GetField> getFields() {
return fields;
}
public GetField field(String name) {
return fields.get(name);
}
@Override
public Iterator<GetField> iterator() {
if (fields == null) {
return emptyIterator();
}
return fields.values().iterator();
}
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");
}
public XContentBuilder toXContentEmbedded(XContentBuilder builder, Params params) throws IOException {
builder.field(Fields.FOUND, exists);
if (source != null) {
RestXContentBuilder.restDocumentSource(source, builder, params);
}
if (fields != null && !fields.isEmpty()) {
builder.startObject(Fields.FIELDS);
for (GetField field : fields.values()) {
if (field.getValues().isEmpty()) {
continue;
}
String fieldName = field.getName();
if (field.isMetadataField()) {
builder.field(fieldName, field.getValue());
} else {
builder.startArray(field.getName());
for (Object value : field.getValues()) {
builder.value(value);
}
builder.endArray();
}
}
builder.endObject();
}
return builder;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (!isExists()) {
builder.startObject();
builder.field(Fields._INDEX, index);
builder.field(Fields._TYPE, type);
builder.field(Fields._ID, id);
builder.field(Fields.FOUND, false);
builder.endObject();
} else {
builder.startObject();
builder.field(Fields._INDEX, index);
builder.field(Fields._TYPE, type);
builder.field(Fields._ID, id);
if (version != -1) {
builder.field(Fields._VERSION, version);
}
toXContentEmbedded(builder, params);
builder.endObject();
}
return builder;
}
public static GetResult readGetResult(StreamInput in) throws IOException {
GetResult result = new GetResult();
result.readFrom(in);
return result;
}
@Override
public void readFrom(StreamInput in) throws IOException {
index = in.readSharedString();
type = in.readOptionalSharedString();
id = in.readString();
version = in.readLong();
exists = in.readBoolean();
if (exists) {
source = in.readBytesReference();
if (source.length() == 0) {
source = null;
}
int size = in.readVInt();
if (size == 0) {
fields = ImmutableMap.of();
} else {
fields = newHashMapWithExpectedSize(size);
for (int i = 0; i < size; i++) {
GetField field = readGetField(in);
fields.put(field.getName(), field);
}
}
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeSharedString(index);
out.writeOptionalSharedString(type);
out.writeString(id);
out.writeLong(version);
out.writeBoolean(exists);
if (exists) {
out.writeBytesReference(source);
if (fields == null) {
out.writeVInt(0);
} else {
out.writeVInt(fields.size());
for (GetField field : fields.values()) {
field.writeTo(out);
}
}
}
}
} | 0true
| src_main_java_org_elasticsearch_index_get_GetResult.java |
122 | @RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientReconnectTest extends HazelcastTestSupport {
@After
@Before
public void cleanup() throws Exception {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testClientReconnectOnClusterDown() throws Exception {
final HazelcastInstance h1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance client = HazelcastClient.newHazelcastClient();
final CountDownLatch connectedLatch = new CountDownLatch(2);
client.getLifecycleService().addLifecycleListener(new LifecycleListener() {
@Override
public void stateChanged(LifecycleEvent event) {
connectedLatch.countDown();
}
});
IMap<String, String> m = client.getMap("default");
h1.shutdown();
Hazelcast.newHazelcastInstance();
assertOpenEventually(connectedLatch, 10);
assertNull(m.put("test", "test"));
assertEquals("test", m.get("test"));
}
@Test
public void testClientReconnectOnClusterDownWithEntryListeners() throws Exception {
HazelcastInstance h1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance client = HazelcastClient.newHazelcastClient();
final CountDownLatch connectedLatch = new CountDownLatch(2);
client.getLifecycleService().addLifecycleListener(new LifecycleListener() {
@Override
public void stateChanged(LifecycleEvent event) {
connectedLatch.countDown();
}
});
final IMap<String, String> m = client.getMap("default");
final CountDownLatch latch = new CountDownLatch(1);
final EntryAdapter<String, String> listener = new EntryAdapter<String, String>() {
public void onEntryEvent(EntryEvent<String, String> event) {
latch.countDown();
}
};
m.addEntryListener(listener, true);
h1.shutdown();
Hazelcast.newHazelcastInstance();
assertOpenEventually(connectedLatch, 10);
m.put("key", "value");
assertOpenEventually(latch, 10);
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_ClientReconnectTest.java |
3,765 | public class LogDocMergePolicyProvider extends AbstractMergePolicyProvider<LogDocMergePolicy> {
private final IndexSettingsService indexSettingsService;
private volatile int minMergeDocs;
private volatile int maxMergeDocs;
private volatile int mergeFactor;
private final boolean calibrateSizeByDeletes;
private boolean asyncMerge;
private final Set<CustomLogDocMergePolicy> policies = new CopyOnWriteArraySet<CustomLogDocMergePolicy>();
private final ApplySettings applySettings = new ApplySettings();
@Inject
public LogDocMergePolicyProvider(Store store, IndexSettingsService indexSettingsService) {
super(store);
Preconditions.checkNotNull(store, "Store must be provided to merge policy");
this.indexSettingsService = indexSettingsService;
this.minMergeDocs = componentSettings.getAsInt("min_merge_docs", LogDocMergePolicy.DEFAULT_MIN_MERGE_DOCS);
this.maxMergeDocs = componentSettings.getAsInt("max_merge_docs", LogDocMergePolicy.DEFAULT_MAX_MERGE_DOCS);
this.mergeFactor = componentSettings.getAsInt("merge_factor", LogDocMergePolicy.DEFAULT_MERGE_FACTOR);
this.calibrateSizeByDeletes = componentSettings.getAsBoolean("calibrate_size_by_deletes", true);
this.asyncMerge = indexSettings.getAsBoolean("index.merge.async", true);
logger.debug("using [log_doc] merge policy with merge_factor[{}], min_merge_docs[{}], max_merge_docs[{}], calibrate_size_by_deletes[{}], async_merge[{}]",
mergeFactor, minMergeDocs, maxMergeDocs, calibrateSizeByDeletes, asyncMerge);
indexSettingsService.addListener(applySettings);
}
@Override
public void close() throws ElasticsearchException {
indexSettingsService.removeListener(applySettings);
}
@Override
public LogDocMergePolicy newMergePolicy() {
CustomLogDocMergePolicy mergePolicy;
if (asyncMerge) {
mergePolicy = new EnableMergeLogDocMergePolicy(this);
} else {
mergePolicy = new CustomLogDocMergePolicy(this);
}
mergePolicy.setMinMergeDocs(minMergeDocs);
mergePolicy.setMaxMergeDocs(maxMergeDocs);
mergePolicy.setMergeFactor(mergeFactor);
mergePolicy.setCalibrateSizeByDeletes(calibrateSizeByDeletes);
mergePolicy.setNoCFSRatio(noCFSRatio);
policies.add(mergePolicy);
return mergePolicy;
}
public static final String INDEX_MERGE_POLICY_MIN_MERGE_DOCS = "index.merge.policy.min_merge_docs";
public static final String INDEX_MERGE_POLICY_MAX_MERGE_DOCS = "index.merge.policy.max_merge_docs";
public static final String INDEX_MERGE_POLICY_MERGE_FACTOR = "index.merge.policy.merge_factor";
class ApplySettings implements IndexSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
int minMergeDocs = settings.getAsInt(INDEX_MERGE_POLICY_MIN_MERGE_DOCS, LogDocMergePolicyProvider.this.minMergeDocs);
if (minMergeDocs != LogDocMergePolicyProvider.this.minMergeDocs) {
logger.info("updating min_merge_docs from [{}] to [{}]", LogDocMergePolicyProvider.this.minMergeDocs, minMergeDocs);
LogDocMergePolicyProvider.this.minMergeDocs = minMergeDocs;
for (CustomLogDocMergePolicy policy : policies) {
policy.setMinMergeDocs(minMergeDocs);
}
}
int maxMergeDocs = settings.getAsInt(INDEX_MERGE_POLICY_MAX_MERGE_DOCS, LogDocMergePolicyProvider.this.maxMergeDocs);
if (maxMergeDocs != LogDocMergePolicyProvider.this.maxMergeDocs) {
logger.info("updating max_merge_docs from [{}] to [{}]", LogDocMergePolicyProvider.this.maxMergeDocs, maxMergeDocs);
LogDocMergePolicyProvider.this.maxMergeDocs = maxMergeDocs;
for (CustomLogDocMergePolicy policy : policies) {
policy.setMaxMergeDocs(maxMergeDocs);
}
}
int mergeFactor = settings.getAsInt(INDEX_MERGE_POLICY_MERGE_FACTOR, LogDocMergePolicyProvider.this.mergeFactor);
if (mergeFactor != LogDocMergePolicyProvider.this.mergeFactor) {
logger.info("updating merge_factor from [{}] to [{}]", LogDocMergePolicyProvider.this.mergeFactor, mergeFactor);
LogDocMergePolicyProvider.this.mergeFactor = mergeFactor;
for (CustomLogDocMergePolicy policy : policies) {
policy.setMergeFactor(mergeFactor);
}
}
final double noCFSRatio = parseNoCFSRatio(settings.get(INDEX_COMPOUND_FORMAT, Double.toString(LogDocMergePolicyProvider.this.noCFSRatio)));
final boolean compoundFormat = noCFSRatio != 0.0;
if (noCFSRatio != LogDocMergePolicyProvider.this.noCFSRatio) {
logger.info("updating index.compound_format from [{}] to [{}]", formatNoCFSRatio(LogDocMergePolicyProvider.this.noCFSRatio), formatNoCFSRatio(noCFSRatio));
LogDocMergePolicyProvider.this.noCFSRatio = noCFSRatio;
for (CustomLogDocMergePolicy policy : policies) {
policy.setNoCFSRatio(noCFSRatio);
}
}
}
}
public static class CustomLogDocMergePolicy extends LogDocMergePolicy {
private final LogDocMergePolicyProvider provider;
public CustomLogDocMergePolicy(LogDocMergePolicyProvider provider) {
super();
this.provider = provider;
}
@Override
public void close() {
super.close();
provider.policies.remove(this);
}
}
public static class EnableMergeLogDocMergePolicy extends CustomLogDocMergePolicy {
public EnableMergeLogDocMergePolicy(LogDocMergePolicyProvider provider) {
super(provider);
}
@Override
public MergeSpecification findMerges(MergeTrigger trigger, SegmentInfos infos) throws IOException {
// we don't enable merges while indexing documents, we do them in the background
if (trigger == MergeTrigger.SEGMENT_FLUSH) {
return null;
}
return super.findMerges(trigger, infos);
}
@Override
public MergePolicy clone() {
// Lucene IW makes a clone internally but since we hold on to this instance
// the clone will just be the identity.
return this;
}
}
} | 1no label
| src_main_java_org_elasticsearch_index_merge_policy_LogDocMergePolicyProvider.java |
315 | public class DynamicResourceIterator extends ArrayList<ResourceInputStream> {
private static final Log LOG = LogFactory.getLog(DynamicResourceIterator.class);
private int position = 0;
private int embeddedInsertPosition = 0;
public ResourceInputStream nextResource() {
ResourceInputStream ris = get(position);
position++;
embeddedInsertPosition = position;
return ris;
}
public int getPosition() {
return position;
}
public void addEmbeddedResource(ResourceInputStream ris) {
if (embeddedInsertPosition == size()) {
add(ris);
} else {
add(embeddedInsertPosition, ris);
}
embeddedInsertPosition++;
}
public boolean hasNext() {
return position < size();
}
@Override
public boolean add(ResourceInputStream resourceInputStream) {
byte[] sourceArray;
try {
sourceArray = buildArrayFromStream(resourceInputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
ResourceInputStream ris = new ResourceInputStream(new ByteArrayInputStream(sourceArray), null, resourceInputStream.getNames());
return super.add(ris);
}
@Override
public boolean addAll(Collection<? extends ResourceInputStream> c) {
for (ResourceInputStream ris : c) {
if (!add(ris)) {
return false;
}
}
return true;
}
@Override
public void add(int index, ResourceInputStream resourceInputStream) {
byte[] sourceArray;
try {
sourceArray = buildArrayFromStream(resourceInputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
ResourceInputStream ris = new ResourceInputStream(new ByteArrayInputStream(sourceArray), null, resourceInputStream.getNames());
super.add(index, ris);
}
protected byte[] buildArrayFromStream(InputStream source) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
boolean eof = false;
try{
while (!eof) {
int temp = source.read();
if (temp == -1) {
eof = true;
} else {
baos.write(temp);
}
}
} finally {
try{ source.close(); } catch (Throwable e) {
LOG.error("Unable to merge source and patch locations", e);
}
}
return baos.toByteArray();
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_DynamicResourceIterator.java |
1,522 | @RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class OutOfMemoryErrorDispatcherTest {
@Before
public void before() {
OutOfMemoryErrorDispatcher.clear();
}
@Test
public void onOutOfMemoryOutOfMemory(){
OutOfMemoryHandler handler = mock(OutOfMemoryHandler.class);
OutOfMemoryError oome = new OutOfMemoryError();
HazelcastInstance hz1 = mock(HazelcastInstance.class);
OutOfMemoryErrorDispatcher.register(hz1);
OutOfMemoryErrorDispatcher.setHandler(handler);
HazelcastInstance[] registeredInstances = OutOfMemoryErrorDispatcher.current();
OutOfMemoryErrorDispatcher.onOutOfMemory(oome);
//make sure the handler is called
verify(handler).onOutOfMemory(oome, registeredInstances);
//make sure that the registered instances are removed.
assertArrayEquals(new HazelcastInstance[]{}, OutOfMemoryErrorDispatcher.current());
}
@Test
public void register() {
HazelcastInstance hz1 = mock(HazelcastInstance.class);
HazelcastInstance hz2 = mock(HazelcastInstance.class);
OutOfMemoryErrorDispatcher.register(hz1);
assertArrayEquals(new HazelcastInstance[]{hz1}, OutOfMemoryErrorDispatcher.current());
OutOfMemoryErrorDispatcher.register(hz2);
assertArrayEquals(new HazelcastInstance[]{hz1, hz2}, OutOfMemoryErrorDispatcher.current());
}
@Test(expected = IllegalArgumentException.class)
public void register_whenNull() {
OutOfMemoryErrorDispatcher.register(null);
}
@Test
public void deregister_Existing() {
HazelcastInstance hz1 = mock(HazelcastInstance.class);
HazelcastInstance hz2 = mock(HazelcastInstance.class);
HazelcastInstance hz3 = mock(HazelcastInstance.class);
OutOfMemoryErrorDispatcher.register(hz1);
OutOfMemoryErrorDispatcher.register(hz2);
OutOfMemoryErrorDispatcher.register(hz3);
OutOfMemoryErrorDispatcher.deregister(hz2);
assertArrayEquals(new HazelcastInstance[]{hz1, hz3}, OutOfMemoryErrorDispatcher.current());
OutOfMemoryErrorDispatcher.deregister(hz1);
assertArrayEquals(new HazelcastInstance[]{hz3}, OutOfMemoryErrorDispatcher.current());
OutOfMemoryErrorDispatcher.deregister(hz3);
assertArrayEquals(new HazelcastInstance[]{}, OutOfMemoryErrorDispatcher.current());
}
@Test
public void deregister_nonExisting() {
HazelcastInstance instance = mock(HazelcastInstance.class);
OutOfMemoryErrorDispatcher.deregister(instance);
}
@Test(expected = IllegalArgumentException.class)
public void deregister_null() {
OutOfMemoryErrorDispatcher.deregister(null);
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_instance_OutOfMemoryErrorDispatcherTest.java |
710 | constructors[COLLECTION_REMOVE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionRemoveRequest();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java |
1,050 | public class TermVectorAction extends Action<TermVectorRequest, TermVectorResponse, TermVectorRequestBuilder> {
public static final TermVectorAction INSTANCE = new TermVectorAction();
public static final String NAME = "tv";
private TermVectorAction() {
super(NAME);
}
@Override
public TermVectorResponse newResponse() {
return new TermVectorResponse();
}
@Override
public TermVectorRequestBuilder newRequestBuilder(Client client) {
return new TermVectorRequestBuilder(client);
}
} | 0true
| src_main_java_org_elasticsearch_action_termvector_TermVectorAction.java |
355 | @Deprecated
public class AnnotationsCopyClassTransformer implements BroadleafClassTransformer {
protected SupportLogger logger;
protected String moduleName;
protected Map<String, String> xformTemplates = new HashMap<String, String>();
protected static List<String> transformedMethods = new ArrayList<String>();
public AnnotationsCopyClassTransformer(String moduleName) {
this.moduleName = moduleName;
logger = SupportLogManager.getLogger(moduleName, this.getClass());
}
@Override
public void compileJPAProperties(Properties props, Object key) throws Exception {
// When simply copying properties over for Java class files, JPA properties do not need modification
}
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String convertedClassName = className.replace('/', '.');
if (xformTemplates.containsKey(convertedClassName)) {
String xformKey = convertedClassName;
String[] xformVals = xformTemplates.get(xformKey).split(",");
logger.lifecycle(LifeCycleEvent.START, String.format("Transform - Copying annotations into [%s] from [%s]", xformKey,
StringUtils.join(xformVals, ",")));
try {
// Load the destination class and defrost it so it is eligible for modifications
ClassPool classPool = ClassPool.getDefault();
CtClass clazz = classPool.makeClass(new ByteArrayInputStream(classfileBuffer), false);
clazz.defrost();
for (String xformVal : xformVals) {
// Load the source class
String trimmed = xformVal.trim();
classPool.appendClassPath(new LoaderClassPath(Class.forName(trimmed).getClassLoader()));
CtClass template = classPool.get(trimmed);
// Copy over all declared annotations from fields from the template class
// Note that we do not copy over fields with the @NonCopiedField annotation
CtField[] fieldsToCopy = template.getDeclaredFields();
for (CtField field : fieldsToCopy) {
if (field.hasAnnotation(NonCopied.class)) {
logger.debug(String.format("Not copying annotation from field [%s]", field.getName()));
} else {
logger.debug(String.format("Copying annotation from field [%s]", field.getName()));
ConstPool constPool = clazz.getClassFile().getConstPool();
CtField fieldFromMainClass = clazz.getField(field.getName());
for (Object o : field.getFieldInfo().getAttributes()) {
if (o instanceof AnnotationsAttribute) {
AnnotationsAttribute templateAnnotations = (AnnotationsAttribute) o;
//have to make a copy of the annotations from the target
AnnotationsAttribute copied = (AnnotationsAttribute) templateAnnotations.copy(constPool, null);
//add all the copied annotations into the target class's field.
for (Object attribute : fieldFromMainClass.getFieldInfo().getAttributes()) {
if (attribute instanceof AnnotationsAttribute) {
for (Annotation annotation : copied.getAnnotations()) {
((AnnotationsAttribute) attribute).addAnnotation(annotation);
}
}
}
}
}
}
}
}
logger.lifecycle(LifeCycleEvent.END, String.format("Transform - Copying annotations into [%s] from [%s]", xformKey,
StringUtils.join(xformVals, ",")));
return clazz.toBytecode();
} catch (Exception e) {
throw new RuntimeException("Unable to transform class", e);
}
}
return null;
}
/**
* This method will do its best to return an implementation type for a given classname. This will allow weaving
* template classes to have initialized values.
*
* We provide default implementations for List, Map, and Set, and will attempt to utilize a default constructor for
* other classes.
*
* If the className contains an '[', we will return null.
*/
protected String getImplementationType(String className) {
if (className.equals("java.util.List")) {
return "java.util.ArrayList";
} else if (className.equals("java.util.Map")) {
return "java.util.HashMap";
} else if (className.equals("java.util.Set")) {
return "java.util.HashSet";
} else if (className.contains("[")) {
return null;
}
return className;
}
protected String methodDescription(CtMethod method) {
return method.getDeclaringClass().getName() + "|" + method.getName() + "|" + method.getSignature();
}
public Map<String, String> getXformTemplates() {
return xformTemplates;
}
public void setXformTemplates(Map<String, String> xformTemplates) {
this.xformTemplates = xformTemplates;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_extensibility_jpa_copy_AnnotationsCopyClassTransformer.java |
1,649 | private class EntryBackupProcessorImpl implements EntryBackupProcessor<K,V>{
@Override
public void processBackup(Map.Entry<K, V> entry) {
process(entry);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_AbstractEntryProcessor.java |
1,500 | public interface CurrencyConversionPricingFilter extends Filter {
@SuppressWarnings("rawtypes")
public HashMap getCurrencyConversionContext(ServletRequest request);
public CurrencyConversionService getCurrencyConversionService(ServletRequest request);
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_money_CurrencyConversionPricingFilter.java |
1,533 | class StopSAXParser extends SAXException {
/** This class is serializable */
private static final long serialVersionUID = 6173561761817524327L;
} | 0true
| object_src_main_java_com_orientechnologies_orient_object_jpa_parsing_PersistenceXmlUtil.java |
801 | public class AlterRequest extends AbstractAlterRequest {
public AlterRequest() {
}
public AlterRequest(String name, Data function) {
super(name, function);
}
@Override
protected Operation prepareOperation() {
return new AlterOperation(name, getFunction());
}
@Override
public int getClassId() {
return AtomicLongPortableHook.ALTER;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_AlterRequest.java |
359 | Collections.sort(indexesToFreeze, new Comparator<OIndex<?>>() {
public int compare(OIndex<?> o1, OIndex<?> o2) {
return o1.getName().compareTo(o2.getName());
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_document_ODatabaseDocumentTx.java |
185 | private class InnerIDBlockSizer implements IDBlockSizer {
@Override
public long getBlockSize(int idNamespace) {
return blockSize;
}
@Override
public long getIdUpperBound(int idNamespace) {
return idUpperBound;
}
} | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_IDAuthorityTest.java |
1,919 | public static class LoggingEntryProcessor extends AbstractEntryProcessor<String, TempData> {
private static final long serialVersionUID = 1L;
public Object process(Map.Entry<String, TempData> entry) {
return true;
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_map_TempData.java |
897 | public abstract class TransportSearchTypeAction extends TransportAction<SearchRequest, SearchResponse> {
protected final ClusterService clusterService;
protected final SearchServiceTransportAction searchService;
protected final SearchPhaseController searchPhaseController;
public TransportSearchTypeAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController) {
super(settings, threadPool);
this.clusterService = clusterService;
this.searchService = searchService;
this.searchPhaseController = searchPhaseController;
}
protected abstract class BaseAsyncAction<FirstResult extends SearchPhaseResult> {
protected final ActionListener<SearchResponse> listener;
protected final GroupShardsIterator shardsIts;
protected final SearchRequest request;
protected final ClusterState clusterState;
protected final DiscoveryNodes nodes;
protected final int expectedSuccessfulOps;
private final int expectedTotalOps;
protected final AtomicInteger successulOps = new AtomicInteger();
private final AtomicInteger totalOps = new AtomicInteger();
protected final AtomicArray<FirstResult> firstResults;
private volatile AtomicArray<ShardSearchFailure> shardFailures;
private final Object shardFailuresMutex = new Object();
protected volatile ScoreDoc[] sortedShardList;
protected final long startTime = System.currentTimeMillis();
protected BaseAsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
this.request = request;
this.listener = listener;
this.clusterState = clusterService.state();
nodes = clusterState.nodes();
clusterState.blocks().globalBlockedRaiseException(ClusterBlockLevel.READ);
String[] concreteIndices = clusterState.metaData().concreteIndices(request.indices(), request.indicesOptions());
for (String index : concreteIndices) {
clusterState.blocks().indexBlockedRaiseException(ClusterBlockLevel.READ, index);
}
Map<String, Set<String>> routingMap = clusterState.metaData().resolveSearchRouting(request.routing(), request.indices());
shardsIts = clusterService.operationRouting().searchShards(clusterState, request.indices(), concreteIndices, routingMap, request.preference());
expectedSuccessfulOps = shardsIts.size();
// we need to add 1 for non active partition, since we count it in the total!
expectedTotalOps = shardsIts.totalSizeWith1ForEmpty();
firstResults = new AtomicArray<FirstResult>(shardsIts.size());
}
public void start() {
if (expectedSuccessfulOps == 0) {
// no search shards to search on, bail with empty response (it happens with search across _all with no indices around and consistent with broadcast operations)
listener.onResponse(new SearchResponse(InternalSearchResponse.EMPTY, null, 0, 0, System.currentTimeMillis() - startTime, ShardSearchFailure.EMPTY_ARRAY));
return;
}
request.beforeStart();
// count the local operations, and perform the non local ones
int localOperations = 0;
int shardIndex = -1;
for (final ShardIterator shardIt : shardsIts) {
shardIndex++;
final ShardRouting shard = shardIt.firstOrNull();
if (shard != null) {
if (shard.currentNodeId().equals(nodes.localNodeId())) {
localOperations++;
} else {
// do the remote operation here, the localAsync flag is not relevant
performFirstPhase(shardIndex, shardIt);
}
} else {
// really, no shards active in this group
onFirstPhaseResult(shardIndex, null, null, shardIt, new NoShardAvailableActionException(shardIt.shardId()));
}
}
// we have local operations, perform them now
if (localOperations > 0) {
if (request.operationThreading() == SearchOperationThreading.SINGLE_THREAD) {
request.beforeLocalFork();
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
int shardIndex = -1;
for (final ShardIterator shardIt : shardsIts) {
shardIndex++;
final ShardRouting shard = shardIt.firstOrNull();
if (shard != null) {
if (shard.currentNodeId().equals(nodes.localNodeId())) {
performFirstPhase(shardIndex, shardIt);
}
}
}
}
});
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
if (localAsync) {
request.beforeLocalFork();
}
shardIndex = -1;
for (final ShardIterator shardIt : shardsIts) {
shardIndex++;
final int fShardIndex = shardIndex;
final ShardRouting shard = shardIt.firstOrNull();
if (shard != null) {
if (shard.currentNodeId().equals(nodes.localNodeId())) {
if (localAsync) {
try {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
performFirstPhase(fShardIndex, shardIt);
}
});
} catch (Throwable t) {
onFirstPhaseResult(shardIndex, shard, shard.currentNodeId(), shardIt, t);
}
} else {
performFirstPhase(fShardIndex, shardIt);
}
}
}
}
}
}
}
void performFirstPhase(final int shardIndex, final ShardIterator shardIt) {
performFirstPhase(shardIndex, shardIt, shardIt.nextOrNull());
}
void performFirstPhase(final int shardIndex, final ShardIterator shardIt, final ShardRouting shard) {
if (shard == null) {
// no more active shards... (we should not really get here, but just for safety)
onFirstPhaseResult(shardIndex, null, null, shardIt, new NoShardAvailableActionException(shardIt.shardId()));
} else {
final DiscoveryNode node = nodes.get(shard.currentNodeId());
if (node == null) {
onFirstPhaseResult(shardIndex, shard, null, shardIt, new NoShardAvailableActionException(shardIt.shardId()));
} else {
String[] filteringAliases = clusterState.metaData().filteringAliases(shard.index(), request.indices());
sendExecuteFirstPhase(node, internalSearchRequest(shard, shardsIts.size(), request, filteringAliases, startTime), new SearchServiceListener<FirstResult>() {
@Override
public void onResult(FirstResult result) {
onFirstPhaseResult(shardIndex, shard, result, shardIt);
}
@Override
public void onFailure(Throwable t) {
onFirstPhaseResult(shardIndex, shard, node.id(), shardIt, t);
}
});
}
}
}
void onFirstPhaseResult(int shardIndex, ShardRouting shard, FirstResult result, ShardIterator shardIt) {
result.shardTarget(new SearchShardTarget(shard.currentNodeId(), shard.index(), shard.id()));
processFirstPhaseResult(shardIndex, shard, result);
// increment all the "future" shards to update the total ops since we some may work and some may not...
// and when that happens, we break on total ops, so we must maintain them
int xTotalOps = totalOps.addAndGet(shardIt.remaining() + 1);
successulOps.incrementAndGet();
if (xTotalOps == expectedTotalOps) {
try {
innerMoveToSecondPhase();
} catch (Throwable e) {
if (logger.isDebugEnabled()) {
logger.debug(shardIt.shardId() + ": Failed to execute [" + request + "] while moving to second phase", e);
}
listener.onFailure(new ReduceSearchPhaseException(firstPhaseName(), "", e, buildShardFailures()));
}
}
}
void onFirstPhaseResult(final int shardIndex, @Nullable ShardRouting shard, @Nullable String nodeId, final ShardIterator shardIt, Throwable t) {
// we always add the shard failure for a specific shard instance
// we do make sure to clean it on a successful response from a shard
SearchShardTarget shardTarget = new SearchShardTarget(nodeId, shardIt.shardId().getIndex(), shardIt.shardId().getId());
addShardFailure(shardIndex, shardTarget, t);
if (totalOps.incrementAndGet() == expectedTotalOps) {
if (logger.isDebugEnabled()) {
if (t != null && !TransportActions.isShardNotAvailableException(t)) {
if (shard != null) {
logger.debug(shard.shortSummary() + ": Failed to execute [" + request + "]", t);
} else {
logger.debug(shardIt.shardId() + ": Failed to execute [" + request + "]", t);
}
}
}
if (successulOps.get() == 0) {
if (logger.isDebugEnabled()) {
logger.debug("All shards failed for phase: [{}]", firstPhaseName(), t);
}
// no successful ops, raise an exception
listener.onFailure(new SearchPhaseExecutionException(firstPhaseName(), "all shards failed", buildShardFailures()));
} else {
try {
innerMoveToSecondPhase();
} catch (Throwable e) {
listener.onFailure(new ReduceSearchPhaseException(firstPhaseName(), "", e, buildShardFailures()));
}
}
} else {
final ShardRouting nextShard = shardIt.nextOrNull();
final boolean lastShard = nextShard == null;
// trace log this exception
if (logger.isTraceEnabled() && t != null) {
logger.trace(executionFailureMsg(shard, shardIt, request, lastShard), t);
}
if (!lastShard) {
try {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
performFirstPhase(shardIndex, shardIt, nextShard);
}
});
} catch (Throwable t1) {
onFirstPhaseResult(shardIndex, shard, shard.currentNodeId(), shardIt, t1);
}
} else {
// no more shards active, add a failure
if (logger.isDebugEnabled() && !logger.isTraceEnabled()) { // do not double log this exception
if (t != null && !TransportActions.isShardNotAvailableException(t)) {
logger.debug(executionFailureMsg(shard, shardIt, request, lastShard), t);
}
}
}
}
}
private String executionFailureMsg(@Nullable ShardRouting shard, final ShardIterator shardIt, SearchRequest request, boolean lastShard) {
if (shard != null) {
return shard.shortSummary() + ": Failed to execute [" + request + "] lastShard [" + lastShard + "]";
} else {
return shardIt.shardId() + ": Failed to execute [" + request + "] lastShard [" + lastShard + "]";
}
}
/**
* Builds how long it took to execute the search.
*/
protected final long buildTookInMillis() {
return System.currentTimeMillis() - startTime;
}
protected final ShardSearchFailure[] buildShardFailures() {
AtomicArray<ShardSearchFailure> shardFailures = this.shardFailures;
if (shardFailures == null) {
return ShardSearchFailure.EMPTY_ARRAY;
}
List<AtomicArray.Entry<ShardSearchFailure>> entries = shardFailures.asList();
ShardSearchFailure[] failures = new ShardSearchFailure[entries.size()];
for (int i = 0; i < failures.length; i++) {
failures[i] = entries.get(i).value;
}
return failures;
}
protected final void addShardFailure(final int shardIndex, @Nullable SearchShardTarget shardTarget, Throwable t) {
// we don't aggregate shard failures on non active shards (but do keep the header counts right)
if (TransportActions.isShardNotAvailableException(t)) {
return;
}
// lazily create shard failures, so we can early build the empty shard failure list in most cases (no failures)
if (shardFailures == null) {
synchronized (shardFailuresMutex) {
if (shardFailures == null) {
shardFailures = new AtomicArray<ShardSearchFailure>(shardsIts.size());
}
}
}
ShardSearchFailure failure = shardFailures.get(shardIndex);
if (failure == null) {
shardFailures.set(shardIndex, new ShardSearchFailure(t, shardTarget));
} else {
// the failure is already present, try and not override it with an exception that is less meaningless
// for example, getting illegal shard state
if (TransportActions.isReadOverrideException(t)) {
shardFailures.set(shardIndex, new ShardSearchFailure(t, shardTarget));
}
}
}
/**
* Releases shard targets that are not used in the docsIdsToLoad.
*/
protected void releaseIrrelevantSearchContexts(AtomicArray<? extends QuerySearchResultProvider> queryResults,
AtomicArray<IntArrayList> docIdsToLoad) {
if (docIdsToLoad == null) {
return;
}
// we only release search context that we did not fetch from if we are not scrolling
if (request.scroll() == null) {
for (AtomicArray.Entry<? extends QuerySearchResultProvider> entry : queryResults.asList()) {
if (docIdsToLoad.get(entry.index) == null) {
DiscoveryNode node = nodes.get(entry.value.queryResult().shardTarget().nodeId());
if (node != null) { // should not happen (==null) but safeguard anyhow
searchService.sendFreeContext(node, entry.value.queryResult().id(), request);
}
}
}
}
}
protected abstract void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchRequest request, SearchServiceListener<FirstResult> listener);
protected final void processFirstPhaseResult(int shardIndex, ShardRouting shard, FirstResult result) {
firstResults.set(shardIndex, result);
// clean a previous error on this shard group (note, this code will be serialized on the same shardIndex value level
// so its ok concurrency wise to miss potentially the shard failures being created because of another failure
// in the #addShardFailure, because by definition, it will happen on *another* shardIndex
AtomicArray<ShardSearchFailure> shardFailures = this.shardFailures;
if (shardFailures != null) {
shardFailures.set(shardIndex, null);
}
}
final void innerMoveToSecondPhase() throws Exception {
if (logger.isTraceEnabled()) {
StringBuilder sb = new StringBuilder();
boolean hadOne = false;
for (int i = 0; i < firstResults.length(); i++) {
FirstResult result = firstResults.get(i);
if (result == null) {
continue; // failure
}
if (hadOne) {
sb.append(",");
} else {
hadOne = true;
}
sb.append(result.shardTarget());
}
logger.trace("Moving to second phase, based on results from: {} (cluster state version: {})", sb, clusterState.version());
}
moveToSecondPhase();
}
protected abstract void moveToSecondPhase() throws Exception;
protected abstract String firstPhaseName();
}
} | 1no label
| src_main_java_org_elasticsearch_action_search_type_TransportSearchTypeAction.java |
1,180 | public class SimpleUuidBenchmark {
private static long NUMBER_OF_ITERATIONS = 10000;
private static int NUMBER_OF_THREADS = 100;
public static void main(String[] args) throws Exception {
StopWatch stopWatch = new StopWatch().start();
System.out.println("Running " + NUMBER_OF_ITERATIONS);
for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) {
UUID.randomUUID().toString();
}
System.out.println("Generated in " + stopWatch.stop().totalTime() + " TP Millis " + (NUMBER_OF_ITERATIONS / stopWatch.totalTime().millisFrac()));
System.out.println("Generating using " + NUMBER_OF_THREADS + " threads with " + NUMBER_OF_ITERATIONS + " iterations");
final CountDownLatch latch = new CountDownLatch(NUMBER_OF_THREADS);
Thread[] threads = new Thread[NUMBER_OF_THREADS];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) {
UUID.randomUUID().toString();
}
latch.countDown();
}
});
}
stopWatch = new StopWatch().start();
for (Thread thread : threads) {
thread.start();
}
latch.await();
stopWatch.stop();
System.out.println("Generate in " + stopWatch.totalTime() + " TP Millis " + ((NUMBER_OF_ITERATIONS * NUMBER_OF_THREADS) / stopWatch.totalTime().millisFrac()));
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_uuid_SimpleUuidBenchmark.java |
2,957 | public interface TokenFilterFactoryFactory {
TokenFilterFactory create(String name, Settings settings);
} | 0true
| src_main_java_org_elasticsearch_index_analysis_TokenFilterFactoryFactory.java |
3,192 | public interface IndexFieldDataCache {
<FD extends AtomicFieldData, IFD extends IndexFieldData<FD>> FD load(AtomicReaderContext context, IFD indexFieldData) throws Exception;
/**
* Clears all the field data stored cached in on this index.
*/
void clear();
/**
* Clears all the field data stored cached in on this index for the specified field name.
*/
void clear(String fieldName);
void clear(Object coreCacheKey);
interface Listener {
void onLoad(FieldMapper.Names fieldNames, FieldDataType fieldDataType, AtomicFieldData fieldData);
void onUnload(FieldMapper.Names fieldNames, FieldDataType fieldDataType, boolean wasEvicted, long sizeInBytes, @Nullable AtomicFieldData fieldData);
}
/**
* The resident field data cache is a *per field* cache that keeps all the values in memory.
*/
static abstract class FieldBased implements IndexFieldDataCache, SegmentReader.CoreClosedListener, RemovalListener<FieldBased.Key, AtomicFieldData> {
@Nullable
private final IndexService indexService;
private final FieldMapper.Names fieldNames;
private final FieldDataType fieldDataType;
private final Cache<Key, AtomicFieldData> cache;
protected FieldBased(@Nullable IndexService indexService, FieldMapper.Names fieldNames, FieldDataType fieldDataType, CacheBuilder cache) {
this.indexService = indexService;
this.fieldNames = fieldNames;
this.fieldDataType = fieldDataType;
cache.removalListener(this);
//noinspection unchecked
this.cache = cache.build();
}
@Override
public void onRemoval(RemovalNotification<Key, AtomicFieldData> notification) {
Key key = notification.getKey();
if (key == null || key.listener == null) {
return; // we can't do anything here...
}
AtomicFieldData value = notification.getValue();
long sizeInBytes = key.sizeInBytes;
if (sizeInBytes == -1 && value != null) {
sizeInBytes = value.getMemorySizeInBytes();
}
key.listener.onUnload(fieldNames, fieldDataType, notification.wasEvicted(), sizeInBytes, value);
}
@Override
public <FD extends AtomicFieldData, IFD extends IndexFieldData<FD>> FD load(final AtomicReaderContext context, final IFD indexFieldData) throws Exception {
final Key key = new Key(context.reader().getCoreCacheKey());
//noinspection unchecked
return (FD) cache.get(key, new Callable<AtomicFieldData>() {
@Override
public AtomicFieldData call() throws Exception {
SegmentReaderUtils.registerCoreListener(context.reader(), FieldBased.this);
AtomicFieldData fieldData = indexFieldData.loadDirect(context);
key.sizeInBytes = fieldData.getMemorySizeInBytes();
if (indexService != null) {
ShardId shardId = ShardUtils.extractShardId(context.reader());
if (shardId != null) {
IndexShard shard = indexService.shard(shardId.id());
if (shard != null) {
key.listener = shard.fieldData();
}
}
}
if (key.listener != null) {
key.listener.onLoad(fieldNames, fieldDataType, fieldData);
}
return fieldData;
}
});
}
@Override
public void clear() {
cache.invalidateAll();
}
@Override
public void clear(String fieldName) {
cache.invalidateAll();
}
@Override
public void clear(Object coreCacheKey) {
cache.invalidate(new Key(coreCacheKey));
}
@Override
public void onClose(Object coreCacheKey) {
cache.invalidate(new Key(coreCacheKey));
}
static class Key {
final Object readerKey;
@Nullable
Listener listener; // optional stats listener
long sizeInBytes = -1; // optional size in bytes (we keep it here in case the values are soft references)
Key(Object readerKey) {
this.readerKey = readerKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
Key key = (Key) o;
if (!readerKey.equals(key.readerKey)) return false;
return true;
}
@Override
public int hashCode() {
return readerKey.hashCode();
}
}
}
static class Resident extends FieldBased {
public Resident(@Nullable IndexService indexService, FieldMapper.Names fieldNames, FieldDataType fieldDataType) {
super(indexService, fieldNames, fieldDataType, CacheBuilder.newBuilder());
}
}
static class Soft extends FieldBased {
public Soft(@Nullable IndexService indexService, FieldMapper.Names fieldNames, FieldDataType fieldDataType) {
super(indexService, fieldNames, fieldDataType, CacheBuilder.newBuilder().softValues());
}
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_IndexFieldDataCache.java |
1,054 | return new TermsEnum() {
int currentTerm = 0;
int freq = 0;
int docFreq = -1;
long totalTermFrequency = -1;
int[] positions = new int[1];
int[] startOffsets = new int[1];
int[] endOffsets = new int[1];
BytesRef[] payloads = new BytesRef[1];
final BytesRef spare = new BytesRef();
@Override
public BytesRef next() throws IOException {
if (currentTerm++ < numTerms) {
// term string. first the size...
int termVectorSize = perFieldTermVectorInput.readVInt();
spare.grow(termVectorSize);
// ...then the value.
perFieldTermVectorInput.readBytes(spare.bytes, 0, termVectorSize);
spare.length = termVectorSize;
if (hasTermStatistic) {
docFreq = readPotentiallyNegativeVInt(perFieldTermVectorInput);
totalTermFrequency = readPotentiallyNegativeVLong(perFieldTermVectorInput);
}
freq = readPotentiallyNegativeVInt(perFieldTermVectorInput);
// grow the arrays to read the values. this is just
// for performance reasons. Re-use memory instead of
// realloc.
growBuffers();
// finally, read the values into the arrays
// curentPosition etc. so that we can just iterate
// later
writeInfos(perFieldTermVectorInput);
return spare;
} else {
return null;
}
}
private void writeInfos(final BytesStreamInput input) throws IOException {
for (int i = 0; i < freq; i++) {
if (hasPositions) {
positions[i] = input.readVInt();
}
if (hasOffsets) {
startOffsets[i] = input.readVInt();
endOffsets[i] = input.readVInt();
}
if (hasPayloads) {
int payloadLength = input.readVInt();
if (payloads[i] == null) {
payloads[i] = new BytesRef(payloadLength);
} else {
payloads[i].grow(payloadLength);
}
input.readBytes(payloads[i].bytes, 0, payloadLength);
payloads[i].length = payloadLength;
payloads[i].offset = 0;
}
}
}
private void growBuffers() {
if (hasPositions) {
positions = grow(positions, freq);
}
if (hasOffsets) {
startOffsets = grow(startOffsets, freq);
endOffsets = grow(endOffsets, freq);
}
if (hasPayloads) {
if (payloads.length < freq) {
final BytesRef[] newArray = new BytesRef[ArrayUtil.oversize(freq, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
System.arraycopy(payloads, 0, newArray, 0, payloads.length);
payloads = newArray;
}
}
}
@Override
public Comparator<BytesRef> getComparator() {
return BytesRef.getUTF8SortedAsUnicodeComparator();
}
@Override
public SeekStatus seekCeil(BytesRef text) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void seekExact(long ord) throws IOException {
throw new UnsupportedOperationException("Seek is not supported");
}
@Override
public BytesRef term() throws IOException {
return spare;
}
@Override
public long ord() throws IOException {
throw new UnsupportedOperationException("ordinals are not supported");
}
@Override
public int docFreq() throws IOException {
return docFreq;
}
@Override
public long totalTermFreq() throws IOException {
return totalTermFrequency;
}
@Override
public DocsEnum docs(Bits liveDocs, DocsEnum reuse, int flags) throws IOException {
return docsAndPositions(liveDocs, reuse instanceof DocsAndPositionsEnum ? (DocsAndPositionsEnum) reuse : null, 0);
}
@Override
public DocsAndPositionsEnum docsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse, int flags) throws IOException {
final TermVectorsDocsAndPosEnum retVal = (reuse instanceof TermVectorsDocsAndPosEnum ? (TermVectorsDocsAndPosEnum) reuse
: new TermVectorsDocsAndPosEnum());
return retVal.reset(hasPositions ? positions : null, hasOffsets ? startOffsets : null, hasOffsets ? endOffsets
: null, hasPayloads ? payloads : null, freq);
}
}; | 0true
| src_main_java_org_elasticsearch_action_termvector_TermVectorFields.java |
3,287 | public abstract class AbstractBytesIndexFieldData<FD extends AtomicFieldData.WithOrdinals<ScriptDocValues.Strings>> extends AbstractIndexFieldData<FD> implements IndexFieldData.WithOrdinals<FD> {
protected Settings frequency;
protected Settings regex;
protected AbstractBytesIndexFieldData(Index index, Settings indexSettings, Names fieldNames, FieldDataType fieldDataType,
IndexFieldDataCache cache) {
super(index, indexSettings, fieldNames, fieldDataType, cache);
final Map<String, Settings> groups = fieldDataType.getSettings().getGroups("filter");
frequency = groups.get("frequency");
regex = groups.get("regex");
}
@Override
public final boolean valuesOrdered() {
return true;
}
@Override
public XFieldComparatorSource comparatorSource(@Nullable Object missingValue, SortMode sortMode) {
return new BytesRefFieldComparatorSource(this, missingValue, sortMode);
}
protected TermsEnum filter(Terms terms, AtomicReader reader) throws IOException {
TermsEnum iterator = terms.iterator(null);
if (iterator == null) {
return null;
}
if (iterator != null && frequency != null) {
iterator = FrequencyFilter.filter(iterator, terms, reader, frequency);
}
if (iterator != null && regex != null) {
iterator = RegexFilter.filter(iterator, terms, reader, regex);
}
return iterator;
}
private static final class FrequencyFilter extends FilteredTermsEnum {
private int minFreq;
private int maxFreq;
public FrequencyFilter(TermsEnum delegate, int minFreq, int maxFreq) {
super(delegate, false);
this.minFreq = minFreq;
this.maxFreq = maxFreq;
}
public static TermsEnum filter(TermsEnum toFilter, Terms terms, AtomicReader reader, Settings settings) throws IOException {
int docCount = terms.getDocCount();
if (docCount == -1) {
docCount = reader.maxDoc();
}
final double minFrequency = settings.getAsDouble("min", 0d);
final double maxFrequency = settings.getAsDouble("max", docCount+1d);
final double minSegmentSize = settings.getAsInt("min_segment_size", 0);
if (minSegmentSize < docCount) {
final int minFreq = minFrequency >= 1.0? (int) minFrequency : (int)(docCount * minFrequency);
final int maxFreq = maxFrequency >= 1.0? (int) maxFrequency : (int)(docCount * maxFrequency);
assert minFreq < maxFreq;
return new FrequencyFilter(toFilter, minFreq, maxFreq);
}
return toFilter;
}
@Override
protected AcceptStatus accept(BytesRef arg0) throws IOException {
int docFreq = docFreq();
if (docFreq >= minFreq && docFreq <= maxFreq) {
return AcceptStatus.YES;
}
return AcceptStatus.NO;
}
}
private static final class RegexFilter extends FilteredTermsEnum {
private final Matcher matcher;
private final CharsRef spare = new CharsRef();
public RegexFilter(TermsEnum delegate, Matcher matcher) {
super(delegate, false);
this.matcher = matcher;
}
public static TermsEnum filter(TermsEnum iterator, Terms terms, AtomicReader reader, Settings regex) {
String pattern = regex.get("pattern");
if (pattern == null) {
return iterator;
}
Pattern p = Pattern.compile(pattern);
return new RegexFilter(iterator, p.matcher(""));
}
@Override
protected AcceptStatus accept(BytesRef arg0) throws IOException {
UnicodeUtil.UTF8toUTF16(arg0, spare);
matcher.reset(spare);
if (matcher.matches()) {
return AcceptStatus.YES;
}
return AcceptStatus.NO;
}
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_AbstractBytesIndexFieldData.java |
3,103 | public class EngineModule extends AbstractModule implements SpawnModules {
private final Settings settings;
public EngineModule(Settings settings) {
this.settings = settings;
}
@Override
public Iterable<? extends Module> spawnModules() {
return ImmutableList.of(Modules.createModule(settings.getAsClass(IndexEngineModule.EngineSettings.ENGINE_TYPE, IndexEngineModule.EngineSettings.DEFAULT_ENGINE, "org.elasticsearch.index.engine.", "EngineModule"), settings));
}
@Override
protected void configure() {
}
} | 0true
| src_main_java_org_elasticsearch_index_engine_EngineModule.java |
982 | public class SignalOperation extends BaseSignalOperation implements BackupAwareOperation {
public SignalOperation() {
}
public SignalOperation(ObjectNamespace namespace, Data key, long threadId, String conditionId, boolean all) {
super(namespace, key, threadId, conditionId, all);
}
@Override
public void beforeRun() throws Exception {
LockStoreImpl lockStore = getLockStore();
boolean isLockOwner = lockStore.isLockedBy(key, getCallerUuid(), threadId);
ensureLockOwner(lockStore, isLockOwner);
}
private void ensureLockOwner(LockStoreImpl lockStore, boolean isLockOwner) {
if (!isLockOwner) {
String ownerInfo = lockStore.getOwnerInfo(key);
throw new IllegalMonitorStateException("Current thread is not owner of the lock! -> " + ownerInfo);
}
}
@Override
public boolean shouldBackup() {
return awaitCount > 0;
}
@Override
public Operation getBackupOperation() {
return new SignalBackupOperation(namespace, key, threadId, conditionId, all);
}
@Override
public int getId() {
return LockDataSerializerHook.SIGNAL;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_operations_SignalOperation.java |
1,480 | public class Hibernate3CacheEntrySerializerHook
implements SerializerHook {
private static final String SKIP_INIT_MSG = "Hibernate3 not available, skipping serializer initialization";
private final Class<?> cacheEntryClass;
public Hibernate3CacheEntrySerializerHook() {
Class<?> cacheEntryClass = null;
if (UnsafeHelper.UNSAFE_AVAILABLE) {
try {
cacheEntryClass = Class.forName("org.hibernate.cache.entry.CacheEntry");
} catch (Exception e) {
Logger.getLogger(Hibernate3CacheEntrySerializerHook.class).finest(SKIP_INIT_MSG);
}
}
this.cacheEntryClass = cacheEntryClass;
}
@Override
public Class getSerializationType() {
return cacheEntryClass;
}
@Override
public Serializer createSerializer() {
if (cacheEntryClass != null) {
return new Hibernate3CacheEntrySerializer();
}
return null;
}
@Override
public boolean isOverwritable() {
return true;
}
} | 0true
| hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_serialization_Hibernate3CacheEntrySerializerHook.java |
125 | static final class ExceptionNode extends WeakReference<ForkJoinTask<?>> {
final Throwable ex;
ExceptionNode next;
final long thrower; // use id not ref to avoid weak cycles
final int hashCode; // store task hashCode before weak ref disappears
ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
super(task, exceptionTableRefQueue);
this.ex = ex;
this.next = next;
this.thrower = Thread.currentThread().getId();
this.hashCode = System.identityHashCode(task);
}
} | 0true
| src_main_java_jsr166e_ForkJoinTask.java |
197 | shell.getDisplay().syncExec(new Runnable() {
@Override
public void run() {
updateTitleImage();
}
}); | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonEditor.java |
357 | public class NodesStatsRequest extends NodesOperationRequest<NodesStatsRequest> {
private CommonStatsFlags indices = new CommonStatsFlags();
private boolean os;
private boolean process;
private boolean jvm;
private boolean threadPool;
private boolean network;
private boolean fs;
private boolean transport;
private boolean http;
private boolean breaker;
protected NodesStatsRequest() {
}
/**
* Get stats from nodes based on the nodes ids specified. If none are passed, stats
* for all nodes will be returned.
*/
public NodesStatsRequest(String... nodesIds) {
super(nodesIds);
}
/**
* Sets all the request flags.
*/
public NodesStatsRequest all() {
this.indices.all();
this.os = true;
this.process = true;
this.jvm = true;
this.threadPool = true;
this.network = true;
this.fs = true;
this.transport = true;
this.http = true;
this.breaker = true;
return this;
}
/**
* Clears all the request flags.
*/
public NodesStatsRequest clear() {
this.indices.clear();
this.os = false;
this.process = false;
this.jvm = false;
this.threadPool = false;
this.network = false;
this.fs = false;
this.transport = false;
this.http = false;
this.breaker = false;
return this;
}
public CommonStatsFlags indices() {
return indices;
}
public NodesStatsRequest indices(CommonStatsFlags indices) {
this.indices = indices;
return this;
}
/**
* Should indices stats be returned.
*/
public NodesStatsRequest indices(boolean indices) {
if (indices) {
this.indices.all();
} else {
this.indices.clear();
}
return this;
}
/**
* Should the node OS be returned.
*/
public boolean os() {
return this.os;
}
/**
* Should the node OS be returned.
*/
public NodesStatsRequest os(boolean os) {
this.os = os;
return this;
}
/**
* Should the node Process be returned.
*/
public boolean process() {
return this.process;
}
/**
* Should the node Process be returned.
*/
public NodesStatsRequest process(boolean process) {
this.process = process;
return this;
}
/**
* Should the node JVM be returned.
*/
public boolean jvm() {
return this.jvm;
}
/**
* Should the node JVM be returned.
*/
public NodesStatsRequest jvm(boolean jvm) {
this.jvm = jvm;
return this;
}
/**
* Should the node Thread Pool be returned.
*/
public boolean threadPool() {
return this.threadPool;
}
/**
* Should the node Thread Pool be returned.
*/
public NodesStatsRequest threadPool(boolean threadPool) {
this.threadPool = threadPool;
return this;
}
/**
* Should the node Network be returned.
*/
public boolean network() {
return this.network;
}
/**
* Should the node Network be returned.
*/
public NodesStatsRequest network(boolean network) {
this.network = network;
return this;
}
/**
* Should the node file system stats be returned.
*/
public boolean fs() {
return this.fs;
}
/**
* Should the node file system stats be returned.
*/
public NodesStatsRequest fs(boolean fs) {
this.fs = fs;
return this;
}
/**
* Should the node Transport be returned.
*/
public boolean transport() {
return this.transport;
}
/**
* Should the node Transport be returned.
*/
public NodesStatsRequest transport(boolean transport) {
this.transport = transport;
return this;
}
/**
* Should the node HTTP be returned.
*/
public boolean http() {
return this.http;
}
/**
* Should the node HTTP be returned.
*/
public NodesStatsRequest http(boolean http) {
this.http = http;
return this;
}
public boolean breaker() {
return this.breaker;
}
/**
* Should the node's circuit breaker stats be returned.
*/
public NodesStatsRequest breaker(boolean breaker) {
this.breaker = breaker;
return this;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
indices = CommonStatsFlags.readCommonStatsFlags(in);
os = in.readBoolean();
process = in.readBoolean();
jvm = in.readBoolean();
threadPool = in.readBoolean();
network = in.readBoolean();
fs = in.readBoolean();
transport = in.readBoolean();
http = in.readBoolean();
breaker = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
indices.writeTo(out);
out.writeBoolean(os);
out.writeBoolean(process);
out.writeBoolean(jvm);
out.writeBoolean(threadPool);
out.writeBoolean(network);
out.writeBoolean(fs);
out.writeBoolean(transport);
out.writeBoolean(http);
out.writeBoolean(breaker);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_node_stats_NodesStatsRequest.java |
840 | return new IAnswer<FulfillmentGroup>() {
@Override
public FulfillmentGroup answer() throws Throwable {
FulfillmentGroupItemRequest fgItemRequest = (FulfillmentGroupItemRequest) EasyMock.getCurrentArguments()[0];
FulfillmentGroup fg = fgItemRequest.getFulfillmentGroup();
FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl();
fgItem.setOrderItem(fgItemRequest.getOrderItem());
fgItem.setQuantity(fgItemRequest.getQuantity());
fg.getFulfillmentGroupItems().add(fgItem);
return fg;
}
}; | 0true
| core_broadleaf-framework_src_test_java_org_broadleafcommerce_core_offer_service_OfferDataItemProvider.java |
3,582 | public static class CustomFloatNumericField extends CustomNumericField {
private final float number;
private final NumberFieldMapper mapper;
public CustomFloatNumericField(NumberFieldMapper mapper, float number, FieldType fieldType) {
super(mapper, number, fieldType);
this.mapper = mapper;
this.number = number;
}
@Override
public TokenStream tokenStream(Analyzer analyzer) throws IOException {
if (fieldType().indexed()) {
return mapper.popCachedStream().setFloatValue(number);
}
return null;
}
@Override
public String numericAsString() {
return Float.toString(number);
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_core_FloatFieldMapper.java |
252 | public class CassandraEmbeddedKeyColumnValueStore implements KeyColumnValueStore {
private static final Logger log = LoggerFactory.getLogger(CassandraEmbeddedKeyColumnValueStore.class);
private final String keyspace;
private final String columnFamily;
private final CassandraEmbeddedStoreManager storeManager;
private final TimestampProvider times;
private final CassandraEmbeddedGetter entryGetter;
public CassandraEmbeddedKeyColumnValueStore(
String keyspace,
String columnFamily,
CassandraEmbeddedStoreManager storeManager) throws RuntimeException {
this.keyspace = keyspace;
this.columnFamily = columnFamily;
this.storeManager = storeManager;
this.times = this.storeManager.getTimestampProvider();
entryGetter = new CassandraEmbeddedGetter(storeManager.getMetaDataSchema(columnFamily),times);
}
@Override
public void close() throws BackendException {
}
@Override
public void acquireLock(StaticBuffer key, StaticBuffer column,
StaticBuffer expectedValue, StoreTransaction txh) throws BackendException {
throw new UnsupportedOperationException();
}
@Override
public KeyIterator getKeys(KeyRangeQuery keyRangeQuery, StoreTransaction txh) throws BackendException {
IPartitioner partitioner = StorageService.getPartitioner();
// see rant about this in Astyanax implementation
if (partitioner instanceof RandomPartitioner || partitioner instanceof Murmur3Partitioner)
throw new PermanentBackendException("This operation is only supported when byte-ordered partitioner is used.");
return new RowIterator(keyRangeQuery, storeManager.getPageSize(), txh);
}
@Override
public KeyIterator getKeys(SliceQuery query, StoreTransaction txh) throws BackendException {
return new RowIterator(getMinimumToken(), getMaximumToken(), query, storeManager.getPageSize(), txh);
}
/**
* Create a RangeSliceCommand and run it against the StorageProxy.
* <p>
* To match the behavior of the standard Cassandra thrift API endpoint, the
* {@code nowMillis} argument should be the number of milliseconds since the
* UNIX Epoch (e.g. System.currentTimeMillis() or equivalent obtained
* through a {@link TimestampProvider}). This is per
* {@link org.apache.cassandra.thrift.CassandraServer#get_range_slices(ColumnParent, SlicePredicate, KeyRange, ConsistencyLevel)},
* which passes the server's System.currentTimeMillis() to the
* {@code RangeSliceCommand} constructor.
*/
private List<Row> getKeySlice(Token start,
Token end,
@Nullable SliceQuery sliceQuery,
int pageSize,
long nowMillis) throws BackendException {
IPartitioner<?> partitioner = StorageService.getPartitioner();
SliceRange columnSlice = new SliceRange();
if (sliceQuery == null) {
columnSlice.setStart(ArrayUtils.EMPTY_BYTE_ARRAY)
.setFinish(ArrayUtils.EMPTY_BYTE_ARRAY)
.setCount(5);
} else {
columnSlice.setStart(sliceQuery.getSliceStart().asByteBuffer())
.setFinish(sliceQuery.getSliceEnd().asByteBuffer())
.setCount(sliceQuery.hasLimit() ? sliceQuery.getLimit() : Integer.MAX_VALUE);
}
/* Note: we need to fetch columns for each row as well to remove "range ghosts" */
SlicePredicate predicate = new SlicePredicate().setSlice_range(columnSlice);
RowPosition startPosition = start.minKeyBound(partitioner);
RowPosition endPosition = end.minKeyBound(partitioner);
List<Row> rows;
try {
CFMetaData cfm = Schema.instance.getCFMetaData(keyspace, columnFamily);
IDiskAtomFilter filter = ThriftValidation.asIFilter(predicate, cfm, null);
RangeSliceCommand cmd = new RangeSliceCommand(keyspace, columnFamily, nowMillis, filter, new Bounds<RowPosition>(startPosition, endPosition), pageSize);
rows = StorageProxy.getRangeSlice(cmd, ConsistencyLevel.QUORUM);
} catch (Exception e) {
throw new PermanentBackendException(e);
}
return rows;
}
@Override
public String getName() {
return columnFamily;
}
@Override
public EntryList getSlice(KeySliceQuery query, StoreTransaction txh) throws BackendException {
/**
* This timestamp mimics the timestamp used by
* {@link org.apache.cassandra.thrift.CassandraServer#get(ByteBuffer,ColumnPath,ConsistencyLevel)}.
*
* That method passes the server's System.currentTimeMillis() to
* {@link ReadCommand#create(String, ByteBuffer, String, long, IDiskAtomFilter)}.
* {@code create(...)} in turn passes that timestamp to the SliceFromReadCommand constructor.
*/
final long nowMillis = times.getTime().getTimestamp(TimeUnit.MILLISECONDS);
SliceQueryFilter sqf = new SliceQueryFilter(query.getSliceStart().asByteBuffer(), query.getSliceEnd().asByteBuffer(), false, query.getLimit() + (query.hasLimit()?1:0));
ReadCommand sliceCmd = new SliceFromReadCommand(keyspace, query.getKey().asByteBuffer(), columnFamily, nowMillis, sqf);
List<Row> slice = read(sliceCmd, getTx(txh).getReadConsistencyLevel().getDB());
if (null == slice || 0 == slice.size())
return EntryList.EMPTY_LIST;
int sliceSize = slice.size();
if (1 < sliceSize)
throw new PermanentBackendException("Received " + sliceSize + " rows for single key");
Row r = slice.get(0);
if (null == r) {
log.warn("Null Row object retrieved from Cassandra StorageProxy");
return EntryList.EMPTY_LIST;
}
ColumnFamily cf = r.cf;
if (null == cf) {
log.debug("null ColumnFamily (\"{}\")", columnFamily);
return EntryList.EMPTY_LIST;
}
if (cf.isMarkedForDelete())
return EntryList.EMPTY_LIST;
return CassandraHelper.makeEntryList(
Iterables.filter(cf.getSortedColumns(), new FilterDeletedColumns(nowMillis)),
entryGetter,
query.getSliceEnd(),
query.getLimit());
}
private class FilterDeletedColumns implements Predicate<Column> {
private final long ts;
private FilterDeletedColumns(long ts) {
this.ts = ts;
}
@Override
public boolean apply(Column input) {
return !input.isMarkedForDelete(ts);
}
}
@Override
public Map<StaticBuffer,EntryList> getSlice(List<StaticBuffer> keys, SliceQuery query, StoreTransaction txh) throws BackendException {
throw new UnsupportedOperationException();
}
@Override
public void mutate(StaticBuffer key, List<Entry> additions,
List<StaticBuffer> deletions, StoreTransaction txh) throws BackendException {
Map<StaticBuffer, KCVMutation> mutations = ImmutableMap.of(key, new
KCVMutation(additions, deletions));
mutateMany(mutations, txh);
}
public void mutateMany(Map<StaticBuffer, KCVMutation> mutations,
StoreTransaction txh) throws BackendException {
storeManager.mutateMany(ImmutableMap.of(columnFamily, mutations), txh);
}
private static List<Row> read(ReadCommand cmd, org.apache.cassandra.db.ConsistencyLevel clvl) throws BackendException {
ArrayList<ReadCommand> cmdHolder = new ArrayList<ReadCommand>(1);
cmdHolder.add(cmd);
return read(cmdHolder, clvl);
}
private static List<Row> read(List<ReadCommand> cmds, org.apache.cassandra.db.ConsistencyLevel clvl) throws BackendException {
try {
return StorageProxy.read(cmds, clvl);
} catch (UnavailableException e) {
throw new TemporaryBackendException(e);
} catch (RequestTimeoutException e) {
throw new PermanentBackendException(e);
} catch (IsBootstrappingException e) {
throw new TemporaryBackendException(e);
} catch (InvalidRequestException e) {
throw new PermanentBackendException(e);
}
}
private static class CassandraEmbeddedGetter implements StaticArrayEntry.GetColVal<Column,ByteBuffer> {
private final EntryMetaData[] schema;
private final TimestampProvider times;
private CassandraEmbeddedGetter(EntryMetaData[] schema, TimestampProvider times) {
this.schema = schema;
this.times = times;
}
@Override
public ByteBuffer getColumn(Column element) {
return org.apache.cassandra.utils.ByteBufferUtil.clone(element.name());
}
@Override
public ByteBuffer getValue(Column element) {
return org.apache.cassandra.utils.ByteBufferUtil.clone(element.value());
}
@Override
public EntryMetaData[] getMetaSchema(Column element) {
return schema;
}
@Override
public Object getMetaData(Column element, EntryMetaData meta) {
switch (meta) {
case TIMESTAMP:
return element.timestamp();
case TTL:
return ((element instanceof ExpiringColumn)
? ((ExpiringColumn) element).getTimeToLive()
: 0);
default:
throw new UnsupportedOperationException("Unsupported meta data: " + meta);
}
}
}
private class RowIterator implements KeyIterator {
private final Token maximumToken;
private final SliceQuery sliceQuery;
private final StoreTransaction txh;
/**
* This RowIterator will use this timestamp for its entire lifetime,
* even if the iterator runs more than one distinct slice query while
* paging. <b>This field must be in units of milliseconds since
* the UNIX Epoch</b>.
* <p>
* This timestamp is passed to three methods/constructors:
* <ul>
* <li>{@link org.apache.cassandra.db.Column#isMarkedForDelete(long now)}</li>
* <li>{@link org.apache.cassandra.db.ColumnFamily#hasOnlyTombstones(long)}</li>
* <li>
* the {@link RangeSliceCommand} constructor via the last argument
* to {@link CassandraEmbeddedKeyColumnValueStore#getKeySlice(Token, Token, SliceQuery, int, long)}
* </li>
* </ul>
* The second list entry just calls the first and almost doesn't deserve
* a mention at present, but maybe the implementation will change in the future.
* <p>
* When this value needs to be compared to TTL seconds expressed in seconds,
* Cassandra internals do the conversion.
* Consider {@link ExpiringColumn#isMarkedForDelete(long)}, which is implemented,
* as of 2.0.6, by the following one-liner:
* <p>
* {@code return (int) (now / 1000) >= getLocalDeletionTime()}
* <p>
* The {@code now / 1000} does the conversion from milliseconds to seconds
* (the units of getLocalDeletionTime()).
*/
private final long nowMillis;
private Iterator<Row> keys;
private ByteBuffer lastSeenKey = null;
private Row currentRow;
private int pageSize;
private boolean isClosed;
public RowIterator(KeyRangeQuery keyRangeQuery, int pageSize, StoreTransaction txh) throws BackendException {
this(StorageService.getPartitioner().getToken(keyRangeQuery.getKeyStart().asByteBuffer()),
StorageService.getPartitioner().getToken(keyRangeQuery.getKeyEnd().asByteBuffer()),
keyRangeQuery,
pageSize,
txh);
}
public RowIterator(Token minimum, Token maximum, SliceQuery sliceQuery, int pageSize, StoreTransaction txh) throws BackendException {
this.pageSize = pageSize;
this.sliceQuery = sliceQuery;
this.maximumToken = maximum;
this.txh = txh;
this.nowMillis = times.getTime().getTimestamp(TimeUnit.MILLISECONDS);
this.keys = getRowsIterator(getKeySlice(minimum, maximum, sliceQuery, pageSize, nowMillis));
}
@Override
public boolean hasNext() {
try {
return hasNextInternal();
} catch (BackendException e) {
throw new RuntimeException(e);
}
}
@Override
public StaticBuffer next() {
ensureOpen();
if (!hasNext())
throw new NoSuchElementException();
currentRow = keys.next();
ByteBuffer currentKey = currentRow.key.key.duplicate();
try {
return StaticArrayBuffer.of(currentKey);
} finally {
lastSeenKey = currentKey;
}
}
@Override
public void close() {
isClosed = true;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public RecordIterator<Entry> getEntries() {
ensureOpen();
if (sliceQuery == null)
throw new IllegalStateException("getEntries() requires SliceQuery to be set.");
return new RecordIterator<Entry>() {
final Iterator<Entry> columns = CassandraHelper.makeEntryIterator(
Iterables.filter(currentRow.cf.getSortedColumns(), new FilterDeletedColumns(nowMillis)),
entryGetter,
sliceQuery.getSliceEnd(),
sliceQuery.getLimit());
//cfToEntries(currentRow.cf, sliceQuery).iterator();
@Override
public boolean hasNext() {
ensureOpen();
return columns.hasNext();
}
@Override
public Entry next() {
ensureOpen();
return columns.next();
}
@Override
public void close() {
isClosed = true;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
private final boolean hasNextInternal() throws BackendException {
ensureOpen();
if (keys == null)
return false;
boolean hasNext = keys.hasNext();
if (!hasNext && lastSeenKey != null) {
Token lastSeenToken = StorageService.getPartitioner().getToken(lastSeenKey.duplicate());
// let's check if we reached key upper bound already so we can skip one useless call to Cassandra
if (maximumToken != getMinimumToken() && lastSeenToken.equals(maximumToken)) {
return false;
}
List<Row> newKeys = getKeySlice(StorageService.getPartitioner().getToken(lastSeenKey), maximumToken, sliceQuery, pageSize, nowMillis);
keys = getRowsIterator(newKeys, lastSeenKey);
hasNext = keys.hasNext();
}
return hasNext;
}
private void ensureOpen() {
if (isClosed)
throw new IllegalStateException("Iterator has been closed.");
}
private Iterator<Row> getRowsIterator(List<Row> rows) {
if (rows == null)
return null;
return Iterators.filter(rows.iterator(), new Predicate<Row>() {
@Override
public boolean apply(@Nullable Row row) {
// The hasOnlyTombstones(x) call below ultimately calls Column.isMarkedForDelete(x)
return !(row == null || row.cf == null || row.cf.isMarkedForDelete() || row.cf.hasOnlyTombstones(nowMillis));
}
});
}
private Iterator<Row> getRowsIterator(List<Row> rows, final ByteBuffer exceptKey) {
Iterator<Row> rowIterator = getRowsIterator(rows);
if (rowIterator == null)
return null;
return Iterators.filter(rowIterator, new Predicate<Row>() {
@Override
public boolean apply(@Nullable Row row) {
return row != null && !row.key.key.equals(exceptKey);
}
});
}
}
private static Token getMinimumToken() throws PermanentBackendException {
IPartitioner partitioner = StorageService.getPartitioner();
if (partitioner instanceof RandomPartitioner) {
return ((RandomPartitioner) partitioner).getMinimumToken();
} else if (partitioner instanceof Murmur3Partitioner) {
return ((Murmur3Partitioner) partitioner).getMinimumToken();
} else if (partitioner instanceof ByteOrderedPartitioner) {
//TODO: This makes the assumption that its an EdgeStore (i.e. 8 byte keys)
return new BytesToken(com.thinkaurelius.titan.diskstorage.util.ByteBufferUtil.zeroByteBuffer(8));
} else {
throw new PermanentBackendException("Unsupported partitioner: " + partitioner);
}
}
private static Token getMaximumToken() throws PermanentBackendException {
IPartitioner partitioner = StorageService.getPartitioner();
if (partitioner instanceof RandomPartitioner) {
return new BigIntegerToken(RandomPartitioner.MAXIMUM);
} else if (partitioner instanceof Murmur3Partitioner) {
return new LongToken(Murmur3Partitioner.MAXIMUM);
} else if (partitioner instanceof ByteOrderedPartitioner) {
//TODO: This makes the assumption that its an EdgeStore (i.e. 8 byte keys)
return new BytesToken(com.thinkaurelius.titan.diskstorage.util.ByteBufferUtil.oneByteBuffer(8));
} else {
throw new PermanentBackendException("Unsupported partitioner: " + partitioner);
}
}
} | 0true
| titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_embedded_CassandraEmbeddedKeyColumnValueStore.java |
665 | constructors[COLLECTION_ITEM] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new CollectionItem();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java |
3,671 | 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;
} | 1no label
| src_main_java_org_elasticsearch_index_mapper_internal_IndexFieldMapper.java |
117 | public static interface ManagedBlocker {
/**
* Possibly blocks the current thread, for example waiting for
* a lock or condition.
*
* @return {@code true} if no additional blocking is necessary
* (i.e., if isReleasable would return true)
* @throws InterruptedException if interrupted while waiting
* (the method is not required to do so, but is allowed to)
*/
boolean block() throws InterruptedException;
/**
* Returns {@code true} if blocking is unnecessary.
* @return {@code true} if blocking is unnecessary
*/
boolean isReleasable();
} | 0true
| src_main_java_jsr166e_ForkJoinPool.java |
1,102 | public class NonDiscreteOrderItemRequestDTO extends OrderItemRequestDTO {
protected String itemName;
public NonDiscreteOrderItemRequestDTO() {
}
public NonDiscreteOrderItemRequestDTO(String itemName, Integer quantity, Money overrideRetailPrice) {
setItemName(itemName);
setQuantity(quantity);
setOverrideRetailPrice(overrideRetailPrice);
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_call_NonDiscreteOrderItemRequestDTO.java |
1,222 | final class DeltaScanner implements IResourceDeltaVisitor {
private final BooleanHolder mustDoFullBuild;
private final IProject project;
private final BooleanHolder somethingToBuild;
private final BooleanHolder mustResolveClasspathContainer;
private IPath explodedDirPath;
private Map<IProject, IPath> modulesDirPathByProject = new HashMap<>();
private boolean astAwareIncrementalBuild = true;
DeltaScanner(BooleanHolder mustDoFullBuild, IProject project,
BooleanHolder somethingToBuild,
BooleanHolder mustResolveClasspathContainer) {
this.mustDoFullBuild = mustDoFullBuild;
this.project = project;
this.somethingToBuild = somethingToBuild;
this.mustResolveClasspathContainer = mustResolveClasspathContainer;
IFolder explodedFolder = CeylonBuilder.getCeylonClassesOutputFolder(project);
explodedDirPath = explodedFolder != null ? explodedFolder.getFullPath() : null;
IFolder modulesFolder = CeylonBuilder.getCeylonModulesOutputFolder(project);
IPath modulesDirPath = modulesFolder != null ? modulesFolder.getFullPath() : null;
modulesDirPathByProject.put(project, modulesDirPath);
try {
for (IProject referencedProject : project.getReferencedProjects()) {
modulesFolder = CeylonBuilder.getCeylonModulesOutputFolder(referencedProject);
modulesDirPath = modulesFolder != null ? modulesFolder.getFullPath() : null;
modulesDirPathByProject.put(referencedProject, modulesDirPath);
}
} catch (CoreException e) {
}
astAwareIncrementalBuild = CeylonBuilder.areAstAwareIncrementalBuildsEnabled(project);
}
@Override
public boolean visit(IResourceDelta resourceDelta)
throws CoreException {
IResource resource = resourceDelta.getResource();
if (resource instanceof IProject) {
if ((resourceDelta.getFlags() & IResourceDelta.DESCRIPTION)!=0) {
//some project setting changed : don't do anything,
// since the possibly impacting changes have already been
// checked by JavaProjectStateManager.hasClasspathChanges()
}
else if (!resource.equals(project)) {
//this is some kind of multi-project build,
//indicating a change in a project we
//depend upon
/*mustDoFullBuild.value = true;
mustResolveClasspathContainer.value = true;*/
}
try {
if (resource.equals(project) &&
resource.findMarkers(CeylonBuilder.PROBLEM_MARKER_ID + ".backend", false, IResource.DEPTH_ZERO).length > 0) {
somethingToBuild.value = true;
}
} catch(Exception e) {}
}
if (resource instanceof IFolder) {
IFolder folder = (IFolder) resource;
if (resourceDelta.getKind()==IResourceDelta.REMOVED) {
Package pkg = getPackage(folder);
if (pkg!=null) {
//a package has been removed
mustDoFullBuild.value = true;
}
IPath fullPath = resource.getFullPath();
if (fullPath != null) {
if (explodedDirPath != null && explodedDirPath.isPrefixOf(fullPath)) {
mustDoFullBuild.value = true;
mustResolveClasspathContainer.value = true;
}
for (Map.Entry<IProject, IPath> entry : modulesDirPathByProject.entrySet()) {
IPath modulesDirPath = entry.getValue();
if (modulesDirPath != null && modulesDirPath.isPrefixOf(fullPath)) {
mustDoFullBuild.value = true;
mustResolveClasspathContainer.value = true;
}
}
}
} else {
if (folder.exists() && folder.getProject().equals(project)) {
if (getPackage(folder) == null || getRootFolder(folder) == null) {
IContainer parent = folder.getParent();
if (parent instanceof IFolder) {
Package parentPkg = getPackage((IFolder)parent);
IFolder rootFolder = getRootFolder((IFolder)parent);
if (parentPkg != null && rootFolder != null) {
Package pkg = getProjectModelLoader(project).findOrCreatePackage(parentPkg.getModule(), parentPkg.getNameAsString() + "." + folder.getName());
resource.setSessionProperty(CeylonBuilder.RESOURCE_PROPERTY_PACKAGE_MODEL, new WeakReference<Package>(pkg));
resource.setSessionProperty(CeylonBuilder.RESOURCE_PROPERTY_ROOT_FOLDER, rootFolder);
}
}
}
}
}
}
if (resource instanceof IFile) {
IFile file = (IFile) resource;
String fileName = file.getName();
if (isInSourceFolder(file)) {
if (fileName.equals(ModuleManager.PACKAGE_FILE) || fileName.equals(ModuleManager.MODULE_FILE)) {
//a package or module descriptor has been added, removed, or changed
boolean descriptorContentChanged = true;
if (astAwareIncrementalBuild && file.isAccessible() && file.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO) <= IMarker.SEVERITY_WARNING) {
IResourceAware unit = CeylonBuilder.getUnit(file);
if (unit instanceof ProjectSourceFile) {
ProjectSourceFile projectSourceFile = (ProjectSourceFile) unit;
CompilationUnitDelta delta = projectSourceFile.buildDeltaAgainstModel();
if (delta != null
&& delta.getChanges().getSize() == 0
&& delta.getChildrenDeltas().getSize() == 0) {
descriptorContentChanged = false;
}
}
}
if (descriptorContentChanged) {
mustDoFullBuild.value = true;
if (fileName.equals(ModuleManager.MODULE_FILE)) {
mustResolveClasspathContainer.value = true;
}
}
}
}
if (fileName.equals(".classpath") ||
fileName.equals("config")) {
//the classpath changed
mustDoFullBuild.value = true;
mustResolveClasspathContainer.value = true;
}
if (isSourceFile(file) ||
isResourceFile(file)) {
// a source file or a resource was modified,
// we should at least compile incrementally
somethingToBuild.value = true;
}
}
return true;
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_builder_DeltaScanner.java |
617 | public class IndicesStatsAction extends IndicesAction<IndicesStatsRequest, IndicesStatsResponse, IndicesStatsRequestBuilder> {
public static final IndicesStatsAction INSTANCE = new IndicesStatsAction();
public static final String NAME = "indices/stats";
private IndicesStatsAction() {
super(NAME);
}
@Override
public IndicesStatsResponse newResponse() {
return new IndicesStatsResponse();
}
@Override
public IndicesStatsRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new IndicesStatsRequestBuilder(client);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_stats_IndicesStatsAction.java |
470 | public class ExpirationKCVSCache extends KCVSCache {
private static final Logger log =
LoggerFactory.getLogger(ExpirationKCVSCache.class);
//Weight estimation
private static final int STATICARRAYBUFFER_SIZE = STATICARRAYBUFFER_RAW_SIZE + 10; // 10 = last number is average length
private static final int KEY_QUERY_SIZE = OBJECT_HEADER + 4 + 1 + 3 * (OBJECT_REFERENCE + STATICARRAYBUFFER_SIZE); // object_size + int + boolean + 3 static buffers
private static final int INVALIDATE_KEY_FRACTION_PENALTY = 1000;
private static final int PENALTY_THRESHOLD = 5;
private volatile CountDownLatch penaltyCountdown;
private final Cache<KeySliceQuery,EntryList> cache;
private final ConcurrentHashMap<StaticBuffer,Long> expiredKeys;
private final long cacheTimeMS;
private final long invalidationGracePeriodMS;
private final CleanupThread cleanupThread;
public ExpirationKCVSCache(final KeyColumnValueStore store, String metricsName, final long cacheTimeMS, final long invalidationGracePeriodMS, final long maximumByteSize) {
super(store, metricsName);
Preconditions.checkArgument(cacheTimeMS > 0, "Cache expiration must be positive: %s", cacheTimeMS);
Preconditions.checkArgument(System.currentTimeMillis()+1000l*3600*24*365*100+cacheTimeMS>0,"Cache expiration time too large, overflow may occur: %s",cacheTimeMS);
this.cacheTimeMS = cacheTimeMS;
int concurrencyLevel = Runtime.getRuntime().availableProcessors();
Preconditions.checkArgument(invalidationGracePeriodMS >=0,"Invalid expiration grace peiod: %s", invalidationGracePeriodMS);
this.invalidationGracePeriodMS = invalidationGracePeriodMS;
CacheBuilder<KeySliceQuery,EntryList> cachebuilder = CacheBuilder.newBuilder()
.maximumWeight(maximumByteSize)
.concurrencyLevel(concurrencyLevel)
.initialCapacity(1000)
.expireAfterWrite(cacheTimeMS, TimeUnit.MILLISECONDS)
.weigher(new Weigher<KeySliceQuery, EntryList>() {
@Override
public int weigh(KeySliceQuery keySliceQuery, EntryList entries) {
return GUAVA_CACHE_ENTRY_SIZE + KEY_QUERY_SIZE + entries.getByteSize();
}
});
cache = cachebuilder.build();
expiredKeys = new ConcurrentHashMap<StaticBuffer, Long>(50,0.75f,concurrencyLevel);
penaltyCountdown = new CountDownLatch(PENALTY_THRESHOLD);
cleanupThread = new CleanupThread();
cleanupThread.start();
}
@Override
public EntryList getSlice(final KeySliceQuery query, final StoreTransaction txh) throws BackendException {
incActionBy(1, CacheMetricsAction.RETRIEVAL,txh);
if (isExpired(query)) {
incActionBy(1, CacheMetricsAction.MISS,txh);
return store.getSlice(query, unwrapTx(txh));
}
try {
return cache.get(query,new Callable<EntryList>() {
@Override
public EntryList call() throws Exception {
incActionBy(1, CacheMetricsAction.MISS,txh);
return store.getSlice(query, unwrapTx(txh));
}
});
} catch (Exception e) {
if (e instanceof TitanException) throw (TitanException)e;
else if (e.getCause() instanceof TitanException) throw (TitanException)e.getCause();
else throw new TitanException(e);
}
}
@Override
public Map<StaticBuffer,EntryList> getSlice(final List<StaticBuffer> keys, final SliceQuery query, final StoreTransaction txh) throws BackendException {
Map<StaticBuffer,EntryList> results = new HashMap<StaticBuffer, EntryList>(keys.size());
List<StaticBuffer> remainingKeys = new ArrayList<StaticBuffer>(keys.size());
KeySliceQuery[] ksqs = new KeySliceQuery[keys.size()];
incActionBy(keys.size(), CacheMetricsAction.RETRIEVAL,txh);
//Find all cached queries
for (int i=0;i<keys.size();i++) {
StaticBuffer key = keys.get(i);
ksqs[i] = new KeySliceQuery(key,query);
EntryList result = null;
if (!isExpired(ksqs[i])) result = cache.getIfPresent(ksqs[i]);
else ksqs[i]=null;
if (result!=null) results.put(key,result);
else remainingKeys.add(key);
}
//Request remaining ones from backend
if (!remainingKeys.isEmpty()) {
incActionBy(remainingKeys.size(), CacheMetricsAction.MISS,txh);
Map<StaticBuffer,EntryList> subresults = store.getSlice(remainingKeys, query, unwrapTx(txh));
for (int i=0;i<keys.size();i++) {
StaticBuffer key = keys.get(i);
EntryList subresult = subresults.get(key);
if (subresult!=null) {
results.put(key,subresult);
if (ksqs[i]!=null) cache.put(ksqs[i],subresult);
}
}
}
return results;
}
@Override
public void clearCache() {
cache.invalidateAll();
expiredKeys.clear();
penaltyCountdown = new CountDownLatch(PENALTY_THRESHOLD);
}
@Override
public void invalidate(StaticBuffer key, List<CachableStaticBuffer> entries) {
Preconditions.checkArgument(!hasValidateKeysOnly() || entries.isEmpty());
expiredKeys.put(key,getExpirationTime());
if (Math.random()<1.0/INVALIDATE_KEY_FRACTION_PENALTY) penaltyCountdown.countDown();
}
@Override
public void close() throws BackendException {
cleanupThread.stopThread();
super.close();
}
private boolean isExpired(final KeySliceQuery query) {
Long until = expiredKeys.get(query.getKey());
if (until==null) return false;
if (isBeyondExpirationTime(until)) {
expiredKeys.remove(query.getKey(),until);
return false;
}
//We suffer a cache miss, hence decrease the count down
penaltyCountdown.countDown();
return true;
}
private final long getExpirationTime() {
return System.currentTimeMillis()+cacheTimeMS;
}
private final boolean isBeyondExpirationTime(long until) {
return until<System.currentTimeMillis();
}
private final long getAge(long until) {
long age = System.currentTimeMillis() - (until-cacheTimeMS);
assert age>=0;
return age;
}
private class CleanupThread extends Thread {
private boolean stop = false;
public CleanupThread() {
this.setDaemon(true);
this.setName("ExpirationStoreCache-" + getId());
}
@Override
public void run() {
while (true) {
if (stop) return;
try {
penaltyCountdown.await();
} catch (InterruptedException e) {
if (stop) return;
else throw new RuntimeException("Cleanup thread got interrupted",e);
}
//Do clean up work by invalidating all entries for expired keys
HashMap<StaticBuffer,Long> expiredKeysCopy = new HashMap<StaticBuffer,Long>(expiredKeys.size());
for (Map.Entry<StaticBuffer,Long> expKey : expiredKeys.entrySet()) {
if (isBeyondExpirationTime(expKey.getValue()))
expiredKeys.remove(expKey.getKey(), expKey.getValue());
else if (getAge(expKey.getValue())>= invalidationGracePeriodMS)
expiredKeysCopy.put(expKey.getKey(),expKey.getValue());
}
for (KeySliceQuery ksq : cache.asMap().keySet()) {
if (expiredKeysCopy.containsKey(ksq.getKey())) cache.invalidate(ksq);
}
penaltyCountdown = new CountDownLatch(PENALTY_THRESHOLD);
for (Map.Entry<StaticBuffer,Long> expKey : expiredKeysCopy.entrySet()) {
expiredKeys.remove(expKey.getKey(),expKey.getValue());
}
}
}
void stopThread() {
stop = true;
this.interrupt();
}
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_cache_ExpirationKCVSCache.java |
2,409 | public interface ByteArray extends BigArray {
/**
* Get an element given its index.
*/
public abstract byte get(long index);
/**
* Set a value at the given index and return the previous value.
*/
public abstract byte set(long index, byte value);
/**
* Get a reference to a slice.
*/
public abstract void get(long index, int len, BytesRef ref);
/**
* Bulk set.
*/
public abstract void set(long index, byte[] buf, int offset, int len);
} | 0true
| src_main_java_org_elasticsearch_common_util_ByteArray.java |
13 | final class AscendingEntrySetView extends EntrySetView {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new SubMapEntryIterator(absLowest(), absHighFence());
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
929 | makeDbCall(iOtherDb, new ODbRelatedCall<Object>() {
public Object call() {
iOther.checkForFields();
return null;
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java |
1,223 | public class SimplePaymentProcessContextFactory implements ProcessContextFactory {
public ProcessContext createContext(Object seedData) throws WorkflowException {
if(!(seedData instanceof PaymentSeed)){
throw new WorkflowException("Seed data instance is incorrect. " +
"Required class is "+PaymentSeed.class.getName()+" " +
"but found class: "+seedData.getClass().getName());
}
SimplePaymentContext response = new SimplePaymentContext();
response.setSeedData(seedData);
return response;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_workflow_SimplePaymentProcessContextFactory.java |
1,153 | iMethodParams = OMultiValue.array(iMethodParams, Object.class, new OCallable<Object, Object>() {
@Override
public Object call(final Object iArgument) {
if (iArgument instanceof String && ((String) iArgument).startsWith("$"))
return iContext.getVariable((String) iArgument);
return iArgument;
}
}); | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodRemove.java |
546 | public abstract class ORecordHookAbstract implements ORecordHook {
/**
* It's called just before to create the new iRecord.
*
* @param iiRecord
* The iRecord to create
* @return True if the iRecord has been modified and a new marshalling is required, otherwise false
*/
public RESULT onRecordBeforeCreate(final ORecord<?> iiRecord) {
return RESULT.RECORD_NOT_CHANGED;
}
/**
* It's called just after the iRecord is created.
*
* @param iiRecord
* The iRecord just created
*/
public void onRecordAfterCreate(final ORecord<?> iiRecord) {
}
public void onRecordCreateFailed(final ORecord<?> iiRecord) {
}
public void onRecordCreateReplicated(final ORecord<?> iiRecord) {
}
/**
* It's called just before to read the iRecord.
*
* @param iRecord
* The iRecord to read
* @return
*/
public RESULT onRecordBeforeRead(final ORecord<?> iRecord) {
return RESULT.RECORD_NOT_CHANGED;
}
/**
* It's called just after the iRecord is read.
*
* @param iiRecord
* The iRecord just read
*/
public void onRecordAfterRead(final ORecord<?> iiRecord) {
}
public void onRecordReadFailed(final ORecord<?> iiRecord) {
}
public void onRecordReadReplicated(final ORecord<?> iiRecord) {
}
/**
* It's called just before to update the iRecord.
*
* @param iiRecord
* The iRecord to update
* @return True if the iRecord has been modified and a new marshalling is required, otherwise false
*/
public RESULT onRecordBeforeUpdate(final ORecord<?> iiRecord) {
return RESULT.RECORD_NOT_CHANGED;
}
/**
* It's called just after the iRecord is updated.
*
* @param iiRecord
* The iRecord just updated
*/
public void onRecordAfterUpdate(final ORecord<?> iiRecord) {
}
public void onRecordUpdateFailed(final ORecord<?> iiRecord) {
}
public void onRecordUpdateReplicated(final ORecord<?> iiRecord) {
}
/**
* It's called just before to delete the iRecord.
*
* @param iiRecord
* The iRecord to delete
* @return True if the iRecord has been modified and a new marshalling is required, otherwise false
*/
public RESULT onRecordBeforeDelete(final ORecord<?> iiRecord) {
return RESULT.RECORD_NOT_CHANGED;
}
/**
* It's called just after the iRecord is deleted.
*
* @param iiRecord
* The iRecord just deleted
*/
public void onRecordAfterDelete(final ORecord<?> iiRecord) {
}
public void onRecordDeleteFailed(final ORecord<?> iiRecord) {
}
public void onRecordDeleteReplicated(final ORecord<?> iiRecord) {
}
public RESULT onRecordBeforeReplicaAdd(final ORecord<?> record) {
return RESULT.RECORD_NOT_CHANGED;
}
public void onRecordAfterReplicaAdd(final ORecord<?> record) {
}
public void onRecordReplicaAddFailed(final ORecord<?> record) {
}
public RESULT onRecordBeforeReplicaUpdate(final ORecord<?> record) {
return RESULT.RECORD_NOT_CHANGED;
}
public void onRecordAfterReplicaUpdate(final ORecord<?> record) {
}
public void onRecordReplicaUpdateFailed(final ORecord<?> record) {
}
public RESULT onRecordBeforeReplicaDelete(final ORecord<?> record) {
return RESULT.RECORD_NOT_CHANGED;
}
public void onRecordAfterReplicaDelete(final ORecord<?> record) {
}
public void onRecordReplicaDeleteFailed(final ORecord<?> record) {
}
public RESULT onTrigger(final TYPE iType, final ORecord<?> iRecord) {
switch (iType) {
case BEFORE_CREATE:
return onRecordBeforeCreate(iRecord);
case AFTER_CREATE:
onRecordAfterCreate(iRecord);
break;
case CREATE_FAILED:
onRecordCreateFailed(iRecord);
break;
case CREATE_REPLICATED:
onRecordCreateReplicated(iRecord);
break;
case BEFORE_READ:
return onRecordBeforeRead(iRecord);
case AFTER_READ:
onRecordAfterRead(iRecord);
break;
case READ_FAILED:
onRecordReadFailed(iRecord);
break;
case READ_REPLICATED:
onRecordReadReplicated(iRecord);
break;
case BEFORE_UPDATE:
return onRecordBeforeUpdate(iRecord);
case AFTER_UPDATE:
onRecordAfterUpdate(iRecord);
break;
case UPDATE_FAILED:
onRecordUpdateFailed(iRecord);
break;
case UPDATE_REPLICATED:
onRecordUpdateReplicated(iRecord);
break;
case BEFORE_DELETE:
return onRecordBeforeDelete(iRecord);
case AFTER_DELETE:
onRecordAfterDelete(iRecord);
break;
case DELETE_FAILED:
onRecordDeleteFailed(iRecord);
break;
case DELETE_REPLICATED:
onRecordDeleteReplicated(iRecord);
break;
case BEFORE_REPLICA_ADD:
return onRecordBeforeReplicaAdd(iRecord);
case AFTER_REPLICA_ADD:
onRecordAfterReplicaAdd(iRecord);
break;
case REPLICA_ADD_FAILED:
onRecordAfterReplicaAdd(iRecord);
break;
case BEFORE_REPLICA_UPDATE:
return onRecordBeforeReplicaUpdate(iRecord);
case AFTER_REPLICA_UPDATE:
onRecordAfterReplicaUpdate(iRecord);
break;
case REPLICA_UPDATE_FAILED:
onRecordReplicaUpdateFailed(iRecord);
break;
case BEFORE_REPLICA_DELETE:
return onRecordBeforeReplicaDelete(iRecord);
case AFTER_REPLICA_DELETE:
onRecordAfterReplicaDelete(iRecord);
break;
case REPLICA_DELETE_FAILED:
onRecordReplicaDeleteFailed(iRecord);
break;
}
return RESULT.RECORD_NOT_CHANGED;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_hook_ORecordHookAbstract.java |
799 | public class AddAndGetRequest extends AtomicLongRequest {
public AddAndGetRequest() {
}
public AddAndGetRequest(String name, long delta) {
super(name, delta);
}
@Override
protected Operation prepareOperation() {
return new AddAndGetOperation(name, delta);
}
@Override
public int getClassId() {
return AtomicLongPortableHook.ADD_AND_GET;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_AddAndGetRequest.java |
1,053 | public class JobTrackerConfigReadOnly
extends JobTrackerConfig {
JobTrackerConfigReadOnly(JobTrackerConfig jobTrackerConfig) {
super(jobTrackerConfig);
}
@Override
public JobTrackerConfigReadOnly setName(String name) {
throw new UnsupportedOperationException("This config is read-only");
}
@Override
public void setMaxThreadSize(int maxThreadSize) {
throw new UnsupportedOperationException("This config is read-only");
}
@Override
public void setRetryCount(int retryCount) {
throw new UnsupportedOperationException("This config is read-only");
}
@Override
public void setChunkSize(int chunkSize) {
throw new UnsupportedOperationException("This config is read-only");
}
@Override
public void setQueueSize(int queueSize) {
throw new UnsupportedOperationException("This config is read-only");
}
@Override
public void setCommunicateStats(boolean communicateStats) {
throw new UnsupportedOperationException("This config is read-only");
}
@Override
public void setTopologyChangedStrategy(TopologyChangedStrategy topologyChangedStrategy) {
throw new UnsupportedOperationException("This config is read-only");
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_config_JobTrackerConfigReadOnly.java |
1,001 | public class InitRequest extends SemaphoreRequest {
public InitRequest() {
}
public InitRequest(String name, int permitCount) {
super(name, permitCount);
}
@Override
protected Operation prepareOperation() {
return new InitOperation(name, permitCount);
}
@Override
public int getClassId() {
return SemaphorePortableHook.INIT;
}
@Override
public Permission getRequiredPermission() {
return new SemaphorePermission(name, ActionConstants.ACTION_RELEASE);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_semaphore_client_InitRequest.java |
1,142 | public class OSQLMethodCharAt extends OAbstractSQLMethod {
public static final String NAME = "charat";
public OSQLMethodCharAt() {
super(NAME, 1);
}
@Override
public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) {
int index = Integer.parseInt(iMethodParams[0].toString());
ioResult = ioResult != null ? ioResult.toString().substring(index, index + 1) : null;
return ioResult;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodCharAt.java |
216 | public class OConsoleDatabaseListener implements ODatabaseListener {
OConsoleDatabaseApp console;
public OConsoleDatabaseListener(OConsoleDatabaseApp console) {
this.console = console;
}
public void onCreate(ODatabase iDatabase) {
}
public void onDelete(ODatabase iDatabase) {
}
public void onOpen(ODatabase iDatabase) {
}
public void onBeforeTxBegin(ODatabase iDatabase) {
}
public void onBeforeTxRollback(ODatabase iDatabase) {
}
public void onAfterTxRollback(ODatabase iDatabase) {
}
public void onBeforeTxCommit(ODatabase iDatabase) {
}
public void onAfterTxCommit(ODatabase iDatabase) {
}
public void onClose(ODatabase iDatabase) {
}
public boolean onCorruptionRepairDatabase(ODatabase iDatabase, final String iProblem, String iWhatWillbeFixed) {
final String answer = console.ask("\nDatabase seems corrupted:\n> " + iProblem + "\nAuto-repair will execute this action:\n> "
+ iWhatWillbeFixed + "\n\nDo you want to repair it (Y/n)? ");
return answer.length() == 0 || answer.equalsIgnoreCase("Y") || answer.equalsIgnoreCase("Yes");
}
} | 0true
| tools_src_main_java_com_orientechnologies_orient_console_OConsoleDatabaseListener.java |
199 | public class ODatabaseHelper {
public static void createDatabase(ODatabase database, final String url) throws IOException {
createDatabase(database, url, "server", "plocal");
}
public static void createDatabase(ODatabase database, final String url, String type) throws IOException {
createDatabase(database, url, "server", type);
}
public static void createDatabase(ODatabase database, final String url, String directory, String type) throws IOException {
if (url.startsWith(OEngineRemote.NAME)) {
new OServerAdmin(url).connect("root", getServerRootPassword(directory)).createDatabase("document", type).close();
} else {
database.create();
database.close();
}
}
public static void deleteDatabase(final ODatabase database, String storageType) throws IOException {
deleteDatabase(database, "server", storageType);
}
@Deprecated
public static void deleteDatabase(final ODatabase database, final String directory, String storageType) throws IOException {
dropDatabase(database, directory, storageType);
}
public static void dropDatabase(final ODatabase database, String storageType) throws IOException {
dropDatabase(database, "server", storageType);
}
public static void dropDatabase(final ODatabase database, final String directory, String storageType) throws IOException {
if (existsDatabase(database, storageType)) {
if (database.getURL().startsWith("remote:")) {
new OServerAdmin(database.getURL()).connect("root", getServerRootPassword(directory)).dropDatabase(storageType);
} else {
if (database.isClosed())
database.open("admin", "admin");
database.drop();
}
}
}
public static boolean existsDatabase(final ODatabase database, String storageType) throws IOException {
if (database.getURL().startsWith("remote")) {
return new OServerAdmin(database.getURL()).connect("root", getServerRootPassword()).existsDatabase(storageType);
} else {
return database.exists();
}
}
public static void freezeDatabase(final ODatabase database) throws IOException {
if (database.getURL().startsWith("remote")) {
final OServerAdmin serverAdmin = new OServerAdmin(database.getURL());
serverAdmin.connect("root", getServerRootPassword()).freezeDatabase("plocal");
serverAdmin.close();
} else {
database.freeze();
}
}
public static void releaseDatabase(final ODatabase database) throws IOException {
if (database.getURL().startsWith("remote")) {
final OServerAdmin serverAdmin = new OServerAdmin(database.getURL());
serverAdmin.connect("root", getServerRootPassword()).releaseDatabase("plocal");
serverAdmin.close();
} else {
database.release();
}
}
public static File getConfigurationFile() {
return getConfigurationFile(null);
}
protected static String getServerRootPassword() throws IOException {
return getServerRootPassword("server");
}
protected static String getServerRootPassword(final String iDirectory) throws IOException {
File file = getConfigurationFile(iDirectory);
FileReader f = new FileReader(file);
final char[] buffer = new char[(int) file.length()];
f.read(buffer);
f.close();
String fileContent = new String(buffer);
// TODO search is wrong because if first user is not root tests will fail
int pos = fileContent.indexOf("password=\"");
pos += "password=\"".length();
return fileContent.substring(pos, fileContent.indexOf('"', pos));
}
protected static File getConfigurationFile(final String iDirectory) {
// LOAD SERVER CONFIG FILE TO EXTRACT THE ROOT'S PASSWORD
String sysProperty = System.getProperty("orientdb.config.file");
File file = new File(sysProperty != null ? sysProperty : "");
if (!file.exists()) {
sysProperty = System.getenv("CONFIG_FILE");
file = new File(sysProperty != null ? sysProperty : "");
}
if (!file.exists())
file = new File("../releases/orientdb-" + OConstants.ORIENT_VERSION + "/config/orientdb-server-config.xml");
if (!file.exists())
file = new File("../releases/orientdb-community-" + OConstants.ORIENT_VERSION + "/config/orientdb-server-config.xml");
if (!file.exists())
file = new File("../../releases/orientdb-" + OConstants.ORIENT_VERSION + "/config/orientdb-server-config.xml");
if (!file.exists())
file = new File("../../releases/orientdb-community-" + OConstants.ORIENT_VERSION + "/config/orientdb-server-config.xml");
if (!file.exists() && iDirectory != null) {
file = new File(iDirectory + "/config/orientdb-server-config.xml");
if (!file.exists())
file = new File("../" + iDirectory + "/config/orientdb-server-config.xml");
}
if (!file.exists())
file = new File(OSystemVariableResolver.resolveSystemVariables("${" + Orient.ORIENTDB_HOME
+ "}/config/orientdb-server-config.xml"));
if (!file.exists())
throw new OConfigurationException(
"Cannot load file orientdb-server-config.xml to execute remote tests. Current directory is "
+ new File(".").getAbsolutePath());
return file;
}
} | 0true
| client_src_main_java_com_orientechnologies_orient_client_db_ODatabaseHelper.java |
1,641 | public class MapConfigRequest implements ConsoleRequest {
private String map;
private MapConfig config;
private boolean update;
private Address target;
public MapConfigRequest() {
}
public MapConfigRequest(String map, MapConfig config) {
this.map = map;
this.config = config;
this.update = true;
}
public MapConfigRequest(String map, Address target) {
this.map = map;
this.target = target;
this.update = false;
}
public Address getTarget() {
return target;
}
public void setTarget(Address target) {
this.target = target;
}
@Override
public int getType() {
return ConsoleRequestConstants.REQUEST_TYPE_MAP_CONFIG;
}
@Override
public void writeResponse(ManagementCenterService mcs, ObjectDataOutput dos)
throws Exception {
dos.writeBoolean(update);
if (update) {
final Set<Member> members = mcs.getHazelcastInstance().getCluster().getMembers();
for (Member member : members) {
mcs.callOnMember(member, new UpdateMapConfigOperation(map, config));
}
dos.writeUTF("success");
} else {
MapConfig cfg = (MapConfig) mcs.callOnAddress(target, new GetMapConfigOperation(map));
if (cfg != null) {
dos.writeBoolean(true);
new MapConfigAdapter(cfg).writeData(dos);
} else {
dos.writeBoolean(false);
}
}
}
@Override
public Object readResponse(ObjectDataInput in) throws IOException {
update = in.readBoolean();
if (!update) {
if (in.readBoolean()) {
final MapConfigAdapter adapter = new MapConfigAdapter();
adapter.readData(in);
return adapter.getMapConfig();
} else {
return null;
}
}
return in.readUTF();
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(map);
out.writeBoolean(update);
if (update) {
new MapConfigAdapter(config).writeData(out);
} else {
target.writeData(out);
}
}
@Override
public void readData(ObjectDataInput in) throws IOException {
map = in.readUTF();
update = in.readBoolean();
if (update) {
final MapConfigAdapter adapter = new MapConfigAdapter();
adapter.readData(in);
config = adapter.getMapConfig();
} else {
target = new Address();
target.readData(in);
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_management_request_MapConfigRequest.java |
148 | public class Backend implements LockerProvider {
private static final Logger log = LoggerFactory.getLogger(Backend.class);
/**
* These are the names for the edge store and property index databases, respectively.
* The edge store contains all edges and properties. The property index contains an
* inverted index from attribute value to vertex.
* <p/>
* These names are fixed and should NEVER be changed. Changing these strings can
* disrupt storage adapters that rely on these names for specific configurations.
*/
public static final String EDGESTORE_NAME = "edgestore";
public static final String INDEXSTORE_NAME = "graphindex";
public static final String ID_STORE_NAME = "titan_ids";
public static final String METRICS_MERGED_STORE = "stores";
public static final String METRICS_MERGED_CACHE = "caches";
public static final String METRICS_CACHE_SUFFIX = ".cache";
public static final String LOCK_STORE_SUFFIX = "_lock_";
public static final String SYSTEM_TX_LOG_NAME = "txlog";
public static final String SYSTEM_MGMT_LOG_NAME = "systemlog";
public static final double EDGESTORE_CACHE_PERCENT = 0.8;
public static final double INDEXSTORE_CACHE_PERCENT = 0.2;
private static final long ETERNAL_CACHE_EXPIRATION = 1000l*3600*24*365*200; //200 years
public static final int THREAD_POOL_SIZE_SCALE_FACTOR = 2;
public static final Map<String, Integer> STATIC_KEY_LENGTHS = new HashMap<String, Integer>() {{
put(EDGESTORE_NAME, 8);
put(EDGESTORE_NAME + LOCK_STORE_SUFFIX, 8);
put(ID_STORE_NAME, 8);
}};
private final KeyColumnValueStoreManager storeManager;
private final KeyColumnValueStoreManager storeManagerLocking;
private final StoreFeatures storeFeatures;
private KCVSCache edgeStore;
private KCVSCache indexStore;
private KCVSCache txLogStore;
private IDAuthority idAuthority;
private KCVSConfiguration systemConfig;
private boolean hasAttemptedClose;
private final KCVSLogManager mgmtLogManager;
private final KCVSLogManager txLogManager;
private final LogManager userLogManager;
private final Map<String, IndexProvider> indexes;
private final int bufferSize;
private final Duration maxWriteTime;
private final Duration maxReadTime;
private final boolean cacheEnabled;
private final ExecutorService threadPool;
private final Function<String, Locker> lockerCreator;
private final ConcurrentHashMap<String, Locker> lockers =
new ConcurrentHashMap<String, Locker>();
private final Configuration configuration;
public Backend(Configuration configuration) {
this.configuration = configuration;
storeManager = getStorageManager(configuration);
indexes = getIndexes(configuration);
storeFeatures = storeManager.getFeatures();
mgmtLogManager = getKCVSLogManager(MANAGEMENT_LOG);
txLogManager = getKCVSLogManager(TRANSACTION_LOG);
userLogManager = getLogManager(USER_LOG);
cacheEnabled = !configuration.get(STORAGE_BATCH) && configuration.get(DB_CACHE);
int bufferSizeTmp = configuration.get(BUFFER_SIZE);
Preconditions.checkArgument(bufferSizeTmp > 0, "Buffer size must be positive");
if (!storeFeatures.hasBatchMutation()) {
bufferSize = Integer.MAX_VALUE;
} else bufferSize = bufferSizeTmp;
maxWriteTime = configuration.get(STORAGE_WRITE_WAITTIME);
maxReadTime = configuration.get(STORAGE_READ_WAITTIME);
if (!storeFeatures.hasLocking()) {
Preconditions.checkArgument(storeFeatures.isKeyConsistent(),"Store needs to support some form of locking");
storeManagerLocking = new ExpectedValueCheckingStoreManager(storeManager,LOCK_STORE_SUFFIX,this,maxReadTime);
} else {
storeManagerLocking = storeManager;
}
if (configuration.get(PARALLEL_BACKEND_OPS)) {
int poolsize = Runtime.getRuntime().availableProcessors() * THREAD_POOL_SIZE_SCALE_FACTOR;
threadPool = Executors.newFixedThreadPool(poolsize);
log.info("Initiated backend operations thread pool of size {}", poolsize);
} else {
threadPool = null;
}
final String lockBackendName = configuration.get(LOCK_BACKEND);
if (REGISTERED_LOCKERS.containsKey(lockBackendName)) {
lockerCreator = REGISTERED_LOCKERS.get(lockBackendName);
} else {
throw new TitanConfigurationException("Unknown lock backend \"" +
lockBackendName + "\". Known lock backends: " +
Joiner.on(", ").join(REGISTERED_LOCKERS.keySet()) + ".");
}
// Never used for backends that have innate transaction support, but we
// want to maintain the non-null invariant regardless; it will default
// to connsistentkey impl if none is specified
Preconditions.checkNotNull(lockerCreator);
}
@Override
public Locker getLocker(String lockerName) {
Preconditions.checkNotNull(lockerName);
Locker l = lockers.get(lockerName);
if (null == l) {
l = lockerCreator.apply(lockerName);
final Locker x = lockers.putIfAbsent(lockerName, l);
if (null != x) {
l = x;
}
}
return l;
}
/**
* Initializes this backend with the given configuration. Must be called before this Backend can be used
*
* @param config
*/
public void initialize(Configuration config) {
try {
boolean reportMetrics = configuration.get(BASIC_METRICS);
//EdgeStore & VertexIndexStore
KeyColumnValueStore idStore = storeManager.openDatabase(ID_STORE_NAME);
if (reportMetrics) {
idStore = new MetricInstrumentedStore(idStore, getMetricsStoreName(ID_STORE_NAME));
}
idAuthority = null;
if (storeFeatures.isKeyConsistent()) {
idAuthority = new ConsistentKeyIDAuthority(idStore, storeManager, config);
} else {
throw new IllegalStateException("Store needs to support consistent key or transactional operations for ID manager to guarantee proper id allocations");
}
KeyColumnValueStore edgeStoreRaw = storeManagerLocking.openDatabase(EDGESTORE_NAME);
KeyColumnValueStore indexStoreRaw = storeManagerLocking.openDatabase(INDEXSTORE_NAME);
if (reportMetrics) {
edgeStoreRaw = new MetricInstrumentedStore(edgeStoreRaw, getMetricsStoreName(EDGESTORE_NAME));
indexStoreRaw = new MetricInstrumentedStore(indexStoreRaw, getMetricsStoreName(INDEXSTORE_NAME));
}
//Configure caches
if (cacheEnabled) {
long expirationTime = configuration.get(DB_CACHE_TIME);
Preconditions.checkArgument(expirationTime>=0,"Invalid cache expiration time: %s",expirationTime);
if (expirationTime==0) expirationTime=ETERNAL_CACHE_EXPIRATION;
long cacheSizeBytes;
double cachesize = configuration.get(DB_CACHE_SIZE);
Preconditions.checkArgument(cachesize>0.0,"Invalid cache size specified: %s",cachesize);
if (cachesize<1.0) {
//Its a percentage
Runtime runtime = Runtime.getRuntime();
cacheSizeBytes = (long)((runtime.maxMemory()-(runtime.totalMemory()-runtime.freeMemory())) * cachesize);
} else {
Preconditions.checkArgument(cachesize>1000,"Cache size is too small: %s",cachesize);
cacheSizeBytes = (long)cachesize;
}
log.info("Configuring total store cache size: {}",cacheSizeBytes);
long cleanWaitTime = configuration.get(DB_CACHE_CLEAN_WAIT);
Preconditions.checkArgument(EDGESTORE_CACHE_PERCENT + INDEXSTORE_CACHE_PERCENT == 1.0,"Cache percentages don't add up!");
long edgeStoreCacheSize = Math.round(cacheSizeBytes * EDGESTORE_CACHE_PERCENT);
long indexStoreCacheSize = Math.round(cacheSizeBytes * INDEXSTORE_CACHE_PERCENT);
edgeStore = new ExpirationKCVSCache(edgeStoreRaw,getMetricsCacheName("edgeStore",reportMetrics),expirationTime,cleanWaitTime,edgeStoreCacheSize);
indexStore = new ExpirationKCVSCache(indexStoreRaw,getMetricsCacheName("indexStore",reportMetrics),expirationTime,cleanWaitTime,indexStoreCacheSize);
} else {
edgeStore = new NoKCVSCache(edgeStoreRaw);
indexStore = new NoKCVSCache(indexStoreRaw);
}
//Just open them so that they are cached
txLogManager.openLog(SYSTEM_TX_LOG_NAME);
mgmtLogManager.openLog(SYSTEM_MGMT_LOG_NAME);
txLogStore = new NoKCVSCache(storeManager.openDatabase(SYSTEM_TX_LOG_NAME));
//Open global configuration
KeyColumnValueStore systemConfigStore = storeManagerLocking.openDatabase(SYSTEM_PROPERTIES_STORE_NAME);
systemConfig = getGlobalConfiguration(new BackendOperation.TransactionalProvider() {
@Override
public StoreTransaction openTx() throws BackendException {
return storeManagerLocking.beginTransaction(StandardBaseTransactionConfig.of(
configuration.get(TIMESTAMP_PROVIDER),
storeFeatures.getKeyConsistentTxConfig()));
}
@Override
public void close() throws BackendException {
//Do nothing, storeManager is closed explicitly by Backend
}
},systemConfigStore,configuration);
} catch (BackendException e) {
throw new TitanException("Could not initialize backend", e);
}
}
/**
* Get information about all registered {@link IndexProvider}s.
*
* @return
*/
public Map<String, IndexInformation> getIndexInformation() {
ImmutableMap.Builder<String, IndexInformation> copy = ImmutableMap.builder();
copy.putAll(indexes);
return copy.build();
}
//
// public IndexProvider getIndexProvider(String name) {
// return indexes.get(name);
// }
public KCVSLog getSystemTxLog() {
try {
return txLogManager.openLog(SYSTEM_TX_LOG_NAME);
} catch (BackendException e) {
throw new TitanException("Could not re-open transaction log", e);
}
}
public Log getSystemMgmtLog() {
try {
return mgmtLogManager.openLog(SYSTEM_MGMT_LOG_NAME);
} catch (BackendException e) {
throw new TitanException("Could not re-open management log", e);
}
}
public Log getUserLog(String identifier) throws BackendException {
return userLogManager.openLog(getUserLogName(identifier));
}
public static final String getUserLogName(String identifier) {
Preconditions.checkArgument(StringUtils.isNotBlank(identifier));
return USER_LOG_PREFIX +identifier;
}
public KCVSConfiguration getGlobalSystemConfig() {
return systemConfig;
}
private String getMetricsStoreName(String storeName) {
return configuration.get(METRICS_MERGE_STORES) ? METRICS_MERGED_STORE : storeName;
}
private String getMetricsCacheName(String storeName, boolean reportMetrics) {
if (!reportMetrics) return null;
return configuration.get(METRICS_MERGE_STORES) ? METRICS_MERGED_CACHE : storeName + METRICS_CACHE_SUFFIX;
}
public KCVSLogManager getKCVSLogManager(String logName) {
Preconditions.checkArgument(configuration.restrictTo(logName).get(LOG_BACKEND).equalsIgnoreCase(LOG_BACKEND.getDefaultValue()));
return (KCVSLogManager)getLogManager(logName);
}
public LogManager getLogManager(String logName) {
return getLogManager(configuration, logName, storeManager);
}
private static LogManager getLogManager(Configuration config, String logName, KeyColumnValueStoreManager sm) {
Configuration logConfig = config.restrictTo(logName);
String backend = logConfig.get(LOG_BACKEND);
if (backend.equalsIgnoreCase(LOG_BACKEND.getDefaultValue())) {
return new KCVSLogManager(sm,logConfig);
} else {
Preconditions.checkArgument(config!=null);
LogManager lm = getImplementationClass(logConfig,logConfig.get(LOG_BACKEND),REGISTERED_LOG_MANAGERS);
Preconditions.checkNotNull(lm);
return lm;
}
}
public static KeyColumnValueStoreManager getStorageManager(Configuration storageConfig) {
StoreManager manager = getImplementationClass(storageConfig, storageConfig.get(STORAGE_BACKEND),
REGISTERED_STORAGE_MANAGERS);
if (manager instanceof OrderedKeyValueStoreManager) {
manager = new OrderedKeyValueStoreManagerAdapter((OrderedKeyValueStoreManager) manager, STATIC_KEY_LENGTHS);
}
Preconditions.checkArgument(manager instanceof KeyColumnValueStoreManager,"Invalid storage manager: %s",manager.getClass());
return (KeyColumnValueStoreManager) manager;
}
private static KCVSConfiguration getGlobalConfiguration(final BackendOperation.TransactionalProvider txProvider,
final KeyColumnValueStore store,
final Configuration config) {
try {
KCVSConfiguration kcvsConfig = new KCVSConfiguration(txProvider,config.get(TIMESTAMP_PROVIDER),store,SYSTEM_CONFIGURATION_IDENTIFIER);
kcvsConfig.setMaxOperationWaitTime(config.get(SETUP_WAITTIME));
return kcvsConfig;
} catch (BackendException e) {
throw new TitanException("Could not open global configuration",e);
}
}
public static KCVSConfiguration getStandaloneGlobalConfiguration(final KeyColumnValueStoreManager manager,
final Configuration config) {
try {
final StoreFeatures features = manager.getFeatures();
return getGlobalConfiguration(new BackendOperation.TransactionalProvider() {
@Override
public StoreTransaction openTx() throws BackendException {
return manager.beginTransaction(StandardBaseTransactionConfig.of(config.get(TIMESTAMP_PROVIDER),features.getKeyConsistentTxConfig()));
}
@Override
public void close() throws BackendException {
manager.close();
}
},manager.openDatabase(SYSTEM_PROPERTIES_STORE_NAME),config);
} catch (BackendException e) {
throw new TitanException("Could not open global configuration",e);
}
}
private final static Map<String, IndexProvider> getIndexes(Configuration config) {
ImmutableMap.Builder<String, IndexProvider> builder = ImmutableMap.builder();
for (String index : config.getContainedNamespaces(INDEX_NS)) {
Preconditions.checkArgument(StringUtils.isNotBlank(index), "Invalid index name [%s]", index);
log.info("Configuring index [{}]", index);
IndexProvider provider = getImplementationClass(config.restrictTo(index), config.get(INDEX_BACKEND,index),
REGISTERED_INDEX_PROVIDERS);
Preconditions.checkNotNull(provider);
builder.put(index, provider);
}
return builder.build();
}
public final static <T> T getImplementationClass(Configuration config, String clazzname, Map<String, String> registeredImpls) {
if (registeredImpls.containsKey(clazzname.toLowerCase())) {
clazzname = registeredImpls.get(clazzname.toLowerCase());
}
return ConfigurationUtil.instantiate(clazzname, new Object[]{config}, new Class[]{Configuration.class});
}
/**
* Returns the configured {@link IDAuthority}.
*
* @return
*/
public IDAuthority getIDAuthority() {
Preconditions.checkNotNull(idAuthority, "Backend has not yet been initialized");
return idAuthority;
}
/**
* Returns the {@link StoreFeatures} of the configured backend storage engine.
*
* @return
*/
public StoreFeatures getStoreFeatures() {
return storeFeatures;
}
/**
* Returns the {@link IndexFeatures} of all configured index backends
*/
public Map<String,IndexFeatures> getIndexFeatures() {
return Maps.transformValues(indexes,new Function<IndexProvider, IndexFeatures>() {
@Nullable
@Override
public IndexFeatures apply(@Nullable IndexProvider indexProvider) {
return indexProvider.getFeatures();
}
});
}
/**
* Opens a new transaction against all registered backend system wrapped in one {@link BackendTransaction}.
*
* @return
* @throws BackendException
*/
public BackendTransaction beginTransaction(TransactionConfiguration configuration, KeyInformation.Retriever indexKeyRetriever) throws BackendException {
StoreTransaction tx = storeManagerLocking.beginTransaction(configuration);
// Cache
CacheTransaction cacheTx = new CacheTransaction(tx, storeManagerLocking, bufferSize, maxWriteTime, configuration.hasEnabledBatchLoading());
// Index transactions
Map<String, IndexTransaction> indexTx = new HashMap<String, IndexTransaction>(indexes.size());
for (Map.Entry<String, IndexProvider> entry : indexes.entrySet()) {
indexTx.put(entry.getKey(), new IndexTransaction(entry.getValue(), indexKeyRetriever.get(entry.getKey()), configuration, maxWriteTime));
}
return new BackendTransaction(cacheTx, configuration, storeFeatures,
edgeStore, indexStore, txLogStore,
maxReadTime, indexTx, threadPool);
}
public synchronized void close() throws BackendException {
if (!hasAttemptedClose) {
hasAttemptedClose = true;
mgmtLogManager.close();
txLogManager.close();
userLogManager.close();
edgeStore.close();
indexStore.close();
idAuthority.close();
systemConfig.close();
storeManager.close();
if(threadPool != null) {
threadPool.shutdown();
}
//Indexes
for (IndexProvider index : indexes.values()) index.close();
} else {
log.debug("Backend {} has already been closed or cleared", this);
}
}
/**
* Clears the storage of all registered backend data providers. This includes backend storage engines and index providers.
* <p/>
* IMPORTANT: Clearing storage means that ALL data will be lost and cannot be recovered.
*
* @throws BackendException
*/
public synchronized void clearStorage() throws BackendException {
if (!hasAttemptedClose) {
hasAttemptedClose = true;
mgmtLogManager.close();
txLogManager.close();
userLogManager.close();
edgeStore.close();
indexStore.close();
idAuthority.close();
systemConfig.close();
storeManager.clearStorage();
storeManager.close();
//Indexes
for (IndexProvider index : indexes.values()) {
index.clearStorage();
index.close();
}
} else {
log.debug("Backend {} has already been closed or cleared", this);
}
}
//############ Registered Storage Managers ##############
private static final ImmutableMap<String, String> REGISTERED_STORAGE_MANAGERS;
static {
ImmutableMap.Builder<String, String> b = ImmutableMap.builder();
b.put("berkeleyje", "com.thinkaurelius.titan.diskstorage.berkeleyje.BerkeleyJEStoreManager");
b.put("infinispan", "com.thinkaurelius.titan.diskstorage.infinispan.InfinispanCacheStoreManager");
b.put("cassandrathrift", "com.thinkaurelius.titan.diskstorage.cassandra.thrift.CassandraThriftStoreManager");
b.put("cassandra", "com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager");
b.put("astyanax", "com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager");
b.put("hbase", "com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager");
b.put("embeddedcassandra", "com.thinkaurelius.titan.diskstorage.cassandra.embedded.CassandraEmbeddedStoreManager");
b.put("inmemory", "com.thinkaurelius.titan.diskstorage.keycolumnvalue.inmemory.InMemoryStoreManager");
REGISTERED_STORAGE_MANAGERS = b.build();
}
public static final Map<String, String> getRegisteredStoreManagers() {
return REGISTERED_STORAGE_MANAGERS;
}
public static final Map<String, ConfigOption> REGISTERED_STORAGE_MANAGERS_SHORTHAND = new HashMap<String, ConfigOption>() {{
put("berkeleyje", STORAGE_DIRECTORY);
put("hazelcast", STORAGE_DIRECTORY);
put("hazelcastcache", STORAGE_DIRECTORY);
put("infinispan", STORAGE_DIRECTORY);
put("cassandra", STORAGE_HOSTS);
put("cassandrathrift", STORAGE_HOSTS);
put("astyanax", STORAGE_HOSTS);
put("hbase", STORAGE_HOSTS);
put("embeddedcassandra", STORAGE_CONF_FILE);
put("inmemory", null);
}};
public static final Map<String, String> REGISTERED_INDEX_PROVIDERS = new HashMap<String, String>() {{
put("lucene", "com.thinkaurelius.titan.diskstorage.lucene.LuceneIndex");
put("elasticsearch", "com.thinkaurelius.titan.diskstorage.es.ElasticSearchIndex");
put("es", "com.thinkaurelius.titan.diskstorage.es.ElasticSearchIndex");
put("solr", "com.thinkaurelius.titan.diskstorage.solr.SolrIndex");
}};
public static final Map<String,String> REGISTERED_LOG_MANAGERS = new HashMap<String, String>() {{
put("default","com.thinkaurelius.titan.diskstorage.log.kcvs.KCVSLogManager");
}};
private final Function<String, Locker> CONSISTENT_KEY_LOCKER_CREATOR = new Function<String, Locker>() {
@Override
public Locker apply(String lockerName) {
KeyColumnValueStore lockerStore;
try {
lockerStore = storeManager.openDatabase(lockerName);
} catch (BackendException e) {
throw new TitanConfigurationException("Could not retrieve store named " + lockerName + " for locker configuration", e);
}
return new ConsistentKeyLocker.Builder(lockerStore, storeManager).fromConfig(configuration).build();
}
};
private final Function<String, Locker> ASTYANAX_RECIPE_LOCKER_CREATOR = new Function<String, Locker>() {
@Override
public Locker apply(String lockerName) {
String expectedManagerName = "com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager";
String actualManagerName = storeManager.getClass().getCanonicalName();
// Require AstyanaxStoreManager
Preconditions.checkArgument(expectedManagerName.equals(actualManagerName),
"Astyanax Recipe locker is only supported with the Astyanax storage backend (configured:"
+ actualManagerName + " != required:" + expectedManagerName + ")");
try {
Class<?> c = storeManager.getClass();
Method method = c.getMethod("openLocker", String.class);
Object o = method.invoke(storeManager, lockerName);
return (Locker) o;
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Could not find method when configuring locking with Astyanax Recipes");
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Could not access method when configuring locking with Astyanax Recipes", e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException("Could not invoke method when configuring locking with Astyanax Recipes", e);
}
}
};
private final Function<String, Locker> TEST_LOCKER_CREATOR = new Function<String, Locker>() {
@Override
public Locker apply(String lockerName) {
return openManagedLocker("com.thinkaurelius.titan.diskstorage.util.TestLockerManager",lockerName);
}
};
private final Map<String, Function<String, Locker>> REGISTERED_LOCKERS = ImmutableMap.of(
"consistentkey", CONSISTENT_KEY_LOCKER_CREATOR,
"astyanaxrecipe", ASTYANAX_RECIPE_LOCKER_CREATOR,
"test", TEST_LOCKER_CREATOR
);
private static Locker openManagedLocker(String classname, String lockerName) {
try {
Class c = Class.forName(classname);
Constructor constructor = c.getConstructor();
Object instance = constructor.newInstance();
Method method = c.getMethod("openLocker", String.class);
Object o = method.invoke(instance, lockerName);
return (Locker) o;
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Could not find implementation class: " + classname);
} catch (InstantiationException e) {
throw new IllegalArgumentException("Could not instantiate implementation: " + classname, e);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Could not find method when configuring locking for: " + classname,e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Could not access method when configuring locking for: " + classname,e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException("Could not invoke method when configuring locking for: " + classname,e);
} catch (ClassCastException e) {
throw new IllegalArgumentException("Could not instantiate implementation: " + classname, e);
}
}
static {
Properties props;
try {
props = new Properties();
InputStream in = TitanFactory.class.getClassLoader().getResourceAsStream(TitanConstants.TITAN_PROPERTIES_FILE);
if (in != null && in.available() > 0) {
props.load(in);
}
} catch (IOException e) {
throw new AssertionError(e);
}
registerShorthands(props, "storage.", REGISTERED_STORAGE_MANAGERS);
registerShorthands(props, "index.", REGISTERED_INDEX_PROVIDERS);
}
public static final void registerShorthands(Properties props, String prefix, Map<String, String> shorthands) {
for (String key : props.stringPropertyNames()) {
if (key.toLowerCase().startsWith(prefix)) {
String shorthand = key.substring(prefix.length()).toLowerCase();
String clazz = props.getProperty(key);
shorthands.put(shorthand, clazz);
log.debug("Registering shorthand [{}] for [{}]", shorthand, clazz);
}
}
}
//
// public synchronized static final void registerStorageManager(String name, Class<? extends StoreManager> clazz) {
// Preconditions.checkNotNull(name);
// Preconditions.checkNotNull(clazz);
// Preconditions.checkArgument(!StringUtils.isEmpty(name));
// Preconditions.checkNotNull(!REGISTERED_STORAGE_MANAGERS.containsKey(name),"A storage manager has already been registered for name: " + name);
// REGISTERED_STORAGE_MANAGERS.put(name,clazz);
// }
//
// public synchronized static final void removeStorageManager(String name) {
// Preconditions.checkNotNull(name);
// REGISTERED_STORAGE_MANAGERS.remove(name);
// }
} | 1no label
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java |
395 | public final class BankersRounding {
public static final int DEFAULT_SCALE = 2;
public static final BigDecimal ZERO = setScale(0);
public static int getScaleForCurrency(Currency currency) {
if (currency != null) {
return currency.getDefaultFractionDigits();
} else {
return DEFAULT_SCALE;
}
}
public static BigDecimal setScale(int scale, BigDecimal amount) {
return amount.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
}
public static BigDecimal setScale(int scale, double amount) {
return setScale(scale, new BigDecimal(amount));
}
public static double multiply(int scale, double multiplicand, double multiplier) {
return setScale(scale, multiplicand).multiply(setScale(scale, multiplier)).doubleValue();
}
public static BigDecimal divide(int scale, BigDecimal dividend, BigDecimal divisor) {
return dividend.divide(divisor, scale, BigDecimal.ROUND_HALF_EVEN);
}
public static double divide(int scale, double dividend, double divisor) {
return divide(setScale(scale, dividend), setScale(scale, divisor)).doubleValue();
}
public static BigDecimal setScale(BigDecimal amount) {
return setScale(DEFAULT_SCALE, amount);
}
public static BigDecimal setScale(BigDecimal amount, int scale) {
return setScale(scale, amount);
}
public static BigDecimal setScale(double amount) {
return setScale(DEFAULT_SCALE, new BigDecimal(amount));
}
public static BigDecimal divide(BigDecimal dividend, BigDecimal divisor) {
return divide(DEFAULT_SCALE, dividend, divisor);
}
public static BigDecimal zeroAmount() {
return ZERO;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_money_BankersRounding.java |
397 | context.getExecutionService().execute(new Runnable() {
public void run() {
try {
TreeSet<CacheRecord<K>> records = new TreeSet<CacheRecord<K>>(comparator);
records.addAll(cache.values());
int evictSize = cache.size() * EVICTION_PERCENTAGE / 100;
int i = 0;
for (CacheRecord<K> record : records) {
cache.remove(record.key);
if (++i > evictSize) {
break;
}
}
} finally {
canEvict.set(true);
}
}
}); | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_nearcache_ClientNearCache.java |
46 | public class TouchCommandProcessor extends MemcacheCommandProcessor<TouchCommand> {
private final ILogger logger;
public TouchCommandProcessor(TextCommandServiceImpl textCommandService) {
super(textCommandService);
logger = textCommandService.getNode().getLogger(this.getClass().getName());
}
public void handle(TouchCommand touchCommand) {
String key = null;
try {
key = URLDecoder.decode(touchCommand.getKey(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new HazelcastException(e);
}
String mapName = DEFAULT_MAP_NAME;
int index = key.indexOf(':');
if (index != -1) {
mapName = MAP_NAME_PRECEDER + key.substring(0, index);
key = key.substring(index + 1);
}
int ttl = textCommandService.getAdjustedTTLSeconds(touchCommand.getExpiration());
try {
textCommandService.lock(mapName, key);
} catch (Exception e) {
touchCommand.setResponse(NOT_STORED);
if (touchCommand.shouldReply()) {
textCommandService.sendResponse(touchCommand);
}
return;
}
final Object value = textCommandService.get(mapName, key);
textCommandService.incrementTouchCount();
if (value != null) {
textCommandService.put(mapName, key, value, ttl);
touchCommand.setResponse(TOUCHED);
} else {
touchCommand.setResponse(NOT_STORED);
}
textCommandService.unlock(mapName, key);
if (touchCommand.shouldReply()) {
textCommandService.sendResponse(touchCommand);
}
}
public void handleRejection(TouchCommand request) {
request.setResponse(NOT_STORED);
if (request.shouldReply()) {
textCommandService.sendResponse(request);
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_ascii_memcache_TouchCommandProcessor.java |
1,388 | @Test
public class OMVRBTreeDatabaseLazySaveCompositeTest extends OMVRBTreeCompositeTest {
private ODatabaseDocumentTx database;
private int oldPageSize;
private int oldEntryPoints;
@BeforeClass
public void beforeClass() {
oldPageSize = OGlobalConfiguration.MVRBTREE_NODE_PAGE_SIZE.getValueAsInteger();
OGlobalConfiguration.MVRBTREE_NODE_PAGE_SIZE.setValue(4);
oldEntryPoints = OGlobalConfiguration.MVRBTREE_ENTRYPOINTS.getValueAsInteger();
OGlobalConfiguration.MVRBTREE_ENTRYPOINTS.setValue(1);
database = new ODatabaseDocumentTx("memory:mvrbtreeindextest").create();
database.addCluster("indextestclsuter", OStorage.CLUSTER_TYPE.MEMORY);
}
@AfterClass
public void afterClass() {
database.drop();
OGlobalConfiguration.MVRBTREE_NODE_PAGE_SIZE.setValue(oldPageSize);
OGlobalConfiguration.MVRBTREE_ENTRYPOINTS.setValue(oldEntryPoints);
}
@BeforeMethod
@Override
public void beforeMethod() throws Exception {
tree = new OMVRBTreeDatabaseLazySave<OCompositeKey, Double>("indextestclsuter", OCompositeKeySerializer.INSTANCE,
OStreamSerializerLiteral.INSTANCE, 2, 5000);
for (double i = 1; i < 4; i++) {
for (double j = 1; j < 10; j++) {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey(i);
compositeKey.addKey(j);
tree.put(compositeKey, i * 4 + j);
}
}
((OMVRBTreeDatabaseLazySave<OCompositeKey, Double>) tree).save();
((OMVRBTreeDatabaseLazySave<OCompositeKey, Double>) tree).optimize(true);
}
} | 0true
| core_src_test_java_com_orientechnologies_orient_core_type_tree_OMVRBTreeDatabaseLazySaveCompositeTest.java |
1,912 | public interface SizeEstimator<T> {
long getSize();
void add(long size);
long getCost(T record);
void reset();
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_SizeEstimator.java |
1,643 | public class FieldMetadataProviderAdapter extends AbstractFieldMetadataProvider {
@Override
public FieldProviderResponse addMetadata(AddMetadataRequest addMetadataRequest, Map<String, FieldMetadata> metadata) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public FieldProviderResponse lateStageAddMetadata(LateStageAddMetadataRequest addMetadataRequest, Map<String, FieldMetadata> metadata) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public FieldProviderResponse overrideViaAnnotation(OverrideViaAnnotationRequest overrideViaAnnotationRequest, Map<String, FieldMetadata> metadata) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public FieldProviderResponse overrideViaXml(OverrideViaXmlRequest overrideViaXmlRequest, Map<String, FieldMetadata> metadata) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public FieldProviderResponse addMetadataFromMappingData(AddMetadataFromMappingDataRequest addMetadataFromMappingDataRequest, FieldMetadata metadata) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public FieldProviderResponse addMetadataFromFieldType(AddMetadataFromFieldTypeRequest addMetadataFromFieldTypeRequest, Map<String, FieldMetadata> metadata) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
} | 0true
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_dao_provider_metadata_FieldMetadataProviderAdapter.java |
721 | preFetchedValues.add(new Map.Entry<K, V>() {
@Override
public K getKey() {
return entry.getKey();
}
@Override
public V getValue() {
return entry.getValue();
}
@Override
public V setValue(V v) {
throw new UnsupportedOperationException("setValue");
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_sbtree_OSBTreeInverseMapEntryIterator.java |
111 | public class TestDeadlockDetection
{
@Test
public void testDeadlockDetection() throws Exception
{
ResourceObject r1 = newResourceObject( "R1" );
ResourceObject r2 = newResourceObject( "R2" );
ResourceObject r3 = newResourceObject( "R3" );
ResourceObject r4 = newResourceObject( "R4" );
PlaceboTm tm = new PlaceboTm( null, null );
LockManager lm = new LockManagerImpl( new RagManager() );
tm.setLockManager( lm );
LockWorker t1 = new LockWorker( "T1", lm );
LockWorker t2 = new LockWorker( "T2", lm );
LockWorker t3 = new LockWorker( "T3", lm );
LockWorker t4 = new LockWorker( "T4", lm );
try
{
t1.getReadLock( r1, true );
t1.getReadLock( r4, true );
t2.getReadLock( r2, true );
t2.getReadLock( r3, true );
t3.getReadLock( r3, true );
t3.getWriteLock( r1, false ); // t3-r1-t1 // T3
t2.getWriteLock( r4, false ); // t2-r4-t1
t1.getWriteLock( r2, true );
assertTrue( t1.isLastGetLockDeadLock() ); // t1-r2-t2-r4-t1
// resolve and try one more time
t1.releaseReadLock( r4 ); // will give r4 to t2
t1.getWriteLock( r2, false );
// t1-r2-t2
t2.releaseReadLock( r2 ); // will give r2 to t1
t1.getWriteLock( r4, false ); // t1-r4-t2 // T1
// dead lock
t2.getWriteLock( r2, true ); // T2
assertTrue( t2.isLastGetLockDeadLock() );
// t2-r2-t3-r1-t1-r4-t2 or t2-r2-t1-r4-t2
t2.releaseWriteLock( r4 ); // give r4 to t1
t1.releaseWriteLock( r4 );
t2.getReadLock( r4, true );
t1.releaseWriteLock( r2 );
t1.getReadLock( r2, true );
t1.releaseReadLock( r1 ); // give r1 to t3
t3.getReadLock( r2, true );
t3.releaseWriteLock( r1 );
t1.getReadLock( r1, true ); // give r1->t1
t1.getWriteLock( r4, false );
t3.getWriteLock( r1, false );
t4.getReadLock( r2, true );
// deadlock
t2.getWriteLock( r2, true );
assertTrue( t2.isLastGetLockDeadLock() );
// t2-r2-t3-r1-t1-r4-t2
// resolve
t2.releaseReadLock( r4 );
t1.releaseWriteLock( r4 );
t1.releaseReadLock( r1 );
t2.getReadLock( r4, true ); // give r1 to t3
t3.releaseWriteLock( r1 );
t1.getReadLock( r1, true ); // give r1 to t1
t1.getWriteLock( r4, false );
t3.releaseReadLock( r2 );
t3.getWriteLock( r1, false );
// cleanup
t2.releaseReadLock( r4 ); // give r4 to t1
t1.releaseWriteLock( r4 );
t1.releaseReadLock( r1 ); // give r1 to t3
t3.releaseWriteLock( r1 );
t1.releaseReadLock( r2 );
t4.releaseReadLock( r2 );
t2.releaseReadLock( r3 );
t3.releaseReadLock( r3 );
// -- special case...
t1.getReadLock( r1, true );
t2.getReadLock( r1, true );
t1.getWriteLock( r1, false ); // t1->r1-t1&t2
t2.getWriteLock( r1, true );
assertTrue( t2.isLastGetLockDeadLock() );
// t2->r1->t1->r1->t2
t2.releaseReadLock( r1 );
t1.releaseReadLock( r1 );
t1.releaseWriteLock( r1 );
}
catch ( Exception e )
{
File file = new LockWorkFailureDump( getClass() ).dumpState( lm, new LockWorker[] { t1, t2, t3, t4 } );
throw new RuntimeException( "Failed, forensics information dumped to " + file.getAbsolutePath(), e );
}
}
public static class StressThread extends Thread
{
private static final Object READ = new Object();
private static final Object WRITE = new Object();
private static ResourceObject resources[] = new ResourceObject[10];
private final Random rand = new Random( currentTimeMillis() );
static
{
for ( int i = 0; i < resources.length; i++ )
resources[i] = new ResourceObject( "RX" + i );
}
private final CountDownLatch startSignal;
private final String name;
private final int numberOfIterations;
private final int depthCount;
private final float readWriteRatio;
private final LockManager lm;
private volatile Exception error;
private final Transaction tx = mock( Transaction.class );
public volatile Long startedWaiting = null;
StressThread( String name, int numberOfIterations, int depthCount,
float readWriteRatio, LockManager lm, CountDownLatch startSignal )
{
super();
this.name = name;
this.numberOfIterations = numberOfIterations;
this.depthCount = depthCount;
this.readWriteRatio = readWriteRatio;
this.lm = lm;
this.startSignal = startSignal;
}
@Override
public void run()
{
try
{
startSignal.await();
java.util.Stack<Object> lockStack = new java.util.Stack<Object>();
java.util.Stack<ResourceObject> resourceStack = new java.util.Stack<ResourceObject>();
for ( int i = 0; i < numberOfIterations; i++ )
{
try
{
int depth = depthCount;
do
{
float f = rand.nextFloat();
int n = rand.nextInt( resources.length );
if ( f < readWriteRatio )
{
startedWaiting = currentTimeMillis();
lm.getReadLock( resources[n], tx );
startedWaiting = null;
lockStack.push( READ );
}
else
{
startedWaiting = currentTimeMillis();
lm.getWriteLock( resources[n], tx );
startedWaiting = null;
lockStack.push( WRITE );
}
resourceStack.push( resources[n] );
}
while ( --depth > 0 );
}
catch ( DeadlockDetectedException e )
{
// This is good
}
finally
{
releaseAllLocks( lockStack, resourceStack );
}
}
}
catch ( Exception e )
{
error = e;
}
}
private void releaseAllLocks( Stack<Object> lockStack, Stack<ResourceObject> resourceStack )
{
while ( !lockStack.isEmpty() )
{
if ( lockStack.pop() == READ )
{
lm.releaseReadLock( resourceStack.pop(), tx );
}
else
{
lm.releaseWriteLock( resourceStack.pop(), tx );
}
}
}
@Override
public String toString()
{
return this.name;
}
}
@Test
public void testStressMultipleThreads() throws Exception
{
/*
This test starts a bunch of threads, and randomly takes read or write locks on random resources.
No thread should wait more than five seconds for a lock - if it does, we consider it a failure.
Successful outcomes are when threads either finish with all their lock taking and releasing, or
are terminated with a DeadlockDetectedException.
*/
for ( int i = 0; i < StressThread.resources.length; i++ )
{
StressThread.resources[i] = new ResourceObject( "RX" + i );
}
StressThread stressThreads[] = new StressThread[50];
PlaceboTm tm = new PlaceboTm( null, null );
LockManager lm = new LockManagerImpl( new RagManager() );
tm.setLockManager( lm );
CountDownLatch startSignal = new CountDownLatch( 1 );
for ( int i = 0; i < stressThreads.length; i++ )
{
int numberOfIterations = 100;
int depthCount = 10;
float readWriteRatio = 0.80f;
stressThreads[i] = new StressThread( "T" + i, numberOfIterations, depthCount, readWriteRatio, lm,
startSignal );
}
for ( Thread thread : stressThreads )
{
thread.start();
}
startSignal.countDown();
while ( anyAliveAndAllWell( stressThreads ) )
{
throwErrorsIfAny( stressThreads );
sleepALittle();
}
}
private String diagnostics( StressThread culprit, StressThread[] stressThreads, long waited )
{
StringBuilder builder = new StringBuilder();
for ( StressThread stressThread : stressThreads )
{
if ( stressThread.isAlive() )
{
if ( stressThread == culprit )
{
builder.append( "This is the thread that waited too long. It waited: " ).append( waited ).append(
" milliseconds" );
}
for ( StackTraceElement element : stressThread.getStackTrace() )
{
builder.append( element.toString() ).append( "\n" );
}
}
builder.append( "\n" );
}
return builder.toString();
}
private void throwErrorsIfAny( StressThread[] stressThreads ) throws Exception
{
for ( StressThread stressThread : stressThreads )
{
if ( stressThread.error != null )
{
throw stressThread.error;
}
}
}
private void sleepALittle()
{
try
{
Thread.sleep( 1000 );
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
}
private boolean anyAliveAndAllWell( StressThread[] stressThreads )
{
for ( StressThread stressThread : stressThreads )
{
if ( stressThread.isAlive() )
{
Long startedWaiting = stressThread.startedWaiting;
if ( startedWaiting != null )
{
long waitingTime = currentTimeMillis() - startedWaiting;
if ( waitingTime > 5000 )
{
fail( "One of the threads waited far too long. Diagnostics: \n" +
diagnostics( stressThread, stressThreads, waitingTime) );
}
}
return true;
}
}
return false;
}
} | 0true
| community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestDeadlockDetection.java |
3,129 | class SearchFactory extends SearcherFactory {
@Override
public IndexSearcher newSearcher(IndexReader reader) throws IOException {
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(similarityService.similarity());
if (warmer != null) {
// we need to pass a custom searcher that does not release anything on Engine.Search Release,
// we will release explicitly
Searcher currentSearcher = null;
IndexSearcher newSearcher = null;
boolean closeNewSearcher = false;
try {
if (searcherManager == null) {
// fresh index writer, just do on all of it
newSearcher = searcher;
} else {
currentSearcher = acquireSearcher("search_factory");
// figure out the newSearcher, with only the new readers that are relevant for us
List<IndexReader> readers = Lists.newArrayList();
for (AtomicReaderContext newReaderContext : searcher.getIndexReader().leaves()) {
if (isMergedSegment(newReaderContext.reader())) {
// merged segments are already handled by IndexWriterConfig.setMergedSegmentWarmer
continue;
}
boolean found = false;
for (AtomicReaderContext currentReaderContext : currentSearcher.reader().leaves()) {
if (currentReaderContext.reader().getCoreCacheKey().equals(newReaderContext.reader().getCoreCacheKey())) {
found = true;
break;
}
}
if (!found) {
readers.add(newReaderContext.reader());
}
}
if (!readers.isEmpty()) {
// we don't want to close the inner readers, just increase ref on them
newSearcher = new IndexSearcher(new MultiReader(readers.toArray(new IndexReader[readers.size()]), false));
closeNewSearcher = true;
}
}
if (newSearcher != null) {
IndicesWarmer.WarmerContext context = new IndicesWarmer.WarmerContext(shardId,
new SimpleSearcher("warmer", newSearcher));
warmer.warm(context);
}
} catch (Throwable e) {
if (!closed) {
logger.warn("failed to prepare/warm", e);
}
} finally {
// no need to release the fullSearcher, nothing really is done...
if (currentSearcher != null) {
currentSearcher.release();
}
if (newSearcher != null && closeNewSearcher) {
IOUtils.closeWhileHandlingException(newSearcher.getIndexReader()); // ignore
}
}
}
return searcher;
}
} | 1no label
| src_main_java_org_elasticsearch_index_engine_internal_InternalEngine.java |
1,245 | public class NodeClientModule extends AbstractModule {
@Override
protected void configure() {
bind(ClusterAdminClient.class).to(NodeClusterAdminClient.class).asEagerSingleton();
bind(IndicesAdminClient.class).to(NodeIndicesAdminClient.class).asEagerSingleton();
bind(AdminClient.class).to(NodeAdminClient.class).asEagerSingleton();
bind(Client.class).to(NodeClient.class).asEagerSingleton();
}
} | 0true
| src_main_java_org_elasticsearch_client_node_NodeClientModule.java |
307 | {
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
Long nodeId = (Long) invocation.getArguments()[0];
Lock lock = lockMocks.get( nodeId );
if ( lock == null )
{
lockMocks.put( nodeId, lock = mock( Lock.class ) );
}
return lock;
}
} ); | 0true
| community_kernel_src_test_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreIndexStoreViewTest.java |
2,142 | public interface ReaderContextAware {
public void setNextReader(AtomicReaderContext reader);
} | 0true
| src_main_java_org_elasticsearch_common_lucene_ReaderContextAware.java |
677 | public class OHashIndexBucket<K, V> implements Iterable<OHashIndexBucket.Entry<K, V>> {
private static final int MAGIC_NUMBER_OFFSET = 0;
private static final int CRC32_OFFSET = MAGIC_NUMBER_OFFSET + OLongSerializer.LONG_SIZE;
private static final int WAL_SEGMENT_OFFSET = CRC32_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int WAL_POSITION_OFFSET = WAL_SEGMENT_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int FREE_POINTER_OFFSET = WAL_POSITION_OFFSET + OLongSerializer.LONG_SIZE;
private static final int DEPTH_OFFSET = FREE_POINTER_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int SIZE_OFFSET = DEPTH_OFFSET + OByteSerializer.BYTE_SIZE;
private static final int HISTORY_OFFSET = SIZE_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int NEXT_REMOVED_BUCKET_OFFSET = HISTORY_OFFSET + OLongSerializer.LONG_SIZE * 64;
private static final int POSITIONS_ARRAY_OFFSET = NEXT_REMOVED_BUCKET_OFFSET + OLongSerializer.LONG_SIZE;
public static final int MAX_BUCKET_SIZE_BYTES = OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024;
private final ODirectMemoryPointer bufferPointer;
private final OBinarySerializer<K> keySerializer;
private final OBinarySerializer<V> valueSerializer;
private final OType[] keyTypes;
private final Comparator keyComparator = ODefaultComparator.INSTANCE;
public OHashIndexBucket(int depth, ODirectMemoryPointer bufferPointer, OBinarySerializer<K> keySerializer,
OBinarySerializer<V> valueSerializer, OType[] keyTypes) {
this.bufferPointer = bufferPointer;
this.keySerializer = keySerializer;
this.valueSerializer = valueSerializer;
this.keyTypes = keyTypes;
bufferPointer.setByte(DEPTH_OFFSET, (byte) depth);
OIntegerSerializer.INSTANCE.serializeInDirectMemory(MAX_BUCKET_SIZE_BYTES, bufferPointer, FREE_POINTER_OFFSET);
}
public OHashIndexBucket(ODirectMemoryPointer bufferPointer, OBinarySerializer<K> keySerializer,
OBinarySerializer<V> valueSerializer, OType[] keyTypes) {
this.bufferPointer = bufferPointer;
this.keySerializer = keySerializer;
this.valueSerializer = valueSerializer;
this.keyTypes = keyTypes;
}
public Entry<K, V> find(final K key, final long hashCode) {
final int index = binarySearch(key, hashCode);
if (index < 0)
return null;
return getEntry(index);
}
private int binarySearch(K key, long hashCode) {
int low = 0;
int high = size() - 1;
while (low <= high) {
final int mid = (low + high) >>> 1;
final long midHashCode = getHashCode(mid);
final int cmp;
if (midHashCode < hashCode)
cmp = -1;
else if (midHashCode > hashCode)
cmp = 1;
else {
final K midVal = getKey(mid);
cmp = keyComparator.compare(midVal, key);
}
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
public Entry<K, V> getEntry(int index) {
int entryPosition = OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, POSITIONS_ARRAY_OFFSET + index
* OIntegerSerializer.INT_SIZE);
final long hashCode = bufferPointer.getLong(entryPosition);
entryPosition += OLongSerializer.LONG_SIZE;
final K key = keySerializer.deserializeFromDirectMemory(bufferPointer, entryPosition);
entryPosition += keySerializer.getObjectSizeInDirectMemory(bufferPointer, entryPosition);
final V value = valueSerializer.deserializeFromDirectMemory(bufferPointer, entryPosition);
return new Entry<K, V>(key, value, hashCode);
}
public long getHashCode(int index) {
int entryPosition = OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, POSITIONS_ARRAY_OFFSET + index
* OIntegerSerializer.INT_SIZE);
return bufferPointer.getLong(entryPosition);
}
public K getKey(int index) {
int entryPosition = OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, POSITIONS_ARRAY_OFFSET + index
* OIntegerSerializer.INT_SIZE);
return keySerializer.deserializeFromDirectMemory(bufferPointer, entryPosition + OLongSerializer.LONG_SIZE);
}
public int getIndex(final long hashCode, final K key) {
return binarySearch(key, hashCode);
}
public int size() {
return OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, SIZE_OFFSET);
}
public Iterator<Entry<K, V>> iterator() {
return new EntryIterator(0);
}
public Iterator<Entry<K, V>> iterator(int index) {
return new EntryIterator(index);
}
public int mergedSize(OHashIndexBucket buddyBucket) {
return POSITIONS_ARRAY_OFFSET
+ size()
* OIntegerSerializer.INT_SIZE
+ (MAX_BUCKET_SIZE_BYTES - OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, FREE_POINTER_OFFSET))
+ buddyBucket.size()
* OIntegerSerializer.INT_SIZE
+ (MAX_BUCKET_SIZE_BYTES - OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(buddyBucket.bufferPointer,
FREE_POINTER_OFFSET));
}
public int getContentSize() {
return POSITIONS_ARRAY_OFFSET + size() * OIntegerSerializer.INT_SIZE
+ (MAX_BUCKET_SIZE_BYTES - OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, FREE_POINTER_OFFSET));
}
public int updateEntry(int index, V value) {
int entryPosition = OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, POSITIONS_ARRAY_OFFSET + index
* OIntegerSerializer.INT_SIZE);
entryPosition += OLongSerializer.LONG_SIZE;
entryPosition += keySerializer.getObjectSizeInDirectMemory(bufferPointer, entryPosition);
final int newSize = valueSerializer.getObjectSize(value);
final int oldSize = valueSerializer.getObjectSizeInDirectMemory(bufferPointer, entryPosition);
if (newSize != oldSize)
return -1;
byte[] newSerializedValue = new byte[newSize];
valueSerializer.serializeNative(value, newSerializedValue, 0);
byte[] oldSerializedValue = bufferPointer.get(entryPosition, oldSize);
if (ODefaultComparator.INSTANCE.compare(oldSerializedValue, newSerializedValue) == 0)
return 0;
bufferPointer.set(entryPosition, newSerializedValue, 0, newSerializedValue.length);
return 1;
}
public Entry<K, V> deleteEntry(int index) {
final Entry<K, V> removedEntry = getEntry(index);
final int freePointer = OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, FREE_POINTER_OFFSET);
final int positionOffset = POSITIONS_ARRAY_OFFSET + index * OIntegerSerializer.INT_SIZE;
final int entryPosition = OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, positionOffset);
final int keySize = keySerializer.getObjectSizeInDirectMemory(bufferPointer, entryPosition + OLongSerializer.LONG_SIZE);
final int ridSize = valueSerializer.getObjectSizeInDirectMemory(bufferPointer, entryPosition + keySize
+ OLongSerializer.LONG_SIZE);
final int entrySize = keySize + ridSize + OLongSerializer.LONG_SIZE;
bufferPointer.moveData(positionOffset + OIntegerSerializer.INT_SIZE, bufferPointer, positionOffset, size()
* OIntegerSerializer.INT_SIZE - (index + 1) * OIntegerSerializer.INT_SIZE);
if (entryPosition > freePointer)
bufferPointer.moveData(freePointer, bufferPointer, freePointer + entrySize, entryPosition - freePointer);
int currentPositionOffset = POSITIONS_ARRAY_OFFSET;
int size = size();
for (int i = 0; i < size - 1; i++) {
int currentEntryPosition = OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, currentPositionOffset);
if (currentEntryPosition < entryPosition)
OIntegerSerializer.INSTANCE.serializeInDirectMemory(currentEntryPosition + entrySize, bufferPointer, currentPositionOffset);
currentPositionOffset += OIntegerSerializer.INT_SIZE;
}
OIntegerSerializer.INSTANCE.serializeInDirectMemory(freePointer + entrySize, bufferPointer, FREE_POINTER_OFFSET);
OIntegerSerializer.INSTANCE.serializeInDirectMemory(size - 1, bufferPointer, SIZE_OFFSET);
return removedEntry;
}
public boolean addEntry(long hashCode, K key, V value) {
int entreeSize = keySerializer.getObjectSize(key, (Object[]) keyTypes) + valueSerializer.getObjectSize(value)
+ OLongSerializer.LONG_SIZE;
int freePointer = OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, FREE_POINTER_OFFSET);
int size = size();
if (freePointer - entreeSize < POSITIONS_ARRAY_OFFSET + (size + 1) * OIntegerSerializer.INT_SIZE)
return false;
final int index = binarySearch(key, hashCode);
if (index >= 0)
throw new IllegalArgumentException("Given value is present in bucket.");
final int insertionPoint = -index - 1;
insertEntry(hashCode, key, value, insertionPoint, entreeSize);
return true;
}
private void insertEntry(long hashCode, K key, V value, int insertionPoint, int entreeSize) {
int freePointer = OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, FREE_POINTER_OFFSET);
int size = size();
final int positionsOffset = insertionPoint * OIntegerSerializer.INT_SIZE + POSITIONS_ARRAY_OFFSET;
bufferPointer.moveData(positionsOffset, bufferPointer, positionsOffset + OIntegerSerializer.INT_SIZE, size()
* OIntegerSerializer.INT_SIZE - insertionPoint * OIntegerSerializer.INT_SIZE);
final int entreePosition = freePointer - entreeSize;
OIntegerSerializer.INSTANCE.serializeInDirectMemory(entreePosition, bufferPointer, positionsOffset);
serializeEntry(hashCode, key, value, entreePosition);
OIntegerSerializer.INSTANCE.serializeInDirectMemory(entreePosition, bufferPointer, FREE_POINTER_OFFSET);
OIntegerSerializer.INSTANCE.serializeInDirectMemory(size + 1, bufferPointer, SIZE_OFFSET);
}
public void appendEntry(long hashCode, K key, V value) {
final int positionsOffset = size() * OIntegerSerializer.INT_SIZE + POSITIONS_ARRAY_OFFSET;
final int entreeSize = keySerializer.getObjectSize(key, (Object[]) keyTypes) + valueSerializer.getObjectSize(value)
+ OLongSerializer.LONG_SIZE;
final int freePointer = OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, FREE_POINTER_OFFSET);
final int entreePosition = freePointer - entreeSize;
OIntegerSerializer.INSTANCE.serializeInDirectMemory(entreePosition, bufferPointer, positionsOffset);
serializeEntry(hashCode, key, value, entreePosition);
OIntegerSerializer.INSTANCE.serializeInDirectMemory(freePointer - entreeSize, bufferPointer, FREE_POINTER_OFFSET);
OIntegerSerializer.INSTANCE.serializeInDirectMemory(size() + 1, bufferPointer, SIZE_OFFSET);
}
private void serializeEntry(long hashCode, K key, V value, int entryOffset) {
bufferPointer.setLong(entryOffset, hashCode);
entryOffset += OLongSerializer.LONG_SIZE;
keySerializer.serializeInDirectMemory(key, bufferPointer, entryOffset, (Object[]) keyTypes);
entryOffset += keySerializer.getObjectSize(key, (Object[]) keyTypes);
valueSerializer.serializeInDirectMemory(value, bufferPointer, entryOffset);
}
public int getDepth() {
return bufferPointer.getByte(DEPTH_OFFSET);
}
public void setDepth(int depth) {
bufferPointer.setByte(DEPTH_OFFSET, (byte) depth);
}
public long getNextRemovedBucketPair() {
return OLongSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, NEXT_REMOVED_BUCKET_OFFSET);
}
public void setNextRemovedBucketPair(long nextRemovedBucketPair) {
OLongSerializer.INSTANCE.serializeInDirectMemory(nextRemovedBucketPair, bufferPointer, NEXT_REMOVED_BUCKET_OFFSET);
}
public long getSplitHistory(int level) {
return OLongSerializer.INSTANCE.deserializeFromDirectMemory(bufferPointer, HISTORY_OFFSET + OLongSerializer.LONG_SIZE * level);
}
public void setSplitHistory(int level, long position) {
OLongSerializer.INSTANCE.serializeInDirectMemory(position, bufferPointer, HISTORY_OFFSET + OLongSerializer.LONG_SIZE * level);
}
public static class Entry<K, V> {
public final K key;
public final V value;
public final long hashCode;
public Entry(K key, V value, long hashCode) {
this.key = key;
this.value = value;
this.hashCode = hashCode;
}
}
private final class EntryIterator implements Iterator<Entry<K, V>> {
private int currentIndex;
private EntryIterator(int currentIndex) {
this.currentIndex = currentIndex;
}
@Override
public boolean hasNext() {
return currentIndex < size();
}
@Override
public Entry<K, V> next() {
if (currentIndex >= size())
throw new NoSuchElementException("Iterator was reached last element");
final Entry<K, V> entry = getEntry(currentIndex);
currentIndex++;
return entry;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove operation is not supported");
}
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_OHashIndexBucket.java |
2,085 | public abstract class Streams {
public static final int BUFFER_SIZE = 1024 * 8;
//---------------------------------------------------------------------
// Copy methods for java.io.File
//---------------------------------------------------------------------
/**
* Copy the contents of the given input File to the given output File.
*
* @param in the file to copy from
* @param out the file to copy to
* @return the number of bytes copied
* @throws IOException in case of I/O errors
*/
public static long copy(File in, File out) throws IOException {
Preconditions.checkNotNull(in, "No input File specified");
Preconditions.checkNotNull(out, "No output File specified");
return copy(new BufferedInputStream(new FileInputStream(in)),
new BufferedOutputStream(new FileOutputStream(out)));
}
/**
* Copy the contents of the given byte array to the given output File.
*
* @param in the byte array to copy from
* @param out the file to copy to
* @throws IOException in case of I/O errors
*/
public static void copy(byte[] in, File out) throws IOException {
Preconditions.checkNotNull(in, "No input byte array specified");
Preconditions.checkNotNull(out, "No output File specified");
ByteArrayInputStream inStream = new ByteArrayInputStream(in);
OutputStream outStream = new BufferedOutputStream(new FileOutputStream(out));
copy(inStream, outStream);
}
/**
* Copy the contents of the given input File into a new byte array.
*
* @param in the file to copy from
* @return the new byte array that has been copied to
* @throws IOException in case of I/O errors
*/
public static byte[] copyToByteArray(File in) throws IOException {
Preconditions.checkNotNull(in, "No input File specified");
return copyToByteArray(new BufferedInputStream(new FileInputStream(in)));
}
//---------------------------------------------------------------------
// Copy methods for java.io.InputStream / java.io.OutputStream
//---------------------------------------------------------------------
public static long copy(InputStream in, OutputStream out) throws IOException {
return copy(in, out, new byte[BUFFER_SIZE]);
}
/**
* Copy the contents of the given InputStream to the given OutputStream.
* Closes both streams when done.
*
* @param in the stream to copy from
* @param out the stream to copy to
* @return the number of bytes copied
* @throws IOException in case of I/O errors
*/
public static long copy(InputStream in, OutputStream out, byte[] buffer) throws IOException {
Preconditions.checkNotNull(in, "No InputStream specified");
Preconditions.checkNotNull(out, "No OutputStream specified");
try {
long byteCount = 0;
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
return byteCount;
} finally {
try {
in.close();
} catch (IOException ex) {
// do nothing
}
try {
out.close();
} catch (IOException ex) {
// do nothing
}
}
}
/**
* Copy the contents of the given byte array to the given OutputStream.
* Closes the stream when done.
*
* @param in the byte array to copy from
* @param out the OutputStream to copy to
* @throws IOException in case of I/O errors
*/
public static void copy(byte[] in, OutputStream out) throws IOException {
Preconditions.checkNotNull(in, "No input byte array specified");
Preconditions.checkNotNull(out, "No OutputStream specified");
try {
out.write(in);
} finally {
try {
out.close();
} catch (IOException ex) {
// do nothing
}
}
}
/**
* Copy the contents of the given InputStream into a new byte array.
* Closes the stream when done.
*
* @param in the stream to copy from
* @return the new byte array that has been copied to
* @throws IOException in case of I/O errors
*/
public static byte[] copyToByteArray(InputStream in) throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
copy(in, out);
return out.bytes().toBytes();
}
//---------------------------------------------------------------------
// Copy methods for java.io.Reader / java.io.Writer
//---------------------------------------------------------------------
/**
* Copy the contents of the given Reader to the given Writer.
* Closes both when done.
*
* @param in the Reader to copy from
* @param out the Writer to copy to
* @return the number of characters copied
* @throws IOException in case of I/O errors
*/
public static int copy(Reader in, Writer out) throws IOException {
Preconditions.checkNotNull(in, "No Reader specified");
Preconditions.checkNotNull(out, "No Writer specified");
try {
int byteCount = 0;
char[] buffer = new char[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
return byteCount;
} finally {
try {
in.close();
} catch (IOException ex) {
// do nothing
}
try {
out.close();
} catch (IOException ex) {
// do nothing
}
}
}
/**
* Copy the contents of the given String to the given output Writer.
* Closes the write when done.
*
* @param in the String to copy from
* @param out the Writer to copy to
* @throws IOException in case of I/O errors
*/
public static void copy(String in, Writer out) throws IOException {
Preconditions.checkNotNull(in, "No input String specified");
Preconditions.checkNotNull(out, "No Writer specified");
try {
out.write(in);
} finally {
try {
out.close();
} catch (IOException ex) {
// do nothing
}
}
}
/**
* Copy the contents of the given Reader into a String.
* Closes the reader when done.
*
* @param in the reader to copy from
* @return the String that has been copied to
* @throws IOException in case of I/O errors
*/
public static String copyToString(Reader in) throws IOException {
StringWriter out = new StringWriter();
copy(in, out);
return out.toString();
}
public static String copyToStringFromClasspath(ClassLoader classLoader, String path) throws IOException {
InputStream is = classLoader.getResourceAsStream(path);
if (is == null) {
throw new FileNotFoundException("Resource [" + path + "] not found in classpath with class loader [" + classLoader + "]");
}
return copyToString(new InputStreamReader(is, Charsets.UTF_8));
}
public static String copyToStringFromClasspath(String path) throws IOException {
InputStream is = Streams.class.getResourceAsStream(path);
if (is == null) {
throw new FileNotFoundException("Resource [" + path + "] not found in classpath");
}
return copyToString(new InputStreamReader(is, Charsets.UTF_8));
}
public static byte[] copyToBytesFromClasspath(String path) throws IOException {
InputStream is = Streams.class.getResourceAsStream(path);
if (is == null) {
throw new FileNotFoundException("Resource [" + path + "] not found in classpath");
}
return copyToByteArray(is);
}
public static int readFully(Reader reader, char[] dest) throws IOException {
return readFully(reader, dest, 0, dest.length);
}
public static int readFully(Reader reader, char[] dest, int offset, int len) throws IOException {
int read = 0;
while (read < len) {
final int r = reader.read(dest, offset + read, len - read);
if (r == -1) {
break;
}
read += r;
}
return read;
}
public static int readFully(InputStream reader, byte[] dest) throws IOException {
return readFully(reader, dest, 0, dest.length);
}
public static int readFully(InputStream reader, byte[] dest, int offset, int len) throws IOException {
int read = 0;
while (read < len) {
final int r = reader.read(dest, offset + read, len - read);
if (r == -1) {
break;
}
read += r;
}
return read;
}
} | 0true
| src_main_java_org_elasticsearch_common_io_Streams.java |
1,882 | class ProviderToInternalFactoryAdapter<T> implements Provider<T> {
private final InjectorImpl injector;
private final InternalFactory<? extends T> internalFactory;
public ProviderToInternalFactoryAdapter(InjectorImpl injector,
InternalFactory<? extends T> internalFactory) {
this.injector = injector;
this.internalFactory = internalFactory;
}
public T get() {
final Errors errors = new Errors();
try {
T t = injector.callInContext(new ContextualCallable<T>() {
public T call(InternalContext context) throws ErrorsException {
Dependency dependency = context.getDependency();
return internalFactory.get(errors, context, dependency);
}
});
errors.throwIfNewErrors(0);
return t;
} catch (ErrorsException e) {
throw new ProvisionException(errors.merge(e.getErrors()).getMessages());
}
}
@Override
public String toString() {
return internalFactory.toString();
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_ProviderToInternalFactoryAdapter.java |
237 | new OProfilerHookValue() {
public Object getValue() {
return getMaxSize();
}
}, profilerMetadataPrefix + "max"); | 0true
| core_src_main_java_com_orientechnologies_orient_core_cache_OAbstractRecordCache.java |
1,632 | public static final Validator MEMORY_SIZE = new Validator() {
@Override
public String validate(String setting, String value) {
try {
parseBytesSizeValueOrHeapRatio(value);
} catch (ElasticsearchParseException ex) {
return ex.getMessage();
}
return null;
}
}; | 0true
| src_main_java_org_elasticsearch_cluster_settings_Validator.java |
1,498 | public class ExactEntity extends AbstractEntity {
private boolean before3Called = false;
public void reset() {
super.reset();
before3Called = false;
}
@OBeforeSerialization
public void before3() {
before3Called = true;
}
@Override
public boolean callbackExecuted() {
return super.callbackExecuted() && before3Called;
}
} | 0true
| object_src_test_java_com_orientechnologies_orient_object_enhancement_ExactEntity.java |
655 | @Repository("blCategoryDao")
public class CategoryDaoImpl implements CategoryDao {
protected Long currentDateResolution = 10000L;
protected Date cachedDate = SystemTime.asDate();
protected Date getCurrentDateAfterFactoringInDateResolution() {
Date returnDate = SystemTime.getCurrentDateWithinTimeResolution(cachedDate, currentDateResolution);
if (returnDate != cachedDate) {
if (SystemTime.shouldCacheDate()) {
cachedDate = returnDate;
}
}
return returnDate;
}
@PersistenceContext(unitName="blPU")
protected EntityManager em;
@Resource(name="blEntityConfiguration")
protected EntityConfiguration entityConfiguration;
@Override
public Category save(Category category) {
return em.merge(category);
}
@Override
public Category readCategoryById(Long categoryId) {
return em.find(CategoryImpl.class, categoryId);
}
@Override
@Deprecated
public Category readCategoryByName(String categoryName) {
Query query = em.createNamedQuery("BC_READ_CATEGORY_BY_NAME");
query.setParameter("categoryName", categoryName);
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
return (Category) query.getSingleResult();
}
@Override
public List<Category> readAllParentCategories() {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Category> criteria = builder.createQuery(Category.class);
Root<CategoryImpl> category = criteria.from(CategoryImpl.class);
criteria.select(category);
criteria.where(builder.isNull(category.get("defaultParentCategory")));
TypedQuery<Category> query = em.createQuery(criteria);
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
try {
return query.getResultList();
} catch (NoResultException e) {
return null;
}
}
@Override
public List<Category> readCategoriesByName(String categoryName) {
TypedQuery<Category> query = em.createNamedQuery("BC_READ_CATEGORY_BY_NAME", Category.class);
query.setParameter("categoryName", categoryName);
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
return query.getResultList();
}
@Override
public List<Category> readCategoriesByName(String categoryName, int limit, int offset) {
TypedQuery<Category> query = em.createNamedQuery("BC_READ_CATEGORY_BY_NAME", Category.class);
query.setParameter("categoryName", categoryName);
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.getResultList();
}
@Override
public List<Category> readAllCategories() {
TypedQuery<Category> query = em.createNamedQuery("BC_READ_ALL_CATEGORIES", Category.class);
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
return query.getResultList();
}
@Override
public List<Category> readAllCategories(int limit, int offset) {
TypedQuery<Category> query = em.createNamedQuery("BC_READ_ALL_CATEGORIES", Category.class);
query.setFirstResult(offset);
query.setMaxResults(limit);
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
return query.getResultList();
}
@Override
public List<Product> readAllProducts() {
TypedQuery<Product> query = em.createNamedQuery("BC_READ_ALL_PRODUCTS", Product.class);
//don't cache - could take up too much memory
return query.getResultList();
}
@Override
public List<Product> readAllProducts(int limit, int offset) {
TypedQuery<Product> query = em.createNamedQuery("BC_READ_ALL_PRODUCTS", Product.class);
//don't cache - could take up too much memory
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.getResultList();
}
@Override
public List<Category> readAllSubCategories(Category category) {
TypedQuery<Category> query = em.createNamedQuery("BC_READ_ALL_SUBCATEGORIES", Category.class);
query.setParameter("defaultParentCategory", category);
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
return query.getResultList();
}
@Override
public List<Category> readAllSubCategories(Category category, int limit, int offset) {
TypedQuery<Category> query = em.createNamedQuery("BC_READ_ALL_SUBCATEGORIES", Category.class);
query.setParameter("defaultParentCategory", category);
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.getResultList();
}
@Override
public List<Category> readActiveSubCategoriesByCategory(Category category) {
TypedQuery<Category> query = em.createNamedQuery("BC_READ_ACTIVE_SUBCATEGORIES_BY_CATEGORY", Category.class);
query.setParameter("defaultParentCategoryId", category.getId());
query.setParameter("currentDate", getCurrentDateAfterFactoringInDateResolution());
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
return query.getResultList();
}
@Override
public List<Category> readActiveSubCategoriesByCategory(Category category, int limit, int offset) {
TypedQuery<Category> query = em.createNamedQuery("BC_READ_ACTIVE_SUBCATEGORIES_BY_CATEGORY", Category.class);
query.setParameter("defaultParentCategoryId", category.getId());
query.setParameter("currentDate", getCurrentDateAfterFactoringInDateResolution());
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.getResultList();
}
@Override
public Long getCurrentDateResolution() {
return currentDateResolution;
}
@Override
public void setCurrentDateResolution(Long currentDateResolution) {
this.currentDateResolution = currentDateResolution;
}
@Override
public void delete(Category category) {
((Status) category).setArchived('Y');
em.merge(category);
}
@Override
public Category create() {
return (Category) entityConfiguration.createEntityInstance(Category.class.getName());
}
@Override
public Category findCategoryByURI(String uri) {
Query query;
query = em.createNamedQuery("BC_READ_CATEGORY_OUTGOING_URL");
query.setParameter("currentDate", getCurrentDateAfterFactoringInDateResolution());
query.setParameter("url", uri);
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
@SuppressWarnings("unchecked")
List<Category> results = query.getResultList();
if (results != null && !results.isEmpty()) {
return results.get(0);
} else {
return null;
}
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_dao_CategoryDaoImpl.java |
0 | public abstract class AbstractEntryIterator<K, V, T> implements OLazyIterator<T>, OResettable {
OMVRBTree<K, V> tree;
OMVRBTreeEntry<K, V> begin;
OMVRBTreeEntry<K, V> next;
OMVRBTreeEntry<K, V> lastReturned;
int expectedModCount;
int pageIndex;
AbstractEntryIterator(final OMVRBTreeEntry<K, V> start) {
begin = start;
init();
}
private void init() {
if (begin == null)
// IN CASE OF ABSTRACTMAP.HASHCODE()
return;
tree = begin.getTree();
next = begin;
expectedModCount = tree.modCount;
lastReturned = null;
pageIndex = begin.getTree().getPageIndex() > -1 ? begin.getTree().getPageIndex() - 1 : -1;
}
@Override
public void reset() {
init();
}
public boolean hasNext() {
if (tree != null && expectedModCount != tree.modCount) {
// CONCURRENT CHANGE: TRY TO REUSE LAST POSITION
pageIndex--;
expectedModCount = tree.modCount;
}
return next != null && (pageIndex < next.getSize() - 1 || OMVRBTree.successor(next) != null);
}
public final boolean hasPrevious() {
if (tree != null && expectedModCount != tree.modCount) {
// CONCURRENT CHANGE: TRY TO REUSE LAST POSITION
pageIndex = -1;
expectedModCount = tree.modCount;
}
return next != null && (pageIndex > 0 || OMVRBTree.predecessor(next) != null);
}
final K nextKey() {
return nextEntry().getKey(pageIndex);
}
final V nextValue() {
return nextEntry().getValue(pageIndex);
}
final V prevValue() {
return prevEntry().getValue(pageIndex);
}
final OMVRBTreeEntry<K, V> nextEntry() {
if (next == null)
throw new NoSuchElementException();
if (pageIndex < next.getSize() - 1) {
// ITERATE INSIDE THE NODE
pageIndex++;
} else {
// GET THE NEXT NODE
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
next = OMVRBTree.successor(next);
pageIndex = 0;
}
lastReturned = next;
tree.pageIndex = pageIndex;
return next;
}
final OMVRBTreeEntry<K, V> prevEntry() {
if (next == null)
throw new NoSuchElementException();
if (pageIndex > 0) {
// ITERATE INSIDE THE NODE
pageIndex--;
} else {
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
next = OMVRBTree.predecessor(next);
pageIndex = next != null ? next.getSize() - 1 : -1;
}
lastReturned = next;
return next;
}
@SuppressWarnings("unchecked")
public T update(final T iValue) {
if (lastReturned == null)
throw new IllegalStateException();
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
tree.pageIndex = pageIndex;
return (T) next.setValue((V) iValue);
}
public void remove() {
if (lastReturned == null)
throw new IllegalStateException();
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
// deleted entries are replaced by their successors
if (lastReturned.getLeft() != null && lastReturned.getRight() != null)
next = lastReturned;
tree.pageIndex = pageIndex;
next = tree.deleteEntry(lastReturned);
pageIndex--;
expectedModCount = tree.modCount;
lastReturned = null;
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_collection_AbstractEntryIterator.java |
2,028 | public interface ElementVisitor<V> {
/**
* Visit a mapping from a key (type and optional annotation) to the strategy for getting
* instances of the type.
*/
<T> V visit(Binding<T> binding);
/**
* Visit a registration of a scope annotation with the scope that implements it.
*/
V visit(ScopeBinding binding);
/**
* Visit a registration of type converters for matching target types.
*/
V visit(TypeConverterBinding binding);
/**
* Visit a request to inject the instance fields and methods of an instance.
*/
V visit(InjectionRequest request);
/**
* Visit a request to inject the static fields and methods of type.
*/
V visit(StaticInjectionRequest request);
/**
* Visit a lookup of the provider for a type.
*/
<T> V visit(ProviderLookup<T> lookup);
/**
* Visit a lookup of the members injector.
*/
<T> V visit(MembersInjectorLookup<T> lookup);
/**
* Visit an error message and the context in which it occured.
*/
V visit(Message message);
/**
* Visit a collection of configuration elements for a {@linkplain org.elasticsearch.common.inject.PrivateBinder
* private binder}.
*/
V visit(PrivateElements elements);
/**
* Visit an injectable type listener binding.
*/
V visit(TypeListenerBinding binding);
} | 0true
| src_main_java_org_elasticsearch_common_inject_spi_ElementVisitor.java |
301 | public class OTraverseRecordSetProcess extends OTraverseAbstractProcess<Iterator<OIdentifiable>> {
protected OIdentifiable record;
protected int index = -1;
public OTraverseRecordSetProcess(final OTraverse iCommand, final Iterator<OIdentifiable> iTarget) {
super(iCommand, iTarget);
}
@SuppressWarnings("unchecked")
public OIdentifiable process() {
while (target.hasNext()) {
record = target.next();
index++;
final ORecord<?> rec = record.getRecord();
if (rec instanceof ODocument) {
ODocument doc = (ODocument) rec;
if (!doc.getIdentity().isPersistent() && doc.fields() == 1) {
// EXTRACT THE FIELD CONTEXT
Object fieldvalue = doc.field(doc.fieldNames()[0]);
if (fieldvalue instanceof Collection<?>) {
final OTraverseRecordSetProcess subProcess = new OTraverseRecordSetProcess(command,
((Collection<OIdentifiable>) fieldvalue).iterator());
final OIdentifiable subValue = subProcess.process();
if (subValue != null)
return subValue;
} else if (fieldvalue instanceof ODocument) {
final OTraverseRecordProcess subProcess = new OTraverseRecordProcess(command, (ODocument) rec);
final OIdentifiable subValue = subProcess.process();
if (subValue != null)
return subValue;
}
} else {
final OTraverseRecordProcess subProcess = new OTraverseRecordProcess(command, (ODocument) rec);
final OIdentifiable subValue = subProcess.process();
if (subValue != null)
return subValue;
}
}
}
return drop();
}
@Override
public String getStatus() {
return null;
}
@Override
public String toString() {
return target != null ? target.toString() : "-";
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_command_traverse_OTraverseRecordSetProcess.java |
242 | public class DynamicMenuItem extends CommandContributionItem {
private boolean enabled;
public DynamicMenuItem(String id, String label, boolean enabled) {
super(new CommandContributionItemParameter(
PlatformUI.getWorkbench().getActiveWorkbenchWindow(),
id + ".cci", id, Collections.emptyMap(), null, null, null,
label, null, null, CommandContributionItem.STYLE_PUSH, null,
false));
this.enabled = enabled;
}
public DynamicMenuItem(String id, String label, boolean enabled,
ImageDescriptor image) {
super(new CommandContributionItemParameter(
PlatformUI.getWorkbench().getActiveWorkbenchWindow(),
id + ".cci", id, Collections.emptyMap(), image, null, null,
label, null, null, CommandContributionItem.STYLE_PUSH, null,
false));
this.enabled = enabled;
}
@Override
public boolean isEnabled() {
return super.isEnabled() && enabled;
}
public static boolean collapseMenuItems(IContributionManager parent) {
return isContextMenu(parent) /*&&
Display.getCurrent().getBounds().height < 2048*/;
}
static boolean isContextMenu(IContributionManager parent) {
return parent instanceof IContributionItem &&
((IContributionItem) parent).getId().equals("#TextEditorContext");
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_DynamicMenuItem.java |
2,964 | public class UniqueTokenFilterFactory extends AbstractTokenFilterFactory {
private final boolean onlyOnSamePosition;
@Inject
public UniqueTokenFilterFactory(Index index, @IndexSettings Settings indexSettings,
@Assisted String name, @Assisted Settings settings) {
super(index, indexSettings, name, settings);
this.onlyOnSamePosition = settings.getAsBoolean("only_on_same_position", false);
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new UniqueTokenFilter(tokenStream, onlyOnSamePosition);
}
} | 0true
| src_main_java_org_elasticsearch_index_analysis_UniqueTokenFilterFactory.java |
90 | public interface ObjectToInt<A> {int apply(A a); } | 0true
| src_main_java_jsr166e_ConcurrentHashMapV8.java |
3,275 | Collections.sort(ordsAndIds, new Comparator<OrdAndId>() {
@Override
public int compare(OrdAndId o1, OrdAndId o2) {
if (o1.id < o2.id) {
return -1;
}
if (o1.id == o2.id) {
if (o1.ord < o2.ord) {
return -1;
}
if (o1.ord > o2.ord) {
return 1;
}
return 0;
}
return 1;
}
}); | 0true
| src_test_java_org_elasticsearch_index_fielddata_ordinals_MultiOrdinalsTests.java |
735 | public class CollectionGetAllRequest extends CollectionRequest {
public CollectionGetAllRequest() {
}
public CollectionGetAllRequest(String name) {
super(name);
}
@Override
protected Operation prepareOperation() {
return new CollectionGetAllOperation(name);
}
@Override
public int getClassId() {
return CollectionPortableHook.COLLECTION_GET_ALL;
}
@Override
public String getRequiredAction() {
return ActionConstants.ACTION_READ;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_client_CollectionGetAllRequest.java |
2,116 | public enum Releasables {
;
private static void rethrow(Throwable t) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof Error) {
throw (Error) t;
}
throw new RuntimeException(t);
}
private static void release(Iterable<Releasable> releasables, boolean ignoreException) {
Throwable th = null;
for (Releasable releasable : releasables) {
if (releasable != null) {
try {
releasable.release();
} catch (Throwable t) {
if (th == null) {
th = t;
}
}
}
}
if (th != null && !ignoreException) {
rethrow(th);
}
}
/** Release the provided {@link Releasable}s. */
public static void release(Iterable<Releasable> releasables) {
release(releasables, false);
}
/** Release the provided {@link Releasable}s. */
public static void release(Releasable... releasables) {
release(Arrays.asList(releasables));
}
/** Release the provided {@link Releasable}s, ignoring exceptions. */
public static void releaseWhileHandlingException(Iterable<Releasable> releasables) {
release(releasables, true);
}
/** Release the provided {@link Releasable}s, ignoring exceptions. */
public static void releaseWhileHandlingException(Releasable... releasables) {
releaseWhileHandlingException(Arrays.asList(releasables));
}
/** Release the provided {@link Releasable}s, ignoring exceptions if <code>success</code> is <tt>false</tt>. */
public static void release(boolean success, Iterable<Releasable> releasables) {
if (success) {
release(releasables);
} else {
releaseWhileHandlingException(releasables);
}
}
/** Release the provided {@link Releasable}s, ignoring exceptions if <code>success</code> is <tt>false</tt>. */
public static void release(boolean success, Releasable... releasables) {
release(success, Arrays.asList(releasables));
}
} | 0true
| src_main_java_org_elasticsearch_common_lease_Releasables.java |
83 | removeListenerActions.add(new Runnable() {
@Override
public void run() {
clientEngine.getProxyService().removeProxyListener(id);
}
}); | 0true
| hazelcast_src_main_java_com_hazelcast_client_ClientEndpoint.java |
238 | XPostingsHighlighter highlighter = new XPostingsHighlighter() {
Iterator<String> valuesIterator = Arrays.asList(firstValue, secondValue, thirdValue).iterator();
Iterator<Integer> offsetsIterator = Arrays.asList(0, firstValue.length() + 1, secondValue.length() + 1).iterator();
@Override
protected String[][] loadFieldValues(IndexSearcher searcher, String[] fields, int[] docids, int maxLength) throws IOException {
return new String[][]{new String[]{valuesIterator.next()}};
}
@Override
protected int getOffsetForCurrentValue(String field, int docId) {
return offsetsIterator.next();
}
@Override
protected BreakIterator getBreakIterator(String field) {
return new WholeBreakIterator();
}
@Override
protected Passage[] getEmptyHighlight(String fieldName, BreakIterator bi, int maxPassages) {
return new Passage[0];
}
}; | 0true
| src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java |
2,475 | public abstract class PrioritizedRunnable implements Runnable, Comparable<PrioritizedRunnable> {
private final Priority priority;
public static PrioritizedRunnable wrap(Runnable runnable, Priority priority) {
return new Wrapped(runnable, priority);
}
protected PrioritizedRunnable(Priority priority) {
this.priority = priority;
}
@Override
public int compareTo(PrioritizedRunnable pr) {
return priority.compareTo(pr.priority);
}
public Priority priority() {
return priority;
}
static class Wrapped extends PrioritizedRunnable {
private final Runnable runnable;
private Wrapped(Runnable runnable, Priority priority) {
super(priority);
this.runnable = runnable;
}
@Override
public void run() {
runnable.run();
}
}
} | 0true
| src_main_java_org_elasticsearch_common_util_concurrent_PrioritizedRunnable.java |
592 | public interface OIndexDefinition extends OIndexCallback {
/**
* @return Names of fields which given index is used to calculate key value. Order of fields is important.
*/
public List<String> getFields();
/**
* @return Names of fields and their index modifiers (like "by value" for fields that hold <code>Map</code> values) which given
* index is used to calculate key value. Order of fields is important.
*/
public List<String> getFieldsToIndex();
/**
* @return Name of the class which this index belongs to.
*/
public String getClassName();
/**
* {@inheritDoc}
*/
public boolean equals(Object index);
/**
* {@inheritDoc}
*/
public int hashCode();
/**
* {@inheritDoc}
*/
public String toString();
/**
* Calculates key value by passed in parameters.
*
* If it is impossible to calculate key value by given parameters <code>null</code> will be returned.
*
* @param params
* Parameters from which index key will be calculated.
*
* @return Key value or null if calculation is impossible.
*/
public Object createValue(List<?> params);
/**
* Calculates key value by passed in parameters.
*
* If it is impossible to calculate key value by given parameters <code>null</code> will be returned.
*
*
* @param params
* Parameters from which index key will be calculated.
*
* @return Key value or null if calculation is impossible.
*/
public Object createValue(Object... params);
/**
* Returns amount of parameters that are used to calculate key value. It does not mean that all parameters should be supplied. It
* only means that if you provide more parameters they will be ignored and will not participate in index key calculation.
*
* @return Amount of that are used to calculate key value. Call result should be equals to {@code getTypes().length}.
*/
public int getParamCount();
/**
* Return types of values from which index key consist. In case of index that is built on single document property value single
* array that contains property type will be returned. In case of composite indexes result will contain several key types.
*
* @return Types of values from which index key consist.
*/
public OType[] getTypes();
/**
* Serializes internal index state to document.
*
* @return Document that contains internal index state.
*/
public ODocument toStream();
/**
* Deserialize internal index state from document.
*
* @param document
* Serialized index presentation.
*/
public void fromStream(ODocument document);
public String toCreateIndexDDL(String indexName, String indexType);
public boolean isAutomatic();
public OCollate getCollate();
public void setCollate(OCollate iCollate);
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_OIndexDefinition.java |
984 | public static class Name {
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_DiscreteOrderItemImpl.java |
411 | @Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface AdminPresentation {
/**
* <p>Optional - only required if you want to display a friendly name to the user</p>
*
* <p><The friendly name to present to a user for this field in a GUI. If supporting i18N,
* the friendly name may be a key to retrieve a localized friendly name using
* the GWT support for i18N.</p>
*
* @return the friendly name
*/
String friendlyName() default "";
/**
* Optional - only required if you want to restrict this field
*
* If a security level is specified, it is registered with org.broadleafcommerce.openadmin.client.security.SecurityManager
* The SecurityManager checks the permission of the current user to
* determine if this field should be disabled based on the specified level.
*
* @return the security level
*/
String securityLevel() default "";
/**
* Optional - only required if you want to order the appearance of this field in the UI
*
* The order in which this field will appear in a GUI relative to other fields from the same class
*
* @return the display order
*/
int order() default 99999;
/**
* Optional - required only if you want to order the appearance of this field as it relates to other fields in a
* Note that this field will only be relevant if {@link #prominent()} is also set to true.
*
* @return
*/
int gridOrder() default 9999;
/**
* Optional - only required if you want to restrict the visibility of this field in the admin tool
*
* Describes how the field is shown in admin GUI.
*
* @return whether or not to hide the form field.
*/
VisibilityEnum visibility() default VisibilityEnum.VISIBLE_ALL;
/**
* Optional - only required if you want to explicitly specify the field type. This
* value is normally inferred by the system based on the field type in the entity class.
*
* Explicity specify the type the GUI should consider this field
* Specifying UNKNOWN will cause the system to make its best guess
*
* @return the field type
*/
SupportedFieldType fieldType() default SupportedFieldType.UNKNOWN;
/**
* Optional - only required if you want to specify a grouping for this field
*
* Specify a GUI grouping for this field
* Fields in the same group will be visually grouped together in the GUI
* <br />
* <br />
* Note: for support I18N, this can also be a key to retrieve a localized String
*
* @return the group for this field
*/
String group() default "General";
/**
* Optional - only required if you want to order the appearance of groups in the UI
*
* Specify an order for this group. Groups will be sorted in the resulting
* form in ascending order based on this parameter.
*
* @return the order for this group
*/
int groupOrder() default 99999;
/**
* Optional - only required if you want to control the initial collapsed state of the group
*
* Specify whether a group is collapsed by default in the admin UI.
*
* @return whether or not the group is collapsed by default
*/
boolean groupCollapsed() default false;
/**
* Optional - only required if you want the field to appear under a different tab
*
* Specify a GUI tab for this field
*
* @return the tab for this field
*/
String tab() default "General";
/**
* Optional - only required if you want to order the appearance of the tabs in the UI
*
* Specify an order for this tab. Tabs will be sorted int he resulting form in
* ascending order based on this parameter.
*
* The default tab will render with an order of 100.
*
* @return the order for this tab
*/
int tabOrder() default 100;
/**
* Optional - only required if you want to give the user extra room to enter a value
* for this field in the UI
*
* If the field is a string, specify that the GUI
* provide a text area
*
* @return is a text area field
*/
boolean largeEntry() default false;
/**
* Optional - only required if you want this field to appear as one of the default
* columns in a grid in the admin tool
*
* Provide a hint to the GUI about the prominence of this field.
* For example, prominent fields will show up as a column in any
* list grid in the admin that displays this entity.
*
* @return whether or not this is a prominent field
*/
boolean prominent() default false;
/**
* Optional - only required if you want to explicitly control column width
* for this field in a grid in the admin tool
*
* Specify the column space this field will occupy in grid widgets.
* This value can be an absolute integer or a percentage. A value
* of "*" will make this field use up equally distributed space.
*
* @return the space utilized in grids for this field
*/
String columnWidth() default "*";
/**
* Optional - only required for BROADLEAF_ENUMERATION field types
*
* For fields with a SupportedFieldType of BROADLEAF_ENUMERATION,
* you must specify the fully qualified class name of the Broadleaf Enumeration here.
*
* @return Broadleaf enumeration class name
*/
String broadleafEnumeration() default "";
/**
* Optional - only required if you want to make the field immutable
*
* Explicityly specify whether or not this field is mutable.
*
* @return whether or not this field is read only
*/
boolean readOnly() default false;
/**
* Optional - only required if you want to provide validation for this field
*
* Specify the validation to use for this field in the admin, if any
*
* @return the configuration for the validation
*/
ValidationConfiguration[] validationConfigurations() default {};
/**
* Optional - only required if you want to explicitly make a field required. This
* setting is normally inferred by the JPA annotations on the field.
*
* Specify whether you would like the admin to require this field,
* even if it is not required by the ORM.
*
* @return the required override enumeration
*/
RequiredOverride requiredOverride() default RequiredOverride.IGNORED;
/**
* Optional - only required if you want to explicitly exclude this field from
* dynamic management by the admin tool
*
* Specify if this field should be excluded from inclusion in the
* admin presentation layer
*
* @return whether or not the field should be excluded
*/
boolean excluded() default false;
/**
* Optional - only required if you want to provide a tooltip for the field
*
* Helpful tooltip to be displayed when the admin user hovers over the field.
* This can be localized by providing a key which will use the GWT
* support for i18N.
*
*/
String tooltip() default "";
/**
* Optional - only required if you want to provide help text for this field
*
* On the form for this entity, this will show a question
* mark icon next to the field. When the user clicks on the icon, whatever
* HTML that is specified in this helpText is shown in a popup.
*
* For i18n support, this can also be a key to a localized version of the text
*
* Reference implementation: http://www.smartclient.com/smartgwt/showcase/#form_details_hints
*
*/
String helpText() default "";
/**
* Optional - only required if you want to provide a hint for this field
*
* Text to display immediately to the right of a form field. For instance, if the user needs
* to put in a date, the hint could be the format the date needs to be in like 'MM/YYYY'.
*
* For i18n support, this can also be a key to a localized version of the text
*
* Reference implementation: http://www.smartclient.com/smartgwt/showcase/#form_details_hints
*/
String hint() default "";
/**
* <p>Optional - propertyName , only required if you want hide the field based on this property's value</p>
*
* <p>If the property is defined and found to be set to false, in the AppConfiguraionService, then this field will be excluded in the
* admin presentation layer</p>
*
* @return name of the property
*/
String showIfProperty() default "";
/**
* Optional - If you have FieldType set to SupportedFieldType.MONEY,
* then you can specify a money currency property field.
*
* @return the currency property field
*/
String currencyCodeField() default "";
/**
* <p>Optional - only required if the fieldType is SupportedFieldType.RULE_SIMPLE or SupportedFieldType.RULE_COMPLEX</p>
*
* <p>Identifies the type for which this rule builder is targeted. See <tt>RuleIdentifier</tt> for a list of
* identifier types supported out-of-the-box. Note - one of the main uses of this value is to help identify
* the proper <tt>RuleBuilderService</tt> instance to generate the correct field value options for this rule builder.</p>
*
* @return The identifier value that denotes what type of rule builder this is - especially influences the fields that are available in the UI
*/
String ruleIdentifier() default "";
/**
* <p>Optional - marks this field as being translatable, which will render the translations modal in the admin UI</p>
*
* @return whether or not this field is translatable
*/
boolean translatable() default false;
} | 0true
| common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentation.java |
958 | public class OrderDaoTest extends BaseTest {
String userName = new String();
Long orderId;
@Resource
private OrderDao orderDao;
@Resource
private CustomerService customerService;
@Test(groups = { "createOrder" }, dataProvider = "basicOrder", dataProviderClass = OrderDataProvider.class, dependsOnGroups = { "readCustomer", "createPhone" })
@Rollback(false)
@Transactional
public void createOrder(Order order) {
userName = "customer1";
Customer customer = customerService.readCustomerByUsername(userName);
assert order.getId() == null;
order.setCustomer(customer);
order = orderDao.save(order);
assert order.getId() != null;
orderId = order.getId();
}
@Test(groups = { "readOrder" }, dependsOnGroups = { "createOrder" })
public void readOrderById() {
Order result = orderDao.readOrderById(orderId);
assert result != null;
}
@Test(groups = { "readOrdersForCustomer" }, dependsOnGroups = { "readCustomer", "createOrder" })
@Transactional
public void readOrdersForCustomer() {
userName = "customer1";
Customer user = customerService.readCustomerByUsername(userName);
List<Order> orders = orderDao.readOrdersForCustomer(user.getId());
assert orders.size() > 0;
}
//FIXME: After the change to cascading the deletion on PaymentResponseItems, this test does not work but for a really
//strange reason; the list of PaymentResponseItems is getting removed from the Hibernate session for some really weird
//reason. This only occurs sometimes, so it is probably due to the somewhat random ordering that TestNG puts around tests
// @Test(groups = {"deleteOrderForCustomer"}, dependsOnGroups = {"readOrder"})
// @Transactional
// public void deleteOrderForCustomer(){
// Order order = orderDao.readOrderById(orderId);
// assert order != null;
// assert order.getId() != null;
// orderDao.delete(order);
// }
} | 0true
| integration_src_test_java_org_broadleafcommerce_core_order_dao_OrderDaoTest.java |
512 | public class OAllCacheEntriesAreUsedException extends ODatabaseException {
public OAllCacheEntriesAreUsedException(String string) {
super(string);
}
public OAllCacheEntriesAreUsedException(String message, Throwable cause) {
super(message, cause);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_exception_OAllCacheEntriesAreUsedException.java |
3,135 | public class QueueProxyImpl<E> extends QueueProxySupport implements IQueue<E>, InitializingObject {
public QueueProxyImpl(String name, QueueService queueService, NodeEngine nodeEngine) {
super(name, queueService, nodeEngine);
}
@Override
public LocalQueueStats getLocalQueueStats() {
return getService().createLocalQueueStats(name, partitionId);
}
@Override
public boolean add(E e) {
if (offer(e)) {
return true;
}
throw new IllegalStateException("Queue is full!");
}
@Override
public boolean offer(E e) {
try {
return offer(e, 0, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
return false;
}
}
@Override
public void put(E e) throws InterruptedException {
offer(e, -1, TimeUnit.MILLISECONDS);
}
@Override
public boolean offer(E e, long timeout, TimeUnit timeUnit) throws InterruptedException {
final NodeEngine nodeEngine = getNodeEngine();
final Data data = nodeEngine.toData(e);
return offerInternal(data, timeUnit.toMillis(timeout));
}
@Override
public E take() throws InterruptedException {
return poll(-1, TimeUnit.MILLISECONDS);
}
@Override
public E poll(long timeout, TimeUnit timeUnit) throws InterruptedException {
final NodeEngine nodeEngine = getNodeEngine();
final Object data = pollInternal(timeUnit.toMillis(timeout));
return nodeEngine.toObject(data);
}
@Override
public int remainingCapacity() {
return config.getMaxSize() - size();
}
@Override
public boolean remove(Object o) {
final NodeEngine nodeEngine = getNodeEngine();
final Data data = nodeEngine.toData(o);
return removeInternal(data);
}
@Override
public boolean contains(Object o) {
final NodeEngine nodeEngine = getNodeEngine();
final Data data = nodeEngine.toData(o);
List<Data> dataSet = new ArrayList<Data>(1);
dataSet.add(data);
return containsInternal(dataSet);
}
@Override
public int drainTo(Collection<? super E> objects) {
return drainTo(objects, -1);
}
@Override
public int drainTo(Collection<? super E> objects, int i) {
final NodeEngine nodeEngine = getNodeEngine();
if (this.equals(objects)) {
throw new IllegalArgumentException("Can not drain to same Queue");
}
Collection<Data> dataList = drainInternal(i);
for (Data data : dataList) {
E e = nodeEngine.toObject(data);
objects.add(e);
}
return dataList.size();
}
@Override
public E remove() {
final E res = poll();
if (res == null) {
throw new NoSuchElementException("Queue is empty!");
}
return res;
}
@Override
public E poll() {
try {
return poll(0, TimeUnit.SECONDS);
} catch (InterruptedException e) {
//todo: interrupt status is lost
return null;
}
}
@Override
public E element() {
final E res = peek();
if (res == null) {
throw new NoSuchElementException("Queue is empty!");
}
return res;
}
@Override
public E peek() {
final NodeEngine nodeEngine = getNodeEngine();
final Object data = peekInternal();
return nodeEngine.toObject(data);
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public Iterator<E> iterator() {
final NodeEngine nodeEngine = getNodeEngine();
return new QueueIterator<E>(listInternal().iterator(), nodeEngine.getSerializationService(), false);
}
@Override
public Object[] toArray() {
final NodeEngine nodeEngine = getNodeEngine();
List<Data> list = listInternal();
int size = list.size();
Object[] array = new Object[size];
for (int i = 0; i < size; i++) {
array[i] = nodeEngine.toObject(list.get(i));
}
return array;
}
@Override
public <T> T[] toArray(T[] ts) {
final NodeEngine nodeEngine = getNodeEngine();
List<Data> list = listInternal();
int size = list.size();
if (ts.length < size) {
ts = (T[]) java.lang.reflect.Array.newInstance(ts.getClass().getComponentType(), size);
}
for (int i = 0; i < size; i++) {
ts[i] = nodeEngine.toObject(list.get(i));
}
return ts;
}
@Override
public boolean containsAll(Collection<?> objects) {
return containsInternal(getDataList(objects));
}
@Override
public boolean addAll(Collection<? extends E> es) {
return addAllInternal(getDataList(es));
}
@Override
public boolean removeAll(Collection<?> objects) {
return compareAndRemove(getDataList(objects), false);
}
@Override
public boolean retainAll(Collection<?> objects) {
return compareAndRemove(getDataList(objects), true);
}
private List<Data> getDataList(Collection<?> objects) {
final NodeEngine nodeEngine = getNodeEngine();
List<Data> dataList = new ArrayList<Data>(objects.size());
for (Object o : objects) {
dataList.add(nodeEngine.toData(o));
}
return dataList;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("IQueue");
sb.append("{name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_queue_proxy_QueueProxyImpl.java |
2,463 | public class PrioritizedEsThreadPoolExecutor extends EsThreadPoolExecutor {
private AtomicLong insertionOrder = new AtomicLong();
PrioritizedEsThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new PriorityBlockingQueue<Runnable>(), threadFactory);
}
public Pending[] getPending() {
Object[] objects = getQueue().toArray();
Pending[] infos = new Pending[objects.length];
for (int i = 0; i < objects.length; i++) {
Object obj = objects[i];
if (obj instanceof TieBreakingPrioritizedRunnable) {
TieBreakingPrioritizedRunnable t = (TieBreakingPrioritizedRunnable) obj;
infos[i] = new Pending(t.runnable, t.priority(), t.insertionOrder);
} else if (obj instanceof PrioritizedFutureTask) {
PrioritizedFutureTask t = (PrioritizedFutureTask) obj;
infos[i] = new Pending(t.task, t.priority, t.insertionOrder);
}
}
return infos;
}
public void execute(Runnable command, final ScheduledExecutorService timer, final TimeValue timeout, final Runnable timeoutCallback) {
if (command instanceof PrioritizedRunnable) {
command = new TieBreakingPrioritizedRunnable((PrioritizedRunnable) command, insertionOrder.incrementAndGet());
} else if (!(command instanceof PrioritizedFutureTask)) { // it might be a callable wrapper...
command = new TieBreakingPrioritizedRunnable(command, Priority.NORMAL, insertionOrder.incrementAndGet());
}
super.execute(command);
if (timeout.nanos() >= 0) {
final Runnable fCommand = command;
timer.schedule(new Runnable() {
@Override
public void run() {
boolean removed = getQueue().remove(fCommand);
if (removed) {
timeoutCallback.run();
}
}
}, timeout.nanos(), TimeUnit.NANOSECONDS);
}
}
@Override
public void execute(Runnable command) {
if (command instanceof PrioritizedRunnable) {
command = new TieBreakingPrioritizedRunnable((PrioritizedRunnable) command, insertionOrder.incrementAndGet());
} else if (!(command instanceof PrioritizedFutureTask)) { // it might be a callable wrapper...
command = new TieBreakingPrioritizedRunnable(command, Priority.NORMAL, insertionOrder.incrementAndGet());
}
super.execute(command);
}
@Override
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
if (!(runnable instanceof PrioritizedRunnable)) {
runnable = PrioritizedRunnable.wrap(runnable, Priority.NORMAL);
}
return new PrioritizedFutureTask<T>((PrioritizedRunnable) runnable, value, insertionOrder.incrementAndGet());
}
@Override
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
if (!(callable instanceof PrioritizedCallable)) {
callable = PrioritizedCallable.wrap(callable, Priority.NORMAL);
}
return new PrioritizedFutureTask<T>((PrioritizedCallable<T>) callable, insertionOrder.incrementAndGet());
}
public static class Pending {
public final Object task;
public final Priority priority;
public final long insertionOrder;
public Pending(Object task, Priority priority, long insertionOrder) {
this.task = task;
this.priority = priority;
this.insertionOrder = insertionOrder;
}
}
static class TieBreakingPrioritizedRunnable extends PrioritizedRunnable {
final Runnable runnable;
final long insertionOrder;
TieBreakingPrioritizedRunnable(PrioritizedRunnable runnable, long insertionOrder) {
this(runnable, runnable.priority(), insertionOrder);
}
TieBreakingPrioritizedRunnable(Runnable runnable, Priority priority, long insertionOrder) {
super(priority);
this.runnable = runnable;
this.insertionOrder = insertionOrder;
}
@Override
public void run() {
runnable.run();
}
@Override
public int compareTo(PrioritizedRunnable pr) {
int res = super.compareTo(pr);
if (res != 0 || !(pr instanceof TieBreakingPrioritizedRunnable)) {
return res;
}
return insertionOrder < ((TieBreakingPrioritizedRunnable) pr).insertionOrder ? -1 : 1;
}
}
static class PrioritizedFutureTask<T> extends FutureTask<T> implements Comparable<PrioritizedFutureTask> {
final Object task;
final Priority priority;
final long insertionOrder;
public PrioritizedFutureTask(PrioritizedRunnable runnable, T value, long insertionOrder) {
super(runnable, value);
this.task = runnable;
this.priority = runnable.priority();
this.insertionOrder = insertionOrder;
}
public PrioritizedFutureTask(PrioritizedCallable<T> callable, long insertionOrder) {
super(callable);
this.task = callable;
this.priority = callable.priority();
this.insertionOrder = insertionOrder;
}
@Override
public int compareTo(PrioritizedFutureTask pft) {
int res = priority.compareTo(pft.priority);
if (res != 0) {
return res;
}
return insertionOrder < pft.insertionOrder ? -1 : 1;
}
}
} | 0true
| src_main_java_org_elasticsearch_common_util_concurrent_PrioritizedEsThreadPoolExecutor.java |
1,958 | public static class JoinException extends RuntimeException {
private JoinException(IOException cause) {
super(cause);
}
private static final long serialVersionUID = 1L;
} | 0true
| src_main_java_org_elasticsearch_common_inject_internal_Join.java |
3,606 | public static class Builder extends NumberFieldMapper.Builder<Builder, ShortFieldMapper> {
protected Short nullValue = Defaults.NULL_VALUE;
public Builder(String name) {
super(name, new FieldType(Defaults.FIELD_TYPE));
builder = this;
}
public Builder nullValue(short nullValue) {
this.nullValue = nullValue;
return this;
}
@Override
public ShortFieldMapper build(BuilderContext context) {
fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f);
ShortFieldMapper fieldMapper = new ShortFieldMapper(buildNames(context), precisionStep, boost, fieldType, docValues, nullValue,
ignoreMalformed(context), coerce(context),postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings,
context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
fieldMapper.includeInAll(includeInAll);
return fieldMapper;
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_core_ShortFieldMapper.java |
1,229 | addOperation(operations, new Runnable() {
public void run() {
IMap map = hazelcast.getMap("myMap");
try {
map.getAsync(random.nextInt(SIZE)).get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
}, 1); | 0true
| hazelcast_src_main_java_com_hazelcast_examples_AllTest.java |
651 | public class GetIndexTemplatesRequestBuilder extends MasterNodeReadOperationRequestBuilder<GetIndexTemplatesRequest, GetIndexTemplatesResponse, GetIndexTemplatesRequestBuilder> {
public GetIndexTemplatesRequestBuilder(IndicesAdminClient indicesClient) {
super((InternalIndicesAdminClient) indicesClient, new GetIndexTemplatesRequest());
}
public GetIndexTemplatesRequestBuilder(IndicesAdminClient indicesClient, String... names) {
super((InternalIndicesAdminClient) indicesClient, new GetIndexTemplatesRequest(names));
}
@Override
protected void doExecute(ActionListener<GetIndexTemplatesResponse> listener) {
((IndicesAdminClient) client).getTemplates(request, listener);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_template_get_GetIndexTemplatesRequestBuilder.java |
93 | @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ConsoleCommand {
String[] aliases() default {};
String description() default "";
boolean splitInWords() default true;
} | 0true
| commons_src_main_java_com_orientechnologies_common_console_annotation_ConsoleCommand.java |
251 | fCollapseImports= new FoldingAction(getResourceBundle(), "Projection.CollapseImports.") {
public void run() {
if (editor instanceof CeylonEditor) {
ProjectionAnnotationModel pam = ((CeylonEditor) editor).getCeylonSourceViewer()
.getProjectionAnnotationModel();
for (@SuppressWarnings("unchecked")
Iterator<ProjectionAnnotation> iter=pam.getAnnotationIterator(); iter.hasNext();) {
ProjectionAnnotation pa = iter.next();
if (pa instanceof CeylonProjectionAnnotation) {
int tt = ((CeylonProjectionAnnotation) pa).getTokenType();
if (tt==CeylonLexer.IMPORT) {
pam.collapse(pa);
}
}
}
}
}
}; | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_FoldingActionGroup.java |
1,445 | private static final SoftLock LOCK_FAILURE = new SoftLock() {
@Override
public String toString() {
return "Lock::Failure";
}
}; | 0true
| hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_local_LocalRegionCache.java |
712 | public class CountRequest extends BroadcastOperationRequest<CountRequest> {
private static final XContentType contentType = Requests.CONTENT_TYPE;
public static final float DEFAULT_MIN_SCORE = -1f;
private float minScore = DEFAULT_MIN_SCORE;
@Nullable
protected String routing;
@Nullable
private String preference;
private BytesReference source;
private boolean sourceUnsafe;
private String[] types = Strings.EMPTY_ARRAY;
long nowInMillis;
CountRequest() {
}
/**
* Constructs a new count request against the provided indices. No indices provided means it will
* run against all indices.
*/
public CountRequest(String... indices) {
super(indices);
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = super.validate();
return validationException;
}
@Override
protected void beforeStart() {
if (sourceUnsafe) {
source = source.copyBytesArray();
sourceUnsafe = false;
}
}
/**
* The minimum score of the documents to include in the count.
*/
float minScore() {
return minScore;
}
/**
* The minimum score of the documents to include in the count. Defaults to <tt>-1</tt> which means all
* documents will be included in the count.
*/
public CountRequest minScore(float minScore) {
this.minScore = minScore;
return this;
}
/**
* The source to execute.
*/
BytesReference source() {
return source;
}
/**
* The source to execute.
*/
public CountRequest source(QuerySourceBuilder sourceBuilder) {
this.source = sourceBuilder.buildAsBytes(contentType);
this.sourceUnsafe = false;
return this;
}
/**
* The source to execute in the form of a map.
*/
public CountRequest source(Map querySource) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(contentType);
builder.map(querySource);
return source(builder);
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + querySource + "]", e);
}
}
public CountRequest source(XContentBuilder builder) {
this.source = builder.bytes();
this.sourceUnsafe = false;
return this;
}
/**
* The source to execute. It is preferable to use either {@link #source(byte[])}
* or {@link #source(QuerySourceBuilder)}.
*/
public CountRequest source(String querySource) {
this.source = new BytesArray(querySource);
this.sourceUnsafe = false;
return this;
}
/**
* The source to execute.
*/
public CountRequest source(byte[] querySource) {
return source(querySource, 0, querySource.length, false);
}
/**
* The source to execute.
*/
public CountRequest source(byte[] querySource, int offset, int length, boolean unsafe) {
return source(new BytesArray(querySource, offset, length), unsafe);
}
public CountRequest source(BytesReference querySource, boolean unsafe) {
this.source = querySource;
this.sourceUnsafe = unsafe;
return this;
}
/**
* The types of documents the query will run against. Defaults to all types.
*/
public String[] types() {
return this.types;
}
/**
* The types of documents the query will run against. Defaults to all types.
*/
public CountRequest types(String... types) {
this.types = types;
return this;
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public String routing() {
return this.routing;
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public CountRequest routing(String routing) {
this.routing = routing;
return this;
}
/**
* The routing values to control the shards that the search will be executed on.
*/
public CountRequest routing(String... routings) {
this.routing = Strings.arrayToCommaDelimitedString(routings);
return this;
}
public CountRequest preference(String preference) {
this.preference = preference;
return this;
}
public String preference() {
return this.preference;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
minScore = in.readFloat();
routing = in.readOptionalString();
preference = in.readOptionalString();
sourceUnsafe = false;
source = in.readBytesReference();
types = in.readStringArray();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeFloat(minScore);
out.writeOptionalString(routing);
out.writeOptionalString(preference);
out.writeBytesReference(source);
out.writeStringArray(types);
}
@Override
public String toString() {
String sSource = "_na_";
try {
sSource = XContentHelper.convertToJson(source, false);
} catch (Exception e) {
// ignore
}
return "[" + Arrays.toString(indices) + "]" + Arrays.toString(types) + ", source[" + sSource + "]";
}
} | 0true
| src_main_java_org_elasticsearch_action_count_CountRequest.java |
15 | static final class DescendingSubMap<K, V> extends NavigableSubMap<K, V> {
private static final long serialVersionUID = 912986545866120460L;
private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator);
DescendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
final K hi, final boolean hiInclusive) {
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
public Comparator<? super K> comparator() {
return reverseComparator;
}
public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) {
if (!inRange(fromKey, fromInclusive))
throw new IllegalArgumentException("fromKey out of range");
if (!inRange(toKey, toInclusive))
throw new IllegalArgumentException("toKey out of range");
return new DescendingSubMap<K, V>(m, false, toKey, toInclusive, false, fromKey, fromInclusive);
}
public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) {
if (!inRange(toKey, inclusive))
throw new IllegalArgumentException("toKey out of range");
return new DescendingSubMap<K, V>(m, false, toKey, inclusive, toEnd, hi, hiInclusive);
}
public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) {
if (!inRange(fromKey, inclusive))
throw new IllegalArgumentException("fromKey out of range");
return new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, fromKey, inclusive);
}
public ONavigableMap<K, V> descendingMap() {
ONavigableMap<K, V> mv = descendingMapView;
return (mv != null) ? mv : (descendingMapView = new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi,
hiInclusive));
}
@Override
OLazyIterator<K> keyIterator() {
return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
}
@Override
OLazyIterator<K> descendingKeyIterator() {
return new SubMapKeyIterator(absLowest(), absHighFence());
}
final class DescendingEntrySetView extends EntrySetView {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
}
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
EntrySetView es = entrySetView;
return (es != null) ? es : new DescendingEntrySetView();
}
@Override
OMVRBTreeEntry<K, V> subLowest() {
return absHighest().entry;
}
@Override
OMVRBTreeEntry<K, V> subHighest() {
return absLowest().entry;
}
@Override
OMVRBTreeEntry<K, V> subCeiling(final K key) {
return absFloor(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subHigher(final K key) {
return absLower(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subFloor(final K key) {
return absCeiling(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subLower(final K key) {
return absHigher(key).entry;
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
1,043 | @Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_ORDER_ITEM_PRICE_DTL")
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
@AdminPresentationMergeOverrides(
{
@AdminPresentationMergeOverride(name = "", mergeEntries =
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.READONLY,
booleanOverrideValue = true))
}
)
public class OrderItemPriceDetailImpl implements OrderItemPriceDetail, CurrencyCodeIdentifiable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "OrderItemPriceDetailId")
@GenericGenerator(
name="OrderItemPriceDetailId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="OrderItemPriceDetailImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.order.domain.OrderItemPriceDetailImpl")
}
)
@Column(name = "ORDER_ITEM_PRICE_DTL_ID")
@AdminPresentation(friendlyName = "OrderItemPriceDetailImpl_Id", group = "OrderItemPriceDetailImpl_Primary_Key", visibility = VisibilityEnum.HIDDEN_ALL)
protected Long id;
@ManyToOne(targetEntity = OrderItemImpl.class)
@JoinColumn(name = "ORDER_ITEM_ID")
@AdminPresentation(excluded = true)
protected OrderItem orderItem;
@OneToMany(mappedBy = "orderItemPriceDetail", targetEntity = OrderItemPriceDetailAdjustmentImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "blOrderElements")
@AdminPresentationCollection(addType = AddMethodType.PERSIST, friendlyName = "OrderItemPriceDetailImpl_orderItemPriceDetailAdjustments")
protected List<OrderItemPriceDetailAdjustment> orderItemPriceDetailAdjustments = new ArrayList<OrderItemPriceDetailAdjustment>();
@Column(name = "QUANTITY", nullable=false)
@AdminPresentation(friendlyName = "OrderItemPriceDetailImpl_quantity", order = 5, group = "OrderItemPriceDetailImpl_Pricing", prominent = true)
protected int quantity;
@Column(name = "USE_SALE_PRICE")
@AdminPresentation(friendlyName = "OrderItemPriceDetailImpl_useSalePrice", order = 5, group = "OrderItemPriceDetailImpl_Pricing", prominent = true)
protected Boolean useSalePrice = true;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public OrderItem getOrderItem() {
return orderItem;
}
@Override
public void setOrderItem(OrderItem orderItem) {
this.orderItem = orderItem;
}
@Override
public List<OrderItemPriceDetailAdjustment> getOrderItemPriceDetailAdjustments() {
return orderItemPriceDetailAdjustments;
}
@Override
public void setOrderItemAdjustments(List<OrderItemPriceDetailAdjustment> orderItemPriceDetailAdjustments) {
this.orderItemPriceDetailAdjustments = orderItemPriceDetailAdjustments;
}
@Override
public int getQuantity() {
return quantity;
}
@Override
public void setQuantity(int quantity) {
this.quantity = quantity;
}
protected BroadleafCurrency getCurrency() {
return getOrderItem().getOrder().getCurrency();
}
@Override
public Money getAdjustmentValue() {
Money adjustmentValue = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, getCurrency());
for (OrderItemPriceDetailAdjustment adjustment : orderItemPriceDetailAdjustments) {
adjustmentValue = adjustmentValue.add(adjustment.getValue());
}
return adjustmentValue;
}
@Override
public Money getTotalAdjustmentValue() {
return getAdjustmentValue().multiply(quantity);
}
@Override
public Money getTotalAdjustedPrice() {
Money basePrice = orderItem.getPriceBeforeAdjustments(getUseSalePrice());
return basePrice.multiply(quantity).subtract(getTotalAdjustmentValue());
}
@Override
public boolean getUseSalePrice() {
if (useSalePrice == null) {
return false;
} else {
return useSalePrice;
}
}
@Override
public void setUseSalePrice(boolean useSalePrice) {
this.useSalePrice = Boolean.valueOf(useSalePrice);
}
@Override
public String getCurrencyCode() {
if (getCurrency() != null) {
return getCurrency().getCurrencyCode();
}
return null;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_OrderItemPriceDetailImpl.java |
341 | private static class PartitionAwareKey implements PartitionAware, Serializable {
private final String key;
private final String pk;
private PartitionAwareKey(String key, String pk) {
this.key = key;
this.pk = pk;
}
@Override
public Object getPartitionKey() {
return pk;
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.