Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
349 |
transportService.sendRequest(state.nodes().masterNode(), NodeShutdownRequestHandler.ACTION, new NodeShutdownRequest(request), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleResponse(TransportResponse.Empty response) {
logger.trace("[cluster_shutdown]: received shutdown response from master");
}
@Override
public void handleException(TransportException exp) {
logger.warn("[cluster_shutdown]: received failed shutdown response master", exp);
}
});
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_shutdown_TransportNodesShutdownAction.java
|
354 |
public enum RUN_MODE {
DEFAULT, RUNNING_DISTRIBUTED
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_OScenarioThreadLocal.java
|
417 |
public class TransportGetSnapshotsAction extends TransportMasterNodeOperationAction<GetSnapshotsRequest, GetSnapshotsResponse> {
private final SnapshotsService snapshotsService;
@Inject
public TransportGetSnapshotsAction(Settings settings, TransportService transportService, ClusterService clusterService,
ThreadPool threadPool, SnapshotsService snapshotsService) {
super(settings, transportService, clusterService, threadPool);
this.snapshotsService = snapshotsService;
}
@Override
protected String executor() {
return ThreadPool.Names.SNAPSHOT;
}
@Override
protected String transportAction() {
return GetSnapshotsAction.NAME;
}
@Override
protected GetSnapshotsRequest newRequest() {
return new GetSnapshotsRequest();
}
@Override
protected GetSnapshotsResponse newResponse() {
return new GetSnapshotsResponse();
}
@Override
protected ClusterBlockException checkBlock(GetSnapshotsRequest request, ClusterState state) {
return state.blocks().indexBlockedException(ClusterBlockLevel.METADATA, "");
}
@Override
protected void masterOperation(final GetSnapshotsRequest request, ClusterState state, final ActionListener<GetSnapshotsResponse> listener) throws ElasticsearchException {
SnapshotId[] snapshotIds = new SnapshotId[request.snapshots().length];
for (int i = 0; i < snapshotIds.length; i++) {
snapshotIds[i] = new SnapshotId(request.repository(), request.snapshots()[i]);
}
try {
ImmutableList.Builder<SnapshotInfo> snapshotInfoBuilder = ImmutableList.builder();
if (snapshotIds.length > 0) {
for (SnapshotId snapshotId : snapshotIds) {
snapshotInfoBuilder.add(new SnapshotInfo(snapshotsService.snapshot(snapshotId)));
}
} else {
ImmutableList<Snapshot> snapshots = snapshotsService.snapshots(request.repository());
for (Snapshot snapshot : snapshots) {
snapshotInfoBuilder.add(new SnapshotInfo(snapshot));
}
}
listener.onResponse(new GetSnapshotsResponse(snapshotInfoBuilder.build()));
} catch (Throwable t) {
listener.onFailure(t);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_get_TransportGetSnapshotsAction.java
|
138 |
class FindBodyVisitor extends Visitor {
@Override
public void visit(Tree.Body that) {
super.visit(that);
if (that.getStatements().contains(statement)) {
for (Tree.Statement st: that.getStatements()) {
if (st instanceof Tree.AttributeDeclaration) {
Tree.AttributeDeclaration ad =
(Tree.AttributeDeclaration) st;
if (ad.getDeclarationModel().equals(dec) &&
ad.getSpecifierOrInitializerExpression()==null) {
createJoinDeclarationProposal(proposals,
spec, file, dec, that,
that.getStatements().indexOf(st),
ad);
break;
}
}
}
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_JoinDeclarationProposal.java
|
2,071 |
public class MergeOperation extends BasePutOperation {
private MapMergePolicy mergePolicy;
private EntryView<Data, Data> mergingEntry;
private boolean merged = false;
public MergeOperation(String name, Data dataKey, EntryView<Data, Data> entryView, MapMergePolicy policy) {
super(name, dataKey, null);
mergingEntry = entryView;
mergePolicy = policy;
}
public MergeOperation() {
}
public void run() {
SimpleEntryView entryView = (SimpleEntryView) mergingEntry;
entryView.setKey(mapService.toObject(mergingEntry.getKey()));
entryView.setValue(mapService.toObject(mergingEntry.getValue()));
merged = recordStore.merge(dataKey, mergingEntry, mergePolicy);
if (merged) {
Record record = recordStore.getRecord(dataKey);
if (record != null)
dataValue = mapService.toData(record.getValue());
}
}
@Override
public Object getResponse() {
return merged;
}
public boolean shouldBackup() {
return merged;
}
public void afterRun() {
if (merged) {
invalidateNearCaches();
}
}
public Operation getBackupOperation() {
if (dataValue == null) {
return new RemoveBackupOperation(name, dataKey);
} else {
RecordInfo replicationInfo = mapService.createRecordInfo(recordStore.getRecord(dataKey));
return new PutBackupOperation(name, dataKey, dataValue, replicationInfo);
}
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeObject(mergingEntry);
out.writeObject(mergePolicy);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
mergingEntry = in.readObject();
mergePolicy = in.readObject();
}
@Override
public String toString() {
return "MergeOperation{" + name + "}";
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_map_operation_MergeOperation.java
|
4,058 |
public class CustomQueryWrappingFilter extends NoCacheFilter implements Releasable {
private final Query query;
private IndexSearcher searcher;
private IdentityHashMap<AtomicReader, DocIdSet> docIdSets;
/** Constructs a filter which only matches documents matching
* <code>query</code>.
*/
public CustomQueryWrappingFilter(Query query) {
if (query == null)
throw new NullPointerException("Query may not be null");
this.query = query;
}
/** returns the inner Query */
public final Query getQuery() {
return query;
}
@Override
public DocIdSet getDocIdSet(final AtomicReaderContext context, final Bits acceptDocs) throws IOException {
final SearchContext searchContext = SearchContext.current();
if (docIdSets == null) {
assert searcher == null;
IndexSearcher searcher = searchContext.searcher();
docIdSets = new IdentityHashMap<AtomicReader, DocIdSet>();
this.searcher = searcher;
searchContext.addReleasable(this);
final Weight weight = searcher.createNormalizedWeight(query);
for (final AtomicReaderContext leaf : searcher.getTopReaderContext().leaves()) {
final DocIdSet set = DocIdSets.toCacheable(leaf.reader(), new DocIdSet() {
@Override
public DocIdSetIterator iterator() throws IOException {
return weight.scorer(leaf, true, false, null);
}
@Override
public boolean isCacheable() { return false; }
});
docIdSets.put(leaf.reader(), set);
}
} else {
assert searcher == SearchContext.current().searcher();
}
final DocIdSet set = docIdSets.get(context.reader());
if (set != null && acceptDocs != null) {
return BitsFilteredDocIdSet.wrap(set, acceptDocs);
}
return set;
}
@Override
public boolean release() throws ElasticsearchException {
// We need to clear the docIdSets, otherwise this is leaved unused
// DocIdSets around and can potentially become a memory leak.
docIdSets = null;
searcher = null;
return true;
}
@Override
public String toString() {
return "CustomQueryWrappingFilter(" + query + ")";
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o != null && o instanceof CustomQueryWrappingFilter &&
this.query.equals(((CustomQueryWrappingFilter)o).query)) {
return true;
}
return false;
}
@Override
public int hashCode() {
return query.hashCode() ^ 0x823D64C9;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_search_child_CustomQueryWrappingFilter.java
|
244 |
public class ODefaultCache extends OAbstractMapCache<ODefaultCache.OLinkedHashMapCache> {
private static final int DEFAULT_LIMIT = 1000;
protected final int limit;
protected OMemoryWatchDog.Listener lowMemoryListener;
public ODefaultCache(final String iName, final int initialLimit) {
super(new OLinkedHashMapCache(initialLimit > 0 ? initialLimit : DEFAULT_LIMIT, 0.75f, initialLimit));
limit = initialLimit;
}
@Override
public void startup() {
lowMemoryListener = Orient.instance().getMemoryWatchDog().addListener(new OLowMemoryListener());
super.startup();
}
@Override
public void shutdown() {
Orient.instance().getMemoryWatchDog().removeListener(lowMemoryListener);
super.shutdown();
}
private void removeEldest(final int threshold) {
lock.acquireExclusiveLock();
try {
cache.removeEldest(threshold);
} finally {
lock.releaseExclusiveLock();
}
}
@Override
public int limit() {
return limit;
}
/**
* Implementation of {@link LinkedHashMap} that will remove eldest entries if size limit will be exceeded.
*
* @author Luca Garulli
*/
@SuppressWarnings("serial")
static final class OLinkedHashMapCache extends OLimitedMap<ORID, ORecordInternal<?>> {
public OLinkedHashMapCache(final int initialCapacity, final float loadFactor, final int limit) {
super(initialCapacity, loadFactor, limit);
}
void removeEldest(final int amount) {
final ORID[] victims = new ORID[amount];
final int skip = size() - amount;
int skipped = 0;
int selected = 0;
for (Map.Entry<ORID, ORecordInternal<?>> entry : entrySet()) {
if (entry.getValue().isDirty() || entry.getValue().isPinned() == Boolean.TRUE || skipped++ < skip)
continue;
victims[selected++] = entry.getKey();
}
for (ORID id : victims)
remove(id);
}
}
class OLowMemoryListener implements OMemoryWatchDog.Listener {
public void memoryUsageLow(final long freeMemory, final long freeMemoryPercentage) {
try {
final int oldSize = size();
if (oldSize == 0)
return;
if (freeMemoryPercentage < 10) {
OLogManager.instance().debug(this, "Low memory (%d%%): clearing %d cached records", freeMemoryPercentage, size());
removeEldest(oldSize);
} else {
final int newSize = (int) (oldSize * 0.9f);
removeEldest(oldSize - newSize);
OLogManager.instance().debug(this, "Low memory (%d%%): reducing cached records number from %d to %d",
freeMemoryPercentage, oldSize, newSize);
}
} catch (Exception e) {
OLogManager.instance().error(this, "Error occurred during default cache cleanup", e);
}
}
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_cache_ODefaultCache.java
|
1,367 |
public class ClusterBlock implements Serializable, Streamable, ToXContent {
private int id;
private String description;
private ClusterBlockLevel[] levels;
private boolean retryable;
private boolean disableStatePersistence = false;
private RestStatus status;
ClusterBlock() {
}
public ClusterBlock(int id, String description, boolean retryable, boolean disableStatePersistence, RestStatus status, ClusterBlockLevel... levels) {
this.id = id;
this.description = description;
this.retryable = retryable;
this.disableStatePersistence = disableStatePersistence;
this.status = status;
this.levels = levels;
}
public int id() {
return this.id;
}
public String description() {
return this.description;
}
public RestStatus status() {
return this.status;
}
public ClusterBlockLevel[] levels() {
return this.levels;
}
public boolean contains(ClusterBlockLevel level) {
for (ClusterBlockLevel testLevel : levels) {
if (testLevel == level) {
return true;
}
}
return false;
}
/**
* Should operations get into retry state if this block is present.
*/
public boolean retryable() {
return this.retryable;
}
/**
* Should global state persistence be disabled when this block is present. Note,
* only relevant for global blocks.
*/
public boolean disableStatePersistence() {
return this.disableStatePersistence;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Integer.toString(id));
builder.field("description", description);
builder.field("retryable", retryable);
if (disableStatePersistence) {
builder.field("disable_state_persistence", disableStatePersistence);
}
builder.startArray("levels");
for (ClusterBlockLevel level : levels) {
builder.value(level.name().toLowerCase(Locale.ROOT));
}
builder.endArray();
builder.endObject();
return builder;
}
public static ClusterBlock readClusterBlock(StreamInput in) throws IOException {
ClusterBlock block = new ClusterBlock();
block.readFrom(in);
return block;
}
@Override
public void readFrom(StreamInput in) throws IOException {
id = in.readVInt();
description = in.readString();
levels = new ClusterBlockLevel[in.readVInt()];
for (int i = 0; i < levels.length; i++) {
levels[i] = ClusterBlockLevel.fromId(in.readVInt());
}
retryable = in.readBoolean();
disableStatePersistence = in.readBoolean();
status = RestStatus.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(id);
out.writeString(description);
out.writeVInt(levels.length);
for (ClusterBlockLevel level : levels) {
out.writeVInt(level.id());
}
out.writeBoolean(retryable);
out.writeBoolean(disableStatePersistence);
RestStatus.writeTo(out, status);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(id).append(",").append(description).append(", blocks ");
for (ClusterBlockLevel level : levels) {
sb.append(level.name()).append(",");
}
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClusterBlock that = (ClusterBlock) o;
if (id != that.id) return false;
return true;
}
@Override
public int hashCode() {
return id;
}
}
| 1no label
|
src_main_java_org_elasticsearch_cluster_block_ClusterBlock.java
|
17 |
public class CompletionProposal implements ICompletionProposal,
ICompletionProposalExtension2, ICompletionProposalExtension4,
ICompletionProposalExtension6 {
protected final String text;
private final Image image;
protected final String prefix;
private final String description;
protected int offset;
private int length;
private boolean toggleOverwrite;
public CompletionProposal(int offset, String prefix, Image image,
String desc, String text) {
this.text = text;
this.image = image;
this.offset = offset;
this.prefix = prefix;
this.length = prefix.length();
this.description = desc;
Assert.isNotNull(description);
}
@Override
public Image getImage() {
return image;
}
@Override
public Point getSelection(IDocument document) {
return new Point(offset + text.length() - prefix.length(), 0);
}
public void apply(IDocument document) {
try {
document.replace(start(), length(document),
withoutDupeSemi(document));
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
protected ReplaceEdit createEdit(IDocument document) {
return new ReplaceEdit(start(), length(document),
withoutDupeSemi(document));
}
public int length(IDocument document) {
String overwrite = EditorsUI.getPreferenceStore().getString(COMPLETION);
if ("overwrite".equals(overwrite)!=toggleOverwrite) {
int length = prefix.length();
try {
for (int i=offset;
i<document.getLength() &&
Character.isJavaIdentifierPart(document.getChar(i));
i++) {
length++;
}
}
catch (BadLocationException e) {
e.printStackTrace();
}
return length;
}
else {
return this.length;
}
}
public int start() {
return offset-prefix.length();
}
public String withoutDupeSemi(IDocument document) {
try {
if (text.endsWith(";") &&
document.getChar(offset)==';') {
return text.substring(0,text.length()-1);
}
}
catch (BadLocationException e) {
e.printStackTrace();
}
return text;
}
public String getDisplayString() {
return description;
}
public String getAdditionalProposalInfo() {
return null;
}
@Override
public boolean isAutoInsertable() {
return true;
}
protected boolean qualifiedNameIsPath() {
return false;
}
@Override
public StyledString getStyledDisplayString() {
StyledString result = new StyledString();
Highlights.styleProposal(result, getDisplayString(),
qualifiedNameIsPath());
return result;
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask,
int offset) {
toggleOverwrite = (stateMask&SWT.CTRL)!=0;
length = prefix.length() + offset - this.offset;
apply(viewer.getDocument());
}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int offset, DocumentEvent event) {
if (offset<this.offset) {
return false;
}
try {
//TODO: really this strategy is only applicable
// for completion of declaration names, so
// move this implementation to subclasses
int start = this.offset-prefix.length();
String typedText = document.get(start, offset-start);
return isNameMatching(typedText, text);
// String typedText = document.get(this.offset, offset-this.offset);
// return text.substring(prefix.length())
// .startsWith(typedText);
}
catch (BadLocationException e) {
return false;
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CompletionProposal.java
|
362 |
public enum DIRECTION {
BOTH, IN, OUT
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_graph_OGraphDatabase.java
|
855 |
public abstract class ReadRequest extends PartitionClientRequest implements Portable, SecureRequest {
protected String name;
public ReadRequest() {
}
public ReadRequest(String name) {
this.name = name;
}
@Override
protected int getPartition() {
ClientEngine clientEngine = getClientEngine();
Data key = clientEngine.getSerializationService().toData(name);
return clientEngine.getPartitionService().getPartitionId(key);
}
@Override
public String getServiceName() {
return AtomicReferenceService.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return AtomicReferencePortableHook.F_ID;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
}
@Override
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
}
@Override
public Permission getRequiredPermission() {
return new AtomicReferencePermission(name, ActionConstants.ACTION_READ);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_ReadRequest.java
|
366 |
public static class TestReducer
extends Reducer<String, Integer, Integer> {
private transient int sum = 0;
@Override
public void reduce(Integer value) {
sum += value;
}
@Override
public Integer finalizeReduce() {
return sum;
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_ClientMapReduceTest.java
|
503 |
public class CreateIndexRequest extends AcknowledgedRequest<CreateIndexRequest> {
private String cause = "";
private String index;
private Settings settings = EMPTY_SETTINGS;
private Map<String, String> mappings = newHashMap();
private Map<String, IndexMetaData.Custom> customs = newHashMap();
CreateIndexRequest() {
}
/**
* Constructs a new request to create an index with the specified name.
*/
public CreateIndexRequest(String index) {
this(index, EMPTY_SETTINGS);
}
/**
* Constructs a new request to create an index with the specified name and settings.
*/
public CreateIndexRequest(String index, Settings settings) {
this.index = index;
this.settings = settings;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (index == null) {
validationException = addValidationError("index is missing", validationException);
}
return validationException;
}
/**
* The index name to create.
*/
String index() {
return index;
}
public CreateIndexRequest index(String index) {
this.index = index;
return this;
}
/**
* The settings to create the index with.
*/
Settings settings() {
return settings;
}
/**
* The cause for this index creation.
*/
String cause() {
return cause;
}
/**
* A simplified version of settings that takes key value pairs settings.
*/
public CreateIndexRequest settings(Object... settings) {
this.settings = ImmutableSettings.builder().put(settings).build();
return this;
}
/**
* The settings to create the index with.
*/
public CreateIndexRequest settings(Settings settings) {
this.settings = settings;
return this;
}
/**
* The settings to create the index with.
*/
public CreateIndexRequest settings(Settings.Builder settings) {
this.settings = settings.build();
return this;
}
/**
* The settings to create the index with (either json/yaml/properties format)
*/
public CreateIndexRequest settings(String source) {
this.settings = ImmutableSettings.settingsBuilder().loadFromSource(source).build();
return this;
}
/**
* Allows to set the settings using a json builder.
*/
public CreateIndexRequest settings(XContentBuilder builder) {
try {
settings(builder.string());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate json settings from builder", e);
}
return this;
}
/**
* The settings to create the index with (either json/yaml/properties format)
*/
@SuppressWarnings("unchecked")
public CreateIndexRequest settings(Map source) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.map(source);
settings(builder.string());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
}
return this;
}
/**
* Adds mapping that will be added when the index gets created.
*
* @param type The mapping type
* @param source The mapping source
*/
public CreateIndexRequest mapping(String type, String source) {
mappings.put(type, source);
return this;
}
/**
* The cause for this index creation.
*/
public CreateIndexRequest cause(String cause) {
this.cause = cause;
return this;
}
/**
* Adds mapping that will be added when the index gets created.
*
* @param type The mapping type
* @param source The mapping source
*/
public CreateIndexRequest mapping(String type, XContentBuilder source) {
try {
mappings.put(type, source.string());
} catch (IOException e) {
throw new ElasticsearchIllegalArgumentException("Failed to build json for mapping request", e);
}
return this;
}
/**
* Adds mapping that will be added when the index gets created.
*
* @param type The mapping type
* @param source The mapping source
*/
@SuppressWarnings("unchecked")
public CreateIndexRequest mapping(String type, Map source) {
// wrap it in a type map if its not
if (source.size() != 1 || !source.containsKey(type)) {
source = MapBuilder.<String, Object>newMapBuilder().put(type, source).map();
}
try {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.map(source);
return mapping(type, builder.string());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
}
}
/**
* A specialized simplified mapping source method, takes the form of simple properties definition:
* ("field1", "type=string,store=true").
*/
public CreateIndexRequest mapping(String type, Object... source) {
mapping(type, PutMappingRequest.buildFromSimplifiedDef(type, source));
return this;
}
/**
* Sets the settings and mappings as a single source.
*/
public CreateIndexRequest source(String source) {
return source(source.getBytes(Charsets.UTF_8));
}
/**
* Sets the settings and mappings as a single source.
*/
public CreateIndexRequest source(XContentBuilder source) {
return source(source.bytes());
}
/**
* Sets the settings and mappings as a single source.
*/
public CreateIndexRequest source(byte[] source) {
return source(source, 0, source.length);
}
/**
* Sets the settings and mappings as a single source.
*/
public CreateIndexRequest source(byte[] source, int offset, int length) {
return source(new BytesArray(source, offset, length));
}
/**
* Sets the settings and mappings as a single source.
*/
public CreateIndexRequest source(BytesReference source) {
XContentType xContentType = XContentFactory.xContentType(source);
if (xContentType != null) {
try {
source(XContentFactory.xContent(xContentType).createParser(source).mapAndClose());
} catch (IOException e) {
throw new ElasticsearchParseException("failed to parse source for create index", e);
}
} else {
settings(new String(source.toBytes(), Charsets.UTF_8));
}
return this;
}
/**
* Sets the settings and mappings as a single source.
*/
@SuppressWarnings("unchecked")
public CreateIndexRequest source(Map<String, Object> source) {
boolean found = false;
for (Map.Entry<String, Object> entry : source.entrySet()) {
String name = entry.getKey();
if (name.equals("settings")) {
found = true;
settings((Map<String, Object>) entry.getValue());
} else if (name.equals("mappings")) {
found = true;
Map<String, Object> mappings = (Map<String, Object>) entry.getValue();
for (Map.Entry<String, Object> entry1 : mappings.entrySet()) {
mapping(entry1.getKey(), (Map<String, Object>) entry1.getValue());
}
} else {
// maybe custom?
IndexMetaData.Custom.Factory factory = IndexMetaData.lookupFactory(name);
if (factory != null) {
found = true;
try {
customs.put(name, factory.fromMap((Map<String, Object>) entry.getValue()));
} catch (IOException e) {
throw new ElasticsearchParseException("failed to parse custom metadata for [" + name + "]");
}
}
}
}
if (!found) {
// the top level are settings, use them
settings(source);
}
return this;
}
Map<String, String> mappings() {
return this.mappings;
}
/**
* Adds custom metadata to the index to be created.
*/
public CreateIndexRequest custom(IndexMetaData.Custom custom) {
customs.put(custom.type(), custom);
return this;
}
Map<String, IndexMetaData.Custom> customs() {
return this.customs;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
cause = in.readString();
index = in.readString();
settings = readSettingsFromStream(in);
readTimeout(in);
int size = in.readVInt();
for (int i = 0; i < size; i++) {
mappings.put(in.readString(), in.readString());
}
int customSize = in.readVInt();
for (int i = 0; i < customSize; i++) {
String type = in.readString();
IndexMetaData.Custom customIndexMetaData = IndexMetaData.lookupFactorySafe(type).readFrom(in);
customs.put(type, customIndexMetaData);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(cause);
out.writeString(index);
writeSettingsToStream(settings, out);
writeTimeout(out);
out.writeVInt(mappings.size());
for (Map.Entry<String, String> entry : mappings.entrySet()) {
out.writeString(entry.getKey());
out.writeString(entry.getValue());
}
out.writeVInt(customs.size());
for (Map.Entry<String, IndexMetaData.Custom> entry : customs.entrySet()) {
out.writeString(entry.getKey());
IndexMetaData.lookupFactorySafe(entry.getKey()).writeTo(entry.getValue(), out);
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_create_CreateIndexRequest.java
|
1,230 |
SOFT_CONCURRENT {
@Override
<T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors) {
return concurrent(softFactory(dequeFactory(c, limit / availableProcessors)), availableProcessors);
}
},
| 0true
|
src_main_java_org_elasticsearch_cache_recycler_PageCacheRecycler.java
|
1,598 |
public class OperationTypes implements Serializable {
private static final long serialVersionUID = 1L;
private OperationType fetchType = OperationType.BASIC;
private OperationType removeType = OperationType.BASIC;
private OperationType addType = OperationType.BASIC;
private OperationType updateType = OperationType.BASIC;
private OperationType inspectType = OperationType.BASIC;
public OperationTypes() {
//do nothing
}
public OperationTypes(OperationType fetchType, OperationType removeType, OperationType addType, OperationType updateType, OperationType inspectType) {
this.removeType = removeType;
this.addType = addType;
this.updateType = updateType;
this.fetchType = fetchType;
this.inspectType = inspectType;
}
/**
* How should the system execute a removal of this item.
* <p/>
* OperationType BASIC will result in the item being removed based on its primary key
* OperationType NONDESTRUCTIVEREMOVE will result in the item being removed from the containing list in the containing entity. This
* is useful when you don't want the item to actually be deleted, but simply removed from the parent collection.
* OperationType ADORNEDTARGETLIST will result in a join structure being deleted (not either of the associated entities).
* org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl is an example of a join structure entity.
* OperationType MAP will result in the item being removed from the requisite map in the containing entity.
*
* @return the type of remove operation
*/
public OperationType getRemoveType() {
return removeType;
}
/**
* How should the system execute a removal of this item.
* <p/>
* OperationType BASIC will result in the item being removed based on its primary key
* OperationType NONDESTRUCTIVEREMOVE will result in the item being removed from the containing list in the containing entity. This
* is useful when you don't want the item to be removed to actually be deleted, but simply removed from the parent collection.
* OperationType ADORNEDTARGETLIST will result in a join structure being deleted (not either of the associated entities).
* org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl is an example of a join structure entity.
* OperationType MAP will result in the item being removed from the requisite map in the containing entity.
*
* @param removeType
*/
public void setRemoveType(OperationType removeType) {
this.removeType = removeType;
}
/**
* How should the system execute an addition for this item
* <p/>
* OperationType BASIC will result in the item being inserted
* OperationType NONDESTRUCTIVEREMOVE is not supported and will result in the same behavior as BASIC. Note, any foreign key associations in the
* persistence perspective (@see PersistencePerspective) will be honored during the BASIC based add.
* OperationType ADORNEDTARGETLIST will result in a join structure entity being added (not either of the associated entities).
* org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl is an example of a join structure entity.
* OperationType MAP will result in the item being added to the requisite map in the containing entity.
*
* @return the type of the add operation
*/
public OperationType getAddType() {
return addType;
}
/**
* How should the system execute an addition for this item
* <p/>
* OperationType BASIC will result in the item being inserted
* OperationType NONDESTRUCTIVEREMOVE is not supported and will result in the same behavior as BASIC. Note, any foreign key associations in the
* persistence perspective (@see PersistencePerspective) will be honored during the BASIC based add.
* OperationType ADORNEDTARGETLIST will result in a join structure entity being added (not either of the associated entities).
* org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl is an example of a join structure entity.
* OperationType MAP will result in the item being added to the requisite map in the containing entity.
*
* @param addType
*/
public void setAddType(OperationType addType) {
this.addType = addType;
}
/**
* How should the system execute an update for this item
* <p/>
* OperationType BASIC will result in the item being updated based on it's primary key
* OperationType NONDESTRUCTIVEREMOVE is not supported and will result in the same behavior as BASIC. Note, any foreign key associations in the
* persistence perspective (@see PersistencePerspective) will be honored during the BASIC based update.
* OperationType ADORNEDTARGETLIST will result in a join structure entity being updated (not either of the associated entities).
* org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl is an example of a join structure entity.
* OperationType MAP will result in the item being updated to the requisite map in the containing entity.
*
* @return the type of the update operation
*/
public OperationType getUpdateType() {
return updateType;
}
/**
* How should the system execute an update for this item
* <p/>
* OperationType BASIC will result in the item being updated based on it's primary key
* OperationType NONDESTRUCTIVEREMOVE is not supported and will result in the same behavior as BASIC. Note, any foreign key associations in the
* persistence perspective (@see PersistencePerspective) will be honored during the BASIC based update.
* OperationType ADORNEDTARGETLIST will result in a join structure entity being updated (not either of the associated entities).
* org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl is an example of a join structure entity.
* OperationType MAP will result in the item being updated to the requisite map in the containing entity.
*
* @param updateType
*/
public void setUpdateType(OperationType updateType) {
this.updateType = updateType;
}
/**
* How should the system execute a fetch
* <p/>
* OperationType BASIC will result in a search for items having one or more basic properties matches
* OperationType FOREINKEY is not support and will result in the same behavior as BASIC. Note, any foreign key associations will be included
* as part of the query.
* OperationType ADORNEDTARGETLIST will result in search for items that match one of the associations in a join structure. For example, CategoryProductXrefImpl
* is used in a AdornedTargetList fetch to retrieve all products for a particular category.
* OperationType MAP will result retrieval of all map entries for the requisite map in the containing entity.
*
* @return the type of the fetch operation
*/
public OperationType getFetchType() {
return fetchType;
}
/**
* How should the system execute a fetch
* <p/>
* OperationType BASIC will result in a search for items having one or more basic properties matches
* OperationType FOREINKEY is not support and will result in the same behavior as BASIC. Note, any foreign key associations will be included
* as part of the query.
* OperationType ADORNEDTARGETLIST will result in search for items that match one of the associations in a join structure. For example, CategoryProductXrefImpl
* is used in a AdornedTargetList fetch to retrieve all products for a particular category.
* OperationType MAP will result retrieval of all map entries for the requisite map in the containing entity.
*
* @param fetchType
*/
public void setFetchType(OperationType fetchType) {
this.fetchType = fetchType;
}
/**
* OperationType values are generally ignored for inspect and should be defined as BASIC for consistency in most circumstances.
* This API is meant to support future persistence modules where specialized inspect phase management may be required.
*
* @return the type of the inspect operation
*/
public OperationType getInspectType() {
return inspectType;
}
/**
* OperationType values are generally ignored for inspect and should be defined as BASIC for consistency in most circumstances.
* This API is meant to support future persistence modules where specialized inspect phase management may be required.
*
* @param inspectType
*/
public void setInspectType(OperationType inspectType) {
this.inspectType = inspectType;
}
public OperationTypes cloneOperationTypes() {
OperationTypes operationTypes = new OperationTypes();
operationTypes.setAddType(addType);
operationTypes.setFetchType(fetchType);
operationTypes.setInspectType(inspectType);
operationTypes.setRemoveType(removeType);
operationTypes.setUpdateType(updateType);
return operationTypes;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OperationTypes)) return false;
OperationTypes that = (OperationTypes) o;
if (addType != that.addType) return false;
if (fetchType != that.fetchType) return false;
if (inspectType != that.inspectType) return false;
if (removeType != that.removeType) return false;
if (updateType != that.updateType) return false;
return true;
}
@Override
public int hashCode() {
int result = fetchType != null ? fetchType.hashCode() : 0;
result = 31 * result + (removeType != null ? removeType.hashCode() : 0);
result = 31 * result + (addType != null ? addType.hashCode() : 0);
result = 31 * result + (updateType != null ? updateType.hashCode() : 0);
result = 31 * result + (inspectType != null ? inspectType.hashCode() : 0);
return result;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_OperationTypes.java
|
233 |
assertTrueEventually(new AssertTask() {
public void run() throws Exception {
assertTrue(map.isEmpty());
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceExecuteTest.java
|
900 |
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
performFirstPhase(fShardIndex, shardIt);
}
});
| 1no label
|
src_main_java_org_elasticsearch_action_search_type_TransportSearchTypeAction.java
|
302 |
@Deprecated
public class InstrumentationRuntimeFactory {
private static final Log LOG = LogFactory.getLog(InstrumentationRuntimeFactory.class);
private static final String IBM_VM_CLASS = "com.ibm.tools.attach.VirtualMachine";
private static final String SUN_VM_CLASS = "com.sun.tools.attach.VirtualMachine";
private static boolean isIBM = false;
private static Instrumentation inst;
/**
* This method is called by the JVM to set the instrumentation. We can't synchronize this because it will cause
* a deadlock with the thread calling the getInstrumentation() method when the instrumentation is installed.
*
* @param agentArgs
* @param instrumentation
*/
public static void agentmain(String agentArgs, Instrumentation instrumentation) {
inst = instrumentation;
}
/**
* This method returns the Instrumentation object provided by the JVM. If the Instrumentation object is null,
* it does its best to add an instrumentation agent to the JVM and then the instrumentation object.
* @return Instrumentation
*/
public static synchronized Instrumentation getInstrumentation() {
if (inst != null) {
return inst;
}
if (System.getProperty("java.vendor").toUpperCase().contains("IBM")) {
isIBM = true;
}
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
try {
if (!InstrumentationRuntimeFactory.class.getClassLoader().equals(
ClassLoader.getSystemClassLoader())) {
return null;
}
} catch (Throwable t) {
return null;
}
File toolsJar = null;
// When running on IBM, the attach api classes are packaged in vm.jar which is a part
// of the default vm classpath.
if (! isIBM) {
// If we can't find the tools.jar and we're not on IBM we can't load the agent.
toolsJar = findToolsJar();
if (toolsJar == null) {
return null;
}
}
Class<?> vmClass = loadVMClass(toolsJar);
if (vmClass == null) {
return null;
}
String agentPath = getAgentJar();
if (agentPath == null) {
return null;
}
loadAgent(agentPath, vmClass);
return null;
}
});
return inst;
}
private static File findToolsJar() {
String javaHome = System.getProperty("java.home");
File javaHomeFile = new File(javaHome);
File toolsJarFile = new File(javaHomeFile, "lib" + File.separator + "tools.jar");
if (!toolsJarFile.exists()) {
// If we're on an IBM SDK, then remove /jre off of java.home and try again.
if (javaHomeFile.getAbsolutePath().endsWith(File.separator + "jre")) {
javaHomeFile = javaHomeFile.getParentFile();
toolsJarFile = new File(javaHomeFile, "lib" + File.separator + "tools.jar");
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
// If we're on a Mac, then change the search path to use ../Classes/classes.jar.
if (javaHomeFile.getAbsolutePath().endsWith(File.separator + "Home")) {
javaHomeFile = javaHomeFile.getParentFile();
toolsJarFile = new File(javaHomeFile, "Classes" + File.separator + "classes.jar");
}
}
}
if (! toolsJarFile.exists()) {
return null;
} else {
return toolsJarFile;
}
}
private static String createAgentJar() throws IOException {
File file =
File.createTempFile(InstrumentationRuntimeFactory.class.getName(), ".jar");
file.deleteOnExit();
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(file));
zout.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(zout));
writer.println("Agent-Class: " + InstrumentationRuntimeFactory.class.getName());
writer.println("Can-Redefine-Classes: true");
// IBM doesn't support retransform
writer.println("Can-Retransform-Classes: " + Boolean.toString(!isIBM));
writer.close();
return file.getAbsolutePath();
}
private static String getAgentJar() {
File agentJarFile = null;
// Find the name of the File that this class was loaded from. That
// jar *should* be the same location as our agent.
CodeSource cs =
InstrumentationRuntimeFactory.class.getProtectionDomain().getCodeSource();
if (cs != null) {
URL loc = cs.getLocation();
if (loc != null) {
agentJarFile = new File(loc.getFile());
}
}
// Determine whether the File that this class was loaded from has this
// class defined as the Agent-Class.
boolean createJar = false;
if (cs == null || agentJarFile == null
|| agentJarFile.isDirectory()) {
createJar = true;
} else if (!validateAgentJarManifest(agentJarFile, InstrumentationRuntimeFactory.class.getName())) {
// We have an agentJarFile, but this class isn't the Agent-Class.
createJar = true;
}
String agentJar;
if (createJar) {
try {
agentJar = createAgentJar();
} catch (IOException ioe) {
agentJar = null;
}
} else {
agentJar = agentJarFile.getAbsolutePath();
}
return agentJar;
}
private static void loadAgent(String agentJar, Class<?> vmClass) {
try {
// first obtain the PID of the currently-running process
// ### this relies on the undocumented convention of the
// RuntimeMXBean's
// ### name starting with the PID, but there appears to be no other
// ### way to obtain the current process' id, which we need for
// ### the attach process
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
String pid = runtime.getName();
if (pid.contains("@"))
pid = pid.substring(0, pid.indexOf("@"));
// JDK1.6: now attach to the current VM so we can deploy a new agent
// ### this is a Sun JVM specific feature; other JVMs may offer
// ### this feature, but in an implementation-dependent way
Object vm = vmClass.getMethod("attach", new Class<?>[]{String.class}).invoke(null, pid);
vmClass.getMethod("loadAgent", new Class[]{String.class}).invoke(vm, agentJar);
vmClass.getMethod("detach", new Class[]{}).invoke(vm);
} catch (Throwable t) {
if (LOG.isTraceEnabled()) {
LOG.trace("Problem loading the agent", t);
}
}
}
private static Class<?> loadVMClass(File toolsJar) {
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String cls = SUN_VM_CLASS;
if (isIBM) {
cls = IBM_VM_CLASS;
} else {
loader = new URLClassLoader(new URL[]{toolsJar.toURI().toURL()}, loader);
}
return loader.loadClass(cls);
} catch (Exception e) {
if (LOG.isTraceEnabled()) {
LOG.trace("Failed to load the virtual machine class", e);
}
}
return null;
}
private static boolean validateAgentJarManifest(File agentJarFile,
String agentClassName) {
try {
JarFile jar = new JarFile(agentJarFile);
Manifest manifest = jar.getManifest();
if (manifest == null) {
return false;
}
Attributes attributes = manifest.getMainAttributes();
String ac = attributes.getValue("Agent-Class");
if (ac != null && ac.equals(agentClassName)) {
return true;
}
} catch (Exception e) {
if (LOG.isTraceEnabled()) {
LOG.trace("Unexpected exception occured.", e);
}
}
return false;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_InstrumentationRuntimeFactory.java
|
718 |
public abstract class CollectionReplicationOperation extends AbstractOperation implements IdentifiedDataSerializable {
protected Map<String, CollectionContainer> migrationData;
public CollectionReplicationOperation() {
}
public CollectionReplicationOperation(Map<String, CollectionContainer> migrationData, int partitionId, int replicaIndex) {
setPartitionId(partitionId).setReplicaIndex(replicaIndex);
this.migrationData = migrationData;
}
@Override
public void run() throws Exception {
CollectionService service = getService();
for (Map.Entry<String, CollectionContainer> entry : migrationData.entrySet()) {
String name = entry.getKey();
CollectionContainer container = entry.getValue();
container.init(getNodeEngine());
service.addContainer(name, container);
}
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
out.writeInt(migrationData.size());
for (Map.Entry<String, CollectionContainer> entry : migrationData.entrySet()) {
out.writeUTF(entry.getKey());
CollectionContainer container = entry.getValue();
container.writeData(out);
}
}
@Override
public int getFactoryId() {
return CollectionDataSerializerHook.F_ID;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionReplicationOperation.java
|
2,668 |
public class DefaultPortableWriter implements PortableWriter {
private final PortableSerializer serializer;
private final ClassDefinition cd;
private final BufferObjectDataOutput out;
private final int begin;
private final int offset;
private final Set<String> writtenFields;
private boolean raw;
public DefaultPortableWriter(PortableSerializer serializer, BufferObjectDataOutput out, ClassDefinition cd)
throws IOException {
this.serializer = serializer;
this.out = out;
this.cd = cd;
this.writtenFields = new HashSet<String>(cd.getFieldCount());
this.begin = out.position();
// room for final offset
out.writeZeroBytes(4);
this.offset = out.position();
// one additional for raw data
final int fieldIndexesLength = (cd.getFieldCount() + 1) * 4;
out.writeZeroBytes(fieldIndexesLength);
}
public int getVersion() {
return cd.getVersion();
}
public void writeInt(String fieldName, int value) throws IOException {
setPosition(fieldName);
out.writeInt(value);
}
public void writeLong(String fieldName, long value) throws IOException {
setPosition(fieldName);
out.writeLong(value);
}
public void writeUTF(String fieldName, String str) throws IOException {
setPosition(fieldName);
out.writeUTF(str);
}
public void writeBoolean(String fieldName, boolean value) throws IOException {
setPosition(fieldName);
out.writeBoolean(value);
}
public void writeByte(String fieldName, byte value) throws IOException {
setPosition(fieldName);
out.writeByte(value);
}
public void writeChar(String fieldName, int value) throws IOException {
setPosition(fieldName);
out.writeChar(value);
}
public void writeDouble(String fieldName, double value) throws IOException {
setPosition(fieldName);
out.writeDouble(value);
}
public void writeFloat(String fieldName, float value) throws IOException {
setPosition(fieldName);
out.writeFloat(value);
}
public void writeShort(String fieldName, short value) throws IOException {
setPosition(fieldName);
out.writeShort(value);
}
public void writePortable(String fieldName, Portable portable) throws IOException {
setPosition(fieldName);
final boolean NULL = portable == null;
out.writeBoolean(NULL);
if (!NULL) {
serializer.write(out, portable);
}
}
public void writeNullPortable(String fieldName, int factoryId, int classId) throws IOException {
setPosition(fieldName);
final boolean NULL = true;
out.writeBoolean(NULL);
}
public void writeByteArray(String fieldName, byte[] values) throws IOException {
setPosition(fieldName);
IOUtil.writeByteArray(out, values);
}
public void writeCharArray(String fieldName, char[] values) throws IOException {
setPosition(fieldName);
out.writeCharArray(values);
}
public void writeIntArray(String fieldName, int[] values) throws IOException {
setPosition(fieldName);
out.writeIntArray(values);
}
public void writeLongArray(String fieldName, long[] values) throws IOException {
setPosition(fieldName);
out.writeLongArray(values);
}
public void writeDoubleArray(String fieldName, double[] values) throws IOException {
setPosition(fieldName);
out.writeDoubleArray(values);
}
public void writeFloatArray(String fieldName, float[] values) throws IOException {
setPosition(fieldName);
out.writeFloatArray(values);
}
public void writeShortArray(String fieldName, short[] values) throws IOException {
setPosition(fieldName);
out.writeShortArray(values);
}
public void writePortableArray(String fieldName, Portable[] portables) throws IOException {
setPosition(fieldName);
final int len = portables == null ? 0 : portables.length;
out.writeInt(len);
if (len > 0) {
final int offset = out.position();
out.writeZeroBytes(len * 4);
for (int i = 0; i < portables.length; i++) {
out.writeInt(offset + i * 4, out.position());
final Portable portable = portables[i];
serializer.write(out, portable);
}
}
}
private void setPosition(String fieldName) throws IOException {
if (raw) {
throw new HazelcastSerializationException("Cannot write Portable fields after getRawDataOutput() is called!");
}
FieldDefinition fd = cd.get(fieldName);
if (fd == null) {
throw new HazelcastSerializationException("Invalid field name: '" + fieldName
+ "' for ClassDefinition {id: " + cd.getClassId() + ", version: " + cd.getVersion() + "}");
}
if (writtenFields.add(fieldName)) {
int pos = out.position();
int index = fd.getIndex();
out.writeInt(offset + index * 4, pos);
} else {
throw new HazelcastSerializationException("Field '" + fieldName + "' has already been written!");
}
}
public ObjectDataOutput getRawDataOutput() throws IOException {
if (!raw) {
int pos = out.position();
// last index
int index = cd.getFieldCount();
out.writeInt(offset + index * 4, pos);
}
raw = true;
return out;
}
void end() throws IOException {
// write final offset
out.writeInt(begin, out.position());
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_serialization_DefaultPortableWriter.java
|
123 |
static final class AdaptedRunnable<T> extends ForkJoinTask<T>
implements RunnableFuture<T> {
final Runnable runnable;
T result;
AdaptedRunnable(Runnable runnable, T result) {
if (runnable == null) throw new NullPointerException();
this.runnable = runnable;
this.result = result; // OK to set this even before completion
}
public final T getRawResult() { return result; }
public final void setRawResult(T v) { result = v; }
public final boolean exec() { runnable.run(); return true; }
public final void run() { invoke(); }
private static final long serialVersionUID = 5232453952276885070L;
}
| 0true
|
src_main_java_jsr166e_ForkJoinTask.java
|
616 |
MulticastListener listener = new MulticastListener() {
public void onMessage(Object msg) {
systemLogService.logJoin("MulticastListener onMessage " + msg);
if (msg != null && msg instanceof JoinMessage) {
JoinMessage joinRequest = (JoinMessage) msg;
if (node.getThisAddress() != null && !node.getThisAddress().equals(joinRequest.getAddress())) {
q.add(joinRequest);
}
}
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_cluster_MulticastJoiner.java
|
800 |
public class PercolateSourceBuilder implements ToXContent {
private DocBuilder docBuilder;
private QueryBuilder queryBuilder;
private FilterBuilder filterBuilder;
private Integer size;
private Boolean sort;
private List<SortBuilder> sorts;
private Boolean trackScores;
private HighlightBuilder highlightBuilder;
private List<FacetBuilder> facets;
private List<AggregationBuilder> aggregations;
public DocBuilder percolateDocument() {
if (docBuilder == null) {
docBuilder = new DocBuilder();
}
return docBuilder;
}
public DocBuilder getDoc() {
return docBuilder;
}
/**
* Sets the document to run the percolate queries against.
*/
public PercolateSourceBuilder setDoc(DocBuilder docBuilder) {
this.docBuilder = docBuilder;
return this;
}
public QueryBuilder getQueryBuilder() {
return queryBuilder;
}
/**
* Sets a query to reduce the number of percolate queries to be evaluated and score the queries that match based
* on this query.
*/
public PercolateSourceBuilder setQueryBuilder(QueryBuilder queryBuilder) {
this.queryBuilder = queryBuilder;
return this;
}
public FilterBuilder getFilterBuilder() {
return filterBuilder;
}
/**
* Sets a filter to reduce the number of percolate queries to be evaluated.
*/
public PercolateSourceBuilder setFilterBuilder(FilterBuilder filterBuilder) {
this.filterBuilder = filterBuilder;
return this;
}
/**
* Limits the maximum number of percolate query matches to be returned.
*/
public PercolateSourceBuilder setSize(int size) {
this.size = size;
return this;
}
/**
* Similar as {@link #setTrackScores(boolean)}, but whether to sort by the score descending.
*/
public PercolateSourceBuilder setSort(boolean sort) {
if (sort) {
addSort(new ScoreSortBuilder());
} else {
this.sorts = null;
}
return this;
}
/**
* Adds a sort builder. Only sorting by score desc is supported.
*/
public PercolateSourceBuilder addSort(SortBuilder sort) {
if (sorts == null) {
sorts = Lists.newArrayList();
}
sorts.add(sort);
return this;
}
/**
* Whether to compute a score for each match and include it in the response. The score is based on
* {@link #setQueryBuilder(QueryBuilder)}.
*/
public PercolateSourceBuilder setTrackScores(boolean trackScores) {
this.trackScores = trackScores;
return this;
}
/**
* Enables highlighting for the percolate document. Per matched percolate query highlight the percolate document.
*/
public PercolateSourceBuilder setHighlightBuilder(HighlightBuilder highlightBuilder) {
this.highlightBuilder = highlightBuilder;
return this;
}
/**
* Add a facet definition.
*/
public PercolateSourceBuilder addFacet(FacetBuilder facetBuilder) {
if (facets == null) {
facets = Lists.newArrayList();
}
facets.add(facetBuilder);
return this;
}
/**
* Add an aggregationB definition.
*/
public PercolateSourceBuilder addAggregation(AggregationBuilder aggregationBuilder) {
if (aggregations == null) {
aggregations = Lists.newArrayList();
}
aggregations.add(aggregationBuilder);
return this;
}
public BytesReference buildAsBytes(XContentType contentType) throws SearchSourceBuilderException {
try {
XContentBuilder builder = XContentFactory.contentBuilder(contentType);
toXContent(builder, ToXContent.EMPTY_PARAMS);
return builder.bytes();
} catch (Exception e) {
throw new SearchSourceBuilderException("Failed to build search source", e);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
if (docBuilder != null) {
docBuilder.toXContent(builder, params);
}
if (queryBuilder != null) {
builder.field("query");
queryBuilder.toXContent(builder, params);
}
if (filterBuilder != null) {
builder.field("filter");
filterBuilder.toXContent(builder, params);
}
if (size != null) {
builder.field("size", size);
}
if (sorts != null) {
builder.startArray("sort");
for (SortBuilder sort : sorts) {
builder.startObject();
sort.toXContent(builder, params);
builder.endObject();
}
builder.endArray();
}
if (trackScores != null) {
builder.field("track_scores", trackScores);
}
if (highlightBuilder != null) {
highlightBuilder.toXContent(builder, params);
}
if (facets != null) {
builder.field("facets");
builder.startObject();
for (FacetBuilder facet : facets) {
facet.toXContent(builder, params);
}
builder.endObject();
}
if (aggregations != null) {
builder.field("aggregations");
builder.startObject();
for (AbstractAggregationBuilder aggregation : aggregations) {
aggregation.toXContent(builder, params);
}
builder.endObject();
}
builder.endObject();
return builder;
}
public static DocBuilder docBuilder() {
return new DocBuilder();
}
public static class DocBuilder implements ToXContent {
private BytesReference doc;
public DocBuilder setDoc(BytesReference doc) {
this.doc = doc;
return this;
}
public DocBuilder setDoc(String field, Object value) {
Map<String, Object> values = new HashMap<String, Object>(2);
values.put(field, value);
setDoc(values);
return this;
}
public DocBuilder setDoc(String doc) {
this.doc = new BytesArray(doc);
return this;
}
public DocBuilder setDoc(XContentBuilder doc) {
this.doc = doc.bytes();
return this;
}
public DocBuilder setDoc(Map doc) {
return setDoc(doc, PercolateRequest.contentType);
}
public DocBuilder setDoc(Map doc, XContentType contentType) {
try {
return setDoc(XContentFactory.contentBuilder(contentType).map(doc));
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + doc + "]", e);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
XContentType contentType = XContentFactory.xContentType(doc);
if (contentType == builder.contentType()) {
builder.rawField("doc", doc);
} else {
XContentParser parser = XContentFactory.xContent(contentType).createParser(doc);
try {
parser.nextToken();
builder.field("doc");
builder.copyCurrentStructure(parser);
} finally {
parser.close();
}
}
return builder;
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_percolate_PercolateSourceBuilder.java
|
32 |
static final class ParameterContextInformation
implements IContextInformation {
private final Declaration declaration;
private final ProducedReference producedReference;
private final ParameterList parameterList;
private final int argumentListOffset;
private final Unit unit;
private final boolean includeDefaulted;
// private final boolean inLinkedMode;
private final boolean namedInvocation;
private ParameterContextInformation(Declaration declaration,
ProducedReference producedReference, Unit unit,
ParameterList parameterList, int argumentListOffset,
boolean includeDefaulted, boolean namedInvocation) {
// boolean inLinkedMode
this.declaration = declaration;
this.producedReference = producedReference;
this.unit = unit;
this.parameterList = parameterList;
this.argumentListOffset = argumentListOffset;
this.includeDefaulted = includeDefaulted;
// this.inLinkedMode = inLinkedMode;
this.namedInvocation = namedInvocation;
}
@Override
public String getContextDisplayString() {
return "Parameters of '" + declaration.getName() + "'";
}
@Override
public Image getImage() {
return getImageForDeclaration(declaration);
}
@Override
public String getInformationDisplayString() {
List<Parameter> ps = getParameters(parameterList,
includeDefaulted, namedInvocation);
if (ps.isEmpty()) {
return "no parameters";
}
StringBuilder result = new StringBuilder();
for (Parameter p: ps) {
boolean isListedValues = namedInvocation &&
p==ps.get(ps.size()-1) &&
p.getModel() instanceof Value &&
p.getType()!=null &&
unit.isIterableParameterType(p.getType());
if (includeDefaulted || !p.isDefaulted() ||
isListedValues) {
if (producedReference==null) {
result.append(p.getName());
}
else {
ProducedTypedReference pr =
producedReference.getTypedParameter(p);
appendParameterContextInfo(result, pr, p, unit,
namedInvocation, isListedValues);
}
if (!isListedValues) {
result.append(namedInvocation ? "; " : ", ");
}
}
}
if (!namedInvocation && result.length()>0) {
result.setLength(result.length()-2);
}
return result.toString();
}
@Override
public boolean equals(Object that) {
if (that instanceof ParameterContextInformation) {
return ((ParameterContextInformation) that).declaration
.equals(declaration);
}
else {
return false;
}
}
int getArgumentListOffset() {
return argumentListOffset;
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_InvocationCompletionProposal.java
|
1,511 |
@Deprecated
@Component("blMergeCartProcessor")
public class MergeCartProcessorImpl implements MergeCartProcessor {
protected String mergeCartResponseKey = "bl_merge_cart_response";
@Resource(name="blCustomerService")
protected CustomerService customerService;
@Resource(name="blOrderService")
protected OrderService orderService;
@Resource(name="blMergeCartService")
protected MergeCartService mergeCartService;
@Resource(name = "blCustomerStateRequestProcessor")
protected CustomerStateRequestProcessor customerStateRequestProcessor;
@Override
public void execute(HttpServletRequest request, HttpServletResponse response, Authentication authResult) {
execute(new ServletWebRequest(request, response), authResult);
}
public void execute(WebRequest request, Authentication authResult) {
Customer loggedInCustomer = customerService.readCustomerByUsername(authResult.getName());
Customer anonymousCustomer = customerStateRequestProcessor.getAnonymousCustomer(request);
Order cart = null;
if (anonymousCustomer != null) {
cart = orderService.findCartForCustomer(anonymousCustomer);
}
MergeCartResponse mergeCartResponse;
try {
mergeCartResponse = mergeCartService.mergeCart(loggedInCustomer, cart);
} catch (PricingException e) {
throw new RuntimeException(e);
} catch (RemoveFromCartException e) {
throw new RuntimeException(e);
}
request.setAttribute(mergeCartResponseKey, mergeCartResponse, WebRequest.SCOPE_GLOBAL_SESSION);
}
public String getMergeCartResponseKey() {
return mergeCartResponseKey;
}
public void setMergeCartResponseKey(String mergeCartResponseKey) {
this.mergeCartResponseKey = mergeCartResponseKey;
}
}
| 1no label
|
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_order_security_MergeCartProcessorImpl.java
|
640 |
@Component("blTranslationRequestProcessor")
public class TranslationRequestProcessor extends AbstractBroadleafWebRequestProcessor {
@Resource(name = "blTranslationService")
protected TranslationService translationService;
@Value("${i18n.translation.enabled}")
protected boolean translationEnabled = false;
@Override
public void process(WebRequest request) {
TranslationConsiderationContext.setTranslationConsiderationContext(translationEnabled);
TranslationConsiderationContext.setTranslationService(translationService);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_web_filter_TranslationRequestProcessor.java
|
123 |
{
@Override
public boolean matchesSafely( LogEntry.Start entry )
{
return entry != null && entry.getIdentifier() == identifier && entry.getMasterId() == masterId
&& entry.getLocalId() == localId;
}
@Override
public void describeTo( Description description )
{
description.appendText( "Start[" + identifier + ",xid=<Any Xid>,master=" + masterId + ",me=" + localId
+ ",time=<Any Date>]" );
}
};
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_LogMatchers.java
|
1,334 |
@Service("blSolrHelperService")
public class SolrHelperServiceImpl implements SolrHelperService {
private static final Log LOG = LogFactory.getLog(SolrHelperServiceImpl.class);
// The value of these two fields has no special significance, but they must be non-blank
protected static final String GLOBAL_FACET_TAG_FIELD = "a";
protected static final String DEFAULT_NAMESPACE = "d";
protected static final String PREFIX_SEPARATOR = "_";
protected static Locale defaultLocale;
protected static SolrServer server;
@Resource(name = "blLocaleService")
protected LocaleService localeService;
@Resource(name = "blSolrSearchServiceExtensionManager")
protected SolrSearchServiceExtensionManager extensionManager;
@Override
public void swapActiveCores() throws ServiceException {
if (SolrContext.isSingleCoreMode()) {
LOG.debug("In single core mode. There are no cores to swap.");
} else {
LOG.debug("Swapping active cores");
CoreAdminRequest car = new CoreAdminRequest();
car.setCoreName(SolrContext.PRIMARY);
car.setOtherCoreName(SolrContext.REINDEX);
car.setAction(CoreAdminAction.SWAP);
try {
SolrContext.getServer().request(car);
} catch (Exception e) {
LOG.error(e);
throw new ServiceException("Unable to swap cores", e);
}
}
}
@Override
public String getCurrentNamespace() {
return DEFAULT_NAMESPACE;
}
@Override
public String getGlobalFacetTagField() {
return GLOBAL_FACET_TAG_FIELD;
}
@Override
public String getPropertyNameForFieldSearchable(Field field, FieldType searchableFieldType, String prefix) {
return new StringBuilder()
.append(prefix)
.append(field.getAbbreviation()).append("_").append(searchableFieldType.getType())
.toString();
}
@Override
public String getPropertyNameForFieldFacet(Field field, String prefix) {
if (field.getFacetFieldType() == null) {
return null;
}
return new StringBuilder()
.append(prefix)
.append(field.getAbbreviation()).append("_").append(field.getFacetFieldType().getType())
.toString();
}
@Override
public List<FieldType> getSearchableFieldTypes(Field field) {
// We will index all configured searchable field types
List<FieldType> typesToConsider = new ArrayList<FieldType>();
if (CollectionUtils.isNotEmpty(field.getSearchableFieldTypes())) {
typesToConsider.addAll(field.getSearchableFieldTypes());
}
// If there were no searchable field types configured, we will use TEXT as a default one
if (CollectionUtils.isEmpty(typesToConsider)) {
typesToConsider.add(FieldType.TEXT);
}
return typesToConsider;
}
@Override
public String getPropertyNameForFieldSearchable(Field field, FieldType searchableFieldType) {
List<String> prefixList = new ArrayList<String>();
extensionManager.getProxy().buildPrefixListForSearchableField(field, searchableFieldType, prefixList);
String prefix = convertPrefixListToString(prefixList);
return getPropertyNameForFieldSearchable(field, searchableFieldType, prefix);
}
@Override
public String getPropertyNameForFieldFacet(Field field) {
FieldType fieldType = field.getFacetFieldType();
if (fieldType == null) {
return null;
}
List<String> prefixList = new ArrayList<String>();
extensionManager.getProxy().buildPrefixListForSearchableFacet(field, prefixList);
String prefix = convertPrefixListToString(prefixList);
return getPropertyNameForFieldFacet(field, prefix);
}
protected String convertPrefixListToString(List<String> prefixList) {
StringBuilder prefixString = new StringBuilder();
for (String prefix : prefixList) {
if (prefix != null && !prefix.isEmpty()) {
prefixString = prefixString.append(prefix).append(PREFIX_SEPARATOR);
}
}
return prefixString.toString();
}
@Override
public String getSolrDocumentId(SolrInputDocument document, Product product) {
return String.valueOf(product.getId());
}
@Override
public String getNamespaceFieldName() {
return "namespace";
}
@Override
public String getIdFieldName() {
return "id";
}
@Override
public String getProductIdFieldName() {
return "productId";
}
@Override
public String getCategoryFieldName() {
return "category";
}
@Override
public String getExplicitCategoryFieldName() {
return "explicitCategory";
}
@Override
public String getCategorySortFieldName(Category category) {
return new StringBuilder()
.append(getCategoryFieldName())
.append("_").append(category.getId()).append("_").append("sort_i")
.toString();
}
public String getLocalePrefix() {
if (BroadleafRequestContext.getBroadleafRequestContext() != null) {
Locale locale = BroadleafRequestContext.getBroadleafRequestContext().getLocale();
if (locale != null) {
return locale.getLocaleCode() + "_";
}
}
return getDefaultLocalePrefix();
}
@Override
public String getDefaultLocalePrefix() {
return getDefaultLocale().getLocaleCode() + "_";
}
@Override
public Locale getDefaultLocale() {
if (defaultLocale == null) {
defaultLocale = localeService.findDefaultLocale();
}
return defaultLocale;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_service_solr_SolrHelperServiceImpl.java
|
375 |
public class MetadataMBeanInfoAssembler extends org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler {
protected void checkManagedBean(Object managedBean) throws IllegalArgumentException {
//do nothing
}
protected ModelMBeanNotificationInfo[] getNotificationInfo(Object managedBean, String beanKey) {
managedBean = AspectUtil.exposeRootBean(managedBean);
return super.getNotificationInfo(managedBean, beanKey);
}
protected void populateMBeanDescriptor(Descriptor desc, Object managedBean, String beanKey) {
managedBean = AspectUtil.exposeRootBean(managedBean);
super.populateMBeanDescriptor(desc, managedBean, beanKey);
}
protected ModelMBeanAttributeInfo[] getAttributeInfo(Object managedBean, String beanKey) throws JMException {
managedBean = AspectUtil.exposeRootBean(managedBean);
return super.getAttributeInfo(managedBean, beanKey);
}
protected ModelMBeanOperationInfo[] getOperationInfo(Object managedBean, String beanKey) {
managedBean = AspectUtil.exposeRootBean(managedBean);
return super.getOperationInfo(managedBean, beanKey);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_jmx_MetadataMBeanInfoAssembler.java
|
22 |
public class DeleteCommandProcessor extends MemcacheCommandProcessor<DeleteCommand> {
public DeleteCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
public void handle(DeleteCommand command) {
String key;
try {
key = URLDecoder.decode(command.getKey(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(format("failed to decode key [%s] using UTF-8", command.getKey()));
}
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);
}
if (key.equals("")) {
textCommandService.deleteAll(mapName);
} else {
final Object oldValue = textCommandService.delete(mapName, key);
if (oldValue == null) {
textCommandService.incrementDeleteMissCount();
command.setResponse(NOT_FOUND);
} else {
textCommandService.incrementDeleteHitCount(1);
command.setResponse(DELETED);
}
}
if (command.shouldReply()) {
textCommandService.sendResponse(command);
}
}
public void handleRejection(DeleteCommand command) {
handle(command);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_ascii_memcache_DeleteCommandProcessor.java
|
173 |
.build(new CacheLoader<String,URLProcessor>() {
public URLProcessor load(String key) throws IOException, ServletException {
if (LOG.isDebugEnabled()) {
LOG.debug("Loading URL processor into Cache");
}
return determineURLProcessor(key);
}
});
| 1no label
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_web_BroadleafProcessURLFilter.java
|
341 |
class Evictor extends TimerTask {
private HashMap<String, Map<DB, Long>> evictionMap = new HashMap<String, Map<DB, Long>>();
private long minIdleTime;
public Evictor(long minIdleTime) {
this.minIdleTime = minIdleTime;
}
/**
* Run pool maintenance. Evict objects qualifying for eviction
*/
@Override
public void run() {
OLogManager.instance().debug(this, "Running Connection Pool Evictor Service...");
lock();
try {
for (Entry<String, Map<DB, Long>> pool : this.evictionMap.entrySet()) {
Map<DB, Long> poolDbs = pool.getValue();
Iterator<Entry<DB, Long>> iterator = poolDbs.entrySet().iterator();
while (iterator.hasNext()) {
Entry<DB, Long> db = iterator.next();
if (System.currentTimeMillis() - db.getValue() >= this.minIdleTime) {
OResourcePool<String, DB> oResourcePool = pools.get(pool.getKey());
if (oResourcePool != null) {
OLogManager.instance().debug(this, "Closing idle pooled database '%s'...", db.getKey().getName());
((ODatabasePooled) db.getKey()).forceClose();
oResourcePool.remove(db.getKey());
iterator.remove();
}
}
}
}
} finally {
unlock();
}
}
public void updateIdleTime(final String poolName, final DB iDatabase) {
Map<DB, Long> pool = this.evictionMap.get(poolName);
if (pool == null) {
pool = new HashMap<DB, Long>();
this.evictionMap.put(poolName, pool);
}
pool.put(iDatabase, System.currentTimeMillis());
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_ODatabasePoolAbstract.java
|
851 |
execute(request, new ActionListener<SearchResponse>() {
@Override
public void onResponse(SearchResponse result) {
try {
channel.sendResponse(result);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response for search", e1);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_search_TransportSearchAction.java
|
795 |
public class ODatabaseFunction implements OSQLFunction {
private final OFunction f;
public ODatabaseFunction(final OFunction f) {
this.f = f;
}
@Override
public Object execute(final OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iFuncParams, final OCommandContext iContext) {
return f.executeInContext(iContext, iFuncParams);
}
@Override
public boolean aggregateResults() {
return false;
}
@Override
public boolean filterResult() {
return false;
}
@Override
public String getName() {
return f.getName();
}
@Override
public int getMinParams() {
return 0;
}
@Override
public int getMaxParams() {
return f.getParameters().size();
}
@Override
public String getSyntax() {
final StringBuilder buffer = new StringBuilder();
buffer.append(f.getName());
buffer.append('(');
final List<String> params = f.getParameters();
for (int p = 0; p < params.size(); ++p) {
if (p > 0)
buffer.append(',');
buffer.append(params.get(p));
}
buffer.append(')');
return buffer.toString();
}
@Override
public Object getResult() {
return null;
}
@Override
public void setResult(final Object iResult) {
}
@Override
public void config(final Object[] configuredParameters) {
}
@Override
public boolean shouldMergeDistributedResult() {
return false;
}
@Override
public Object mergeDistributedResult(List<Object> resultsToMerge) {
return null;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_metadata_function_ODatabaseFunction.java
|
111 |
public abstract class OListenerManger<L> {
private final Collection<L> listeners;
private final OLock lock;
public OListenerManger() {
this(new HashSet<L>(8), new ONoLock());
}
public OListenerManger(final OLock iLock) {
listeners = new HashSet<L>(8);
lock = iLock;
}
public OListenerManger(final Collection<L> iListeners, final OLock iLock) {
listeners = iListeners;
lock = iLock;
}
public void registerListener(final L iListener) {
if (iListener != null) {
lock.lock();
try {
listeners.add(iListener);
} finally {
lock.unlock();
}
}
}
public void unregisterListener(final L iListener) {
if (iListener != null) {
lock.lock();
try {
listeners.remove(iListener);
} finally {
lock.unlock();
}
}
}
public void resetListeners() {
lock.lock();
try {
listeners.clear();
} finally {
lock.unlock();
}
}
public Iterable<L> browseListeners() {
return listeners;
}
@SuppressWarnings("unchecked")
public Iterable<L> getListenersCopy() {
lock.lock();
try {
return (Iterable<L>) new HashSet<Object>(listeners);
} finally {
lock.unlock();
}
}
public OLock getLock() {
return lock;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_listener_OListenerManger.java
|
4,426 |
public class IndicesClusterStateService extends AbstractLifecycleComponent<IndicesClusterStateService> implements ClusterStateListener {
private final IndicesService indicesService;
private final ClusterService clusterService;
private final ThreadPool threadPool;
private final RecoveryTarget recoveryTarget;
private final ShardStateAction shardStateAction;
private final NodeIndexDeletedAction nodeIndexDeletedAction;
private final NodeMappingRefreshAction nodeMappingRefreshAction;
// a map of mappings type we have seen per index due to cluster state
// we need this so we won't remove types automatically created as part of the indexing process
private final ConcurrentMap<Tuple<String, String>, Boolean> seenMappings = ConcurrentCollections.newConcurrentMap();
// a list of shards that failed during recovery
// we keep track of these shards in order to prevent repeated recovery of these shards on each cluster state update
private final ConcurrentMap<ShardId, FailedShard> failedShards = ConcurrentCollections.newConcurrentMap();
static class FailedShard {
public final long version;
public final long timestamp;
FailedShard(long version) {
this.version = version;
this.timestamp = System.currentTimeMillis();
}
}
private final Object mutex = new Object();
private final FailedEngineHandler failedEngineHandler = new FailedEngineHandler();
private final boolean sendRefreshMapping;
@Inject
public IndicesClusterStateService(Settings settings, IndicesService indicesService, ClusterService clusterService,
ThreadPool threadPool, RecoveryTarget recoveryTarget,
ShardStateAction shardStateAction,
NodeIndexDeletedAction nodeIndexDeletedAction,
NodeMappingRefreshAction nodeMappingRefreshAction) {
super(settings);
this.indicesService = indicesService;
this.clusterService = clusterService;
this.threadPool = threadPool;
this.recoveryTarget = recoveryTarget;
this.shardStateAction = shardStateAction;
this.nodeIndexDeletedAction = nodeIndexDeletedAction;
this.nodeMappingRefreshAction = nodeMappingRefreshAction;
this.sendRefreshMapping = componentSettings.getAsBoolean("send_refresh_mapping", true);
}
@Override
protected void doStart() throws ElasticsearchException {
clusterService.addFirst(this);
}
@Override
protected void doStop() throws ElasticsearchException {
clusterService.remove(this);
}
@Override
protected void doClose() throws ElasticsearchException {
}
@Override
public void clusterChanged(final ClusterChangedEvent event) {
if (!indicesService.changesAllowed()) {
return;
}
if (!lifecycle.started()) {
return;
}
synchronized (mutex) {
// we need to clean the shards and indices we have on this node, since we
// are going to recover them again once state persistence is disabled (no master / not recovered)
// TODO: this feels a bit hacky here, a block disables state persistence, and then we clean the allocated shards, maybe another flag in blocks?
if (event.state().blocks().disableStatePersistence()) {
for (final String index : indicesService.indices()) {
IndexService indexService = indicesService.indexService(index);
for (Integer shardId : indexService.shardIds()) {
logger.debug("[{}][{}] removing shard (disabled block persistence)", index, shardId);
try {
indexService.removeShard(shardId, "removing shard (disabled block persistence)");
} catch (Throwable e) {
logger.warn("[{}] failed to remove shard (disabled block persistence)", e, index);
}
}
removeIndex(index, "cleaning index (disabled block persistence)");
}
return;
}
cleanFailedShards(event);
cleanMismatchedIndexUUIDs(event);
applyNewIndices(event);
applyMappings(event);
applyAliases(event);
applyNewOrUpdatedShards(event);
applyDeletedIndices(event);
applyDeletedShards(event);
applyCleanedIndices(event);
applySettings(event);
sendIndexLifecycleEvents(event);
}
}
private void sendIndexLifecycleEvents(final ClusterChangedEvent event) {
String localNodeId = event.state().nodes().localNodeId();
assert localNodeId != null;
for (String index : event.indicesDeleted()) {
try {
nodeIndexDeletedAction.nodeIndexDeleted(event.state(), index, localNodeId);
} catch (Throwable e) {
logger.debug("failed to send to master index {} deleted event", e, index);
}
}
}
private void cleanMismatchedIndexUUIDs(final ClusterChangedEvent event) {
for (IndexService indexService : indicesService) {
IndexMetaData indexMetaData = event.state().metaData().index(indexService.index().name());
if (indexMetaData == null) {
// got deleted on us, will be deleted later
continue;
}
if (!indexMetaData.isSameUUID(indexService.indexUUID())) {
logger.debug("[{}] mismatch on index UUIDs between cluster state and local state, cleaning the index so it will be recreated", indexMetaData.index());
removeIndex(indexMetaData.index(), "mismatch on index UUIDs between cluster state and local state, cleaning the index so it will be recreated");
}
}
}
private void applyCleanedIndices(final ClusterChangedEvent event) {
// handle closed indices, since they are not allocated on a node once they are closed
// so applyDeletedIndices might not take them into account
for (final String index : indicesService.indices()) {
IndexMetaData indexMetaData = event.state().metaData().index(index);
if (indexMetaData != null && indexMetaData.state() == IndexMetaData.State.CLOSE) {
IndexService indexService = indicesService.indexService(index);
for (Integer shardId : indexService.shardIds()) {
logger.debug("[{}][{}] removing shard (index is closed)", index, shardId);
try {
indexService.removeShard(shardId, "removing shard (index is closed)");
} catch (Throwable e) {
logger.warn("[{}] failed to remove shard (index is closed)", e, index);
}
}
}
}
for (final String index : indicesService.indices()) {
if (indicesService.indexService(index).shardIds().isEmpty()) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] cleaning index (no shards allocated)", index);
}
// clean the index
removeIndex(index, "removing index (no shards allocated)");
}
}
}
private void applyDeletedIndices(final ClusterChangedEvent event) {
for (final String index : indicesService.indices()) {
if (!event.state().metaData().hasIndex(index)) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] cleaning index, no longer part of the metadata", index);
}
removeIndex(index, "index no longer part of the metadata");
}
}
}
private void applyDeletedShards(final ClusterChangedEvent event) {
RoutingNodes.RoutingNodeIterator routingNode = event.state().readOnlyRoutingNodes().routingNodeIter(event.state().nodes().localNodeId());
if (routingNode == null) {
return;
}
IntOpenHashSet newShardIds = new IntOpenHashSet();
for (IndexService indexService : indicesService) {
String index = indexService.index().name();
IndexMetaData indexMetaData = event.state().metaData().index(index);
if (indexMetaData == null) {
continue;
}
// now, go over and delete shards that needs to get deleted
newShardIds.clear();
for (MutableShardRouting shard : routingNode) {
if (shard.index().equals(index)) {
newShardIds.add(shard.id());
}
}
for (Integer existingShardId : indexService.shardIds()) {
if (!newShardIds.contains(existingShardId)) {
if (indexMetaData.state() == IndexMetaData.State.CLOSE) {
if (logger.isDebugEnabled()) {
logger.debug("[{}][{}] removing shard (index is closed)", index, existingShardId);
}
indexService.removeShard(existingShardId, "removing shard (index is closed)");
} else {
// we can just remove the shard, without cleaning it locally, since we will clean it
// when all shards are allocated in the IndicesStore
if (logger.isDebugEnabled()) {
logger.debug("[{}][{}] removing shard (not allocated)", index, existingShardId);
}
indexService.removeShard(existingShardId, "removing shard (not allocated)");
}
}
}
}
}
private void applyNewIndices(final ClusterChangedEvent event) {
// we only create indices for shards that are allocated
RoutingNodes.RoutingNodeIterator routingNode = event.state().readOnlyRoutingNodes().routingNodeIter(event.state().nodes().localNodeId());
if (routingNode == null) {
return;
}
for (MutableShardRouting shard : routingNode) {
if (!indicesService.hasIndex(shard.index())) {
final IndexMetaData indexMetaData = event.state().metaData().index(shard.index());
if (logger.isDebugEnabled()) {
logger.debug("[{}] creating index", indexMetaData.index());
}
indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), event.state().nodes().localNode().id());
}
}
}
private void applySettings(ClusterChangedEvent event) {
if (!event.metaDataChanged()) {
return;
}
for (IndexMetaData indexMetaData : event.state().metaData()) {
if (!indicesService.hasIndex(indexMetaData.index())) {
// we only create / update here
continue;
}
// if the index meta data didn't change, no need check for refreshed settings
if (!event.indexMetaDataChanged(indexMetaData)) {
continue;
}
String index = indexMetaData.index();
IndexService indexService = indicesService.indexServiceSafe(index);
IndexSettingsService indexSettingsService = indexService.injector().getInstance(IndexSettingsService.class);
indexSettingsService.refreshSettings(indexMetaData.settings());
}
}
private void applyMappings(ClusterChangedEvent event) {
// go over and update mappings
for (IndexMetaData indexMetaData : event.state().metaData()) {
if (!indicesService.hasIndex(indexMetaData.index())) {
// we only create / update here
continue;
}
List<String> typesToRefresh = null;
String index = indexMetaData.index();
IndexService indexService = indicesService.indexService(index);
if (indexService == null) {
// got deleted on us, ignore (closing the node)
return;
}
MapperService mapperService = indexService.mapperService();
// first, go over and update the _default_ mapping (if exists)
if (indexMetaData.mappings().containsKey(MapperService.DEFAULT_MAPPING)) {
processMapping(index, mapperService, MapperService.DEFAULT_MAPPING, indexMetaData.mapping(MapperService.DEFAULT_MAPPING).source());
}
// go over and add the relevant mappings (or update them)
for (ObjectCursor<MappingMetaData> cursor : indexMetaData.mappings().values()) {
MappingMetaData mappingMd = cursor.value;
String mappingType = mappingMd.type();
CompressedString mappingSource = mappingMd.source();
if (mappingType.equals(MapperService.DEFAULT_MAPPING)) { // we processed _default_ first
continue;
}
boolean requireRefresh = processMapping(index, mapperService, mappingType, mappingSource);
if (requireRefresh) {
if (typesToRefresh == null) {
typesToRefresh = Lists.newArrayList();
}
typesToRefresh.add(mappingType);
}
}
if (typesToRefresh != null) {
if (sendRefreshMapping) {
nodeMappingRefreshAction.nodeMappingRefresh(event.state(),
new NodeMappingRefreshAction.NodeMappingRefreshRequest(index, indexMetaData.uuid(),
typesToRefresh.toArray(new String[typesToRefresh.size()]), event.state().nodes().localNodeId()));
}
}
// go over and remove mappings
for (DocumentMapper documentMapper : mapperService) {
if (seenMappings.containsKey(new Tuple<String, String>(index, documentMapper.type())) && !indexMetaData.mappings().containsKey(documentMapper.type())) {
// we have it in our mappings, but not in the metadata, and we have seen it in the cluster state, remove it
mapperService.remove(documentMapper.type());
seenMappings.remove(new Tuple<String, String>(index, documentMapper.type()));
}
}
}
}
private boolean processMapping(String index, MapperService mapperService, String mappingType, CompressedString mappingSource) {
if (!seenMappings.containsKey(new Tuple<String, String>(index, mappingType))) {
seenMappings.put(new Tuple<String, String>(index, mappingType), true);
}
// refresh mapping can happen for 2 reasons. The first is less urgent, and happens when the mapping on this
// node is ahead of what there is in the cluster state (yet an update-mapping has been sent to it already,
// it just hasn't been processed yet and published). Eventually, the mappings will converge, and the refresh
// mapping sent is more of a safe keeping (assuming the update mapping failed to reach the master, ...)
// the second case is where the parsing/merging of the mapping from the metadata doesn't result in the same
// mapping, in this case, we send to the master to refresh its own version of the mappings (to conform with the
// merge version of it, which it does when refreshing the mappings), and warn log it.
boolean requiresRefresh = false;
try {
if (!mapperService.hasMapping(mappingType)) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] adding mapping [{}], source [{}]", index, mappingType, mappingSource.string());
}
// we don't apply default, since it has been applied when the mappings were parsed initially
mapperService.merge(mappingType, mappingSource, false);
if (!mapperService.documentMapper(mappingType).mappingSource().equals(mappingSource)) {
logger.debug("[{}] parsed mapping [{}], and got different sources\noriginal:\n{}\nparsed:\n{}", index, mappingType, mappingSource, mapperService.documentMapper(mappingType).mappingSource());
requiresRefresh = true;
}
} else {
DocumentMapper existingMapper = mapperService.documentMapper(mappingType);
if (!mappingSource.equals(existingMapper.mappingSource())) {
// mapping changed, update it
if (logger.isDebugEnabled()) {
logger.debug("[{}] updating mapping [{}], source [{}]", index, mappingType, mappingSource.string());
}
// we don't apply default, since it has been applied when the mappings were parsed initially
mapperService.merge(mappingType, mappingSource, false);
if (!mapperService.documentMapper(mappingType).mappingSource().equals(mappingSource)) {
requiresRefresh = true;
logger.debug("[{}] parsed mapping [{}], and got different sources\noriginal:\n{}\nparsed:\n{}", index, mappingType, mappingSource, mapperService.documentMapper(mappingType).mappingSource());
}
}
}
} catch (Throwable e) {
logger.warn("[{}] failed to add mapping [{}], source [{}]", e, index, mappingType, mappingSource);
}
return requiresRefresh;
}
private boolean aliasesChanged(ClusterChangedEvent event) {
return !event.state().metaData().aliases().equals(event.previousState().metaData().aliases()) ||
!event.state().routingTable().equals(event.previousState().routingTable());
}
private void applyAliases(ClusterChangedEvent event) {
// check if aliases changed
if (aliasesChanged(event)) {
// go over and update aliases
for (IndexMetaData indexMetaData : event.state().metaData()) {
if (!indicesService.hasIndex(indexMetaData.index())) {
// we only create / update here
continue;
}
String index = indexMetaData.index();
IndexService indexService = indicesService.indexService(index);
IndexAliasesService indexAliasesService = indexService.aliasesService();
processAliases(index, indexMetaData.aliases().values(), indexAliasesService);
// go over and remove aliases
for (IndexAlias indexAlias : indexAliasesService) {
if (!indexMetaData.aliases().containsKey(indexAlias.alias())) {
// we have it in our aliases, but not in the metadata, remove it
indexAliasesService.remove(indexAlias.alias());
}
}
}
}
}
private void processAliases(String index, ObjectContainer<AliasMetaData> aliases, IndexAliasesService indexAliasesService) {
HashMap<String, IndexAlias> newAliases = newHashMap();
for (ObjectCursor<AliasMetaData> cursor : aliases) {
AliasMetaData aliasMd = cursor.value;
String alias = aliasMd.alias();
CompressedString filter = aliasMd.filter();
try {
if (!indexAliasesService.hasAlias(alias)) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] adding alias [{}], filter [{}]", index, alias, filter);
}
newAliases.put(alias, indexAliasesService.create(alias, filter));
} else {
if ((filter == null && indexAliasesService.alias(alias).filter() != null) ||
(filter != null && !filter.equals(indexAliasesService.alias(alias).filter()))) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] updating alias [{}], filter [{}]", index, alias, filter);
}
newAliases.put(alias, indexAliasesService.create(alias, filter));
}
}
} catch (Throwable e) {
logger.warn("[{}] failed to add alias [{}], filter [{}]", e, index, alias, filter);
}
}
indexAliasesService.addAll(newAliases);
}
private void applyNewOrUpdatedShards(final ClusterChangedEvent event) throws ElasticsearchException {
if (!indicesService.changesAllowed()) {
return;
}
RoutingTable routingTable = event.state().routingTable();
RoutingNodes.RoutingNodeIterator routingNode = event.state().readOnlyRoutingNodes().routingNodeIter(event.state().nodes().localNodeId());;
if (routingNode == null) {
failedShards.clear();
return;
}
DiscoveryNodes nodes = event.state().nodes();
for (final ShardRouting shardRouting : routingNode) {
final IndexService indexService = indicesService.indexService(shardRouting.index());
if (indexService == null) {
// got deleted on us, ignore
continue;
}
final IndexMetaData indexMetaData = event.state().metaData().index(shardRouting.index());
if (indexMetaData == null) {
// the index got deleted on the metadata, we will clean it later in the apply deleted method call
continue;
}
final int shardId = shardRouting.id();
if (!indexService.hasShard(shardId) && shardRouting.started()) {
if (!failedShards.containsKey(shardRouting.shardId())) {
// the master thinks we are started, but we don't have this shard at all, mark it as failed
logger.warn("[{}][{}] master [{}] marked shard as started, but shard has not been created, mark shard as failed", shardRouting.index(), shardId, nodes.masterNode());
failedShards.put(shardRouting.shardId(), new FailedShard(shardRouting.version()));
shardStateAction.shardFailed(shardRouting, indexMetaData.getUUID(),
"master " + nodes.masterNode() + " marked shard as started, but shard has not been created, mark shard as failed");
}
continue;
}
if (indexService.hasShard(shardId)) {
InternalIndexShard indexShard = (InternalIndexShard) indexService.shard(shardId);
ShardRouting currentRoutingEntry = indexShard.routingEntry();
// if the current and global routing are initializing, but are still not the same, its a different "shard" being allocated
// for example: a shard that recovers from one node and now needs to recover to another node,
// or a replica allocated and then allocating a primary because the primary failed on another node
if (currentRoutingEntry.initializing() && shardRouting.initializing() && !currentRoutingEntry.equals(shardRouting)) {
logger.debug("[{}][{}] removing shard (different instance of it allocated on this node, current [{}], global [{}])", shardRouting.index(), shardRouting.id(), currentRoutingEntry, shardRouting);
// cancel recovery just in case we are in recovery (its fine if we are not in recovery, it will be a noop).
recoveryTarget.cancelRecovery(indexShard);
indexService.removeShard(shardRouting.id(), "removing shard (different instance of it allocated on this node)");
}
}
if (indexService.hasShard(shardId)) {
InternalIndexShard indexShard = (InternalIndexShard) indexService.shard(shardId);
if (!shardRouting.equals(indexShard.routingEntry())) {
indexShard.routingEntry(shardRouting);
indexService.shardInjector(shardId).getInstance(IndexShardGatewayService.class).routingStateChanged();
}
}
if (shardRouting.initializing()) {
applyInitializingShard(routingTable, nodes, indexMetaData, routingTable.index(shardRouting.index()).shard(shardRouting.id()), shardRouting);
}
}
}
private void cleanFailedShards(final ClusterChangedEvent event) {
RoutingTable routingTable = event.state().routingTable();
RoutingNodes.RoutingNodeIterator routingNode = event.state().readOnlyRoutingNodes().routingNodeIter(event.state().nodes().localNodeId());;
if (routingNode == null) {
failedShards.clear();
return;
}
DiscoveryNodes nodes = event.state().nodes();
long now = System.currentTimeMillis();
String localNodeId = nodes.localNodeId();
Iterator<Map.Entry<ShardId, FailedShard>> iterator = failedShards.entrySet().iterator();
shards:
while (iterator.hasNext()) {
Map.Entry<ShardId, FailedShard> entry = iterator.next();
FailedShard failedShard = entry.getValue();
IndexRoutingTable indexRoutingTable = routingTable.index(entry.getKey().getIndex());
if (indexRoutingTable != null) {
IndexShardRoutingTable shardRoutingTable = indexRoutingTable.shard(entry.getKey().id());
if (shardRoutingTable != null) {
for (ShardRouting shardRouting : shardRoutingTable.assignedShards()) {
if (localNodeId.equals(shardRouting.currentNodeId())) {
// we have a timeout here just to make sure we don't have dangled failed shards for some reason
// its just another safely layer
if (shardRouting.version() == failedShard.version && ((now - failedShard.timestamp) < TimeValue.timeValueMinutes(60).millis())) {
// It's the same failed shard - keep it if it hasn't timed out
continue shards;
} else {
// Different version or expired, remove it
break;
}
}
}
}
}
iterator.remove();
}
}
private void applyInitializingShard(final RoutingTable routingTable, final DiscoveryNodes nodes, final IndexMetaData indexMetaData, final IndexShardRoutingTable indexShardRouting, final ShardRouting shardRouting) throws ElasticsearchException {
final IndexService indexService = indicesService.indexService(shardRouting.index());
if (indexService == null) {
// got deleted on us, ignore
return;
}
final int shardId = shardRouting.id();
if (indexService.hasShard(shardId)) {
IndexShard indexShard = indexService.shardSafe(shardId);
if (indexShard.state() == IndexShardState.STARTED || indexShard.state() == IndexShardState.POST_RECOVERY) {
// the master thinks we are initializing, but we are already started or on POST_RECOVERY and waiting
// for master to confirm a shard started message (either master failover, or a cluster event before
// we managed to tell the master we started), mark us as started
if (logger.isTraceEnabled()) {
logger.trace("{} master marked shard as initializing, but shard has state [{}], resending shard started",
indexShard.shardId(), indexShard.state());
}
shardStateAction.shardStarted(shardRouting, indexMetaData.getUUID(),
"master " + nodes.masterNode() + " marked shard as initializing, but shard state is [" + indexShard.state() + "], mark shard as started");
return;
} else {
if (indexShard.ignoreRecoveryAttempt()) {
return;
}
}
}
// if there is no shard, create it
if (!indexService.hasShard(shardId)) {
if (failedShards.containsKey(shardRouting.shardId())) {
// already tried to create this shard but it failed - ignore
logger.trace("[{}][{}] not initializing, this shards failed to recover on this node before, waiting for reassignment", shardRouting.index(), shardRouting.id());
return;
}
try {
if (logger.isDebugEnabled()) {
logger.debug("[{}][{}] creating shard", shardRouting.index(), shardId);
}
InternalIndexShard indexShard = (InternalIndexShard) indexService.createShard(shardId);
indexShard.routingEntry(shardRouting);
indexShard.engine().addFailedEngineListener(failedEngineHandler);
} catch (IndexShardAlreadyExistsException e) {
// ignore this, the method call can happen several times
} catch (Throwable e) {
logger.warn("[{}][{}] failed to create shard", e, shardRouting.index(), shardRouting.id());
try {
indexService.removeShard(shardId, "failed to create [" + ExceptionsHelper.detailedMessage(e) + "]");
} catch (IndexShardMissingException e1) {
// ignore
} catch (Throwable e1) {
logger.warn("[{}][{}] failed to remove shard after failed creation", e1, shardRouting.index(), shardRouting.id());
}
failedShards.put(shardRouting.shardId(), new FailedShard(shardRouting.version()));
shardStateAction.shardFailed(shardRouting, indexMetaData.getUUID(), "Failed to create shard, message [" + detailedMessage(e) + "]");
return;
}
}
final InternalIndexShard indexShard = (InternalIndexShard) indexService.shardSafe(shardId);
if (indexShard.ignoreRecoveryAttempt()) {
// we are already recovering (we can get to this state since the cluster event can happen several
// times while we recover)
return;
}
if (!shardRouting.primary()) {
// recovery from primary
IndexShardRoutingTable shardRoutingTable = routingTable.index(shardRouting.index()).shard(shardRouting.id());
for (ShardRouting entry : shardRoutingTable) {
if (entry.primary() && entry.started()) {
// only recover from started primary, if we can't find one, we will do it next round
final DiscoveryNode sourceNode = nodes.get(entry.currentNodeId());
try {
// we are recovering a backup from a primary, so no need to mark it as relocated
final StartRecoveryRequest request = new StartRecoveryRequest(indexShard.shardId(), sourceNode, nodes.localNode(), false, indexShard.store().list());
recoveryTarget.startRecovery(request, indexShard, new PeerRecoveryListener(request, shardRouting, indexService, indexMetaData));
} catch (Throwable e) {
handleRecoveryFailure(indexService, indexMetaData, shardRouting, true, e);
break;
}
break;
}
}
} else {
if (shardRouting.relocatingNodeId() == null) {
// we are the first primary, recover from the gateway
// if its post api allocation, the index should exists
boolean indexShouldExists = indexShardRouting.primaryAllocatedPostApi();
IndexShardGatewayService shardGatewayService = indexService.shardInjector(shardId).getInstance(IndexShardGatewayService.class);
shardGatewayService.recover(indexShouldExists, new IndexShardGatewayService.RecoveryListener() {
@Override
public void onRecoveryDone() {
shardStateAction.shardStarted(shardRouting, indexMetaData.getUUID(), "after recovery from gateway");
}
@Override
public void onIgnoreRecovery(String reason) {
}
@Override
public void onRecoveryFailed(IndexShardGatewayRecoveryException e) {
handleRecoveryFailure(indexService, indexMetaData, shardRouting, true, e);
}
});
} else {
// relocating primaries, recovery from the relocating shard
final DiscoveryNode sourceNode = nodes.get(shardRouting.relocatingNodeId());
try {
// we don't mark this one as relocated at the end, requests in any case are routed to both when its relocating
// and that way we handle the edge case where its mark as relocated, and we might need to roll it back...
final StartRecoveryRequest request = new StartRecoveryRequest(indexShard.shardId(), sourceNode, nodes.localNode(), false, indexShard.store().list());
recoveryTarget.startRecovery(request, indexShard, new PeerRecoveryListener(request, shardRouting, indexService, indexMetaData));
} catch (Throwable e) {
handleRecoveryFailure(indexService, indexMetaData, shardRouting, true, e);
}
}
}
}
private class PeerRecoveryListener implements RecoveryTarget.RecoveryListener {
private final StartRecoveryRequest request;
private final ShardRouting shardRouting;
private final IndexService indexService;
private final IndexMetaData indexMetaData;
private PeerRecoveryListener(StartRecoveryRequest request, ShardRouting shardRouting, IndexService indexService, IndexMetaData indexMetaData) {
this.request = request;
this.shardRouting = shardRouting;
this.indexService = indexService;
this.indexMetaData = indexMetaData;
}
@Override
public void onRecoveryDone() {
shardStateAction.shardStarted(shardRouting, indexMetaData.getUUID(), "after recovery (replica) from node [" + request.sourceNode() + "]");
}
@Override
public void onRetryRecovery(TimeValue retryAfter, RecoveryStatus recoveryStatus) {
recoveryTarget.retryRecovery(request, recoveryStatus, PeerRecoveryListener.this);
}
@Override
public void onIgnoreRecovery(boolean removeShard, String reason) {
if (!removeShard) {
return;
}
synchronized (mutex) {
if (indexService.hasShard(shardRouting.shardId().id())) {
if (logger.isDebugEnabled()) {
logger.debug("[{}][{}] removing shard on ignored recovery, reason [{}]", shardRouting.index(), shardRouting.shardId().id(), reason);
}
try {
indexService.removeShard(shardRouting.shardId().id(), "ignore recovery: " + reason);
} catch (IndexShardMissingException e) {
// the node got closed on us, ignore it
} catch (Throwable e1) {
logger.warn("[{}][{}] failed to delete shard after ignore recovery", e1, indexService.index().name(), shardRouting.shardId().id());
}
}
}
}
@Override
public void onRecoveryFailure(RecoveryFailedException e, boolean sendShardFailure) {
handleRecoveryFailure(indexService, indexMetaData, shardRouting, sendShardFailure, e);
}
}
private void handleRecoveryFailure(IndexService indexService, IndexMetaData indexMetaData, ShardRouting shardRouting, boolean sendShardFailure, Throwable failure) {
logger.warn("[{}][{}] failed to start shard", failure, indexService.index().name(), shardRouting.shardId().id());
synchronized (mutex) {
if (indexService.hasShard(shardRouting.shardId().id())) {
try {
indexService.removeShard(shardRouting.shardId().id(), "recovery failure [" + ExceptionsHelper.detailedMessage(failure) + "]");
} catch (IndexShardMissingException e) {
// the node got closed on us, ignore it
} catch (Throwable e1) {
logger.warn("[{}][{}] failed to delete shard after failed startup", e1, indexService.index().name(), shardRouting.shardId().id());
}
}
if (sendShardFailure) {
try {
failedShards.put(shardRouting.shardId(), new FailedShard(shardRouting.version()));
shardStateAction.shardFailed(shardRouting, indexMetaData.getUUID(), "Failed to start shard, message [" + detailedMessage(failure) + "]");
} catch (Throwable e1) {
logger.warn("[{}][{}] failed to mark shard as failed after a failed start", e1, indexService.index().name(), shardRouting.id());
}
}
}
}
private void removeIndex(String index, String reason) {
try {
indicesService.removeIndex(index, reason);
} catch (Throwable e) {
logger.warn("failed to clean index ({})", e, reason);
}
// clear seen mappings as well
for (Tuple<String, String> tuple : seenMappings.keySet()) {
if (tuple.v1().equals(index)) {
seenMappings.remove(tuple);
}
}
}
private class FailedEngineHandler implements Engine.FailedEngineListener {
@Override
public void onFailedEngine(final ShardId shardId, final Throwable failure) {
ShardRouting shardRouting = null;
final IndexService indexService = indicesService.indexService(shardId.index().name());
if (indexService != null) {
IndexShard indexShard = indexService.shard(shardId.id());
if (indexShard != null) {
shardRouting = indexShard.routingEntry();
}
}
if (shardRouting == null) {
logger.warn("[{}][{}] engine failed, but can't find index shard", shardId.index().name(), shardId.id());
return;
}
final ShardRouting fShardRouting = shardRouting;
final String indexUUID = indexService.indexUUID(); // we know indexService is not null here.
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
synchronized (mutex) {
if (indexService.hasShard(shardId.id())) {
try {
indexService.removeShard(shardId.id(), "engine failure [" + ExceptionsHelper.detailedMessage(failure) + "]");
} catch (IndexShardMissingException e) {
// the node got closed on us, ignore it
} catch (Throwable e1) {
logger.warn("[{}][{}] failed to delete shard after failed engine", e1, indexService.index().name(), shardId.id());
}
}
try {
failedShards.put(fShardRouting.shardId(), new FailedShard(fShardRouting.version()));
shardStateAction.shardFailed(fShardRouting, indexUUID, "engine failure, message [" + detailedMessage(failure) + "]");
} catch (Throwable e1) {
logger.warn("[{}][{}] failed to mark shard as failed after a failed engine", e1, indexService.index().name(), shardId.id());
}
}
}
});
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_indices_cluster_IndicesClusterStateService.java
|
426 |
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java
|
563 |
private static final class CompositeWrapperMap implements Map<Object, Integer> {
private final Map<OCompositeKey, Integer> underlying;
private final Object[] params;
private final List<OIndexDefinition> indexDefinitions;
private final int multiValueIndex;
private CompositeWrapperMap(Map<OCompositeKey, Integer> underlying, List<OIndexDefinition> indexDefinitions, Object[] params,
int multiValueIndex) {
this.underlying = underlying;
this.params = params;
this.multiValueIndex = multiValueIndex;
this.indexDefinitions = indexDefinitions;
}
public int size() {
return underlying.size();
}
public boolean isEmpty() {
return underlying.isEmpty();
}
public boolean containsKey(Object key) {
final OCompositeKey compositeKey = convertToCompositeKey(key);
return underlying.containsKey(compositeKey);
}
public boolean containsValue(Object value) {
return underlying.containsValue(value);
}
public Integer get(Object key) {
return underlying.get(convertToCompositeKey(key));
}
public Integer put(Object key, Integer value) {
final OCompositeKey compositeKey = convertToCompositeKey(key);
return underlying.put(compositeKey, value);
}
public Integer remove(Object key) {
return underlying.remove(convertToCompositeKey(key));
}
public void putAll(Map<? extends Object, ? extends Integer> m) {
throw new UnsupportedOperationException("Unsupported because of performance reasons");
}
public void clear() {
underlying.clear();
}
public Set<Object> keySet() {
throw new UnsupportedOperationException("Unsupported because of performance reasons");
}
public Collection<Integer> values() {
return underlying.values();
}
public Set<Entry<Object, Integer>> entrySet() {
throw new UnsupportedOperationException();
}
private OCompositeKey convertToCompositeKey(Object key) {
final OCompositeKey compositeKey = new OCompositeKey();
int paramsIndex = 0;
for (int i = 0; i < indexDefinitions.size(); i++) {
final OIndexDefinition indexDefinition = indexDefinitions.get(i);
if (i != multiValueIndex) {
compositeKey.addKey(indexDefinition.createValue(params[paramsIndex]));
paramsIndex++;
} else
compositeKey.addKey(((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(key));
}
return compositeKey;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_index_OCompositeIndexDefinition.java
|
521 |
public class OQueryParsingException extends OException {
private String text;
private int position = -1;
private static final long serialVersionUID = -7430575036316163711L;
public OQueryParsingException(final String iMessage) {
super(iMessage);
}
public OQueryParsingException(final String iMessage, final Throwable cause) {
super(iMessage, cause);
}
public OQueryParsingException(final String iMessage, final String iText, final int iPosition, final Throwable cause) {
super(iMessage, cause);
text = iText;
position = iPosition;
}
public OQueryParsingException(final String iMessage, final String iText, final int iPosition) {
super(iMessage);
text = iText;
position = iPosition;
}
@Override
public String getMessage() {
StringBuilder buffer = new StringBuilder();
if (position > -1) {
buffer.append("Error on parsing query at position #");
buffer.append(position);
buffer.append(": ");
}
buffer.append(super.getMessage());
if (text != null) {
buffer.append("\nQuery: ");
buffer.append(text);
buffer.append("\n------");
for (int i = 0; i < position - 1; ++i)
buffer.append("-");
buffer.append("^");
}
return buffer.toString();
}
public String getText() {
return text;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_exception_OQueryParsingException.java
|
1,410 |
public class IMapRegionCache implements RegionCache {
private final String name;
private final HazelcastInstance hazelcastInstance;
private final IMap<Object, Object> map;
private final Comparator versionComparator;
private final int lockTimeout;
private final long tryLockAndGetTimeout;
private final boolean explicitVersionCheckEnabled;
private final ILogger logger;
public IMapRegionCache(final String name, final HazelcastInstance hazelcastInstance,
final Properties props, final CacheDataDescription metadata) {
this.name = name;
this.hazelcastInstance = hazelcastInstance;
this.versionComparator = metadata != null && metadata.isVersioned() ? metadata.getVersionComparator() : null;
this.map = hazelcastInstance.getMap(this.name);
lockTimeout = CacheEnvironment.getLockTimeoutInMillis(props);
final long maxOperationTimeout = HazelcastTimestamper.getMaxOperationTimeout(hazelcastInstance);
tryLockAndGetTimeout = Math.min(maxOperationTimeout, 500);
explicitVersionCheckEnabled = CacheEnvironment.isExplicitVersionCheckEnabled(props);
logger = createLogger(name, hazelcastInstance);
}
public Object get(final Object key) {
return map.get(key);
}
public boolean put(final Object key, final Object value, final Object currentVersion) {
return update(key, value, currentVersion, null, null);
}
public boolean update(final Object key, final Object value, final Object currentVersion,
final Object previousVersion, final SoftLock lock) {
if (lock == LOCK_FAILURE) {
logger.warning("Cache lock could not be acquired!");
return false;
}
if (versionComparator != null && currentVersion != null) {
if (explicitVersionCheckEnabled && value instanceof CacheEntry) {
final CacheEntry currentEntry = (CacheEntry) value;
try {
if (map.tryLock(key, tryLockAndGetTimeout, TimeUnit.MILLISECONDS)) {
try {
final CacheEntry previousEntry = (CacheEntry) map.get(key);
if (previousEntry == null ||
versionComparator.compare(currentEntry.getVersion(), previousEntry.getVersion()) > 0) {
map.set(key, value);
return true;
} else {
return false;
}
} finally {
map.unlock(key);
}
} else {
return false;
}
} catch (InterruptedException e) {
return false;
}
} else if (previousVersion == null || versionComparator.compare(currentVersion, previousVersion) > 0) {
map.set(key, value);
return true;
}
return false;
} else {
map.set(key, value);
return true;
}
}
public boolean remove(final Object key) {
return map.remove(key) != null;
}
public SoftLock tryLock(final Object key, final Object version) {
try {
return map.tryLock(key, lockTimeout, TimeUnit.MILLISECONDS) ? LOCK_SUCCESS : LOCK_FAILURE;
} catch (InterruptedException e) {
return LOCK_FAILURE;
}
}
public void unlock(final Object key, SoftLock lock) {
if (lock == LOCK_SUCCESS) {
map.unlock(key);
}
}
public boolean contains(final Object key) {
return map.containsKey(key);
}
public void clear() {
// clear all cache and destroy proxies
// when a new operation done over this proxy
// Hazelcast will initialize and create map again.
map.destroy();
// create Hazelcast internal proxies, has no effect on map operations
hazelcastInstance.getMap(name);
}
public long size() {
return map.size();
}
public long getSizeInMemory() {
long size = 0;
for (final Object key : map.keySet()) {
final EntryView entry = map.getEntryView(key);
if (entry != null) {
size += entry.getCost();
}
}
return size;
}
public Map asMap() {
return map;
}
private ILogger createLogger(final String name, final HazelcastInstance hazelcastInstance) {
try {
return hazelcastInstance.getLoggingService().getLogger(name);
} catch (UnsupportedOperationException e) {
return Logger.getLogger(name);
}
}
private static final SoftLock LOCK_SUCCESS = new SoftLock() {};
private static final SoftLock LOCK_FAILURE = new SoftLock() {};
}
| 1no label
|
hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_distributed_IMapRegionCache.java
|
61 |
public interface FieldEnumeration extends Serializable {
List<FieldEnumerationItem> getEnumerationItems();
void setEnumerationItems(List<FieldEnumerationItem> enumerationItems);
Long getId();
void setId(Long id);
String getName();
void setName(String name);
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_field_domain_FieldEnumeration.java
|
976 |
public abstract class IndicesReplicationOperationRequestBuilder<Request extends IndicesReplicationOperationRequest<Request>, Response extends ActionResponse, RequestBuilder extends IndicesReplicationOperationRequestBuilder<Request, Response, RequestBuilder>>
extends ActionRequestBuilder<Request, Response, RequestBuilder> {
protected IndicesReplicationOperationRequestBuilder(InternalGenericClient client, Request request) {
super(client, request);
}
/**
* A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>.
*/
@SuppressWarnings("unchecked")
public final RequestBuilder setTimeout(TimeValue timeout) {
request.timeout(timeout);
return (RequestBuilder) this;
}
/**
* A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>.
*/
@SuppressWarnings("unchecked")
public final RequestBuilder setTimeout(String timeout) {
request.timeout(timeout);
return (RequestBuilder) this;
}
@SuppressWarnings("unchecked")
public final RequestBuilder setIndices(String... indices) {
request.indices(indices);
return (RequestBuilder) this;
}
/**
* Specifies what type of requested indices to ignore and how to deal with wildcard indices expressions.
* For example indices that don't exist.
*/
@SuppressWarnings("unchecked")
public RequestBuilder setIndicesOptions(IndicesOptions indicesOptions) {
request().indicesOptions(indicesOptions);
return (RequestBuilder) this;
}
/**
* Sets the replication type.
*/
@SuppressWarnings("unchecked")
public RequestBuilder setReplicationType(ReplicationType replicationType) {
request.replicationType(replicationType);
return (RequestBuilder) this;
}
/**
* Sets the replication type.
*/
@SuppressWarnings("unchecked")
public RequestBuilder setReplicationType(String replicationType) {
request.replicationType(replicationType);
return (RequestBuilder) this;
}
/**
* Sets the consistency level of write. Defaults to {@link org.elasticsearch.action.WriteConsistencyLevel#DEFAULT}
*/
@SuppressWarnings("unchecked")
public RequestBuilder setConsistencyLevel(WriteConsistencyLevel consistencyLevel) {
request.consistencyLevel(consistencyLevel);
return (RequestBuilder) this;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_replication_IndicesReplicationOperationRequestBuilder.java
|
504 |
public abstract class OEngineAbstract implements OEngine {
protected String getMode(Map<String, String> iConfiguration) {
String dbMode = null;
if (iConfiguration != null)
dbMode = iConfiguration.get("mode");
if (dbMode == null)
dbMode = "rw";
return dbMode;
}
public void shutdown() {
}
public void removeStorage(final OStorage iStorage) {
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_engine_OEngineAbstract.java
|
461 |
public abstract class IndicesAction<Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>>
extends GenericAction<Request, Response> {
protected IndicesAction(String name) {
super(name);
}
public abstract RequestBuilder newRequestBuilder(IndicesAdminClient client);
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_IndicesAction.java
|
1,692 |
public class OHttpRequest {
public final OContextConfiguration configuration;
public final InputStream in;
public String authorization;
public String sessionId;
public String url;
public Map<String, String> parameters;
public String httpMethod;
public String httpVersion;
public String contentType;
public String contentEncoding;
public String content;
public OHttpMultipartBaseInputStream multipartStream;
public String boundary;
public String databaseName;
public boolean isMultipart;
public String ifMatch;
public String authentication;
protected Map<String, String> headers;
public final ONetworkProtocolData data;
public final ONetworkProtocolHttpAbstract executor;
public OHttpRequest(final ONetworkProtocolHttpAbstract iExecutor, final InputStream iInStream, final ONetworkProtocolData iData,
final OContextConfiguration iConfiguration) {
executor = iExecutor;
in = iInStream;
data = iData;
configuration = iConfiguration;
}
public String getUser() {
return authorization != null ? authorization.substring(0, authorization.indexOf(":")) : null;
}
public InputStream getInputStream() {
return in;
}
public String getParameter(final String iName) {
return parameters != null ? parameters.get(iName) : null;
}
public void addHeader(final String h) {
if (headers == null)
headers = new HashMap<String, String>();
final int pos = h.indexOf(':');
if (pos > -1) {
headers.put(h.substring(0, pos).trim(), h.substring(pos + 1).trim());
}
}
public String getHeader(final String iName) {
return headers.get(iName);
}
public Set<Entry<String, String>> getHeaders() {
return headers.entrySet();
}
public String getRemoteAddress() {
if (data.caller != null)
return data.caller;
return ((InetSocketAddress) executor.channel.socket.getRemoteSocketAddress()).getAddress().getHostAddress();
}
}
| 1no label
|
server_src_main_java_com_orientechnologies_orient_server_network_protocol_http_OHttpRequest.java
|
1,101 |
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) {
counter.incrementAndGet();
}
latch.countDown();
}
});
| 0true
|
src_test_java_org_elasticsearch_benchmark_counter_SimpleCounterBenchmark.java
|
1,403 |
listener.future = threadPool.schedule(request.timeout, ThreadPool.Names.SAME, new Runnable() {
@Override
public void run() {
listener.onResponse(new Response(false));
nodeIndexDeletedAction.remove(nodeIndexDeleteListener);
}
});
| 0true
|
src_main_java_org_elasticsearch_cluster_metadata_MetaDataDeleteIndexService.java
|
567 |
public class BindOperation extends AbstractClusterOperation implements JoinOperation {
private Address localAddress;
private Address targetAddress;
private boolean reply;
public BindOperation() {
}
public BindOperation(Address localAddress, final Address targetAddress, final boolean reply) {
this.localAddress = localAddress;
this.targetAddress = targetAddress;
this.reply = reply;
}
@Override
public void run() {
NodeEngineImpl ns = (NodeEngineImpl) getNodeEngine();
TcpIpConnectionManager connectionManager = (TcpIpConnectionManager) ns.getNode().getConnectionManager();
TcpIpConnection connection = (TcpIpConnection) getConnection();
connectionManager.bind(connection, localAddress, targetAddress, reply);
}
@Override
protected void readInternal(final ObjectDataInput in) throws IOException {
localAddress = new Address();
localAddress.readData(in);
boolean hasTarget = in.readBoolean();
if (hasTarget) {
targetAddress = new Address();
targetAddress.readData(in);
}
reply = in.readBoolean();
}
@Override
protected void writeInternal(final ObjectDataOutput out) throws IOException {
localAddress.writeData(out);
boolean hasTarget = targetAddress != null;
out.writeBoolean(hasTarget);
if (hasTarget) {
targetAddress.writeData(out);
}
out.writeBoolean(reply);
}
@Override
public String toString() {
return "Bind " + localAddress;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_cluster_BindOperation.java
|
416 |
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface AdminPresentationMap {
/**
* <p>Optional - field name will be used if not specified</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 "";
/**
* <p>Optional - only required if you wish to apply security to this field</p>
*
* <p>If a security level is specified, it is registered with the SecurityManager.
* The SecurityManager checks the permission of the current user to
* determine if this field should be disabled based on the specified level.</p>
*
* @return the security level
*/
String securityLevel() default "";
/**
* <p>Optional - fields are not excluded by default</p>
*
* <p>Specify if this field should be excluded from inclusion in the
* admin presentation layer</p>
*
* @return whether or not the field should be excluded
*/
boolean excluded() default false;
/**
* 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;
/**
* <p>Optional - only required if you want to make the field ignore caching</p>
*
* <p>Explicitly specify whether or not this field will use server-side
* caching during inspection</p>
*
* @return whether or not this field uses caching
*/
boolean useServerSideInspectionCache() default true;
/**
* <p>Optional - only required if you want to specify ordering for this field</p>
*
* <p>The order in which this field will appear in a GUI relative to other collections from the same class</p>
*
* @return the display order
*/
int order() default 99999;
/**
* 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;
/**
* <p>Optional - only required if the type for the key of this map
* is other than java.lang.String, or if the map is not a generic
* type from which the key type can be derived</p>
*
* <p>The type for the key of this map</p>
*
* @return The type for the key of this map
*/
Class<?> keyClass() default void.class;
/**
* <p>Optional - only required if you wish to specify a key different from the one on the
* {@link MapKey} annotation for the same field.
*
* @return the property for the key
*/
String mapKeyValueProperty() default "";
/**
* <p>Optional - only required if the key field title for this
* map should be translated to another lang, or should be
* something other than the constant "Key"</p>
*
* <p>The friendly name to present to a user for this key field title 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 keyPropertyFriendlyName() default "Key";
/**
* <p>Optional - only required if the type for the value of this map
* is other than java.lang.String, or if the map is not a generic
* type from which the value type can be derived, or if there is
* not a @ManyToMany annotation used from which a targetEntity
* can be inferred.</p>
*
* <p>The type for the value of this map</p>
*
* @return The type for the value of this map
*/
Class<?> valueClass() default void.class;
/**
* <p>Optional - only required if the value class is a
* JPA managed type and the persisted entity should
* be deleted upon removal from this map</p>
*
* <p>Whether or not a complex (JPA managed) value should
* be deleted upon removal from this map</p>
*
* @return Whether or not a complex value is deleted upon map removal
*/
boolean deleteEntityUponRemove() default false;
/**
* <p>Optional - only required if the value property for this map
* is simple (Not JPA managed - e.g. java.lang.String) and if the
* value field title for this map should be translated to another lang, or
* should be something other than the constant "Value"</p>
*
* <p>The friendly name to present to a user for this value field title 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 valuePropertyFriendlyName() default "Value";
/**
* <p>Optional - only required if the value type cannot be derived from the map
* declaration in the JPA managed entity and the value type is complex (JPA managed entity)</p>
*
* <p>Whether or not the value type for the map is complex (JPA managed entity), rather than an simple
* type (e.g. java.lang.String). This can usually be inferred from the parameterized type of the map
* (if available), or from the targetEntity property of a @ManyToMany annotation for the map (if available).</p>
*
* @return Whether or not the value type for the map is complex
*/
UnspecifiedBooleanType isSimpleValue() default UnspecifiedBooleanType.UNSPECIFIED;
/**
* <p>Optional - only required if the value type for the map is complex (JPA managed) and one of the fields
* of the complex value provides a URL value that points to a resolvable image url.</p>
*
* <p>The field name of complex value that provides an image url</p>
*
* @return The field name of complex value that provides an image url
*/
String mediaField() default "";
/**
* <p>Optional - only required when the user should select from a list of pre-defined
* keys when adding/editing this map. Either this value, or the mapKeyOptionEntityClass
* should be user - not both.</p>
*
* <p>Specify the keys available for the user to select from</p>
*
* @return the array of keys from which the user can select
*/
AdminPresentationMapKey[] keys() default {};
/**
* <p>Optional - only required when you want to allow the user to create his/her own
* key value, rather than select from a pre-defined list. The default is to
* force selection from a pre-defined list.</p>
*
* @return whether or not the user will create their own key values.
*/
boolean forceFreeFormKeys() default false;
/**
* <p>Optional - only required with a complex value class that has a bi-directional
* association back to the parent class containing the map. This can generally
* be inferred by the system from a "mappedBy" attribute for maps of a OneToMany
* type. For map configurations without a mappedBy value, or if you wish to
* explicitly set a bi-directional association field on the complex value, use
* this property.</p>
*
* @return the bi-directional association field on the complex value, if any
*/
String manyToField() default "";
/**
* <p>Optional - only required when the user should select from a list of database
* persisted values for keys when adding/editing this map. Either this value, or the
* keys parameter should be user - not both</p>
*
* <p>Specify the entity class that represents the table in the database that contains
* the key values for this map</p>
*
* @return the entity class for the map keys
*/
Class<?> mapKeyOptionEntityClass() default void.class;
/**
* <p>Optional - only required when the user should select from a list of database
* persisted values for keys when adding/editing this map.</p>
*
* <p>Specify the field in the option entity class that contains the value that will
* be shown to the user. This can be the same field as the value field. This option
* does not support i18n out-of-the-box.</p>
*
* @return the display field in the entity class
*/
String mapKeyOptionEntityDisplayField() default "";
/**
* <p>Optional - only required when the user should select from a list of database
* persisted values for keys when adding/editing this map.</p>
*
* <p>Specify the field in the option entity class that contains the value that will
* actually be saved for the selected key. This can be the same field as the display
* field.</p>
*
* @return the value field in the entity class
*/
String mapKeyOptionEntityValueField() default "";
/**
* <p>Optional - only required if you need to specially handle crud operations for this
* specific collection on the server</p>
*
* <p>Custom string values that will be passed to the server during CRUD operations on this
* collection. These criteria values can be detected in a custom persistence handler
* (@CustomPersistenceHandler) in order to engage special handling through custom server
* side code for this collection.</p>
*
* @return the custom string array to pass to the server during CRUD operations
*/
String[] customCriteria() default {};
/**
* <p>Optional - only required if a special operation type is required for a CRUD operation. This
* setting is not normally changed and is an advanced setting</p>
*
* <p>The operation type for a CRUD operation</p>
*
* @return the operation type
*/
AdminPresentationOperationTypes operationTypes() default @AdminPresentationOperationTypes(addType = OperationType.MAP, fetchType = OperationType.MAP, inspectType = OperationType.MAP, removeType = OperationType.MAP, updateType = OperationType.MAP);
/**
* <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 "";
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentationMap.java
|
347 |
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(request.delay.millis());
} catch (InterruptedException e) {
// ignore
}
// first, stop the cluster service
logger.trace("[cluster_shutdown]: stopping the cluster service so no re-routing will occur");
clusterService.stop();
final CountDownLatch latch = new CountDownLatch(nodes.size());
for (ObjectCursor<DiscoveryNode> cursor : nodes) {
final DiscoveryNode node = cursor.value;
if (node.id().equals(state.nodes().masterNodeId())) {
// don't shutdown the master yet...
latch.countDown();
} else {
logger.trace("[cluster_shutdown]: sending shutdown request to [{}]", node);
transportService.sendRequest(node, NodeShutdownRequestHandler.ACTION, new NodeShutdownRequest(request), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleResponse(TransportResponse.Empty response) {
logger.trace("[cluster_shutdown]: received shutdown response from [{}]", node);
latch.countDown();
}
@Override
public void handleException(TransportException exp) {
logger.warn("[cluster_shutdown]: received failed shutdown response from [{}]", exp, node);
latch.countDown();
}
});
}
}
try {
latch.await();
} catch (InterruptedException e) {
// ignore
}
logger.info("[cluster_shutdown]: done shutting down all nodes except master, proceeding to master");
// now, kill the master
logger.trace("[cluster_shutdown]: shutting down the master [{}]", state.nodes().masterNode());
transportService.sendRequest(state.nodes().masterNode(), NodeShutdownRequestHandler.ACTION, new NodeShutdownRequest(request), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleResponse(TransportResponse.Empty response) {
logger.trace("[cluster_shutdown]: received shutdown response from master");
}
@Override
public void handleException(TransportException exp) {
logger.warn("[cluster_shutdown]: received failed shutdown response master", exp);
}
});
}
});
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_shutdown_TransportNodesShutdownAction.java
|
235 |
assertTrueEventually(new AssertTask() {
public void run() throws Exception {
assertEquals(CLUSTER_SIZE, map.size());
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceExecuteTest.java
|
50 |
public abstract class HttpCommandProcessor<T> extends AbstractTextCommandProcessor<T> {
public static final String URI_MAPS = "/hazelcast/rest/maps/";
public static final String URI_QUEUES = "/hazelcast/rest/queues/";
public static final String URI_CLUSTER = "/hazelcast/rest/cluster";
public static final String URI_STATE_DUMP = "/hazelcast/rest/dump";
public static final String URI_MANCENTER_CHANGE_URL = "/hazelcast/rest/mancenter/changeurl";
protected HttpCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpCommandProcessor.java
|
5,127 |
public class AggregatorFactories {
public static final AggregatorFactories EMPTY = new Empty();
private final AggregatorFactory[] factories;
public static Builder builder() {
return new Builder();
}
private AggregatorFactories(AggregatorFactory[] factories) {
this.factories = factories;
}
private static Aggregator createAndRegisterContextAware(AggregationContext context, AggregatorFactory factory, Aggregator parent, long estimatedBucketsCount) {
final Aggregator aggregator = factory.create(context, parent, estimatedBucketsCount);
if (aggregator.shouldCollect()) {
context.registerReaderContextAware(aggregator);
}
return aggregator;
}
/**
* Create all aggregators so that they can be consumed with multiple buckets.
*/
public Aggregator[] createSubAggregators(Aggregator parent, final long estimatedBucketsCount) {
Aggregator[] aggregators = new Aggregator[count()];
for (int i = 0; i < factories.length; ++i) {
final AggregatorFactory factory = factories[i];
final Aggregator first = createAndRegisterContextAware(parent.context(), factory, parent, estimatedBucketsCount);
if (first.bucketAggregationMode() == BucketAggregationMode.MULTI_BUCKETS) {
// This aggregator already supports multiple bucket ordinals, can be used directly
aggregators[i] = first;
continue;
}
// the aggregator doesn't support multiple ordinals, let's wrap it so that it does.
aggregators[i] = new Aggregator(first.name(), BucketAggregationMode.MULTI_BUCKETS, AggregatorFactories.EMPTY, 1, first.context(), first.parent()) {
ObjectArray<Aggregator> aggregators;
{
aggregators = BigArrays.newObjectArray(estimatedBucketsCount, context.pageCacheRecycler());
aggregators.set(0, first);
for (long i = 1; i < estimatedBucketsCount; ++i) {
aggregators.set(i, createAndRegisterContextAware(parent.context(), factory, parent, estimatedBucketsCount));
}
}
@Override
public boolean shouldCollect() {
return first.shouldCollect();
}
@Override
protected void doPostCollection() {
for (long i = 0; i < aggregators.size(); ++i) {
final Aggregator aggregator = aggregators.get(i);
if (aggregator != null) {
aggregator.postCollection();
}
}
}
@Override
public void collect(int doc, long owningBucketOrdinal) throws IOException {
aggregators = BigArrays.grow(aggregators, owningBucketOrdinal + 1);
Aggregator aggregator = aggregators.get(owningBucketOrdinal);
if (aggregator == null) {
aggregator = createAndRegisterContextAware(parent.context(), factory, parent, estimatedBucketsCount);
aggregators.set(owningBucketOrdinal, aggregator);
}
aggregator.collect(doc, 0);
}
@Override
public void setNextReader(AtomicReaderContext reader) {
}
@Override
public InternalAggregation buildAggregation(long owningBucketOrdinal) {
return aggregators.get(owningBucketOrdinal).buildAggregation(0);
}
@Override
public InternalAggregation buildEmptyAggregation() {
return first.buildEmptyAggregation();
}
@Override
public void doRelease() {
Releasables.release(aggregators);
}
};
}
return aggregators;
}
public Aggregator[] createTopLevelAggregators(AggregationContext ctx) {
// These aggregators are going to be used with a single bucket ordinal, no need to wrap the PER_BUCKET ones
Aggregator[] aggregators = new Aggregator[factories.length];
for (int i = 0; i < factories.length; i++) {
aggregators[i] = createAndRegisterContextAware(ctx, factories[i], null, 0);
}
return aggregators;
}
public int count() {
return factories.length;
}
void setParent(AggregatorFactory parent) {
for (AggregatorFactory factory : factories) {
factory.parent = parent;
}
}
public void validate() {
for (AggregatorFactory factory : factories) {
factory.validate();
}
}
private final static class Empty extends AggregatorFactories {
private static final AggregatorFactory[] EMPTY_FACTORIES = new AggregatorFactory[0];
private static final Aggregator[] EMPTY_AGGREGATORS = new Aggregator[0];
private Empty() {
super(EMPTY_FACTORIES);
}
@Override
public Aggregator[] createSubAggregators(Aggregator parent, long estimatedBucketsCount) {
return EMPTY_AGGREGATORS;
}
@Override
public Aggregator[] createTopLevelAggregators(AggregationContext ctx) {
return EMPTY_AGGREGATORS;
}
}
public static class Builder {
private List<AggregatorFactory> factories = new ArrayList<AggregatorFactory>();
public Builder add(AggregatorFactory factory) {
factories.add(factory);
return this;
}
public AggregatorFactories build() {
if (factories.isEmpty()) {
return EMPTY;
}
return new AggregatorFactories(factories.toArray(new AggregatorFactory[factories.size()]));
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_AggregatorFactories.java
|
626 |
public class BroadleafRedirectController {
public String redirect(HttpServletRequest request, HttpServletResponse response, Model model) {
String path = (String) request.getSession().getAttribute("BLC_REDIRECT_URL");
if (path == null) {
path = request.getContextPath();
}
return "ajaxredirect:" + path;
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_web_controller_BroadleafRedirectController.java
|
601 |
public class GetSettingsRequest extends MasterNodeReadOperationRequest<GetSettingsRequest> {
private String[] indices = Strings.EMPTY_ARRAY;
private IndicesOptions indicesOptions = IndicesOptions.fromOptions(false, true, true, true);
private String[] names = Strings.EMPTY_ARRAY;
public GetSettingsRequest indices(String... indices) {
this.indices = indices;
return this;
}
public GetSettingsRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
public String[] indices() {
return indices;
}
public IndicesOptions indicesOptions() {
return indicesOptions;
}
public String[] names() {
return names;
}
public GetSettingsRequest names(String... names) {
this.names = names;
return this;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (names == null) {
validationException = ValidateActions.addValidationError("names may not be null", validationException);
}
return validationException;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
indices = in.readStringArray();
indicesOptions = IndicesOptions.readIndicesOptions(in);
names = in.readStringArray();
readLocal(in, Version.V_1_0_0_RC2);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeStringArray(indices);
indicesOptions.writeIndicesOptions(out);
out.writeStringArray(names);
writeLocal(out, Version.V_1_0_0_RC2);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_settings_get_GetSettingsRequest.java
|
141 |
public static class Order {
public static final int Description = 1000;
public static final int Internal = 2000;
public static final int Rules = 1000;
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentImpl.java
|
215 |
public class ClientInSelectorImpl extends ClientAbstractIOSelector {
public ClientInSelectorImpl(ThreadGroup threadGroup) {
super(threadGroup, "InSelector");
}
protected void handleSelectionKey(SelectionKey sk) {
if (sk.isValid() && sk.isReadable()) {
final SelectionHandler handler = (SelectionHandler) sk.attachment();
handler.handle();
}
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientInSelectorImpl.java
|
3,734 |
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Map<String, Object> objectNode = node;
ObjectMapper.Builder builder = createBuilder(name);
boolean nested = false;
boolean nestedIncludeInParent = false;
boolean nestedIncludeInRoot = false;
for (Map.Entry<String, Object> entry : objectNode.entrySet()) {
String fieldName = Strings.toUnderscoreCase(entry.getKey());
Object fieldNode = entry.getValue();
if (fieldName.equals("dynamic")) {
String value = fieldNode.toString();
if (value.equalsIgnoreCase("strict")) {
builder.dynamic(Dynamic.STRICT);
} else {
builder.dynamic(nodeBooleanValue(fieldNode) ? Dynamic.TRUE : Dynamic.FALSE);
}
} else if (fieldName.equals("type")) {
String type = fieldNode.toString();
if (type.equals(CONTENT_TYPE)) {
builder.nested = Nested.NO;
} else if (type.equals(NESTED_CONTENT_TYPE)) {
nested = true;
} else {
throw new MapperParsingException("Trying to parse an object but has a different type [" + type + "] for [" + name + "]");
}
} else if (fieldName.equals("include_in_parent")) {
nestedIncludeInParent = nodeBooleanValue(fieldNode);
} else if (fieldName.equals("include_in_root")) {
nestedIncludeInRoot = nodeBooleanValue(fieldNode);
} else if (fieldName.equals("enabled")) {
builder.enabled(nodeBooleanValue(fieldNode));
} else if (fieldName.equals("path")) {
builder.pathType(parsePathType(name, fieldNode.toString()));
} else if (fieldName.equals("properties")) {
parseProperties(builder, (Map<String, Object>) fieldNode, parserContext);
} else if (fieldName.equals("include_in_all")) {
builder.includeInAll(nodeBooleanValue(fieldNode));
} else {
processField(builder, fieldName, fieldNode);
}
}
if (nested) {
builder.nested = Nested.newNested(nestedIncludeInParent, nestedIncludeInRoot);
}
return builder;
}
private void parseProperties(ObjectMapper.Builder objBuilder, Map<String, Object> propsNode, ParserContext parserContext) {
for (Map.Entry<String, Object> entry : propsNode.entrySet()) {
String propName = entry.getKey();
Map<String, Object> propNode = (Map<String, Object>) entry.getValue();
String type;
Object typeNode = propNode.get("type");
if (typeNode != null) {
type = typeNode.toString();
} else {
// lets see if we can derive this...
if (propNode.get("properties") != null) {
type = ObjectMapper.CONTENT_TYPE;
} else if (propNode.size() == 1 && propNode.get("enabled") != null) {
// if there is a single property with the enabled flag on it, make it an object
// (usually, setting enabled to false to not index any type, including core values, which
// non enabled object type supports).
type = ObjectMapper.CONTENT_TYPE;
} else {
throw new MapperParsingException("No type specified for property [" + propName + "]");
}
}
Mapper.TypeParser typeParser = parserContext.typeParser(type);
if (typeParser == null) {
throw new MapperParsingException("No handler for type [" + type + "] declared on field [" + propName + "]");
}
objBuilder.add(typeParser.parse(propName, propNode, parserContext));
}
}
protected Builder createBuilder(String name) {
return object(name);
}
protected void processField(Builder builder, String fieldName, Object fieldNode) {
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_mapper_object_ObjectMapper.java
|
264 |
public class Build {
public static final Build CURRENT;
static {
String hash = "NA";
String hashShort = "NA";
String timestamp = "NA";
try {
String properties = Streams.copyToStringFromClasspath("/es-build.properties");
Properties props = new Properties();
props.load(new FastStringReader(properties));
hash = props.getProperty("hash", hash);
if (!hash.equals("NA")) {
hashShort = hash.substring(0, 7);
}
String gitTimestampRaw = props.getProperty("timestamp");
if (gitTimestampRaw != null) {
timestamp = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).print(Long.parseLong(gitTimestampRaw));
}
} catch (Exception e) {
// just ignore...
}
CURRENT = new Build(hash, hashShort, timestamp);
}
private String hash;
private String hashShort;
private String timestamp;
Build(String hash, String hashShort, String timestamp) {
this.hash = hash;
this.hashShort = hashShort;
this.timestamp = timestamp;
}
public String hash() {
return hash;
}
public String hashShort() {
return hashShort;
}
public String timestamp() {
return timestamp;
}
public static Build readBuild(StreamInput in) throws IOException {
String hash = in.readString();
String hashShort = in.readString();
String timestamp = in.readString();
return new Build(hash, hashShort, timestamp);
}
public static void writeBuild(Build build, StreamOutput out) throws IOException {
out.writeString(build.hash());
out.writeString(build.hashShort());
out.writeString(build.timestamp());
}
}
| 0true
|
src_main_java_org_elasticsearch_Build.java
|
532 |
public class PomEvaluator {
private static String SEPARATOR = "============================================================";
private static Map<String, Category> knownLibraries = new HashMap<String,Category>();
private static Map<LicenseType, List<Dependency>> licenseDependencyMap = new HashMap<LicenseType, List<Dependency>>();
private static Category SPRING = new Category("Spring Framework", LicenseType.APACHE2, FrameworkType.GENERAL);
private static Category HIBERNATE = new Category("Hibernate Framework", LicenseType.LGPL, FrameworkType.PERSISTENCE);
private static Category GOOGLE = new Category("Google", LicenseType.APACHE2, FrameworkType.GENERAL);
private static Category BROADLEAF_OPEN_SOURCE = new Category("Broadleaf Framework Open Source", LicenseType.APACHE2, FrameworkType.ECOMMERCE);
private static Category BROADLEAF_COMMERCIAL = new Category("Broadleaf Framework Commercial", LicenseType.APACHE2, FrameworkType.ECOMMERCE);
private static Category APACHE_FOUNDATION = new Category("Apache 2.0", LicenseType.APACHE2, FrameworkType.GENERAL);
private static Category JAVAX = new Category("javax", LicenseType.JAVA_EXTENSION, FrameworkType.OTHER);
private static Category THYMELEAF = new Category("thymeleaf", LicenseType.APACHE2, FrameworkType.UI);
private static Category SLF4J = new Category("slfj", LicenseType.MIT, FrameworkType.LOGGING);
private static Category LOG4J = new Category("log4j", LicenseType.APACHE2, FrameworkType.LOGGING);
private static Category OTHER = new Category("Other", LicenseType.OTHER, FrameworkType.OTHER);
private static Category SMART_GWT = new Category("Smart GWT UI Toolkit", LicenseType.LGPL, FrameworkType.UI);
// CODEHAUS is used by Apache and Spring Framework
private static Category JACKSON = new Category("Codehaus Jackson Library", LicenseType.APACHE2, FrameworkType.XML, SPRING, APACHE_FOUNDATION);
private static Category PLEXUS = new Category("Codehaus Plexus Library", LicenseType.APACHE2, FrameworkType.XML, SPRING, APACHE_FOUNDATION);
private static Category ASM = new Category("OW2 ASM libraries", LicenseType.OW2, FrameworkType.GENERAL, APACHE_FOUNDATION, GOOGLE);
private static Category CGLIB = new Category("CGLIB libraries", LicenseType.APACHE2, FrameworkType.GENERAL, SPRING, HIBERNATE);
private static Category JERSEY = new Category("Jersey Libraries", LicenseType.LGPL, FrameworkType.XML);
private static Category XSTREAM = new Category("Codehaus XML parsing library", LicenseType.XSTREAM_BSD, FrameworkType.XML);
private static Category JODA_TIME = new Category("Date and time utilities", LicenseType.APACHE2, FrameworkType.UTILITY, APACHE_FOUNDATION);
private static Category TRANSMORPH = new Category("Entropy Transmorph - SalesForce.com", LicenseType.APACHE2, FrameworkType.UTILITY);
private static Category QUARTZ = new Category("Teracotta Quartz", LicenseType.APACHE2, FrameworkType.SCHEDULER);
private static Category EHCACHE = new Category("Teracotta ehCache", LicenseType.APACHE2, FrameworkType.CACHE);
private static Category ANTLR = new Category("Antlr Runtime", LicenseType.ANTLR_BSD, FrameworkType.UTILITY, APACHE_FOUNDATION);
private static Category ASPECTJ = new Category("Aspect J", LicenseType.ECLIPSE_PUBLIC, FrameworkType.GENERAL, SPRING);
private static Category MVEL = new Category("MVEL rules evaluation", LicenseType.APACHE2, FrameworkType.RULES);
private static Category ORO = new Category("ORO regular expressions", LicenseType.APACHE2, FrameworkType.RULES);
private static Category JAVA_ASSIST = new Category("Java Assist", LicenseType.APACHE2, FrameworkType.GENERAL);
private static Category ANTISAMMY = new Category("Anti-Sammy", LicenseType.ANTISAMMY_BSD, FrameworkType.GENERAL);
private static void initializeKnownLibraries() {
// Spring
knownLibraries.put("org.springframework", SPRING);
knownLibraries.put("org.springframework.security", SPRING);
knownLibraries.put("org.springframework.social", SPRING);
// Hibernate
knownLibraries.put("org.hibernate", HIBERNATE);
knownLibraries.put("org.hibernate.javax.persistence", HIBERNATE);
// Broadleaf
knownLibraries.put("org.broadleafcommerce", BROADLEAF_OPEN_SOURCE);
knownLibraries.put("com.broadleafcommerce", BROADLEAF_COMMERCIAL);
// Thymeleaf
knownLibraries.put("org.thymeleaf", THYMELEAF);
// JavaX
knownLibraries.put("javax.xml.bind", JAVAX);
knownLibraries.put("javax.mail", JAVAX);
knownLibraries.put("javax.servlet", JAVAX);
knownLibraries.put("javax.servlet.jsp", JAVAX);
knownLibraries.put("jstl", JAVAX);
// Logging
knownLibraries.put("org.slf4j", SLF4J);
knownLibraries.put("log4j", LOG4J);
// Apache
knownLibraries.put("commons-validator", APACHE_FOUNDATION);
knownLibraries.put("commons-collections", APACHE_FOUNDATION);
knownLibraries.put("commons-beanutils", APACHE_FOUNDATION);
knownLibraries.put("commons-cli", APACHE_FOUNDATION);
knownLibraries.put("commons-fileupload", APACHE_FOUNDATION);
knownLibraries.put("commons-dbcp", APACHE_FOUNDATION);
knownLibraries.put("commons-codec", APACHE_FOUNDATION);
knownLibraries.put("org.apache.commons", APACHE_FOUNDATION);
knownLibraries.put("commons-lang", APACHE_FOUNDATION);
knownLibraries.put("commons-digester", APACHE_FOUNDATION);
knownLibraries.put("commons-logging", APACHE_FOUNDATION);
knownLibraries.put("commons-pool", APACHE_FOUNDATION);
knownLibraries.put("org.apache.geronimo.specs", APACHE_FOUNDATION);
knownLibraries.put("org.apache.solr", APACHE_FOUNDATION);
knownLibraries.put("org.apache.velocity", APACHE_FOUNDATION);
knownLibraries.put("org.apache.xmlbeans", APACHE_FOUNDATION);
knownLibraries.put("taglibs", APACHE_FOUNDATION);
knownLibraries.put("jakarta-regexp", APACHE_FOUNDATION);
// Google - Will retire
knownLibraries.put("com.google.gwt", GOOGLE);
knownLibraries.put("com.google.code.gwt-math", GOOGLE);
knownLibraries.put("com.google.code.findbugs", GOOGLE);
knownLibraries.put("net.sf.gwt-widget", GOOGLE);
// SmartGWT - Will retire with 3.0
knownLibraries.put("com.smartgwt", SMART_GWT);
// CodeHaus - JSON / XML processing
knownLibraries.put("org.codehaus.jackson", JACKSON);
knownLibraries.put("org.codehaus.plexus", PLEXUS);
// ASM
knownLibraries.put("asm", ASM);
// CGLIB
knownLibraries.put("cglib", CGLIB);
// Jersey - used for REST services
knownLibraries.put("com.sun.jersey", JERSEY);
knownLibraries.put("com.sun.jersey.contribs", JERSEY);
// XStream - used for REST services
knownLibraries.put("com.thoughtworks.xstream", JERSEY);
// Joda-Time
knownLibraries.put("joda-time", JODA_TIME);
// Cache
knownLibraries.put("net.sf.jsr107cache", JAVAX);
// Transmorph - Will retire with 3.0
knownLibraries.put("net.sf.transmorph", TRANSMORPH);
// Teracotta software
knownLibraries.put("net.sf.ehcache", EHCACHE);
knownLibraries.put("org.opensymphony.quartz", QUARTZ);
// Antlr
knownLibraries.put("org.antlr", ANTLR);
// Aspect J
knownLibraries.put("org.aspectj", ASPECTJ);
// MVEL
knownLibraries.put("org.mvel", MVEL);
// ORO
knownLibraries.put("oro", ORO);
// Java Assist
knownLibraries.put("org.javassist", JAVA_ASSIST);
// OWASP
knownLibraries.put("org.owasp.antisamy", ANTISAMMY);
}
/**
* @param args
*/
public static void main(String[] args) {
initializeKnownLibraries();
BufferedReader br = null;
try {
String fileName = "/Users/brianpolster/blc-workspace/BroadleafCommerce/pom.xml";
if (args.length > 0) {
fileName = args[0];
}
br = new BufferedReader(new FileReader(fileName));
forwardToTag("<dependencies>", br);
List<Dependency> dependencies = populateDependencies(br);
for (Dependency dependency : dependencies) {
Category category = knownLibraries.get(dependency.groupId);
if (category != null) {
category.dependencyList.add(dependency);
List<Dependency> licenseDependencyList = licenseDependencyMap.get(category.licenseType);
if (licenseDependencyList == null) {
licenseDependencyList = new ArrayList<Dependency>();
licenseDependencyList.add(dependency);
licenseDependencyMap.put(category.licenseType, licenseDependencyList);
}
} else {
if (dependency.scope.equals("test") ||
dependency.scope.equals("provided")) {
continue;
}
OTHER.dependencyList.add(dependency);
}
}
Set<Category> categoryList = new HashSet<Category>(knownLibraries.values());
System.out.println("Related Software Report\r");
for (Category category : categoryList) {
printOutDependencies(category, category.dependencyList);
}
if (OTHER.dependencyList.size() > 0) {
printOutDependencies(OTHER, OTHER.dependencyList);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void printOutDependencies(Category category, List<Dependency> dependencies) {
List<String> dependencyNames = new ArrayList<String>();
for (Dependency d : dependencies) {
dependencyNames.add(d.toString());
}
Collections.sort(dependencyNames);
System.out.println(category);
System.out.println(SEPARATOR);
for (String name : dependencyNames) {
System.out.println(name);
}
System.out.println("Total count for category " + category.categoryName + ": " + dependencyNames.size() + "\r\r");
}
public static List<Dependency> populateDependencies(BufferedReader br) throws IOException {
String currentLine;
List<Dependency> dependencyList = new ArrayList<Dependency>();
while (forwardToTag("<dependency", br)) {
Dependency current = new Dependency();
while ((currentLine = br.readLine()) != null) {
if (currentLine.contains("</dependency>")) {
break;
}
current.scope = getTagValue("<scope>", currentLine, current.scope);
current.groupId = getTagValue("<groupId>", currentLine, current.groupId);
current.artifactId = getTagValue("<artifactId>", currentLine, current.artifactId);
current.version = getTagValue("<version>", currentLine, current.version);
}
dependencyList.add(current);
}
return dependencyList;
}
public static String getTagValue(String tagName, String line, String currentValue) {
int startPos = line.indexOf(tagName);
if (startPos >= 0) {
int endPos = line.indexOf("</", startPos + 1);
if (endPos >= 0) {
return line.substring(startPos + tagName.length(), endPos);
}
}
return currentValue;
}
public static boolean forwardToTag(String tagName, BufferedReader br) throws IOException {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
String lowerCaseLine = sCurrentLine.toLowerCase();
if (lowerCaseLine.indexOf(tagName) >= 0) {
return true;
}
}
return false;
}
static class Dependency {
String groupId;
String artifactId;
String version;
String scope;
List<Category> categoriesThatDependOnThis = new ArrayList<Category>();
public String toString() {
return groupId + "." + artifactId + "." + version + " [" + scope + "]";
}
}
static class LicenseType {
private String name;
private String url;
public static LicenseType APACHE2 = new LicenseType("APACHE2", "http://www.apache.org/licenses/LICENSE-2.0.html");
public static LicenseType LGPL = new LicenseType("LGPL", "http://www.gnu.org/licenses/lgpl-3.0.html, http://www.gnu.org/licenses/lgpl-2.1.html,");
public static LicenseType MIT = new LicenseType("MIT", "http://opensource.org/licenses/MIT");
public static LicenseType JAVA_EXTENSION = new LicenseType("JAVA_EXTENSION", "n/a");
public static LicenseType OW2 = new LicenseType("OW2", "http://asm.ow2.org/license.html");
public static LicenseType XSTREAM_BSD = new LicenseType("XSTREAM_BSD", "http://xstream.codehaus.org/license.html");
public static LicenseType ANTLR_BSD = new LicenseType("ANTLR_BSD", "http://www.antlr.org/license.html");
public static LicenseType ANTISAMMY_BSD = new LicenseType("ANTISAMMY_BSD", "http://opensource.org/licenses/bsd-license.php");
public static LicenseType OTHER = new LicenseType("OTHER", "Unknown");
public static LicenseType ECLIPSE_PUBLIC = new LicenseType("ECLIPSE PUBLIC", "http://www.eclipse.org/legal/epl-v10.html");
public LicenseType(String name, String url) {
this.name = name;
this.url = url;
}
public String toString() {
return name.toString() + ":" + url;
}
}
static enum FrameworkType {
PERSISTENCE,
GENERAL,
LOGGING,
UI,
XML,
UTILITY,
SCHEDULER,
CACHE,
RULES,
ECOMMERCE,
OTHER
}
static class Category {
String categoryName;
LicenseType licenseType;
FrameworkType frameworkType;
List<Dependency> dependencyList = new ArrayList<Dependency>();
Category[] usedByCategories;
public Category(String categoryName, LicenseType type, FrameworkType frameworkType) {
this.categoryName = categoryName;
this.licenseType = type;
this.frameworkType = frameworkType;
}
public Category(String categoryName, LicenseType type, FrameworkType frameworkType, Category... usedByCategories) {
this(categoryName, type, frameworkType);
this.usedByCategories = usedByCategories;
}
public String toString() {
return "Category Name : " + categoryName +
"\rLicense Type : " + licenseType.name +
"\rLicense URL : " + licenseType.url;
}
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_util_PomEvaluator.java
|
451 |
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
firedEvents.add(event);
}
});
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedSetTest.java
|
2,274 |
public class PropertyPlaceholder {
private final String placeholderPrefix;
private final String placeholderSuffix;
private final boolean ignoreUnresolvablePlaceholders;
/**
* Creates a new <code>PropertyPlaceholderHelper</code> that uses the supplied prefix and suffix. Unresolvable
* placeholders are ignored.
*
* @param placeholderPrefix the prefix that denotes the start of a placeholder.
* @param placeholderSuffix the suffix that denotes the end of a placeholder.
*/
public PropertyPlaceholder(String placeholderPrefix, String placeholderSuffix) {
this(placeholderPrefix, placeholderSuffix, true);
}
/**
* Creates a new <code>PropertyPlaceholderHelper</code> that uses the supplied prefix and suffix.
*
* @param placeholderPrefix the prefix that denotes the start of a placeholder.
* @param placeholderSuffix the suffix that denotes the end of a placeholder.
* @param ignoreUnresolvablePlaceholders indicates whether unresolvable placeholders should be ignored
* (<code>true</code>) or cause an exception (<code>false</code>).
*/
public PropertyPlaceholder(String placeholderPrefix, String placeholderSuffix,
boolean ignoreUnresolvablePlaceholders) {
Preconditions.checkNotNull(placeholderPrefix, "Argument 'placeholderPrefix' must not be null.");
Preconditions.checkNotNull(placeholderSuffix, "Argument 'placeholderSuffix' must not be null.");
this.placeholderPrefix = placeholderPrefix;
this.placeholderSuffix = placeholderSuffix;
this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
}
/**
* Replaces all placeholders of format <code>${name}</code> with the value returned from the supplied {@link
* PlaceholderResolver}.
*
* @param value the value containing the placeholders to be replaced.
* @param placeholderResolver the <code>PlaceholderResolver</code> to use for replacement.
* @return the supplied value with placeholders replaced inline.
*/
public String replacePlaceholders(String value, PlaceholderResolver placeholderResolver) {
Preconditions.checkNotNull(value, "Argument 'value' must not be null.");
return parseStringValue(value, placeholderResolver, new HashSet<String>());
}
protected String parseStringValue(String strVal, PlaceholderResolver placeholderResolver,
Set<String> visitedPlaceholders) {
StringBuilder buf = new StringBuilder(strVal);
int startIndex = strVal.indexOf(this.placeholderPrefix);
while (startIndex != -1) {
int endIndex = findPlaceholderEndIndex(buf, startIndex);
if (endIndex != -1) {
String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex);
if (!visitedPlaceholders.add(placeholder)) {
throw new IllegalArgumentException(
"Circular placeholder reference '" + placeholder + "' in property definitions");
}
// Recursive invocation, parsing placeholders contained in the placeholder key.
placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders);
// Now obtain the value for the fully resolved key...
int defaultValueIdx = placeholder.indexOf(':');
String defaultValue = null;
if (defaultValueIdx != -1) {
defaultValue = placeholder.substring(defaultValueIdx + 1);
placeholder = placeholder.substring(0, defaultValueIdx);
}
String propVal = placeholderResolver.resolvePlaceholder(placeholder);
if (propVal == null) {
propVal = defaultValue;
}
if (propVal == null && placeholderResolver.shouldIgnoreMissing(placeholder)) {
propVal = "";
}
if (propVal != null) {
// Recursive invocation, parsing placeholders contained in the
// previously resolved placeholder value.
propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
buf.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
startIndex = buf.indexOf(this.placeholderPrefix, startIndex + propVal.length());
} else if (this.ignoreUnresolvablePlaceholders) {
// Proceed with unprocessed value.
startIndex = buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
} else {
throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "'");
}
visitedPlaceholders.remove(placeholder);
} else {
startIndex = -1;
}
}
return buf.toString();
}
private int findPlaceholderEndIndex(CharSequence buf, int startIndex) {
int index = startIndex + this.placeholderPrefix.length();
int withinNestedPlaceholder = 0;
while (index < buf.length()) {
if (Strings.substringMatch(buf, index, this.placeholderSuffix)) {
if (withinNestedPlaceholder > 0) {
withinNestedPlaceholder--;
index = index + this.placeholderPrefix.length() - 1;
} else {
return index;
}
} else if (Strings.substringMatch(buf, index, this.placeholderPrefix)) {
withinNestedPlaceholder++;
index = index + this.placeholderPrefix.length();
} else {
index++;
}
}
return -1;
}
/**
* Strategy interface used to resolve replacement values for placeholders contained in Strings.
*
* @see PropertyPlaceholder
*/
public static interface PlaceholderResolver {
/**
* Resolves the supplied placeholder name into the replacement value.
*
* @param placeholderName the name of the placeholder to resolve.
* @return the replacement value or <code>null</code> if no replacement is to be made.
*/
String resolvePlaceholder(String placeholderName);
boolean shouldIgnoreMissing(String placeholderName);
}
}
| 1no label
|
src_main_java_org_elasticsearch_common_property_PropertyPlaceholder.java
|
460 |
public class OSBTreeRIDSetPersistencyTest {
private ODatabaseDocumentTx db;
@BeforeClass
public void setUp() throws Exception {
OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(Boolean.FALSE);
db = new ODatabaseDocumentTx("plocal:target/testdb/OSBTreeRIDSetPersistencyTest");
if (db.exists()) {
db.open("admin", "admin");
db.drop();
}
db.create();
ODatabaseRecordThreadLocal.INSTANCE.set(db);
}
@AfterClass
public void tearDown() throws Exception {
db.drop();
}
@Test
public void testSaveLoad() throws Exception {
Set<OIdentifiable> expected = new HashSet<OIdentifiable>(8);
expected.add(new ORecordId("#77:12"));
expected.add(new ORecordId("#77:13"));
expected.add(new ORecordId("#77:14"));
expected.add(new ORecordId("#77:15"));
expected.add(new ORecordId("#77:16"));
expected.add(new ORecordId("#77:17"));
expected.add(new ORecordId("#77:18"));
expected.add(new ORecordId("#77:19"));
expected.add(new ORecordId("#77:20"));
expected.add(new ORecordId("#77:21"));
expected.add(new ORecordId("#77:22"));
final ODocument doc = new ODocument();
final OSBTreeRIDSet ridSet = new OSBTreeRIDSet(doc);
ridSet.addAll(expected);
doc.field("ridset", ridSet);
doc.save();
final ORID id = doc.getIdentity();
db.close();
db.open("admin", "admin");
final OSBTreeRIDSet loaded = ((ODocument) db.load(id)).field("ridset");
Assert.assertEquals(loaded.size(), expected.size());
Assert.assertTrue(loaded.containsAll(expected));
}
}
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_ridset_sbtree_OSBTreeRIDSetPersistencyTest.java
|
553 |
abstract class ClientTxnProxy implements TransactionalObject {
final String objectName;
final TransactionContextProxy proxy;
ClientTxnProxy(String objectName, TransactionContextProxy proxy) {
this.objectName = objectName;
this.proxy = proxy;
}
final <T> T invoke(ClientRequest request) {
if (request instanceof BaseTransactionRequest) {
((BaseTransactionRequest) request).setTxnId(proxy.getTxnId());
((BaseTransactionRequest) request).setClientThreadId(Thread.currentThread().getId());
}
final ClientInvocationServiceImpl invocationService = (ClientInvocationServiceImpl)
proxy.getClient().getInvocationService();
final SerializationService ss = proxy.getClient().getSerializationService();
try {
final Future f = invocationService.send(request, proxy.getConnection());
return ss.toObject(f.get());
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
abstract void onDestroy();
public final void destroy() {
onDestroy();
ClientDestroyRequest request = new ClientDestroyRequest(objectName, getServiceName());
invoke(request);
}
public Object getId() {
return objectName;
}
public String getPartitionKey() {
return StringPartitioningStrategy.getPartitionKey(getName());
}
Data toData(Object obj) {
return proxy.getClient().getSerializationService().toData(obj);
}
Object toObject(Data data) {
return proxy.getClient().getSerializationService().toObject(data);
}
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_txn_proxy_ClientTxnProxy.java
|
202 |
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.METHOD})
public @interface Hydrated {
String factoryMethod();
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_cache_Hydrated.java
|
4,103 |
public class IncludeNestedDocsQuery extends Query {
private final Filter parentFilter;
private final Query parentQuery;
// If we are rewritten, this is the original childQuery we
// were passed; we use this for .equals() and
// .hashCode(). This makes rewritten query equal the
// original, so that user does not have to .rewrite() their
// query before searching:
private final Query origParentQuery;
public IncludeNestedDocsQuery(Query parentQuery, Filter parentFilter) {
this.origParentQuery = parentQuery;
this.parentQuery = parentQuery;
this.parentFilter = parentFilter;
}
// For rewritting
IncludeNestedDocsQuery(Query rewrite, Query originalQuery, IncludeNestedDocsQuery previousInstance) {
this.origParentQuery = originalQuery;
this.parentQuery = rewrite;
this.parentFilter = previousInstance.parentFilter;
setBoost(previousInstance.getBoost());
}
// For cloning
IncludeNestedDocsQuery(Query originalQuery, IncludeNestedDocsQuery previousInstance) {
this.origParentQuery = originalQuery;
this.parentQuery = originalQuery;
this.parentFilter = previousInstance.parentFilter;
}
@Override
public Weight createWeight(IndexSearcher searcher) throws IOException {
return new IncludeNestedDocsWeight(parentQuery, parentQuery.createWeight(searcher), parentFilter);
}
static class IncludeNestedDocsWeight extends Weight {
private final Query parentQuery;
private final Weight parentWeight;
private final Filter parentsFilter;
IncludeNestedDocsWeight(Query parentQuery, Weight parentWeight, Filter parentsFilter) {
this.parentQuery = parentQuery;
this.parentWeight = parentWeight;
this.parentsFilter = parentsFilter;
}
@Override
public Query getQuery() {
return parentQuery;
}
@Override
public void normalize(float norm, float topLevelBoost) {
parentWeight.normalize(norm, topLevelBoost);
}
@Override
public float getValueForNormalization() throws IOException {
return parentWeight.getValueForNormalization(); // this query is never boosted so just delegate...
}
@Override
public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException {
final Scorer parentScorer = parentWeight.scorer(context, true, false, acceptDocs);
// no matches
if (parentScorer == null) {
return null;
}
DocIdSet parents = parentsFilter.getDocIdSet(context, acceptDocs);
if (parents == null) {
// No matches
return null;
}
if (!(parents instanceof FixedBitSet)) {
throw new IllegalStateException("parentFilter must return FixedBitSet; got " + parents);
}
int firstParentDoc = parentScorer.nextDoc();
if (firstParentDoc == DocIdSetIterator.NO_MORE_DOCS) {
// No matches
return null;
}
return new IncludeNestedDocsScorer(this, parentScorer, (FixedBitSet) parents, firstParentDoc);
}
@Override
public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
return null; //Query is used internally and not by users, so explain can be empty
}
@Override
public boolean scoresDocsOutOfOrder() {
return false;
}
}
static class IncludeNestedDocsScorer extends Scorer {
final Scorer parentScorer;
final FixedBitSet parentBits;
int currentChildPointer = -1;
int currentParentPointer = -1;
int currentDoc = -1;
IncludeNestedDocsScorer(Weight weight, Scorer parentScorer, FixedBitSet parentBits, int currentParentPointer) {
super(weight);
this.parentScorer = parentScorer;
this.parentBits = parentBits;
this.currentParentPointer = currentParentPointer;
if (currentParentPointer == 0) {
currentChildPointer = 0;
} else {
this.currentChildPointer = parentBits.prevSetBit(currentParentPointer - 1);
if (currentChildPointer == -1) {
// no previous set parent, we delete from doc 0
currentChildPointer = 0;
} else {
currentChildPointer++; // we only care about children
}
}
currentDoc = currentChildPointer;
}
@Override
public Collection<ChildScorer> getChildren() {
return parentScorer.getChildren();
}
public int nextDoc() throws IOException {
if (currentParentPointer == NO_MORE_DOCS) {
return (currentDoc = NO_MORE_DOCS);
}
if (currentChildPointer == currentParentPointer) {
// we need to return the current parent as well, but prepare to return
// the next set of children
currentDoc = currentParentPointer;
currentParentPointer = parentScorer.nextDoc();
if (currentParentPointer != NO_MORE_DOCS) {
currentChildPointer = parentBits.prevSetBit(currentParentPointer - 1);
if (currentChildPointer == -1) {
// no previous set parent, just set the child to the current parent
currentChildPointer = currentParentPointer;
} else {
currentChildPointer++; // we only care about children
}
}
} else {
currentDoc = currentChildPointer++;
}
assert currentDoc != -1;
return currentDoc;
}
public int advance(int target) throws IOException {
if (target == NO_MORE_DOCS) {
return (currentDoc = NO_MORE_DOCS);
}
if (target == 0) {
return nextDoc();
}
if (target < currentParentPointer) {
currentDoc = currentParentPointer = parentScorer.advance(target);
if (currentParentPointer == NO_MORE_DOCS) {
return (currentDoc = NO_MORE_DOCS);
}
if (currentParentPointer == 0) {
currentChildPointer = 0;
} else {
currentChildPointer = parentBits.prevSetBit(currentParentPointer - 1);
if (currentChildPointer == -1) {
// no previous set parent, just set the child to 0 to delete all up to the parent
currentChildPointer = 0;
} else {
currentChildPointer++; // we only care about children
}
}
} else {
currentDoc = currentChildPointer++;
}
return currentDoc;
}
public float score() throws IOException {
return parentScorer.score();
}
public int freq() throws IOException {
return parentScorer.freq();
}
public int docID() {
return currentDoc;
}
@Override
public long cost() {
return parentScorer.cost();
}
}
@Override
public void extractTerms(Set<Term> terms) {
parentQuery.extractTerms(terms);
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
final Query parentRewrite = parentQuery.rewrite(reader);
if (parentRewrite != parentQuery) {
return new IncludeNestedDocsQuery(parentRewrite, parentQuery, this);
} else {
return this;
}
}
@Override
public String toString(String field) {
return "IncludeNestedDocsQuery (" + parentQuery.toString() + ")";
}
@Override
public boolean equals(Object _other) {
if (_other instanceof IncludeNestedDocsQuery) {
final IncludeNestedDocsQuery other = (IncludeNestedDocsQuery) _other;
return origParentQuery.equals(other.origParentQuery) && parentFilter.equals(other.parentFilter);
} else {
return false;
}
}
@Override
public int hashCode() {
final int prime = 31;
int hash = 1;
hash = prime * hash + origParentQuery.hashCode();
hash = prime * hash + parentFilter.hashCode();
return hash;
}
@Override
public Query clone() {
Query clonedQuery = origParentQuery.clone();
return new IncludeNestedDocsQuery(clonedQuery, this);
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_search_nested_IncludeNestedDocsQuery.java
|
11 |
public class StorageSetup {
//############ UTILITIES #############
public static final String getHomeDir(String subdir) {
String homedir = System.getProperty("titan.testdir");
if (null == homedir) {
homedir = "target" + File.separator + "db";
}
if (subdir!=null && !StringUtils.isEmpty(subdir)) homedir += File.separator + subdir;
File homefile = new File(homedir);
if (!homefile.exists()) homefile.mkdirs();
return homedir;
}
public static final String getHomeDir() {
return getHomeDir(null);
}
public static final File getHomeDirFile() {
return getHomeDirFile(null);
}
public static final File getHomeDirFile(String subdir) {
return new File(getHomeDir(subdir));
}
public static final void deleteHomeDir() {
deleteHomeDir(null);
}
public static final void deleteHomeDir(String subdir) {
File homeDirFile = getHomeDirFile(subdir);
// Make directory if it doesn't exist
if (!homeDirFile.exists())
homeDirFile.mkdirs();
boolean success = IOUtils.deleteFromDirectory(homeDirFile);
if (!success) throw new IllegalStateException("Could not remove " + homeDirFile);
}
public static TitanGraph getInMemoryGraph() {
return TitanFactory.open(buildConfiguration().set(STORAGE_BACKEND,"inmemory"));
}
public static WriteConfiguration addPermanentCache(ModifiableConfiguration conf) {
conf.set(DB_CACHE, true);
conf.set(DB_CACHE_TIME,0l);
return conf.getConfiguration();
}
public static ModifiableConfiguration getConfig(WriteConfiguration config) {
return new ModifiableConfiguration(ROOT_NS,config, BasicConfiguration.Restriction.NONE);
}
public static BasicConfiguration getConfig(ReadConfiguration config) {
return new BasicConfiguration(ROOT_NS,config, BasicConfiguration.Restriction.NONE);
}
}
| 0true
|
titan-test_src_main_java_com_thinkaurelius_titan_StorageSetup.java
|
1,968 |
public final class EvictionHelper {
private static final int ONE_HUNDRED_PERCENT = 100;
private static final int EVICTION_START_THRESHOLD_PERCENTAGE = 95;
private static final int ONE_KILOBYTE = 1024;
private EvictionHelper() {
}
public static boolean checkEvictable(MapContainer mapContainer) {
final MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig();
final MaxSizeConfig.MaxSizePolicy maxSizePolicy = maxSizeConfig.getMaxSizePolicy();
boolean result;
switch (maxSizePolicy) {
case PER_NODE:
result = isEvictablePerNode(mapContainer);
break;
case PER_PARTITION:
result = isEvictablePerPartition(mapContainer);
break;
case USED_HEAP_PERCENTAGE:
result = isEvictableHeapPercentage(mapContainer);
break;
case USED_HEAP_SIZE:
result = isEvictableHeapSize(mapContainer);
break;
default:
throw new IllegalArgumentException("Not an appropriate max size policy [" + maxSizePolicy + ']');
}
return result;
}
public static void removeEvictableRecords(final RecordStore recordStore, final MapConfig mapConfig,
final MapService mapService) {
final int partitionSize = recordStore.size();
if (partitionSize < 1) {
return;
}
final int evictableSize = getEvictableSize(partitionSize, mapConfig, mapService);
if (evictableSize < 1) {
return;
}
final MapConfig.EvictionPolicy evictionPolicy = mapConfig.getEvictionPolicy();
final Map<Data, Record> entries = recordStore.getReadonlyRecordMap();
final int size = entries.size();
// size have a tendency to change to here so check again.
if (entries.isEmpty()) {
return;
}
// criteria is a long value, like last access times or hits,
// used for calculating LFU or LRU.
final long[] criterias = new long[size];
int index = 0;
for (final Record record : entries.values()) {
criterias[index] = getEvictionCriteriaValue(record, evictionPolicy);
index++;
//in case size may change (increase or decrease) when iterating.
if (index == size) {
break;
}
}
if (criterias.length == 0) {
return;
}
// just in case there may be unassigned indexes in criterias array due to size variances
// assign them to Long.MAX_VALUE so when sorting asc they will locate
// in the upper array indexes and we wont care about them.
if (index < criterias.length) {
for (int i = index; i < criterias.length; i++) {
criterias[i] = Long.MAX_VALUE;
}
}
Arrays.sort(criterias);
// check in case record store size may be smaller than evictable size.
final int evictableBaseIndex = index == 0 ? index : Math.min(evictableSize, index - 1);
final long criteriaValue = criterias[evictableBaseIndex];
int evictedRecordCounter = 0;
for (final Map.Entry<Data, Record> entry : entries.entrySet()) {
final Record record = entry.getValue();
final long value = getEvictionCriteriaValue(record, evictionPolicy);
if (value <= criteriaValue) {
final Data tmpKey = record.getKey();
final Object tmpValue = record.getValue();
if (evictIfNotLocked(tmpKey, recordStore)) {
evictedRecordCounter++;
final String mapName = mapConfig.getName();
mapService.interceptAfterRemove(mapName, value);
if (mapService.isNearCacheAndInvalidationEnabled(mapName)) {
mapService.invalidateAllNearCaches(mapName, tmpKey);
}
fireEvent(tmpKey, tmpValue, mapName, mapService);
}
}
if (evictedRecordCounter >= evictableSize) {
break;
}
}
}
public static void fireEvent(Data key, Object value, String mapName, MapService mapService) {
final NodeEngine nodeEngine = mapService.getNodeEngine();
mapService.publishEvent(nodeEngine.getThisAddress(), mapName, EntryEventType.EVICTED,
key, mapService.toData(value), null);
}
public static boolean evictIfNotLocked(Data key, RecordStore recordStore) {
if (recordStore.isLocked(key)) {
return false;
}
recordStore.evict(key);
return true;
}
public static int getEvictableSize(int currentPartitionSize, MapConfig mapConfig, MapService mapService) {
int evictableSize;
final MaxSizeConfig.MaxSizePolicy maxSizePolicy = mapConfig.getMaxSizeConfig().getMaxSizePolicy();
final int evictionPercentage = mapConfig.getEvictionPercentage();
switch (maxSizePolicy) {
case PER_PARTITION:
int maxSize = mapConfig.getMaxSizeConfig().getSize();
int targetSizePerPartition = Double.valueOf(maxSize
* ((ONE_HUNDRED_PERCENT - evictionPercentage) / (1D * ONE_HUNDRED_PERCENT))).intValue();
int diffFromTargetSize = currentPartitionSize - targetSizePerPartition;
int prunedSize = currentPartitionSize * evictionPercentage / ONE_HUNDRED_PERCENT + 1;
evictableSize = Math.max(diffFromTargetSize, prunedSize);
break;
case PER_NODE:
maxSize = mapConfig.getMaxSizeConfig().getSize();
int memberCount = mapService.getNodeEngine().getClusterService().getMembers().size();
int maxPartitionSize = (maxSize
* memberCount / mapService.getNodeEngine().getPartitionService().getPartitionCount());
targetSizePerPartition = Double.valueOf(maxPartitionSize
* ((ONE_HUNDRED_PERCENT - evictionPercentage) / (1D * ONE_HUNDRED_PERCENT))).intValue();
diffFromTargetSize = currentPartitionSize - targetSizePerPartition;
prunedSize = currentPartitionSize * evictionPercentage / ONE_HUNDRED_PERCENT + 1;
evictableSize = Math.max(diffFromTargetSize, prunedSize);
break;
case USED_HEAP_PERCENTAGE:
case USED_HEAP_SIZE:
evictableSize = currentPartitionSize * evictionPercentage / ONE_HUNDRED_PERCENT;
break;
default:
throw new IllegalArgumentException("Max size policy is not defined [" + maxSizePolicy + "]");
}
return evictableSize;
}
private static long getEvictionCriteriaValue(Record record, MapConfig.EvictionPolicy evictionPolicy) {
long value;
switch (evictionPolicy) {
case LRU:
case LFU:
value = record.getEvictionCriteriaNumber();
break;
default:
throw new IllegalArgumentException("Not an appropriate eviction policy [" + evictionPolicy + ']');
}
return value;
}
private static boolean isEvictablePerNode(MapContainer mapContainer) {
int nodeTotalSize = 0;
final MapService mapService = mapContainer.getMapService();
final MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig();
final int maxSize = getApproximateMaxSize(maxSizeConfig.getSize());
final String mapName = mapContainer.getName();
final NodeEngine nodeEngine = mapService.getNodeEngine();
final InternalPartitionService partitionService = nodeEngine.getPartitionService();
final int partitionCount = partitionService.getPartitionCount();
for (int i = 0; i < partitionCount; i++) {
final Address owner = partitionService.getPartitionOwner(i);
if (nodeEngine.getThisAddress().equals(owner)) {
final PartitionContainer container = mapService.getPartitionContainer(i);
if (container == null) {
return false;
}
nodeTotalSize += getRecordStoreSize(mapName, container);
if (nodeTotalSize >= maxSize) {
return true;
}
}
}
return false;
}
private static int getRecordStoreSize(String mapName, PartitionContainer partitionContainer) {
final RecordStore existingRecordStore = partitionContainer.getExistingRecordStore(mapName);
if (existingRecordStore == null) {
return 0;
}
return existingRecordStore.size();
}
private static long getRecordStoreHeapCost(String mapName, PartitionContainer partitionContainer) {
final RecordStore existingRecordStore = partitionContainer.getExistingRecordStore(mapName);
if (existingRecordStore == null) {
return 0L;
}
return existingRecordStore.getHeapCost();
}
/**
* used when deciding evictable or not.
*/
private static int getApproximateMaxSize(int maxSizeFromConfig) {
// because not to exceed the max size much we start eviction early.
// so decrease the max size with ratio .95 below
return maxSizeFromConfig * EVICTION_START_THRESHOLD_PERCENTAGE / ONE_HUNDRED_PERCENT;
}
private static boolean isEvictablePerPartition(final MapContainer mapContainer) {
final MapService mapService = mapContainer.getMapService();
final MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig();
final int maxSize = getApproximateMaxSize(maxSizeConfig.getSize());
final String mapName = mapContainer.getName();
final NodeEngine nodeEngine = mapService.getNodeEngine();
final InternalPartitionService partitionService = nodeEngine.getPartitionService();
for (int i = 0; i < partitionService.getPartitionCount(); i++) {
final Address owner = partitionService.getPartitionOwner(i);
if (nodeEngine.getThisAddress().equals(owner)) {
final PartitionContainer container = mapService.getPartitionContainer(i);
if (container == null) {
return false;
}
final int size = getRecordStoreSize(mapName, container);
if (size >= maxSize) {
return true;
}
}
}
return false;
}
private static boolean isEvictableHeapSize(final MapContainer mapContainer) {
final long usedHeapSize = getUsedHeapSize(mapContainer);
if (usedHeapSize == -1L) {
return false;
}
final MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig();
final int maxSize = getApproximateMaxSize(maxSizeConfig.getSize());
return maxSize < (usedHeapSize / ONE_KILOBYTE / ONE_KILOBYTE);
}
private static boolean isEvictableHeapPercentage(final MapContainer mapContainer) {
final long usedHeapSize = getUsedHeapSize(mapContainer);
if (usedHeapSize == -1L) {
return false;
}
final MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig();
final int maxSize = getApproximateMaxSize(maxSizeConfig.getSize());
final long total = Runtime.getRuntime().totalMemory();
return maxSize < (1D * ONE_HUNDRED_PERCENT * usedHeapSize / total);
}
private static long getUsedHeapSize(final MapContainer mapContainer) {
long heapCost = 0L;
final MapService mapService = mapContainer.getMapService();
final String mapName = mapContainer.getName();
final NodeEngine nodeEngine = mapService.getNodeEngine();
final Address thisAddress = nodeEngine.getThisAddress();
for (int i = 0; i < nodeEngine.getPartitionService().getPartitionCount(); i++) {
if (nodeEngine.getPartitionService().getPartition(i).isOwnerOrBackup(thisAddress)) {
final PartitionContainer container = mapService.getPartitionContainer(i);
if (container == null) {
return -1L;
}
heapCost += getRecordStoreHeapCost(mapName, container);
}
}
heapCost += mapContainer.getNearCacheSizeEstimator().getSize();
return heapCost;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_map_eviction_EvictionHelper.java
|
1,453 |
return new MessageListener<Object>() {
public void onMessage(final Message<Object> message) {
final Timestamp ts = (Timestamp) message.getMessageObject();
final Object key = ts.getKey();
for (;;) {
final Value value = cache.get(key);
final Long current = value != null ? (Long) value.getValue() : null;
if (current != null) {
if (ts.getTimestamp() > current) {
if (cache.replace(key, value, new Value(value.getVersion(),
ts.getTimestamp(), Clock.currentTimeMillis()))) {
return;
}
} else {
return;
}
} else {
if (cache.putIfAbsent(key, new Value(null, ts.getTimestamp(),
Clock.currentTimeMillis())) == null) {
return;
}
}
}
}
};
| 1no label
|
hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_local_TimestampsRegionCache.java
|
539 |
public class DeleteMappingClusterStateUpdateRequest extends IndicesClusterStateUpdateRequest<DeleteMappingClusterStateUpdateRequest> {
private String[] types;
DeleteMappingClusterStateUpdateRequest() {
}
/**
* Returns the type to be removed
*/
public String[] types() {
return types;
}
/**
* Sets the type to be removed
*/
public DeleteMappingClusterStateUpdateRequest types(String[] types) {
this.types = types;
return this;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_mapping_delete_DeleteMappingClusterStateUpdateRequest.java
|
1,605 |
public class ResultHookClosure extends Closure {
private final String resultPrompt;
private final IO io;
private static final int LINES = 15;
public ResultHookClosure(final Object owner, final IO io, final String resultPrompt) {
super(owner);
this.io = io;
this.resultPrompt = resultPrompt;
}
public Object call(final Object[] args) {
final Object result = args[0];
final Iterator itty;
if (result instanceof HadoopPipeline) {
try {
final HadoopPipeline pipeline = (HadoopPipeline) result;
pipeline.submit();
final FileSystem hdfs = FileSystem.get(pipeline.getGraph().getConf());
final Path output = HDFSTools.getOutputsFinalJob(hdfs, pipeline.getGraph().getJobDir().toString());
itty = new TextFileLineIterator(hdfs, hdfs.globStatus(new Path(output.toString() + "/" + Tokens.SIDEEFFECT + "*")), LINES);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
} else {
itty = new ToStringPipe();
((Pipe) itty).setStarts(new SingleIterator<Object>(result));
}
int counter = 0;
while (itty.hasNext()) {
counter++;
this.io.out.println(this.resultPrompt + itty.next());
}
if (counter == LINES)
this.io.out.println(this.resultPrompt + "...");
return null;
}
}
| 1no label
|
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_tinkerpop_gremlin_ResultHookClosure.java
|
790 |
new ConstructorFunction<String, LongWrapper>() {
public LongWrapper createNew(String key) {
return new LongWrapper();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_AtomicLongService.java
|
500 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_SITE")
@Cache(usage= CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blCMSElements")
@AdminPresentationClass(friendlyName = "baseSite")
@SQLDelete(sql="UPDATE BLC_SITE SET ARCHIVED = 'Y' WHERE SITE_ID = ?")
public class SiteImpl implements Site, Status {
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(SiteImpl.class);
@Id
@GeneratedValue(generator = "SiteId")
@GenericGenerator(
name="SiteId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="SiteImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.common.site.domain.SiteImpl")
}
)
@Column(name = "SITE_ID")
protected Long id;
@Column (name = "NAME")
@AdminPresentation(friendlyName = "SiteImpl_Site_Name", order=1, gridOrder = 1, group = "SiteImpl_Site", prominent = true, requiredOverride = RequiredOverride.REQUIRED)
protected String name;
@Column (name = "SITE_IDENTIFIER_TYPE")
@AdminPresentation(friendlyName = "SiteImpl_Site_Identifier_Type", order=2, gridOrder = 2, group = "SiteImpl_Site", prominent = true, broadleafEnumeration = "org.broadleafcommerce.common.site.service.type.SiteResolutionType", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, requiredOverride = RequiredOverride.REQUIRED)
protected String siteIdentifierType;
@Column (name = "SITE_IDENTIFIER_VALUE")
@AdminPresentation(friendlyName = "SiteImpl_Site_Identifier_Value", order=3, gridOrder = 3, group = "SiteImpl_Site", prominent = true, requiredOverride = RequiredOverride.REQUIRED)
@Index(name = "BLC_SITE_ID_VAL_INDEX", columnNames = { "SITE_IDENTIFIER_VALUE" })
protected String siteIdentifierValue;
@ManyToOne(targetEntity = SandBoxImpl.class)
@JoinColumn(name = "PRODUCTION_SANDBOX_ID")
@AdminPresentation(friendlyName = "SiteImpl_Production_SandBox", visibility = VisibilityEnum.HIDDEN_ALL)
protected SandBox productionSandbox;
@ManyToMany(targetEntity = CatalogImpl.class, cascade = {CascadeType.PERSIST, CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH})
@JoinTable(name = "BLC_SITE_CATALOG", joinColumns = @JoinColumn(name = "SITE_ID"), inverseJoinColumns = @JoinColumn(name = "CATALOG_ID"))
@BatchSize(size = 50)
@AdminPresentationCollection(addType = AddMethodType.LOOKUP, friendlyName = "siteCatalogTitle", manyToField = "sites")
protected List<Catalog> catalogs = new ArrayList<Catalog>();
@Column(name = "DEACTIVATED")
@AdminPresentation(friendlyName = "SiteImpl_Deactivated", order=4, gridOrder = 4, group = "SiteImpl_Site")
protected Boolean deactivated = false;
@Embedded
protected ArchiveStatus archiveStatus = new ArchiveStatus();
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getSiteIdentifierType() {
return siteIdentifierType;
}
@Override
public void setSiteIdentifierType(String siteIdentifierType) {
this.siteIdentifierType = siteIdentifierType;
}
@Override
public String getSiteIdentifierValue() {
return siteIdentifierValue;
}
@Override
public void setSiteIdentifierValue(String siteIdentifierValue) {
this.siteIdentifierValue = siteIdentifierValue;
}
@Override
public SandBox getProductionSandbox() {
return productionSandbox;
}
@Override
public void setProductionSandbox(SandBox productionSandbox) {
this.productionSandbox = productionSandbox;
}
@Override
public SiteResolutionType getSiteResolutionType() {
return SiteResolutionType.getInstance(siteIdentifierType);
}
@Override
public void setSiteResolutionType(SiteResolutionType siteResolutionType) {
this.siteIdentifierType = siteResolutionType.getType();
}
@Override
public List<Catalog> getCatalogs() {
return catalogs;
}
@Override
public void setCatalogs(List<Catalog> catalogs) {
this.catalogs = catalogs;
}
@Override
public Character getArchived() {
if (archiveStatus == null) {
archiveStatus = new ArchiveStatus();
}
return archiveStatus.getArchived();
}
@Override
public void setArchived(Character archived) {
if (archiveStatus == null) {
archiveStatus = new ArchiveStatus();
}
archiveStatus.setArchived(archived);
}
@Override
public boolean isActive() {
if (LOG.isDebugEnabled()) {
if (isDeactivated()) {
LOG.debug("site, " + id + ", inactive due to deactivated property");
}
if ('Y'==getArchived()) {
LOG.debug("site, " + id + ", inactive due to archived status");
}
}
return !isDeactivated() && 'Y'!=getArchived();
}
@Override
public boolean isDeactivated() {
if (deactivated == null) {
return false;
} else {
return deactivated;
}
}
@Override
public void setDeactivated(boolean deactivated) {
this.deactivated = deactivated;
}
public void checkCloneable(Site site) throws CloneNotSupportedException, SecurityException, NoSuchMethodException {
Method cloneMethod = site.getClass().getMethod("clone", new Class[]{});
if (cloneMethod.getDeclaringClass().getName().startsWith("org.broadleafcommerce") && !site.getClass().getName().startsWith("org.broadleafcommerce")) {
//subclass is not implementing the clone method
throw new CloneNotSupportedException("Custom extensions and implementations should implement clone.");
}
}
@Override
public Site clone() {
Site clone;
try {
clone = (Site) Class.forName(this.getClass().getName()).newInstance();
try {
checkCloneable(clone);
} catch (CloneNotSupportedException e) {
LOG.warn("Clone implementation missing in inheritance hierarchy outside of Broadleaf: " + clone.getClass().getName(), e);
}
clone.setId(id);
clone.setName(name);
clone.setDeactivated(isDeactivated());
((Status) clone).setArchived(getArchived());
for (Catalog catalog : getCatalogs()) {
Catalog cloneCatalog = new CatalogImpl();
cloneCatalog.setId(catalog.getId());
cloneCatalog.setName(catalog.getName());
clone.getCatalogs().add(cloneCatalog);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return clone;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_site_domain_SiteImpl.java
|
1,187 |
public class OQueryOperatorMajorEquals extends OQueryOperatorEqualityNotNulls {
public OQueryOperatorMajorEquals() {
super(">=", 5, false);
}
@Override
@SuppressWarnings("unchecked")
protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft,
final Object iRight, OCommandContext iContext) {
final Object right = OType.convert(iRight, iLeft.getClass());
if (right == null)
return false;
return ((Comparable<Object>) iLeft).compareTo(right) >= 0;
}
@Override
public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) {
if (iRight == null || iLeft == null)
return OIndexReuseType.NO_INDEX;
return OIndexReuseType.INDEX_METHOD;
}
@Override
public Object executeIndexQuery(OCommandContext iContext, OIndex<?> index, INDEX_OPERATION_TYPE iOperationType,
List<Object> keyParams, IndexResultListener resultListener, int fetchLimit) {
final OIndexDefinition indexDefinition = index.getDefinition();
final OIndexInternal<?> internalIndex = index.getInternal();
if (!internalIndex.canBeUsedInEqualityOperators() || !internalIndex.hasRangeQuerySupport())
return null;
final Object result;
if (indexDefinition.getParamCount() == 1) {
final Object key;
if (indexDefinition instanceof OIndexDefinitionMultiValue)
key = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(keyParams.get(0));
else
key = indexDefinition.createValue(keyParams);
if (key == null)
return null;
if (INDEX_OPERATION_TYPE.COUNT.equals(iOperationType))
result = index.count(key, true, null, false, fetchLimit);
else if (resultListener != null) {
index.getValuesMajor(key, true, resultListener);
result = resultListener.getResult();
} else
result = index.getValuesMajor(key, true);
} else {
// if we have situation like "field1 = 1 AND field2 >= 2"
// then we fetch collection which left included boundary is the smallest composite key in the
// index that contains keys with values field1=1 and field2=2 and which right included boundary
// is the biggest composite key in the index that contains key with value field1=1.
final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams);
if (keyOne == null)
return null;
final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams.subList(0, keyParams.size() - 1));
if (keyTwo == null)
return null;
if (INDEX_OPERATION_TYPE.COUNT.equals(iOperationType))
result = index.count(keyOne, true, keyTwo, true, fetchLimit);
else if (resultListener != null) {
index.getValuesBetween(keyOne, true, keyTwo, true, resultListener);
result = resultListener.getResult();
} else
result = index.getValuesBetween(keyOne, true, keyTwo, true);
}
updateProfiler(iContext, index, keyParams, indexDefinition);
return result;
}
@Override
public ORID getBeginRidRange(final Object iLeft, final Object iRight) {
if (iLeft instanceof OSQLFilterItemField && ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iLeft).getRoot()))
if (iRight instanceof ORID)
return (ORID) iRight;
else {
if (iRight instanceof OSQLFilterItemParameter && ((OSQLFilterItemParameter) iRight).getValue(null, null) instanceof ORID)
return (ORID) ((OSQLFilterItemParameter) iRight).getValue(null, null);
}
return null;
}
@Override
public ORID getEndRidRange(Object iLeft, Object iRight) {
return null;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorMajorEquals.java
|
129 |
public interface RelationTypeMaker {
/**
* Returns the name of this configured relation type.
*
* @return
*/
public String getName();
/**
* Configures the signature of this relation type.
* <p/>
* Specifying the signature of a type tells the graph database to <i>expect</i> that relations of this type
* always have or are likely to have an incident property or unidirected edge of the type included in the
* signature. This allows the graph database to store such relations more compactly and retrieve them more quickly.
* <br />
* For instance, if all edges with label <i>friend</i> have a property with key <i>createdOn</i>, then specifying
* (<i>createdOn</i>) as the signature for label <i>friend</i> allows friend edges to be stored more efficiently.
* <br />
* {@link RelationType}s used in the signature must be either property out-unique keys or out-unique unidirected edge labels.
* <br />
* The signature is empty by default.
*
* @param types RelationTypes composing the signature for the configured relation type. The order is irrelevant.
* @return this RelationTypeMaker
*/
public RelationTypeMaker signature(RelationType... types);
/**
* Builds the configured relation type
*
* @return the configured {@link RelationType}
*/
public RelationType make();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_schema_RelationTypeMaker.java
|
597 |
public class ServiceStatusType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, ServiceStatusType> TYPES = new LinkedHashMap<String, ServiceStatusType>();
public static final ServiceStatusType UP = new ServiceStatusType("UP", "Up");
public static final ServiceStatusType DOWN = new ServiceStatusType("DOWN", "Down");
public static final ServiceStatusType PAUSED = new ServiceStatusType("PAUSED", "Paused");
public static ServiceStatusType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public ServiceStatusType() {
//do nothing
}
public ServiceStatusType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)){
TYPES.put(type, this);
} else {
throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ServiceStatusType other = (ServiceStatusType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_vendor_service_type_ServiceStatusType.java
|
730 |
public class TransportShardDeleteAction extends TransportShardReplicationOperationAction<ShardDeleteRequest, ShardDeleteRequest, ShardDeleteResponse> {
@Inject
public TransportShardDeleteAction(Settings settings, TransportService transportService,
ClusterService clusterService, IndicesService indicesService, ThreadPool threadPool,
ShardStateAction shardStateAction) {
super(settings, transportService, clusterService, indicesService, threadPool, shardStateAction);
}
@Override
protected boolean checkWriteConsistency() {
return true;
}
@Override
protected ShardDeleteRequest newRequestInstance() {
return new ShardDeleteRequest();
}
@Override
protected ShardDeleteRequest newReplicaRequestInstance() {
return new ShardDeleteRequest();
}
@Override
protected ShardDeleteResponse newResponseInstance() {
return new ShardDeleteResponse();
}
@Override
protected String transportAction() {
return "indices/index/b_shard/delete";
}
@Override
protected String executor() {
return ThreadPool.Names.INDEX;
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, ShardDeleteRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.WRITE);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, ShardDeleteRequest request) {
return state.blocks().indexBlockedException(ClusterBlockLevel.WRITE, request.index());
}
@Override
protected PrimaryResponse<ShardDeleteResponse, ShardDeleteRequest> shardOperationOnPrimary(ClusterState clusterState, PrimaryOperationRequest shardRequest) {
ShardDeleteRequest request = shardRequest.request;
IndexShard indexShard = indicesService.indexServiceSafe(shardRequest.request.index()).shardSafe(shardRequest.shardId);
Engine.Delete delete = indexShard.prepareDelete(request.type(), request.id(), request.version())
.origin(Engine.Operation.Origin.PRIMARY);
indexShard.delete(delete);
// update the version to happen on the replicas
request.version(delete.version());
if (request.refresh()) {
try {
indexShard.refresh(new Engine.Refresh("refresh_flag_delete").force(false));
} catch (Exception e) {
// ignore
}
}
ShardDeleteResponse response = new ShardDeleteResponse(delete.version(), delete.found());
return new PrimaryResponse<ShardDeleteResponse, ShardDeleteRequest>(shardRequest.request, response, null);
}
@Override
protected void shardOperationOnReplica(ReplicaOperationRequest shardRequest) {
ShardDeleteRequest request = shardRequest.request;
IndexShard indexShard = indicesService.indexServiceSafe(shardRequest.request.index()).shardSafe(shardRequest.shardId);
Engine.Delete delete = indexShard.prepareDelete(request.type(), request.id(), request.version())
.origin(Engine.Operation.Origin.REPLICA);
indexShard.delete(delete);
if (request.refresh()) {
try {
indexShard.refresh(new Engine.Refresh("refresh_flag_delete").force(false));
} catch (Exception e) {
// ignore
}
}
}
@Override
protected ShardIterator shards(ClusterState clusterState, ShardDeleteRequest request) {
GroupShardsIterator group = clusterService.operationRouting().broadcastDeleteShards(clusterService.state(), request.index());
for (ShardIterator shardIt : group) {
if (shardIt.shardId().id() == request.shardId()) {
return shardIt;
}
}
throw new ElasticsearchIllegalStateException("No shards iterator found for shard [" + request.shardId() + "]");
}
}
| 0true
|
src_main_java_org_elasticsearch_action_delete_index_TransportShardDeleteAction.java
|
4,680 |
final static class MatchAndSort extends QueryCollector {
private final TopScoreDocCollector topDocsCollector;
MatchAndSort(ESLogger logger, PercolateContext context) {
super(logger, context);
// TODO: Use TopFieldCollector.create(...) for ascending and decending scoring?
topDocsCollector = TopScoreDocCollector.create(context.size, false);
}
@Override
public void collect(int doc) throws IOException {
final Query query = getQuery(doc);
if (query == null) {
// log???
return;
}
// run the query
try {
collector.reset();
searcher.search(query, collector);
if (collector.exists()) {
topDocsCollector.collect(doc);
if (facetAndAggregatorCollector != null) {
facetAndAggregatorCollector.collect(doc);
}
}
} catch (IOException e) {
logger.warn("[" + spare.bytes.utf8ToString() + "] failed to execute query", e);
}
}
@Override
public void setNextReader(AtomicReaderContext context) throws IOException {
super.setNextReader(context);
topDocsCollector.setNextReader(context);
}
@Override
public void setScorer(Scorer scorer) throws IOException {
topDocsCollector.setScorer(scorer);
}
TopDocs topDocs() {
return topDocsCollector.topDocs();
}
}
| 1no label
|
src_main_java_org_elasticsearch_percolator_QueryCollector.java
|
304 |
public class MergeEhCacheManagerFactoryBean extends EhCacheManagerFactoryBean implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@javax.annotation.Resource(name="blMergedCacheConfigLocations")
protected Set<String> mergedCacheConfigLocations;
protected List<Resource> configLocations;
@Override
public void destroy() {
super.destroy();
try {
CacheManager cacheManager = getObject();
Field cacheManagerTimer = CacheManager.class.getDeclaredField("cacheManagerTimer");
cacheManagerTimer.setAccessible(true);
Object failSafeTimer = cacheManagerTimer.get(cacheManager);
Field timer = failSafeTimer.getClass().getDeclaredField("timer");
timer.setAccessible(true);
Object time = timer.get(failSafeTimer);
Field thread = time.getClass().getDeclaredField("thread");
thread.setAccessible(true);
Thread item = (Thread) thread.get(time);
item.setContextClassLoader(Thread.currentThread().getContextClassLoader().getParent());
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@PostConstruct
public void configureMergedItems() {
List<Resource> temp = new ArrayList<Resource>();
if (mergedCacheConfigLocations != null && !mergedCacheConfigLocations.isEmpty()) {
for (String location : mergedCacheConfigLocations) {
temp.add(applicationContext.getResource(location));
}
}
if (configLocations != null && !configLocations.isEmpty()) {
for (Resource resource : configLocations) {
temp.add(resource);
}
}
try {
MergeXmlConfigResource merge = new MergeXmlConfigResource();
ResourceInputStream[] sources = new ResourceInputStream[temp.size()];
int j=0;
for (Resource resource : temp) {
sources[j] = new ResourceInputStream(resource.getInputStream(), resource.getURL().toString());
j++;
}
setConfigLocation(merge.getMergedConfigResource(sources));
} catch (Exception e) {
throw new FatalBeanException("Unable to merge cache locations", e);
}
}
public void setConfigLocations(List<Resource> configLocations) throws BeansException {
this.configLocations = configLocations;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_cache_ehcache_MergeEhCacheManagerFactoryBean.java
|
266 |
@Service("blEmailTrackingManager")
public class EmailTrackingManagerImpl implements EmailTrackingManager {
private static final Log LOG = LogFactory.getLog(EmailTrackingManagerImpl.class);
@Resource(name = "blEmailReportingDao")
protected EmailReportingDao emailReportingDao;
public Long createTrackedEmail(String emailAddress, String type, String extraValue) {
return emailReportingDao.createTracking(emailAddress, type, extraValue);
}
public void recordClick(Long emailId, Map<String, String> parameterMap, String customerId, Map<String, String> extraValues) {
if (LOG.isDebugEnabled()) {
LOG.debug("recordClick() => Click detected for Email[" + emailId + "]");
}
Iterator<String> keys = parameterMap.keySet().iterator();
// clean up and normalize the query string
ArrayList<String> queryParms = new ArrayList<String>();
while (keys.hasNext()) {
String p = keys.next();
// exclude email_id from the parms list
if (!p.equals("email_id")) {
queryParms.add(p);
}
}
String newQuery = null;
if (!queryParms.isEmpty()) {
String[] p = queryParms.toArray(new String[queryParms.size()]);
Arrays.sort(p);
StringBuffer newQueryParms = new StringBuffer();
for (int cnt = 0; cnt < p.length; cnt++) {
newQueryParms.append(p[cnt]);
newQueryParms.append("=");
newQueryParms.append(parameterMap.get(p[cnt]));
if (cnt != p.length - 1) {
newQueryParms.append("&");
}
}
newQuery = newQueryParms.toString();
}
emailReportingDao.recordClick(emailId, customerId, extraValues.get("requestUri"), newQuery);
}
/*
* (non-Javadoc)
* @see
* com.containerstore.web.task.service.EmailTrackingManager#recordOpen(java
* .lang.String, javax.servlet.http.HttpServletRequest)
*/
public void recordOpen(Long emailId, Map<String, String> extraValues) {
if (LOG.isDebugEnabled()) {
LOG.debug("Recording open for email id: " + emailId);
}
// extract necessary information from the request and record the open
emailReportingDao.recordOpen(emailId, extraValues.get("userAgent"));
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_email_service_EmailTrackingManagerImpl.java
|
1,363 |
@ClusterScope(scope = Scope.TEST, numNodes = 0)
public class ClusterRerouteTests extends ElasticsearchIntegrationTest {
private final ESLogger logger = Loggers.getLogger(ClusterRerouteTests.class);
@Test
public void rerouteWithCommands_disableAllocationSettings() throws Exception {
Settings commonSettings = settingsBuilder()
.put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_NEW_ALLOCATION, true)
.put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_ALLOCATION, true)
.build();
rerouteWithCommands(commonSettings);
}
@Test
public void rerouteWithCommands_enableAllocationSettings() throws Exception {
Settings commonSettings = settingsBuilder()
.put(EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE, EnableAllocationDecider.Allocation.NONE.name())
.put("gateway.type", "local")
.build();
rerouteWithCommands(commonSettings);
}
private void rerouteWithCommands(Settings commonSettings) throws Exception {
String node_1 = cluster().startNode(commonSettings);
String node_2 = cluster().startNode(commonSettings);
logger.info("--> create an index with 1 shard, 1 replica, nothing should allocate");
client().admin().indices().prepareCreate("test")
.setSettings(settingsBuilder().put("index.number_of_shards", 1))
.execute().actionGet();
ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState();
assertThat(state.routingNodes().unassigned().size(), equalTo(2));
logger.info("--> explicitly allocate shard 1, *under dry_run*");
state = client().admin().cluster().prepareReroute()
.add(new AllocateAllocationCommand(new ShardId("test", 0), node_1, true))
.setDryRun(true)
.execute().actionGet().getState();
assertThat(state.routingNodes().unassigned().size(), equalTo(1));
assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.INITIALIZING));
logger.info("--> get the state, verify nothing changed because of the dry run");
state = client().admin().cluster().prepareState().execute().actionGet().getState();
assertThat(state.routingNodes().unassigned().size(), equalTo(2));
logger.info("--> explicitly allocate shard 1, actually allocating, no dry run");
state = client().admin().cluster().prepareReroute()
.add(new AllocateAllocationCommand(new ShardId("test", 0), node_1, true))
.execute().actionGet().getState();
assertThat(state.routingNodes().unassigned().size(), equalTo(1));
assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.INITIALIZING));
ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
logger.info("--> get the state, verify shard 1 primary allocated");
state = client().admin().cluster().prepareState().execute().actionGet().getState();
assertThat(state.routingNodes().unassigned().size(), equalTo(1));
assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.STARTED));
logger.info("--> move shard 1 primary from node1 to node2");
state = client().admin().cluster().prepareReroute()
.add(new MoveAllocationCommand(new ShardId("test", 0), node_1, node_2))
.execute().actionGet().getState();
assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.RELOCATING));
assertThat(state.routingNodes().node(state.nodes().resolveNode(node_2).id()).get(0).state(), equalTo(ShardRoutingState.INITIALIZING));
healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().setWaitForRelocatingShards(0).execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
logger.info("--> get the state, verify shard 1 primary moved from node1 to node2");
state = client().admin().cluster().prepareState().execute().actionGet().getState();
assertThat(state.routingNodes().unassigned().size(), equalTo(1));
assertThat(state.routingNodes().node(state.nodes().resolveNode(node_2).id()).get(0).state(), equalTo(ShardRoutingState.STARTED));
}
@Test
public void rerouteWithAllocateLocalGateway_disableAllocationSettings() throws Exception {
Settings commonSettings = settingsBuilder()
.put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_NEW_ALLOCATION, true)
.put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_ALLOCATION, true)
.put("gateway.type", "local")
.build();
rerouteWithAllocateLocalGateway(commonSettings);
}
@Test
public void rerouteWithAllocateLocalGateway_enableAllocationSettings() throws Exception {
Settings commonSettings = settingsBuilder()
.put(EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE, EnableAllocationDecider.Allocation.NONE.name())
.put("gateway.type", "local")
.build();
rerouteWithAllocateLocalGateway(commonSettings);
}
private void rerouteWithAllocateLocalGateway(Settings commonSettings) throws Exception {
logger.info("--> starting 2 nodes");
String node_1 = cluster().startNode(commonSettings);
cluster().startNode(commonSettings);
assertThat(cluster().size(), equalTo(2));
ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth().setWaitForNodes("2").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
logger.info("--> create an index with 1 shard, 1 replica, nothing should allocate");
client().admin().indices().prepareCreate("test")
.setSettings(settingsBuilder().put("index.number_of_shards", 1))
.execute().actionGet();
ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState();
assertThat(state.routingNodes().unassigned().size(), equalTo(2));
logger.info("--> explicitly allocate shard 1, actually allocating, no dry run");
state = client().admin().cluster().prepareReroute()
.add(new AllocateAllocationCommand(new ShardId("test", 0), node_1, true))
.execute().actionGet().getState();
assertThat(state.routingNodes().unassigned().size(), equalTo(1));
assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.INITIALIZING));
healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
logger.info("--> get the state, verify shard 1 primary allocated");
state = client().admin().cluster().prepareState().execute().actionGet().getState();
assertThat(state.routingNodes().unassigned().size(), equalTo(1));
assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.STARTED));
client().prepareIndex("test", "type", "1").setSource("field", "value").setRefresh(true).execute().actionGet();
logger.info("--> closing all nodes");
File[] shardLocation = cluster().getInstance(NodeEnvironment.class, node_1).shardLocations(new ShardId("test", 0));
assertThat(FileSystemUtils.exists(shardLocation), equalTo(true)); // make sure the data is there!
cluster().closeNonSharedNodes(false); // don't wipe data directories the index needs to be there!
logger.info("--> deleting the shard data [{}] ", Arrays.toString(shardLocation));
assertThat(FileSystemUtils.exists(shardLocation), equalTo(true)); // verify again after cluster was shut down
assertThat(FileSystemUtils.deleteRecursively(shardLocation), equalTo(true));
logger.info("--> starting nodes back, will not allocate the shard since it has no data, but the index will be there");
node_1 = cluster().startNode(commonSettings);
cluster().startNode(commonSettings);
// wait a bit for the cluster to realize that the shard is not there...
// TODO can we get around this? the cluster is RED, so what do we wait for?
client().admin().cluster().prepareReroute().get();
assertThat(client().admin().cluster().prepareHealth().setWaitForNodes("2").execute().actionGet().getStatus(), equalTo(ClusterHealthStatus.RED));
logger.info("--> explicitly allocate primary");
state = client().admin().cluster().prepareReroute()
.add(new AllocateAllocationCommand(new ShardId("test", 0), node_1, true))
.execute().actionGet().getState();
assertThat(state.routingNodes().unassigned().size(), equalTo(1));
assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.INITIALIZING));
healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
logger.info("--> get the state, verify shard 1 primary allocated");
state = client().admin().cluster().prepareState().execute().actionGet().getState();
assertThat(state.routingNodes().unassigned().size(), equalTo(1));
assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.STARTED));
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_allocation_ClusterRerouteTests.java
|
197 |
public static class Order {
public static final int Audit = 1000;
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_audit_Auditable.java
|
216 |
public class Snippet {
private final String text;
private final float score;
private final boolean isHighlighted;
public Snippet(String text, float score, boolean isHighlighted) {
this.text = text;
this.score = score;
this.isHighlighted = isHighlighted;
}
public String getText() {
return text;
}
public float getScore() {
return score;
}
public boolean isHighlighted() {
return isHighlighted;
}
}
| 0true
|
src_main_java_org_apache_lucene_search_postingshighlight_Snippet.java
|
1,321 |
new SingleSourceUnitPackage(pkg, sourceUnitFullPath), moduleManager, CeylonBuilder.getProjectTypeChecker(project), tokens) {
@Override
protected boolean reuseExistingDescriptorModels() {
return true;
}
};
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_JDTModule.java
|
585 |
public class RefreshRequestBuilder extends BroadcastOperationRequestBuilder<RefreshRequest, RefreshResponse, RefreshRequestBuilder> {
public RefreshRequestBuilder(IndicesAdminClient indicesClient) {
super((InternalIndicesAdminClient) indicesClient, new RefreshRequest());
}
/**
* Forces calling refresh, overriding the check that dirty operations even happened. Defaults
* to true (note, still lightweight if no refresh is needed).
*/
public RefreshRequestBuilder setForce(boolean force) {
request.force(force);
return this;
}
@Override
protected void doExecute(ActionListener<RefreshResponse> listener) {
((IndicesAdminClient) client).refresh(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_refresh_RefreshRequestBuilder.java
|
732 |
public class DeleteByQueryRequest extends IndicesReplicationOperationRequest<DeleteByQueryRequest> {
private static final XContentType contentType = Requests.CONTENT_TYPE;
private BytesReference source;
private boolean sourceUnsafe;
private String[] types = Strings.EMPTY_ARRAY;
@Nullable
private String routing;
/**
* Constructs a new delete by query request to run against the provided indices. No indices means
* it will run against all indices.
*/
public DeleteByQueryRequest(String... indices) {
this.indices = indices;
}
public DeleteByQueryRequest() {
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = super.validate();
if (source == null) {
validationException = addValidationError("source is missing", validationException);
}
return validationException;
}
/**
* The source to execute.
*/
BytesReference source() {
if (sourceUnsafe) {
source = source.copyBytesArray();
}
return source;
}
/**
* The source to execute.
*/
public DeleteByQueryRequest source(QuerySourceBuilder sourceBuilder) {
this.source = sourceBuilder.buildAsBytes(contentType);
this.sourceUnsafe = false;
return this;
}
/**
* The source to execute. It is preferable to use either {@link #source(byte[])}
* or {@link #source(QuerySourceBuilder)}.
*/
public DeleteByQueryRequest source(String query) {
this.source = new BytesArray(query.getBytes(Charsets.UTF_8));
this.sourceUnsafe = false;
return this;
}
/**
* The source to execute in the form of a map.
*/
public DeleteByQueryRequest source(Map source) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(contentType);
builder.map(source);
return source(builder);
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
}
}
public DeleteByQueryRequest source(XContentBuilder builder) {
this.source = builder.bytes();
this.sourceUnsafe = false;
return this;
}
/**
* The source to execute.
*/
public DeleteByQueryRequest source(byte[] source) {
return source(source, 0, source.length, false);
}
/**
* The source to execute.
*/
public DeleteByQueryRequest source(byte[] source, int offset, int length, boolean unsafe) {
this.source = new BytesArray(source, offset, length);
this.sourceUnsafe = unsafe;
return this;
}
public DeleteByQueryRequest source(BytesReference source, boolean unsafe) {
this.source = source;
this.sourceUnsafe = unsafe;
return this;
}
/**
* The types of documents the query will run against. Defaults to all types.
*/
String[] types() {
return this.types;
}
/**
* 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 DeleteByQueryRequest routing(String routing) {
this.routing = routing;
return this;
}
/**
* The routing values to control the shards that the search will be executed on.
*/
public DeleteByQueryRequest routing(String... routings) {
this.routing = Strings.arrayToCommaDelimitedString(routings);
return this;
}
/**
* The types of documents the query will run against. Defaults to all types.
*/
public DeleteByQueryRequest types(String... types) {
this.types = types;
return this;
}
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
sourceUnsafe = false;
source = in.readBytesReference();
routing = in.readOptionalString();
types = in.readStringArray();
}
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBytesReference(source);
out.writeOptionalString(routing);
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_deletebyquery_DeleteByQueryRequest.java
|
533 |
static class Category {
String categoryName;
LicenseType licenseType;
FrameworkType frameworkType;
List<Dependency> dependencyList = new ArrayList<Dependency>();
Category[] usedByCategories;
public Category(String categoryName, LicenseType type, FrameworkType frameworkType) {
this.categoryName = categoryName;
this.licenseType = type;
this.frameworkType = frameworkType;
}
public Category(String categoryName, LicenseType type, FrameworkType frameworkType, Category... usedByCategories) {
this(categoryName, type, frameworkType);
this.usedByCategories = usedByCategories;
}
public String toString() {
return "Category Name : " + categoryName +
"\rLicense Type : " + licenseType.name +
"\rLicense URL : " + licenseType.url;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_util_PomEvaluator.java
|
328 |
public class PluginInfo implements Streamable, Serializable, ToXContent {
public static final String DESCRIPTION_NOT_AVAILABLE = "No description found.";
public static final String VERSION_NOT_AVAILABLE = "NA";
static final class Fields {
static final XContentBuilderString NAME = new XContentBuilderString("name");
static final XContentBuilderString DESCRIPTION = new XContentBuilderString("description");
static final XContentBuilderString URL = new XContentBuilderString("url");
static final XContentBuilderString JVM = new XContentBuilderString("jvm");
static final XContentBuilderString SITE = new XContentBuilderString("site");
static final XContentBuilderString VERSION = new XContentBuilderString("version");
}
private String name;
private String description;
private boolean site;
private boolean jvm;
private String version;
public PluginInfo() {
}
/**
* Information about plugins
*
* @param name Its name
* @param description Its description
* @param site true if it's a site plugin
* @param jvm true if it's a jvm plugin
* @param version Version number is applicable (NA otherwise)
*/
public PluginInfo(String name, String description, boolean site, boolean jvm, String version) {
this.name = name;
this.description = description;
this.site = site;
this.jvm = jvm;
if (Strings.hasText(version)) {
this.version = version;
} else {
this.version = VERSION_NOT_AVAILABLE;
}
}
/**
* @return Plugin's name
*/
public String getName() {
return name;
}
/**
* @return Plugin's description if any
*/
public String getDescription() {
return description;
}
/**
* @return true if it's a site plugin
*/
public boolean isSite() {
return site;
}
/**
* @return true if it's a plugin running in the jvm
*/
public boolean isJvm() {
return jvm;
}
/**
* We compute the URL for sites: "/_plugin/" + name + "/"
*
* @return relative URL for site plugin
*/
public String getUrl() {
if (site) {
return ("/_plugin/" + name + "/");
} else {
return null;
}
}
/**
* @return Version number for the plugin
*/
public String getVersion() {
return version;
}
public static PluginInfo readPluginInfo(StreamInput in) throws IOException {
PluginInfo info = new PluginInfo();
info.readFrom(in);
return info;
}
@Override
public void readFrom(StreamInput in) throws IOException {
this.name = in.readString();
this.description = in.readString();
this.site = in.readBoolean();
this.jvm = in.readBoolean();
if (in.getVersion().onOrAfter(Version.V_1_0_0_RC2)) {
this.version = in.readString();
} else {
this.version = VERSION_NOT_AVAILABLE;
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
out.writeString(description);
out.writeBoolean(site);
out.writeBoolean(jvm);
if (out.getVersion().onOrAfter(Version.V_1_0_0_RC2)) {
out.writeString(version);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(Fields.NAME, name);
builder.field(Fields.VERSION, version);
builder.field(Fields.DESCRIPTION, description);
if (site) {
builder.field(Fields.URL, getUrl());
}
builder.field(Fields.JVM, jvm);
builder.field(Fields.SITE, site);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PluginInfo that = (PluginInfo) o;
if (!name.equals(that.name)) return false;
if (version != null ? !version.equals(that.version) : that.version != null) return false;
return true;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("PluginInfo{");
sb.append("name='").append(name).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append(", site=").append(site);
sb.append(", jvm=").append(jvm);
sb.append(", version='").append(version).append('\'');
sb.append('}');
return sb.toString();
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_info_PluginInfo.java
|
4,446 |
return (FD) cache.get(key, new Callable<AtomicFieldData>() {
@Override
public AtomicFieldData call() throws Exception {
SegmentReaderUtils.registerCoreListener(context.reader(), IndexFieldCache.this);
AtomicFieldData fieldData = indexFieldData.loadDirect(context);
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;
}
});
| 1no label
|
src_main_java_org_elasticsearch_indices_fielddata_cache_IndicesFieldDataCache.java
|
1,246 |
public class NodeClusterAdminClient extends AbstractClusterAdminClient implements InternalClusterAdminClient {
private final ThreadPool threadPool;
private final ImmutableMap<ClusterAction, TransportAction> actions;
@Inject
public NodeClusterAdminClient(Settings settings, ThreadPool threadPool, Map<GenericAction, TransportAction> actions) {
this.threadPool = threadPool;
MapBuilder<ClusterAction, TransportAction> actionsBuilder = new MapBuilder<ClusterAction, TransportAction>();
for (Map.Entry<GenericAction, TransportAction> entry : actions.entrySet()) {
if (entry.getKey() instanceof ClusterAction) {
actionsBuilder.put((ClusterAction) entry.getKey(), entry.getValue());
}
}
this.actions = actionsBuilder.immutableMap();
}
@Override
public ThreadPool threadPool() {
return this.threadPool;
}
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute(ClusterAction<Request, Response, RequestBuilder> action, Request request) {
TransportAction<Request, Response> transportAction = actions.get(action);
return transportAction.execute(request);
}
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute(ClusterAction<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
TransportAction<Request, Response> transportAction = actions.get(action);
transportAction.execute(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_client_node_NodeClusterAdminClient.java
|
1,827 |
@Component("blBasicFieldTypeValidator")
public class BasicFieldTypeValidator implements PopulateValueRequestValidator {
@Override
public PropertyValidationResult validate(PopulateValueRequest populateValueRequest, Serializable instance) {
switch(populateValueRequest.getMetadata().getFieldType()) {
case INTEGER:
try {
if (int.class.isAssignableFrom(populateValueRequest.getReturnType()) || Integer.class.isAssignableFrom(populateValueRequest.getReturnType())) {
Integer.parseInt(populateValueRequest.getRequestedValue());
} else if (byte.class.isAssignableFrom(populateValueRequest.getReturnType()) || Byte.class.isAssignableFrom(populateValueRequest.getReturnType())) {
Byte.parseByte(populateValueRequest.getRequestedValue());
} else if (short.class.isAssignableFrom(populateValueRequest.getReturnType()) || Short.class.isAssignableFrom(populateValueRequest.getReturnType())) {
Short.parseShort(populateValueRequest.getRequestedValue());
} else if (long.class.isAssignableFrom(populateValueRequest.getReturnType()) || Long.class.isAssignableFrom(populateValueRequest.getReturnType())) {
Long.parseLong(populateValueRequest.getRequestedValue());
}
} catch (NumberFormatException e) {
return new PropertyValidationResult(false, "Field must be an valid number");
}
break;
case DECIMAL:
try {
if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) {
new BigDecimal(populateValueRequest.getRequestedValue());
} else {
Double.parseDouble(populateValueRequest.getRequestedValue());
}
} catch (NumberFormatException e) {
return new PropertyValidationResult(false, "Field must be a valid decimal");
}
break;
case MONEY:
try {
if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType()) || Money.class.isAssignableFrom(populateValueRequest.getReturnType())) {
new BigDecimal(populateValueRequest.getRequestedValue());
} else if (Double.class.isAssignableFrom(populateValueRequest.getReturnType())) {
Double.parseDouble(populateValueRequest.getRequestedValue());
}
} catch (NumberFormatException e) {
return new PropertyValidationResult(false, "Field must be a valid number");
}
break;
case DATE:
try {
populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().parse(populateValueRequest.getRequestedValue());
} catch (ParseException e) {
return new PropertyValidationResult(false, "Field must be a date of the format: " + populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().toPattern());
}
break;
case FOREIGN_KEY:
case ADDITIONAL_FOREIGN_KEY:
if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) {
Collection collection;
try {
collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
} catch (FieldNotAvailableException e) {
return new PropertyValidationResult(false, "External entity cannot be added to the specified collection at " + populateValueRequest.getProperty().getName());
} catch (IllegalAccessException e) {
return new PropertyValidationResult(false, "External entity cannot be added to the specified collection at " + populateValueRequest.getProperty().getName());
}
} else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) {
return new PropertyValidationResult(false, "External entity cannot be added to a map at " + populateValueRequest.getProperty().getName());
}
case ID:
if (populateValueRequest.getSetId()) {
switch (populateValueRequest.getMetadata().getSecondaryType()) {
case INTEGER:
Long.valueOf(populateValueRequest.getRequestedValue());
break;
default:
//do nothing
}
}
default:
return new PropertyValidationResult(true);
}
return new PropertyValidationResult(true);
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_validation_BasicFieldTypeValidator.java
|
262 |
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@TestGroup(enabled = true, sysProperty = SYSPROP_INTEGRATION)
public @interface IntegrationTests {
}
| 0true
|
src_test_java_org_apache_lucene_util_AbstractRandomizedTest.java
|
267 |
public class ElasticsearchGenerationException extends ElasticsearchException {
public ElasticsearchGenerationException(String msg) {
super(msg);
}
public ElasticsearchGenerationException(String msg, Throwable cause) {
super(msg, cause);
}
}
| 0true
|
src_main_java_org_elasticsearch_ElasticsearchGenerationException.java
|
79 |
@SuppressWarnings("serial")
static final class MapReduceMappingsToIntTask<K,V>
extends BulkTask<K,V,Integer> {
final ObjectByObjectToInt<? super K, ? super V> transformer;
final IntByIntToInt reducer;
final int basis;
int result;
MapReduceMappingsToIntTask<K,V> rights, nextRight;
MapReduceMappingsToIntTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceMappingsToIntTask<K,V> nextRight,
ObjectByObjectToInt<? super K, ? super V> transformer,
int basis,
IntByIntToInt reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Integer getRawResult() { return result; }
public final void compute() {
final ObjectByObjectToInt<? super K, ? super V> transformer;
final IntByIntToInt reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
int r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceMappingsToIntTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.apply(r, transformer.apply(p.key, p.val));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
t = (MapReduceMappingsToIntTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.apply(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
749 |
public class GetRequestBuilder extends SingleShardOperationRequestBuilder<GetRequest, GetResponse, GetRequestBuilder> {
public GetRequestBuilder(Client client) {
super((InternalClient) client, new GetRequest());
}
public GetRequestBuilder(Client client, @Nullable String index) {
super((InternalClient) client, new GetRequest(index));
}
/**
* Sets the type of the document to fetch. If set to <tt>null</tt>, will use just the id to fetch the
* first document matching it.
*/
public GetRequestBuilder setType(@Nullable String type) {
request.type(type);
return this;
}
/**
* Sets the id of the document to fetch.
*/
public GetRequestBuilder setId(String id) {
request.id(id);
return this;
}
/**
* Sets the parent id of this document. Will simply set the routing to this value, as it is only
* used for routing with delete requests.
*/
public GetRequestBuilder setParent(String parent) {
request.parent(parent);
return this;
}
/**
* Controls the shard routing of the request. Using this value to hash the shard
* and not the id.
*/
public GetRequestBuilder setRouting(String routing) {
request.routing(routing);
return this;
}
/**
* Sets the preference to execute the search. Defaults to randomize across shards. Can be set to
* <tt>_local</tt> to prefer local shards, <tt>_primary</tt> to execute only on primary shards, or
* a custom value, which guarantees that the same order will be used across different requests.
*/
public GetRequestBuilder setPreference(String preference) {
request.preference(preference);
return this;
}
/**
* Explicitly specify the fields that will be returned. By default, the <tt>_source</tt>
* field will be returned.
*/
public GetRequestBuilder setFields(String... fields) {
request.fields(fields);
return this;
}
/**
* Indicates whether the response should contain the stored _source
*
* @param fetch
* @return
*/
public GetRequestBuilder setFetchSource(boolean fetch) {
FetchSourceContext context = request.fetchSourceContext();
if (context == null) {
request.fetchSourceContext(new FetchSourceContext(fetch));
}
else {
context.fetchSource(fetch);
}
return this;
}
/**
* Indicate that _source should be returned, with an "include" and/or "exclude" set which can include simple wildcard
* elements.
*
* @param include An optional include (optionally wildcarded) pattern to filter the returned _source
* @param exclude An optional exclude (optionally wildcarded) pattern to filter the returned _source
*/
public GetRequestBuilder setFetchSource(@Nullable String include, @Nullable String exclude) {
return setFetchSource(
include == null? Strings.EMPTY_ARRAY : new String[] {include},
exclude == null? Strings.EMPTY_ARRAY : new String[] {exclude});
}
/**
* Indicate that _source should be returned, with an "include" and/or "exclude" set which can include simple wildcard
* elements.
*
* @param includes An optional list of include (optionally wildcarded) pattern to filter the returned _source
* @param excludes An optional list of exclude (optionally wildcarded) pattern to filter the returned _source
*/
public GetRequestBuilder setFetchSource(@Nullable String[] includes, @Nullable String[] excludes) {
FetchSourceContext context = request.fetchSourceContext();
if (context == null) {
request.fetchSourceContext(new FetchSourceContext(includes, excludes));
}
else {
context.fetchSource(true);
context.includes(includes);
context.excludes(excludes);
}
return this;
}
/**
* Should a refresh be executed before this get operation causing the operation to
* return the latest value. Note, heavy get should not set this to <tt>true</tt>. Defaults
* to <tt>false</tt>.
*/
public GetRequestBuilder setRefresh(boolean refresh) {
request.refresh(refresh);
return this;
}
public GetRequestBuilder setRealtime(Boolean realtime) {
request.realtime(realtime);
return this;
}
/**
* Sets the version, which will cause the get operation to only be performed if a matching
* version exists and no changes happened on the doc since then.
*/
public GetRequestBuilder setVersion(long version) {
request.version(version);
return this;
}
/**
* Sets the versioning type. Defaults to {@link org.elasticsearch.index.VersionType#INTERNAL}.
*/
public GetRequestBuilder setVersionType(VersionType versionType) {
request.versionType(versionType);
return this;
}
@Override
protected void doExecute(ActionListener<GetResponse> listener) {
((Client) client).get(request, listener);
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_get_GetRequestBuilder.java
|
6 |
public class OIterableObjectArray<T> implements Iterable<T> {
private final Object object;
private int length;
public OIterableObjectArray(Object o) {
object = o;
length = Array.getLength(o);
}
/**
* Returns an iterator over a set of elements of type T.
*
* @return an Iterator.
*/
public Iterator<T> iterator() {
return new ObjIterator();
}
private class ObjIterator implements Iterator<T> {
private int p = 0;
/**
* Returns <tt>true</tt> if the iteration has more elements. (In other words, returns <tt>true</tt> if <tt>next</tt> would
* return an element rather than throwing an exception.)
*
* @return <tt>true</tt> if the iterator has more elements.
*/
public boolean hasNext() {
return p < length;
}
/**
* Returns the next element in the iteration.
*
* @return the next element in the iteration.
* @throws java.util.NoSuchElementException
* iteration has no more elements.
*/
@SuppressWarnings("unchecked")
public T next() {
if (p < length) {
return (T) Array.get(object, p++);
} else {
throw new NoSuchElementException();
}
}
/**
* Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be
* called only once per call to <tt>next</tt>. The behavior of an iterator is unspecified if the underlying collection is
* modified while the iteration is in progress in any way other than by calling this method.
*
* @throws UnsupportedOperationException
* if the <tt>remove</tt> operation is not supported by this Iterator.
* @throws IllegalStateException
* if the <tt>next</tt> method has not yet been called, or the <tt>remove</tt> method has already been called after
* the last call to the <tt>next</tt> method.
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_collection_OIterableObjectArray.java
|
1,788 |
public class FilterMapping {
public static final String RANGE_SPECIFIER_REGEX = "->";
protected String fullPropertyName;
protected List<String> filterValues = new ArrayList<String>();
protected List directFilterValues = new ArrayList();
protected SortDirection sortDirection;
protected Restriction restriction;
protected FieldPath fieldPath;
protected Class<?> inheritedFromClass;
public FilterMapping withFullPropertyName(String fullPropertyName) {
setFullPropertyName(fullPropertyName);
return this;
}
public FilterMapping withFilterValues(List<String> filterValues) {
setFilterValues(filterValues);
return this;
}
public FilterMapping withDirectFilterValues(List directFilterValues) {
setDirectFilterValues(directFilterValues);
return this;
}
public FilterMapping withSortDirection(SortDirection sortDirection) {
setSortDirection(sortDirection);
return this;
}
public FilterMapping withRestriction(Restriction restriction) {
setRestriction(restriction);
return this;
}
public FilterMapping withFieldPath(FieldPath fieldPath) {
setFieldPath(fieldPath);
return this;
}
public FilterMapping withInheritedFromClass(Class<?> inheritedFromClass) {
setInheritedFromClass(inheritedFromClass);
return this;
}
public String getFullPropertyName() {
return fullPropertyName;
}
public void setFullPropertyName(String fullPropertyName) {
this.fullPropertyName = fullPropertyName;
}
public List<String> getFilterValues() {
return filterValues;
}
public void setFilterValues(List<String> filterValues) {
if (CollectionUtils.isNotEmpty(directFilterValues)) {
throw new IllegalArgumentException("Cannot set both filter values and direct filter values");
}
List<String> parsedValues = new ArrayList<String>();
for (String unfiltered : filterValues) {
parsedValues.addAll(Arrays.asList(parseFilterValue(unfiltered)));
}
this.filterValues.addAll(parsedValues);
}
public SortDirection getSortDirection() {
return sortDirection;
}
public void setSortDirection(SortDirection sortDirection) {
this.sortDirection = sortDirection;
}
public Restriction getRestriction() {
return restriction;
}
public void setRestriction(Restriction restriction) {
this.restriction = restriction;
}
public FieldPath getFieldPath() {
return fieldPath;
}
public void setFieldPath(FieldPath fieldPath) {
this.fieldPath = fieldPath;
}
public List getDirectFilterValues() {
return directFilterValues;
}
public void setDirectFilterValues(List directFilterValues) {
if (CollectionUtils.isNotEmpty(filterValues)) {
throw new IllegalArgumentException("Cannot set both filter values and direct filter values");
}
this.directFilterValues = directFilterValues;
}
public Class<?> getInheritedFromClass() {
return inheritedFromClass;
}
public void setInheritedFromClass(Class<?> inheritedFromClass) {
this.inheritedFromClass = inheritedFromClass;
}
protected String[] parseFilterValue(String filterValue) {
//We do it this way because the String.split() method will return only a single array member
//when there is nothing on one side of the delimiter. We want to have two array members (one empty)
//in this case.
String[] vals;
if (filterValue.contains(RANGE_SPECIFIER_REGEX)) {
vals = new String[]{filterValue.substring(0, filterValue.indexOf(RANGE_SPECIFIER_REGEX)),
filterValue.substring(filterValue.indexOf(RANGE_SPECIFIER_REGEX) + RANGE_SPECIFIER_REGEX.length(),
filterValue.length())};
} else {
vals = new String[]{filterValue};
}
for (int j=0;j<vals.length;j++) {
vals[j] = vals[j].trim();
}
return vals;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_criteria_FilterMapping.java
|
449 |
public class ClientReplicatedMapTest
extends HazelcastTestSupport {
@After
public void cleanup() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testAddObjectDelay0()
throws Exception {
testAdd(buildConfig(InMemoryFormat.OBJECT, 0));
}
@Test
public void testAddObjectDelayDefault()
throws Exception {
testAdd(buildConfig(InMemoryFormat.OBJECT, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
@Test
public void testAddBinaryDelay0()
throws Exception {
testAdd(buildConfig(InMemoryFormat.BINARY, 0));
}
@Test
public void testAddBinaryDelayDefault()
throws Exception {
testAdd(buildConfig(InMemoryFormat.BINARY, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
private void testAdd(Config config)
throws Exception {
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance instance2 = HazelcastClient.newHazelcastClient();
final ReplicatedMap<String, String> map1 = instance1.getReplicatedMap("default");
final ReplicatedMap<String, String> map2 = instance2.getReplicatedMap("default");
final int operations = 100;
WatchedOperationExecutor executor = new WatchedOperationExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < operations; i++) {
map1.put("foo-" + i, "bar");
}
}
}, 60, EntryEventType.ADDED, operations, 0.75, map1, map2);
for (Map.Entry<String, String> entry : map2.entrySet()) {
assertStartsWith("foo-", entry.getKey());
assertEquals("bar", entry.getValue());
}
for (Map.Entry<String, String> entry : map1.entrySet()) {
assertStartsWith("foo-", entry.getKey());
assertEquals("bar", entry.getValue());
}
}
@Test
public void testClearObjectDelay0()
throws Exception {
testClear(buildConfig(InMemoryFormat.OBJECT, 0));
}
@Test
public void testClearObjectDelayDefault()
throws Exception {
testClear(buildConfig(InMemoryFormat.OBJECT, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
@Test
public void testClearBinaryDelay0()
throws Exception {
testClear(buildConfig(InMemoryFormat.BINARY, 0));
}
@Test
public void testClearBinaryDelayDefault()
throws Exception {
testClear(buildConfig(InMemoryFormat.BINARY, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
private void testClear(Config config)
throws Exception {
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance instance2 = HazelcastClient.newHazelcastClient();
final ReplicatedMap<String, String> map1 = instance1.getReplicatedMap("default");
final ReplicatedMap<String, String> map2 = instance2.getReplicatedMap("default");
final int operations = 100;
WatchedOperationExecutor executor = new WatchedOperationExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < operations; i++) {
map1.put("foo-" + i, "bar");
}
}
}, 60, EntryEventType.ADDED, operations, 0.75, map1, map2);
for (Map.Entry<String, String> entry : map2.entrySet()) {
assertStartsWith("foo-", entry.getKey());
assertEquals("bar", entry.getValue());
}
for (Map.Entry<String, String> entry : map1.entrySet()) {
assertStartsWith("foo-", entry.getKey());
assertEquals("bar", entry.getValue());
}
// TODO Should clear be a sychronous operation? What happens on lost clear message?
final AtomicBoolean happened = new AtomicBoolean(false);
for (int i = 0; i < 10; i++) {
map1.clear();
Thread.sleep(1000);
try {
assertEquals(0, map1.size());
assertEquals(0, map2.size());
happened.set(true);
} catch (AssertionError ignore) {
// ignore and retry
}
if (happened.get()) {
break;
}
}
}
@Test
public void testUpdateObjectDelay0()
throws Exception {
testUpdate(buildConfig(InMemoryFormat.OBJECT, 0));
}
@Test
public void testUpdateObjectDelayDefault()
throws Exception {
testUpdate(buildConfig(InMemoryFormat.OBJECT, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
@Test
public void testUpdateBinaryDelay0()
throws Exception {
testUpdate(buildConfig(InMemoryFormat.BINARY, 0));
}
@Test
public void testUpdateBinaryDelayDefault()
throws Exception {
testUpdate(buildConfig(InMemoryFormat.BINARY, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
private void testUpdate(Config config)
throws Exception {
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance instance2 = HazelcastClient.newHazelcastClient();
final ReplicatedMap<String, String> map1 = instance1.getReplicatedMap("default");
final ReplicatedMap<String, String> map2 = instance2.getReplicatedMap("default");
final int operations = 100;
WatchedOperationExecutor executor = new WatchedOperationExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < operations; i++) {
map1.put("foo-" + i, "bar");
}
}
}, 60, EntryEventType.ADDED, operations, 0.75, map1, map2);
for (Map.Entry<String, String> entry : map2.entrySet()) {
assertStartsWith("foo-", entry.getKey());
assertEquals("bar", entry.getValue());
}
for (Map.Entry<String, String> entry : map1.entrySet()) {
assertStartsWith("foo-", entry.getKey());
assertEquals("bar", entry.getValue());
}
executor.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < operations; i++) {
map2.put("foo-" + i, "bar2");
}
}
}, 60, EntryEventType.UPDATED, operations, 0.75, map1, map2);
int map2Updated = 0;
for (Map.Entry<String, String> entry : map2.entrySet()) {
if ("bar2".equals(entry.getValue())) {
map2Updated++;
}
}
int map1Updated = 0;
for (Map.Entry<String, String> entry : map1.entrySet()) {
if ("bar2".equals(entry.getValue())) {
map1Updated++;
}
}
assertMatchSuccessfulOperationQuota(0.75, operations, map1Updated, map2Updated);
}
@Test
public void testRemoveObjectDelay0()
throws Exception {
testRemove(buildConfig(InMemoryFormat.OBJECT, 0));
}
@Test
public void testRemoveObjectDelayDefault()
throws Exception {
testRemove(buildConfig(InMemoryFormat.OBJECT, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
@Test
public void testRemoveBinaryDelay0()
throws Exception {
testRemove(buildConfig(InMemoryFormat.BINARY, 0));
}
@Test
public void testRemoveBinaryDelayDefault()
throws Exception {
testRemove(buildConfig(InMemoryFormat.BINARY, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
private void testRemove(Config config)
throws Exception {
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance instance2 = HazelcastClient.newHazelcastClient();
final ReplicatedMap<String, String> map1 = instance1.getReplicatedMap("default");
final ReplicatedMap<String, String> map2 = instance2.getReplicatedMap("default");
final int operations = 100;
WatchedOperationExecutor executor = new WatchedOperationExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < operations; i++) {
map1.put("foo-" + i, "bar");
}
}
}, 60, EntryEventType.ADDED, operations, 0.75, map1, map2);
for (Map.Entry<String, String> entry : map2.entrySet()) {
assertStartsWith("foo-", entry.getKey());
assertEquals("bar", entry.getValue());
}
for (Map.Entry<String, String> entry : map1.entrySet()) {
assertStartsWith("foo-", entry.getKey());
assertEquals("bar", entry.getValue());
}
executor.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < operations; i++) {
map2.remove("foo-" + i);
}
}
}, 60, EntryEventType.REMOVED, operations, 0.75, map1, map2);
int map2Updated = 0;
for (int i = 0; i < operations; i++) {
Object value = map2.get("foo-" + i);
if (value == null) {
map2Updated++;
}
}
int map1Updated = 0;
for (int i = 0; i < operations; i++) {
Object value = map1.get("foo-" + i);
if (value == null) {
map1Updated++;
}
}
assertMatchSuccessfulOperationQuota(0.75, operations, map1Updated, map2Updated);
}
@Test
public void testSizeObjectDelay0()
throws Exception {
testSize(buildConfig(InMemoryFormat.OBJECT, 0));
}
@Test
public void testSizeObjectDelayDefault()
throws Exception {
testSize(buildConfig(InMemoryFormat.OBJECT, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
@Test
public void testSizeBinaryDelay0()
throws Exception {
testSize(buildConfig(InMemoryFormat.BINARY, 0));
}
@Test
public void testSizeBinaryDelayDefault()
throws Exception {
testSize(buildConfig(InMemoryFormat.BINARY, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
private void testSize(Config config)
throws Exception {
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance instance2 = HazelcastClient.newHazelcastClient();
final ReplicatedMap<Integer, Integer> map1 = instance1.getReplicatedMap("default");
final ReplicatedMap<Integer, Integer> map2 = instance2.getReplicatedMap("default");
final AbstractMap.SimpleEntry<Integer, Integer>[] testValues = buildTestValues();
WatchedOperationExecutor executor = new WatchedOperationExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
int half = testValues.length / 2;
for (int i = 0; i < testValues.length; i++) {
final ReplicatedMap map = i < half ? map1 : map2;
final AbstractMap.SimpleEntry<Integer, Integer> entry = testValues[i];
map.put(entry.getKey(), entry.getValue());
}
}
}, 2, EntryEventType.ADDED, 100, 0.75, map1, map2);
assertMatchSuccessfulOperationQuota(0.75, map1.size(), map2.size());
}
@Test
public void testContainsKeyObjectDelay0()
throws Exception {
testContainsKey(buildConfig(InMemoryFormat.OBJECT, 0));
}
@Test
public void testContainsKeyObjectDelayDefault()
throws Exception {
testContainsKey(buildConfig(InMemoryFormat.OBJECT, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
@Test
public void testContainsKeyBinaryDelay0()
throws Exception {
testContainsKey(buildConfig(InMemoryFormat.BINARY, 0));
}
@Test
public void testContainsKeyBinaryDelayDefault()
throws Exception {
testContainsKey(buildConfig(InMemoryFormat.BINARY, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
private void testContainsKey(Config config)
throws Exception {
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance instance2 = HazelcastClient.newHazelcastClient();
final ReplicatedMap<String, String> map1 = instance1.getReplicatedMap("default");
final ReplicatedMap<String, String> map2 = instance2.getReplicatedMap("default");
final int operations = 100;
WatchedOperationExecutor executor = new WatchedOperationExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < operations; i++) {
map1.put("foo-" + i, "bar");
}
}
}, 60, EntryEventType.ADDED, operations, 0.75, map1, map2);
int map2Contains = 0;
for (int i = 0; i < operations; i++) {
if (map2.containsKey("foo-" + i)) {
map2Contains++;
}
}
int map1Contains = 0;
for (int i = 0; i < operations; i++) {
if (map1.containsKey("foo-" + i)) {
map1Contains++;
}
}
assertMatchSuccessfulOperationQuota(0.75, operations, map1Contains, map2Contains);
}
@Test
public void testContainsValueObjectDelay0()
throws Exception {
testContainsValue(buildConfig(InMemoryFormat.OBJECT, 0));
}
@Test
public void testContainsValueObjectDelayDefault()
throws Exception {
testContainsValue(buildConfig(InMemoryFormat.OBJECT, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
@Test
public void testContainsValueBinaryDelay0()
throws Exception {
testContainsValue(buildConfig(InMemoryFormat.BINARY, 0));
}
@Test
public void testContainsValueBinaryDelayDefault()
throws Exception {
testContainsValue(buildConfig(InMemoryFormat.BINARY, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
private void testContainsValue(Config config)
throws Exception {
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance instance2 = HazelcastClient.newHazelcastClient();
final ReplicatedMap<Integer, Integer> map1 = instance1.getReplicatedMap("default");
final ReplicatedMap<Integer, Integer> map2 = instance2.getReplicatedMap("default");
final AbstractMap.SimpleEntry<Integer, Integer>[] testValues = buildTestValues();
WatchedOperationExecutor executor = new WatchedOperationExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
int half = testValues.length / 2;
for (int i = 0; i < testValues.length; i++) {
final ReplicatedMap map = i < half ? map1 : map2;
final AbstractMap.SimpleEntry<Integer, Integer> entry = testValues[i];
map.put(entry.getKey(), entry.getValue());
}
}
}, 2, EntryEventType.ADDED, testValues.length, 0.75, map1, map2);
int map2Contains = 0;
for (int i = 0; i < testValues.length; i++) {
if (map2.containsValue(testValues[i].getValue())) {
map2Contains++;
}
}
int map1Contains = 0;
for (int i = 0; i < testValues.length; i++) {
if (map1.containsValue(testValues[i].getValue())) {
map1Contains++;
}
}
assertMatchSuccessfulOperationQuota(0.75, testValues.length, map1Contains, map2Contains);
}
@Test
public void testValuesObjectDelay0()
throws Exception {
testValues(buildConfig(InMemoryFormat.OBJECT, 0));
}
@Test
public void testValuesObjectDelayDefault()
throws Exception {
testValues(buildConfig(InMemoryFormat.OBJECT, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
@Test
public void testValuesBinaryDelay0()
throws Exception {
testValues(buildConfig(InMemoryFormat.BINARY, 0));
}
@Test
public void testValuesBinaryDefault()
throws Exception {
testValues(buildConfig(InMemoryFormat.BINARY, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
private void testValues(Config config)
throws Exception {
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance instance2 = HazelcastClient.newHazelcastClient();
final ReplicatedMap<Integer, Integer> map1 = instance1.getReplicatedMap("default");
final ReplicatedMap<Integer, Integer> map2 = instance2.getReplicatedMap("default");
final AbstractMap.SimpleEntry<Integer, Integer>[] testValues = buildTestValues();
final List<Integer> valuesTestValues = new ArrayList<Integer>(testValues.length);
WatchedOperationExecutor executor = new WatchedOperationExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
int half = testValues.length / 2;
for (int i = 0; i < testValues.length; i++) {
final ReplicatedMap map = i < half ? map1 : map2;
final AbstractMap.SimpleEntry<Integer, Integer> entry = testValues[i];
map.put(entry.getKey(), entry.getValue());
valuesTestValues.add(entry.getValue());
}
}
}, 2, EntryEventType.ADDED, 100, 0.75, map1, map2);
List<Integer> values1 = new ArrayList<Integer>(map1.values());
List<Integer> values2 = new ArrayList<Integer>(map2.values());
int map1Contains = 0;
int map2Contains = 0;
for (Integer value : valuesTestValues) {
if (values2.contains(value)) {
map2Contains++;
}
if (values1.contains(value)) {
map1Contains++;
}
}
assertMatchSuccessfulOperationQuota(0.75, testValues.length, map1Contains, map2Contains);
}
@Test
public void testKeySetObjectDelay0()
throws Exception {
testKeySet(buildConfig(InMemoryFormat.OBJECT, 0));
}
@Test
public void testKeySetObjectDelayDefault()
throws Exception {
testKeySet(buildConfig(InMemoryFormat.OBJECT, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
@Test
public void testKeySetBinaryDelay0()
throws Exception {
testKeySet(buildConfig(InMemoryFormat.BINARY, 0));
}
@Test
public void testKeySetBinaryDelayDefault()
throws Exception {
testKeySet(buildConfig(InMemoryFormat.BINARY, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
private void testKeySet(Config config)
throws Exception {
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance instance2 = HazelcastClient.newHazelcastClient();
final ReplicatedMap<Integer, Integer> map1 = instance1.getReplicatedMap("default");
final ReplicatedMap<Integer, Integer> map2 = instance2.getReplicatedMap("default");
final AbstractMap.SimpleEntry<Integer, Integer>[] testValues = buildTestValues();
final List<Integer> keySetTestValues = new ArrayList<Integer>(testValues.length);
WatchedOperationExecutor executor = new WatchedOperationExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
int half = testValues.length / 2;
for (int i = 0; i < testValues.length; i++) {
final ReplicatedMap map = i < half ? map1 : map2;
final AbstractMap.SimpleEntry<Integer, Integer> entry = testValues[i];
map.put(entry.getKey(), entry.getValue());
keySetTestValues.add(entry.getKey());
}
}
}, 2, EntryEventType.ADDED, 100, 0.75, map1, map2);
List<Integer> keySet1 = new ArrayList<Integer>(map1.keySet());
List<Integer> keySet2 = new ArrayList<Integer>(map2.keySet());
int map1Contains = 0;
int map2Contains = 0;
for (Integer value : keySetTestValues) {
if (keySet2.contains(value)) {
map2Contains++;
}
if (keySet1.contains(value)) {
map1Contains++;
}
}
assertMatchSuccessfulOperationQuota(0.75, testValues.length, map1Contains, map2Contains);
}
@Test
public void testEntrySetObjectDelay0()
throws Exception {
testEntrySet(buildConfig(InMemoryFormat.OBJECT, 0));
}
@Test
public void testEntrySetObjectDelayDefault()
throws Exception {
testEntrySet(buildConfig(InMemoryFormat.OBJECT, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
@Test
public void testEntrySetBinaryDelay0()
throws Exception {
testEntrySet(buildConfig(InMemoryFormat.BINARY, 0));
}
@Test
public void testEntrySetBinaryDelayDefault()
throws Exception {
testEntrySet(buildConfig(InMemoryFormat.BINARY, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
private void testEntrySet(Config config)
throws Exception {
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance instance2 = HazelcastClient.newHazelcastClient();
final ReplicatedMap<Integer, Integer> map1 = instance1.getReplicatedMap("default");
final ReplicatedMap<Integer, Integer> map2 = instance2.getReplicatedMap("default");
final AbstractMap.SimpleEntry<Integer, Integer>[] testValues = buildTestValues();
final List<AbstractMap.SimpleEntry<Integer, Integer>> entrySetTestValues = Arrays.asList(testValues);
WatchedOperationExecutor executor = new WatchedOperationExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
int half = testValues.length / 2;
for (int i = 0; i < testValues.length; i++) {
final ReplicatedMap map = i < half ? map1 : map2;
final AbstractMap.SimpleEntry<Integer, Integer> entry = testValues[i];
map.put(entry.getKey(), entry.getValue());
}
}
}, 2, EntryEventType.ADDED, 100, 0.75, map1, map2);
List<Entry<Integer, Integer>> entrySet1 = new ArrayList<Entry<Integer, Integer>>(map1.entrySet());
List<Entry<Integer, Integer>> entrySet2 = new ArrayList<Entry<Integer, Integer>>(map2.entrySet());
int map2Contains = 0;
for (Entry<Integer, Integer> entry : entrySet2) {
Integer value = findValue(entry.getKey(), testValues);
if (value.equals(entry.getValue())) {
map2Contains++;
}
}
int map1Contains = 0;
for (Entry<Integer, Integer> entry : entrySet1) {
Integer value = findValue(entry.getKey(), testValues);
if (value.equals(entry.getValue())) {
map1Contains++;
}
}
assertMatchSuccessfulOperationQuota(0.75, testValues.length, map1Contains, map2Contains);
}
@Test
public void testRetrieveUnknownValueObjectDelay0()
throws Exception {
testRetrieveUnknownValue(buildConfig(InMemoryFormat.OBJECT, 0));
}
@Test
public void testRetrieveUnknownValueObjectDelayDefault()
throws Exception {
testRetrieveUnknownValue(buildConfig(InMemoryFormat.OBJECT, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
@Test
public void testRetrieveUnknownValueBinaryDelay0()
throws Exception {
testRetrieveUnknownValue(buildConfig(InMemoryFormat.BINARY, 0));
}
@Test
public void testRetrieveUnknownValueBinaryDelayDefault()
throws Exception {
testRetrieveUnknownValue(buildConfig(InMemoryFormat.BINARY, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
}
private void testRetrieveUnknownValue(Config config)
throws Exception {
HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance instance2 = HazelcastClient.newHazelcastClient();
ReplicatedMap<String, String> map = instance2.getReplicatedMap("default");
String value = map.get("foo");
assertNull(value);
}
private Config buildConfig(InMemoryFormat inMemoryFormat, long replicationDelay) {
Config config = new Config();
ReplicatedMapConfig replicatedMapConfig = config.getReplicatedMapConfig("default");
replicatedMapConfig.setReplicationDelayMillis(replicationDelay);
replicatedMapConfig.setInMemoryFormat(inMemoryFormat);
return config;
}
private Integer findValue(int key, AbstractMap.SimpleEntry<Integer, Integer>[] values) {
for (int i = 0; i < values.length; i++) {
if (values[i].getKey().equals(key)) {
return values[i].getValue();
}
}
return null;
}
private void assertMatchSuccessfulOperationQuota(double quota, int completeOps, int... values) {
float[] quotas = new float[values.length];
Object[] args = new Object[values.length + 1];
args[0] = quota;
for (int i = 0; i < values.length; i++) {
quotas[i] = (float) values[i] / completeOps;
args[i + 1] = new Float(quotas[i]);
}
boolean success = true;
for (int i = 0; i < values.length; i++) {
if (quotas[i] < quota) {
success = false;
break;
}
}
if (!success) {
StringBuilder sb = new StringBuilder("Quote (%s) for updates not reached,");
for (int i = 0; i < values.length; i++) {
sb.append(" map").append(i + 1).append(": %s,");
}
sb.deleteCharAt(sb.length() - 1);
fail(String.format(sb.toString(), args));
}
}
private AbstractMap.SimpleEntry<Integer, Integer>[] buildTestValues() {
Random random = new Random();
AbstractMap.SimpleEntry<Integer, Integer>[] testValues = new AbstractMap.SimpleEntry[100];
for (int i = 0; i < testValues.length; i++) {
testValues[i] = new AbstractMap.SimpleEntry<Integer, Integer>(random.nextInt(), random.nextInt());
}
return testValues;
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_replicatedmap_ClientReplicatedMapTest.java
|
178 |
@Controller
@RequestMapping(PreviewTemplateController.REQUEST_MAPPING_PREFIX + "**")
public class PreviewTemplateController {
private String templatePathPrefix = "templates";
public static final String REQUEST_MAPPING_PREFIX = "/preview/";
@RequestMapping
public String displayPreview(HttpServletRequest httpServletRequest) {
String requestURIPrefix = httpServletRequest.getContextPath() + REQUEST_MAPPING_PREFIX;
String templatePath = httpServletRequest.getRequestURI().substring(requestURIPrefix.length() - 1);
return templatePathPrefix + templatePath;
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_web_PreviewTemplateController.java
|
152 |
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);
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.