Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
418 |
public class RestoreSnapshotAction extends ClusterAction<RestoreSnapshotRequest, RestoreSnapshotResponse, RestoreSnapshotRequestBuilder> {
public static final RestoreSnapshotAction INSTANCE = new RestoreSnapshotAction();
public static final String NAME = "cluster/snapshot/restore";
private RestoreSnapshotAction() {
super(NAME);
}
@Override
public RestoreSnapshotResponse newResponse() {
return new RestoreSnapshotResponse();
}
@Override
public RestoreSnapshotRequestBuilder newRequestBuilder(ClusterAdminClient client) {
return new RestoreSnapshotRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_restore_RestoreSnapshotAction.java
|
3,126 |
static class EngineSearcher implements Searcher {
private final String source;
private final IndexSearcher searcher;
private final SearcherManager manager;
private EngineSearcher(String source, IndexSearcher searcher, SearcherManager manager) {
this.source = source;
this.searcher = searcher;
this.manager = manager;
}
@Override
public String source() {
return this.source;
}
@Override
public IndexReader reader() {
return searcher.getIndexReader();
}
@Override
public IndexSearcher searcher() {
return searcher;
}
@Override
public boolean release() throws ElasticsearchException {
try {
manager.release(searcher);
return true;
} catch (IOException e) {
return false;
} catch (AlreadyClosedException e) {
/* this one can happen if we already closed the
* underlying store / directory and we call into the
* IndexWriter to free up pending files. */
return false;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_engine_internal_InternalEngine.java
|
1,312 |
public interface SearchFacetRange {
/**
* Returns the internal id
*
* @return the internal id
*/
public Long getId();
/**
* Sets the internal id
*
* @param id
*/
public void setId(Long id);
/**
* Gets the minimum value for this SearchFacetRange
*
* Note: The default SearchFacetRangeImpl does not allow this value to be null
*
* @return the min value
*/
public BigDecimal getMinValue();
/**
* Sets the minium value for this SearchFacetRange
*
* @param minValue
*/
public void setMinValue(BigDecimal minValue);
/**
* Gets the maximum value for this SearchFacetRange
*
* Note: The default SearchFacetRangeImpl allows this value to be null
*
* @return the max value
*/
public BigDecimal getMaxValue();
/**
* Sets the maximum value for this SearchFacetRange
*
* @param maxValue
*/
public void setMaxValue(BigDecimal maxValue);
/**
* Gets the associated SearchFacet to this range
*
* @return the associated SearchFacet
*/
public SearchFacet getSearchFacet();
/**
* Sets the associated SearchFacet
*
* @param searchFacet
*/
public void setSearchFacet(SearchFacet searchFacet);
}
| 0true
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_domain_SearchFacetRange.java
|
53 |
@SuppressWarnings("serial")
static final class ForEachEntryTask<K,V>
extends BulkTask<K,V,Void> {
final Action<? super Entry<K,V>> action;
ForEachEntryTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Action<? super Entry<K,V>> action) {
super(p, b, i, f, t);
this.action = action;
}
public final void compute() {
final Action<? super Entry<K,V>> action;
if ((action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachEntryTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
action).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
action.apply(p);
propagateCompletion();
}
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
235 |
public class CassandraTransaction extends AbstractStoreTransaction {
private static final Logger log = LoggerFactory.getLogger(CassandraTransaction.class);
private final CLevel read;
private final CLevel write;
public CassandraTransaction(BaseTransactionConfig c) {
super(c);
read = CLevel.parse(getConfiguration().getCustomOption(CASSANDRA_READ_CONSISTENCY));
write = CLevel.parse(getConfiguration().getCustomOption(CASSANDRA_WRITE_CONSISTENCY));
log.debug("Created {}", this.toString());
}
public CLevel getReadConsistencyLevel() {
return read;
}
public CLevel getWriteConsistencyLevel() {
return write;
}
public static CassandraTransaction getTx(StoreTransaction txh) {
Preconditions.checkArgument(txh != null);
Preconditions.checkArgument(txh instanceof CassandraTransaction, "Unexpected transaction type %s", txh.getClass().getName());
return (CassandraTransaction) txh;
}
public String toString() {
StringBuilder sb = new StringBuilder(64);
sb.append("CassandraTransaction@");
sb.append(Integer.toHexString(hashCode()));
sb.append("[read=");
sb.append(read);
sb.append(",write=");
sb.append(write);
sb.append("]");
return sb.toString();
}
}
| 0true
|
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_CassandraTransaction.java
|
740 |
public class ListAddAllRequest extends CollectionAddAllRequest {
private int index;
public ListAddAllRequest() {
}
public ListAddAllRequest(String name, List<Data> valueList, int index) {
super(name, valueList);
this.index = index;
}
@Override
protected Operation prepareOperation() {
return new ListAddAllOperation(name, index, valueList);
}
@Override
public int getClassId() {
return CollectionPortableHook.LIST_ADD_ALL;
}
public void write(PortableWriter writer) throws IOException {
writer.writeInt("i", index);
super.write(writer);
}
public void read(PortableReader reader) throws IOException {
index = reader.readInt("i");
super.read(reader);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_client_ListAddAllRequest.java
|
317 |
public class ImportProcessor {
private static final Log LOG = LogFactory.getLog(ImportProcessor.class);
private static final String IMPORT_PATH = "/beans/import";
protected ApplicationContext applicationContext;
protected DocumentBuilder builder;
protected XPath xPath;
public ImportProcessor(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
builder = dbf.newDocumentBuilder();
XPathFactory factory=XPathFactory.newInstance();
xPath=factory.newXPath();
} catch (ParserConfigurationException e) {
LOG.error("Unable to create document builder", e);
throw new RuntimeException(e);
}
}
public ResourceInputStream[] extract(ResourceInputStream[] sources) throws MergeException {
if (sources == null) {
return null;
}
try {
DynamicResourceIterator resourceList = new DynamicResourceIterator();
resourceList.addAll(Arrays.asList(sources));
while(resourceList.hasNext()) {
ResourceInputStream myStream = resourceList.nextResource();
Document doc = builder.parse(myStream);
NodeList nodeList = (NodeList) xPath.evaluate(IMPORT_PATH, doc, XPathConstants.NODESET);
int length = nodeList.getLength();
for (int j=0;j<length;j++) {
Element element = (Element) nodeList.item(j);
Resource resource = applicationContext.getResource(element.getAttribute("resource"));
ResourceInputStream ris = new ResourceInputStream(resource.getInputStream(), resource.getURL().toString());
resourceList.addEmbeddedResource(ris);
element.getParentNode().removeChild(element);
}
if (length > 0) {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer xmlTransformer = tFactory.newTransformer();
xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0");
xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos));
StreamResult result = new StreamResult(writer);
xmlTransformer.transform(source, result);
byte[] itemArray = baos.toByteArray();
resourceList.set(resourceList.getPosition() - 1, new ResourceInputStream(new ByteArrayInputStream(itemArray), null, myStream.getNames()));
} else {
myStream.reset();
}
}
return resourceList.toArray(new ResourceInputStream[resourceList.size()]);
} catch (Exception e) {
throw new MergeException(e);
}
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_ImportProcessor.java
|
3,497 |
public interface InternalMapper {
}
| 0true
|
src_main_java_org_elasticsearch_index_mapper_InternalMapper.java
|
870 |
public interface ShippingOfferService {
public void reviewOffers(Order order) throws PricingException;
}
| 0true
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_ShippingOfferService.java
|
1,911 |
internalConvertToTypes(new AbstractMatcher<TypeLiteral<?>>() {
public boolean matches(TypeLiteral<?> typeLiteral) {
Type type = typeLiteral.getType();
if (!(type instanceof Class)) {
return false;
}
Class<?> clazz = (Class<?>) type;
return typeMatcher.matches(clazz);
}
@Override
public String toString() {
return typeMatcher.toString();
}
}, converter);
| 0true
|
src_main_java_org_elasticsearch_common_inject_TypeConverterBindingProcessor.java
|
221 |
private static final DocsAndPositionsEnum EMPTY = new DocsAndPositionsEnum() {
@Override
public int nextPosition() throws IOException { return 0; }
@Override
public int startOffset() throws IOException { return Integer.MAX_VALUE; }
@Override
public int endOffset() throws IOException { return Integer.MAX_VALUE; }
@Override
public BytesRef getPayload() throws IOException { return null; }
@Override
public int freq() throws IOException { return 0; }
@Override
public int docID() { return NO_MORE_DOCS; }
@Override
public int nextDoc() throws IOException { return NO_MORE_DOCS; }
@Override
public int advance(int target) throws IOException { return NO_MORE_DOCS; }
@Override
public long cost() { return 0; }
};
| 0true
|
src_main_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighter.java
|
1,111 |
public class SetConfig extends CollectionConfig<SetConfig> {
private SetConfigReadOnly readOnly;
public SetConfig() {
}
public SetConfig(SetConfig config) {
super(config);
}
public SetConfigReadOnly getAsReadOnly() {
if (readOnly == null){
readOnly = new SetConfigReadOnly(this);
}
return readOnly;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_config_SetConfig.java
|
240 |
assertTrueEventually(new AssertTask() {
public void run() throws Exception {
assertEquals(1, map.size());
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceSubmitTest.java
|
696 |
public class BulkRequest extends ActionRequest<BulkRequest> {
private static final int REQUEST_OVERHEAD = 50;
final List<ActionRequest> requests = Lists.newArrayList();
List<Object> payloads = null;
protected TimeValue timeout = BulkShardRequest.DEFAULT_TIMEOUT;
private ReplicationType replicationType = ReplicationType.DEFAULT;
private WriteConsistencyLevel consistencyLevel = WriteConsistencyLevel.DEFAULT;
private boolean refresh = false;
private long sizeInBytes = 0;
/**
* Adds a list of requests to be executed. Either index or delete requests.
*/
public BulkRequest add(ActionRequest... requests) {
for (ActionRequest request : requests) {
add(request, null);
}
return this;
}
public BulkRequest add(ActionRequest request) {
return add(request, null);
}
public BulkRequest add(ActionRequest request, @Nullable Object payload) {
if (request instanceof IndexRequest) {
add((IndexRequest) request, payload);
} else if (request instanceof DeleteRequest) {
add((DeleteRequest) request, payload);
} else if (request instanceof UpdateRequest) {
add((UpdateRequest) request, payload);
} else {
throw new ElasticsearchIllegalArgumentException("No support for request [" + request + "]");
}
return this;
}
/**
* Adds a list of requests to be executed. Either index or delete requests.
*/
public BulkRequest add(Iterable<ActionRequest> requests) {
for (ActionRequest request : requests) {
if (request instanceof IndexRequest) {
add((IndexRequest) request);
} else if (request instanceof DeleteRequest) {
add((DeleteRequest) request);
} else {
throw new ElasticsearchIllegalArgumentException("No support for request [" + request + "]");
}
}
return this;
}
/**
* Adds an {@link IndexRequest} to the list of actions to execute. Follows the same behavior of {@link IndexRequest}
* (for example, if no id is provided, one will be generated, or usage of the create flag).
*/
public BulkRequest add(IndexRequest request) {
request.beforeLocalFork();
return internalAdd(request, null);
}
public BulkRequest add(IndexRequest request, @Nullable Object payload) {
request.beforeLocalFork();
return internalAdd(request, payload);
}
BulkRequest internalAdd(IndexRequest request, @Nullable Object payload) {
requests.add(request);
addPayload(payload);
sizeInBytes += request.source().length() + REQUEST_OVERHEAD;
return this;
}
/**
* Adds an {@link UpdateRequest} to the list of actions to execute.
*/
public BulkRequest add(UpdateRequest request) {
request.beforeLocalFork();
return internalAdd(request, null);
}
public BulkRequest add(UpdateRequest request, @Nullable Object payload) {
request.beforeLocalFork();
return internalAdd(request, payload);
}
BulkRequest internalAdd(UpdateRequest request, @Nullable Object payload) {
requests.add(request);
addPayload(payload);
if (request.doc() != null) {
sizeInBytes += request.doc().source().length();
}
if (request.upsertRequest() != null) {
sizeInBytes += request.upsertRequest().source().length();
}
if (request.script() != null) {
sizeInBytes += request.script().length() * 2;
}
return this;
}
/**
* Adds an {@link DeleteRequest} to the list of actions to execute.
*/
public BulkRequest add(DeleteRequest request) {
return add(request, null);
}
public BulkRequest add(DeleteRequest request, @Nullable Object payload) {
requests.add(request);
addPayload(payload);
sizeInBytes += REQUEST_OVERHEAD;
return this;
}
private void addPayload(Object payload) {
if (payloads == null) {
if (payload == null) {
return;
}
payloads = new ArrayList<Object>(requests.size() + 10);
// add requests#size-1 elements to the payloads if it null (we add for an *existing* request)
for (int i = 1; i < requests.size(); i++) {
payloads.add(null);
}
}
payloads.add(payload);
}
/**
* The list of requests in this bulk request.
*/
public List<ActionRequest> requests() {
return this.requests;
}
/**
* The list of optional payloads associated with requests in the same order as the requests. Note, elements within
* it might be null if no payload has been provided.
* <p/>
* Note, if no payloads have been provided, this method will return null (as to conserve memory overhead).
*/
@Nullable
public List<Object> payloads() {
return this.payloads;
}
/**
* The number of actions in the bulk request.
*/
public int numberOfActions() {
return requests.size();
}
/**
* The estimated size in bytes of the bulk request.
*/
public long estimatedSizeInBytes() {
return sizeInBytes;
}
/**
* Adds a framed data in binary format
*/
public BulkRequest add(byte[] data, int from, int length, boolean contentUnsafe) throws Exception {
return add(data, from, length, contentUnsafe, null, null);
}
/**
* Adds a framed data in binary format
*/
public BulkRequest add(byte[] data, int from, int length, boolean contentUnsafe, @Nullable String defaultIndex, @Nullable String defaultType) throws Exception {
return add(new BytesArray(data, from, length), contentUnsafe, defaultIndex, defaultType);
}
/**
* Adds a framed data in binary format
*/
public BulkRequest add(BytesReference data, boolean contentUnsafe, @Nullable String defaultIndex, @Nullable String defaultType) throws Exception {
return add(data, contentUnsafe, defaultIndex, defaultType, null, null, true);
}
/**
* Adds a framed data in binary format
*/
public BulkRequest add(BytesReference data, boolean contentUnsafe, @Nullable String defaultIndex, @Nullable String defaultType, boolean allowExplicitIndex) throws Exception {
return add(data, contentUnsafe, defaultIndex, defaultType, null, null, allowExplicitIndex);
}
public BulkRequest add(BytesReference data, boolean contentUnsafe, @Nullable String defaultIndex, @Nullable String defaultType, @Nullable String defaultRouting, @Nullable Object payload, boolean allowExplicitIndex) throws Exception {
XContent xContent = XContentFactory.xContent(data);
int from = 0;
int length = data.length();
byte marker = xContent.streamSeparator();
while (true) {
int nextMarker = findNextMarker(marker, from, data, length);
if (nextMarker == -1) {
break;
}
// now parse the action
XContentParser parser = xContent.createParser(data.slice(from, nextMarker - from));
try {
// move pointers
from = nextMarker + 1;
// Move to START_OBJECT
XContentParser.Token token = parser.nextToken();
if (token == null) {
continue;
}
assert token == XContentParser.Token.START_OBJECT;
// Move to FIELD_NAME, that's the action
token = parser.nextToken();
assert token == XContentParser.Token.FIELD_NAME;
String action = parser.currentName();
String index = defaultIndex;
String type = defaultType;
String id = null;
String routing = defaultRouting;
String parent = null;
String timestamp = null;
Long ttl = null;
String opType = null;
long version = Versions.MATCH_ANY;
VersionType versionType = VersionType.INTERNAL;
int retryOnConflict = 0;
// at this stage, next token can either be END_OBJECT (and use default index and type, with auto generated id)
// or START_OBJECT which will have another set of parameters
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if ("_index".equals(currentFieldName)) {
if (!allowExplicitIndex) {
throw new ElasticsearchIllegalArgumentException("explicit index in bulk is not allowed");
}
index = parser.text();
} else if ("_type".equals(currentFieldName)) {
type = parser.text();
} else if ("_id".equals(currentFieldName)) {
id = parser.text();
} else if ("_routing".equals(currentFieldName) || "routing".equals(currentFieldName)) {
routing = parser.text();
} else if ("_parent".equals(currentFieldName) || "parent".equals(currentFieldName)) {
parent = parser.text();
} else if ("_timestamp".equals(currentFieldName) || "timestamp".equals(currentFieldName)) {
timestamp = parser.text();
} else if ("_ttl".equals(currentFieldName) || "ttl".equals(currentFieldName)) {
if (parser.currentToken() == XContentParser.Token.VALUE_STRING) {
ttl = TimeValue.parseTimeValue(parser.text(), null).millis();
} else {
ttl = parser.longValue();
}
} else if ("op_type".equals(currentFieldName) || "opType".equals(currentFieldName)) {
opType = parser.text();
} else if ("_version".equals(currentFieldName) || "version".equals(currentFieldName)) {
version = parser.longValue();
} else if ("_version_type".equals(currentFieldName) || "_versionType".equals(currentFieldName) || "version_type".equals(currentFieldName) || "versionType".equals(currentFieldName)) {
versionType = VersionType.fromString(parser.text());
} else if ("_retry_on_conflict".equals(currentFieldName) || "_retryOnConflict".equals(currentFieldName)) {
retryOnConflict = parser.intValue();
}
}
}
if ("delete".equals(action)) {
add(new DeleteRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType), payload);
} else {
nextMarker = findNextMarker(marker, from, data, length);
if (nextMarker == -1) {
break;
}
// order is important, we set parent after routing, so routing will be set to parent if not set explicitly
// we use internalAdd so we don't fork here, this allows us not to copy over the big byte array to small chunks
// of index request. All index requests are still unsafe if applicable.
if ("index".equals(action)) {
if (opType == null) {
internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).timestamp(timestamp).ttl(ttl).version(version).versionType(versionType)
.source(data.slice(from, nextMarker - from), contentUnsafe), payload);
} else {
internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).timestamp(timestamp).ttl(ttl).version(version).versionType(versionType)
.create("create".equals(opType))
.source(data.slice(from, nextMarker - from), contentUnsafe), payload);
}
} else if ("create".equals(action)) {
internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).timestamp(timestamp).ttl(ttl).version(version).versionType(versionType)
.create(true)
.source(data.slice(from, nextMarker - from), contentUnsafe), payload);
} else if ("update".equals(action)) {
UpdateRequest updateRequest = new UpdateRequest(index, type, id).routing(routing).parent(parent).retryOnConflict(retryOnConflict)
.version(version).versionType(versionType)
.source(data.slice(from, nextMarker - from));
IndexRequest upsertRequest = updateRequest.upsertRequest();
if (upsertRequest != null) {
upsertRequest.routing(routing);
upsertRequest.parent(parent); // order is important, set it after routing, so it will set the routing
upsertRequest.timestamp(timestamp);
upsertRequest.ttl(ttl);
upsertRequest.version(version);
upsertRequest.versionType(versionType);
}
IndexRequest doc = updateRequest.doc();
if (doc != null) {
doc.routing(routing);
doc.parent(parent); // order is important, set it after routing, so it will set the routing
doc.timestamp(timestamp);
doc.ttl(ttl);
doc.version(version);
doc.versionType(versionType);
}
internalAdd(updateRequest, payload);
}
// move pointers
from = nextMarker + 1;
}
} finally {
parser.close();
}
}
return this;
}
/**
* Sets the consistency level of write. Defaults to {@link org.elasticsearch.action.WriteConsistencyLevel#DEFAULT}
*/
public BulkRequest consistencyLevel(WriteConsistencyLevel consistencyLevel) {
this.consistencyLevel = consistencyLevel;
return this;
}
public WriteConsistencyLevel consistencyLevel() {
return this.consistencyLevel;
}
/**
* Should a refresh be executed post this bulk operation causing the operations to
* be searchable. Note, heavy indexing should not set this to <tt>true</tt>. Defaults
* to <tt>false</tt>.
*/
public BulkRequest refresh(boolean refresh) {
this.refresh = refresh;
return this;
}
public boolean refresh() {
return this.refresh;
}
/**
* Set the replication type for this operation.
*/
public BulkRequest replicationType(ReplicationType replicationType) {
this.replicationType = replicationType;
return this;
}
public ReplicationType replicationType() {
return this.replicationType;
}
/**
* A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>.
*/
public final BulkRequest timeout(TimeValue timeout) {
this.timeout = timeout;
return this;
}
/**
* A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>.
*/
public final BulkRequest timeout(String timeout) {
return timeout(TimeValue.parseTimeValue(timeout, null));
}
public TimeValue timeout() {
return timeout;
}
private int findNextMarker(byte marker, int from, BytesReference data, int length) {
for (int i = from; i < length; i++) {
if (data.get(i) == marker) {
return i;
}
}
return -1;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (requests.isEmpty()) {
validationException = addValidationError("no requests added", validationException);
}
for (int i = 0; i < requests.size(); i++) {
ActionRequestValidationException ex = requests.get(i).validate();
if (ex != null) {
if (validationException == null) {
validationException = new ActionRequestValidationException();
}
validationException.addValidationErrors(ex.validationErrors());
}
}
return validationException;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
replicationType = ReplicationType.fromId(in.readByte());
consistencyLevel = WriteConsistencyLevel.fromId(in.readByte());
int size = in.readVInt();
for (int i = 0; i < size; i++) {
byte type = in.readByte();
if (type == 0) {
IndexRequest request = new IndexRequest();
request.readFrom(in);
requests.add(request);
} else if (type == 1) {
DeleteRequest request = new DeleteRequest();
request.readFrom(in);
requests.add(request);
} else if (type == 2) {
UpdateRequest request = new UpdateRequest();
request.readFrom(in);
requests.add(request);
}
}
refresh = in.readBoolean();
timeout = TimeValue.readTimeValue(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeByte(replicationType.id());
out.writeByte(consistencyLevel.id());
out.writeVInt(requests.size());
for (ActionRequest request : requests) {
if (request instanceof IndexRequest) {
out.writeByte((byte) 0);
} else if (request instanceof DeleteRequest) {
out.writeByte((byte) 1);
} else if (request instanceof UpdateRequest) {
out.writeByte((byte) 2);
}
request.writeTo(out);
}
out.writeBoolean(refresh);
timeout.writeTo(out);
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_bulk_BulkRequest.java
|
528 |
ex.execute(new Runnable() {
public void run() {
multiMap.put(key, "value");
final TransactionContext context = client.newTransactionContext();
try {
context.beginTransaction();
final TransactionalMultiMap txnMultiMap = context.getMultiMap(mapName);
txnMultiMap.put(key, "value");
txnMultiMap.put(key, "value1");
txnMultiMap.put(key, "value2");
assertEquals(3, txnMultiMap.get(key).size());
context.commitTransaction();
assertEquals(3, multiMap.get(key).size());
} catch (Exception e) {
error.compareAndSet(null, e);
} finally {
latch.countDown();
}
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientTxnMultiMapTest.java
|
1,071 |
createIndexAction.execute(new CreateIndexRequest(request.index()).cause("auto(update api)").masterNodeTimeout(request.timeout()), new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse result) {
innerExecute(request, listener);
}
@Override
public void onFailure(Throwable e) {
if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) {
// we have the index, do it
try {
innerExecute(request, listener);
} catch (Throwable e1) {
listener.onFailure(e1);
}
} else {
listener.onFailure(e);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_update_TransportUpdateAction.java
|
3,250 |
public class GeoDistanceComparator extends NumberComparatorBase<Double> {
protected final IndexGeoPointFieldData<?> indexFieldData;
protected final double lat;
protected final double lon;
protected final DistanceUnit unit;
protected final GeoDistance geoDistance;
protected final GeoDistance.FixedSourceDistance fixedSourceDistance;
protected final SortMode sortMode;
private static final Double MISSING_VALUE = Double.MAX_VALUE;
private final double[] values;
private double bottom;
private GeoDistanceValues geoDistanceValues;
public GeoDistanceComparator(int numHits, IndexGeoPointFieldData<?> indexFieldData, double lat, double lon, DistanceUnit unit, GeoDistance geoDistance, SortMode sortMode) {
this.values = new double[numHits];
this.indexFieldData = indexFieldData;
this.lat = lat;
this.lon = lon;
this.unit = unit;
this.geoDistance = geoDistance;
this.fixedSourceDistance = geoDistance.fixedSourceDistance(lat, lon, unit);
this.sortMode = sortMode;
}
@Override
public FieldComparator<Double> setNextReader(AtomicReaderContext context) throws IOException {
GeoPointValues readerValues = indexFieldData.load(context).getGeoPointValues();
if (readerValues.isMultiValued()) {
geoDistanceValues = new MV(readerValues, fixedSourceDistance, sortMode);
} else {
geoDistanceValues = new SV(readerValues, fixedSourceDistance);
}
return this;
}
@Override
public int compare(int slot1, int slot2) {
return Double.compare(values[slot1], values[slot2]);
}
@Override
public int compareBottom(int doc) {
final double v2 = geoDistanceValues.computeDistance(doc);
return Double.compare(bottom, v2);
}
@Override
public int compareDocToValue(int doc, Double distance2) throws IOException {
double distance1 = geoDistanceValues.computeDistance(doc);
return Double.compare(distance1, distance2);
}
@Override
public void copy(int slot, int doc) {
values[slot] = geoDistanceValues.computeDistance(doc);
}
@Override
public void setBottom(final int bottom) {
this.bottom = values[bottom];
}
@Override
public Double value(int slot) {
return values[slot];
}
@Override
public void add(int slot, int doc) {
values[slot] += geoDistanceValues.computeDistance(doc);
}
@Override
public void divide(int slot, int divisor) {
values[slot] /= divisor;
}
@Override
public void missing(int slot) {
values[slot] = MISSING_VALUE;
}
@Override
public int compareBottomMissing() {
return Double.compare(bottom, MISSING_VALUE);
}
// Computes the distance based on geo points.
// Due to this abstractions the geo distance comparator doesn't need to deal with whether fields have one
// or multiple geo points per document.
private static abstract class GeoDistanceValues {
protected final GeoPointValues readerValues;
protected final GeoDistance.FixedSourceDistance fixedSourceDistance;
protected GeoDistanceValues(GeoPointValues readerValues, GeoDistance.FixedSourceDistance fixedSourceDistance) {
this.readerValues = readerValues;
this.fixedSourceDistance = fixedSourceDistance;
}
public abstract double computeDistance(int doc);
}
// Deals with one geo point per document
private static final class SV extends GeoDistanceValues {
SV(GeoPointValues readerValues, GeoDistance.FixedSourceDistance fixedSourceDistance) {
super(readerValues, fixedSourceDistance);
}
@Override
public double computeDistance(int doc) {
int numValues = readerValues.setDocument(doc);
double result = MISSING_VALUE;
for (int i = 0; i < numValues; i++) {
GeoPoint geoPoint = readerValues.nextValue();
return fixedSourceDistance.calculate(geoPoint.lat(), geoPoint.lon());
}
return MISSING_VALUE;
}
}
// Deals with more than one geo point per document
private static final class MV extends GeoDistanceValues {
private final SortMode sortMode;
MV(GeoPointValues readerValues, GeoDistance.FixedSourceDistance fixedSourceDistance, SortMode sortMode) {
super(readerValues, fixedSourceDistance);
this.sortMode = sortMode;
}
@Override
public double computeDistance(int doc) {
final int length = readerValues.setDocument(doc);
double distance = sortMode.startDouble();
double result = MISSING_VALUE;
for (int i = 0; i < length; i++) {
GeoPoint point = readerValues.nextValue();
result = distance = sortMode.apply(distance, fixedSourceDistance.calculate(point.lat(), point.lon()));
}
return sortMode.reduce(result, length);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_fielddata_fieldcomparator_GeoDistanceComparator.java
|
21 |
}), new Function<ByteEntry, Vertex>() {
@Override
public Vertex apply(@Nullable ByteEntry entry) {
return new ByteVertex(entry.key.getLong(8), tx);
}
});
| 0true
|
titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java
|
1,475 |
public class RoutingNode implements Iterable<MutableShardRouting> {
private final String nodeId;
private final DiscoveryNode node;
private final List<MutableShardRouting> shards;
public RoutingNode(String nodeId, DiscoveryNode node) {
this(nodeId, node, new ArrayList<MutableShardRouting>());
}
public RoutingNode(String nodeId, DiscoveryNode node, List<MutableShardRouting> shards) {
this.nodeId = nodeId;
this.node = node;
this.shards = shards;
}
@Override
public Iterator<MutableShardRouting> iterator() {
return Iterators.unmodifiableIterator(shards.iterator());
}
Iterator<MutableShardRouting> mutableIterator() {
return shards.iterator();
}
/**
* Returns the nodes {@link DiscoveryNode}.
*
* @return discoveryNode of this node
*/
public DiscoveryNode node() {
return this.node;
}
/**
* Get the id of this node
* @return id of the node
*/
public String nodeId() {
return this.nodeId;
}
public int size() {
return shards.size();
}
/**
* Add a new shard to this node
* @param shard Shard to crate on this Node
*/
void add(MutableShardRouting shard) {
// TODO use Set with ShardIds for faster lookup.
for (MutableShardRouting shardRouting : shards) {
if (shardRouting.shardId().equals(shard.shardId())) {
throw new ElasticsearchIllegalStateException("Trying to add a shard [" + shard.shardId().index().name() + "][" + shard.shardId().id() + "] to a node [" + nodeId + "] where it already exists");
}
}
shards.add(shard);
}
/**
* Determine the number of shards with a specific state
* @param states set of states which should be counted
* @return number of shards
*/
public int numberOfShardsWithState(ShardRoutingState... states) {
int count = 0;
for (MutableShardRouting shardEntry : this) {
for (ShardRoutingState state : states) {
if (shardEntry.state() == state) {
count++;
}
}
}
return count;
}
/**
* Determine the shards with a specific state
* @param states set of states which should be listed
* @return List of shards
*/
public List<MutableShardRouting> shardsWithState(ShardRoutingState... states) {
List<MutableShardRouting> shards = newArrayList();
for (MutableShardRouting shardEntry : this) {
for (ShardRoutingState state : states) {
if (shardEntry.state() == state) {
shards.add(shardEntry);
}
}
}
return shards;
}
/**
* Determine the shards of an index with a specific state
* @param index id of the index
* @param states set of states which should be listed
* @return a list of shards
*/
public List<MutableShardRouting> shardsWithState(String index, ShardRoutingState... states) {
List<MutableShardRouting> shards = newArrayList();
for (MutableShardRouting shardEntry : this) {
if (!shardEntry.index().equals(index)) {
continue;
}
for (ShardRoutingState state : states) {
if (shardEntry.state() == state) {
shards.add(shardEntry);
}
}
}
return shards;
}
/**
* The number of shards on this node that will not be eventually relocated.
*/
public int numberOfOwningShards() {
int count = 0;
for (MutableShardRouting shardEntry : this) {
if (shardEntry.state() != ShardRoutingState.RELOCATING) {
count++;
}
}
return count;
}
public String prettyPrint() {
StringBuilder sb = new StringBuilder();
sb.append("-----node_id[").append(nodeId).append("][" + (node == null ? "X" : "V") + "]\n");
for (MutableShardRouting entry : shards) {
sb.append("--------").append(entry.shortSummary()).append('\n');
}
return sb.toString();
}
public MutableShardRouting get(int i) {
return shards.get(i) ;
}
public Collection<MutableShardRouting> copyShards() {
return new ArrayList<MutableShardRouting>(shards);
}
public boolean isEmpty() {
return shards.isEmpty();
}
}
| 0true
|
src_main_java_org_elasticsearch_cluster_routing_RoutingNode.java
|
464 |
public class CeylonNavigatorLabelProvider extends
CeylonLabelProvider implements ICommonLabelProvider {
ICommonContentExtensionSite extensionSite;
public CeylonNavigatorLabelProvider() {
super(true); // small images
}
@Override
public StyledString getStyledText(Object element) {
if (element instanceof ExternalModuleNode) {
ExternalModuleNode externalModule = (ExternalModuleNode) element;
JDTModule jdtModule = externalModule.getModule();
JDTModule mod = ((ExternalModuleNode) element).getModule();
String name = super.getStyledText(mod).toString();
StyledString moduleText = new StyledString(name);
if (jdtModule != null) {
moduleText.append(" - " + jdtModule.getVersion(), QUALIFIER_STYLER);
}
return moduleText;
}
if (element instanceof SourceModuleNode) {
JDTModule module = ((SourceModuleNode) element).getModule();
if (module==null) {
return new StyledString(((SourceModuleNode) element).getElementName());
}
else {
String name = super.getStyledText(module).toString();
StyledString result = new StyledString(name);
if (module != null && module.isDefaultModule()) {
result = result.insert('(', 0).append(')').append("");
}
return result;
}
}
if (element instanceof RepositoryNode) {
RepositoryNode repoNode = (RepositoryNode) element;
String stringToDisplay = getRepositoryString(repoNode);
return new StyledString(stringToDisplay);
}
if (element instanceof Package || element instanceof IPackageFragment) {
return new StyledString(super.getStyledText(element).getString());
}
if (element instanceof CeylonArchiveFileStore) {
CeylonArchiveFileStore archiveFileStore = (CeylonArchiveFileStore)element;
if (archiveFileStore.getParent() == null) {
return new StyledString("Ceylon Sources").append(" - " + archiveFileStore.getArchivePath().toOSString(), QUALIFIER_STYLER);
}
return new StyledString(archiveFileStore.getName());
}
if (element instanceof JarPackageFragmentRoot) {
JarPackageFragmentRoot jpfr = (JarPackageFragmentRoot) element;
if (ArtifactContext.CAR.substring(1).equalsIgnoreCase(jpfr.getPath().getFileExtension())) {
return new StyledString("Java Binaries").append(" - " + jpfr.getPath().toOSString(), QUALIFIER_STYLER);
} else {
return getJavaNavigatorLabelProvider().getStyledText(element);
}
}
if (element instanceof IProject || element instanceof IJavaProject) {
return getJavaNavigatorLabelProvider().getStyledText(element);
}
StyledString styledString = super.getStyledText(element);
if (styledString.getString().equals("<something>")) {
StyledString javaResult = getJavaNavigatorLabelProvider().getStyledText(element);
if (! javaResult.getString().trim().isEmpty()) {
return javaResult;
}
}
return styledString;
}
private String getRepositoryString(RepositoryNode repoNode) {
String displayString = repoNode.getDisplayString();
String stringToDisplay = null;
if (Constants.REPO_URL_CEYLON.equals(displayString)) {
stringToDisplay = "Herd Modules";
}
if (stringToDisplay == null && JDKRepository.JDK_REPOSITORY_DISPLAY_STRING.equals(displayString)) {
stringToDisplay = "JDK Modules";
}
if (stringToDisplay == null && CeylonBuilder.getInterpolatedCeylonSystemRepo(repoNode.project).equals(displayString)) {
stringToDisplay = "System Modules";
}
if (stringToDisplay == null && CeylonBuilder.getCeylonModulesOutputDirectory(repoNode.project).getAbsolutePath().equals(displayString)) {
stringToDisplay = "Output Modules";
}
if (stringToDisplay == null && CeylonProjectConfig.get(repoNode.project).getMergedRepositories().getCacheRepoDir().getAbsolutePath().equals(displayString)) {
stringToDisplay = "Cached Modules";
}
if (stringToDisplay == null && CeylonProjectConfig.get(repoNode.project).getMergedRepositories().getUserRepoDir().getAbsolutePath().equals(displayString)) {
stringToDisplay = "User Modules";
}
if (stringToDisplay == null) {
try {
for (IProject referencedProject: repoNode.project.getReferencedProjects()) {
if (referencedProject.isOpen() && CeylonNature.isEnabled(referencedProject)) {
if (CeylonBuilder.getCeylonModulesOutputDirectory(referencedProject).getAbsolutePath().equals(displayString)) {
stringToDisplay = "Modules of Referenced Project : " + referencedProject.getName() + "";
break;
}
}
}
} catch (CoreException e) {
}
}
if (stringToDisplay == null) {
for (Repositories.Repository repo : CeylonProjectConfig.get(repoNode.project).getMergedRepositories().getLocalLookupRepositories()) {
if (repo.getUrl().startsWith("./") && repo.getUrl().length() > 2) {
IPath relativePath = Path.fromPortableString(repo.getUrl().substring(2));
IFolder folder = repoNode.project.getFolder(relativePath);
if (folder.exists() && folder.getLocation().toFile().getAbsolutePath().equals(displayString)) {
stringToDisplay = "Local Repository : " + relativePath.toString() + "";
break;
}
}
}
}
if (stringToDisplay == null && NodeUtils.UNKNOWN_REPOSITORY.equals(displayString)) {
stringToDisplay = "Unknown Repository";
}
if (stringToDisplay == null) {
stringToDisplay = displayString;
}
return stringToDisplay;
}
@Override
public Image getImage(Object element) {
JavaNavigatorLabelProvider javaProvider = getJavaNavigatorLabelProvider();
if (element instanceof IProject || element instanceof IJavaProject) {
Image javaContributedImage = javaProvider.getImage(element);
if (javaContributedImage != null) {
return javaContributedImage;
}
}
if (element instanceof IPackageFragment &&
! CeylonBuilder.isInSourceFolder((IPackageFragment)element)) {
return javaProvider.getImage(element);
}
if (element instanceof ExternalModuleNode) {
return super.getImage(((ExternalModuleNode)element).getModule());
}
if (element instanceof SourceModuleNode) {
int decorationAttributes = 0;
for (Object child : getContentProvider().getChildren(element)) {
if (!hasPipelinedChildren(child)) {
continue;
}
int childValue = getDecorationAttributes(child);
if ((childValue & ERROR) != 0) {
decorationAttributes = ERROR;
break;
}
if ((childValue & WARNING) != 0) {
decorationAttributes = WARNING;
}
}
JDTModule module = ((SourceModuleNode)element).getModule();
if (module==null) {
return getDecoratedImage(CEYLON_MODULE, decorationAttributes, true);
}
else {
return getDecoratedImage(getImageKey(module), decorationAttributes, true);
}
}
if (element instanceof CeylonArchiveFileStore) {
CeylonArchiveFileStore archiveFileStore = (CeylonArchiveFileStore)element;
if (archiveFileStore.getParent() != null
&& ! archiveFileStore.fetchInfo().isDirectory()) {
IFolder sourceArchiveFolder = ExternalSourceArchiveManager.getExternalSourceArchiveManager().getSourceArchive(archiveFileStore.getArchivePath());
if (sourceArchiveFolder != null && sourceArchiveFolder.exists()) {
IResource file = sourceArchiveFolder.findMember(archiveFileStore.getEntryPath());
if (file instanceof IFile) {
element = file;
}
}
}
}
if (element instanceof IFile) {
if (! CeylonBuilder.isCeylon((IFile) element)) {
return javaProvider.getImage(element);
}
}
return super.getImage(element);
}
private boolean hasPipelinedChildren(Object child) {
return getContentProvider().hasPipelinedChildren(child,
getJavaNavigatorContentProvider().hasChildren(child));
}
@Override
protected String getImageKey(Object element) {
if (element instanceof RepositoryNode) {
return RUNTIME_OBJ;
}
if (element instanceof IPackageFragment) {
return CEYLON_PACKAGE;
}
if (element instanceof CeylonArchiveFileStore) {
CeylonArchiveFileStore archiveFileStore = (CeylonArchiveFileStore)element;
if (archiveFileStore.getParent() == null) {
return CEYLON_SOURCE_ARCHIVE;
} else {
if (archiveFileStore.fetchInfo().isDirectory()) {
return CEYLON_PACKAGE;
} else {
return CEYLON_FILE;
}
}
}
if (element instanceof JarPackageFragmentRoot) {
return CEYLON_BINARY_ARCHIVE;
}
return super.getImageKey(element);
}
@Override
public void restoreState(IMemento aMemento) {
// TODO Auto-generated method stub
}
@Override
public void saveState(IMemento aMemento) {
// TODO Auto-generated method stub
}
@Override
public String getDescription(Object anElement) {
if (anElement instanceof RepositoryNode) {
Repository repo = ((RepositoryNode)anElement).getRepository();
if (repo != null) {
return "Repository path : " + repo.getDisplayString();
}
}
if (anElement instanceof CeylonArchiveFileStore) {
CeylonArchiveFileStore archive = (CeylonArchiveFileStore)anElement;
if (archive.getParent() == null) {
return archive.getArchivePath().toOSString();
}
}
return null;
}
@Override
public void init(ICommonContentExtensionSite aConfig) {
extensionSite = aConfig;
}
private INavigatorContentExtension getJavaNavigatorExtension() {
@SuppressWarnings("unchecked")
Set<INavigatorContentExtension> set = extensionSite.getService().findContentExtensionsByTriggerPoint(JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()));
for (INavigatorContentExtension extension : set) {
if (extension.getDescriptor().equals(extensionSite.getExtension().getDescriptor().getOverriddenDescriptor())) {
return extension;
}
}
return null;
}
private JavaNavigatorLabelProvider getJavaNavigatorLabelProvider() {
INavigatorContentExtension javaExtension = getJavaNavigatorExtension();
if (javaExtension != null) {
return (JavaNavigatorLabelProvider) javaExtension.getLabelProvider();
}
return null;
}
private JavaNavigatorContentProvider getJavaNavigatorContentProvider() {
INavigatorContentExtension javaExtension = getJavaNavigatorExtension();
if (javaExtension != null) {
return (JavaNavigatorContentProvider) javaExtension.getContentProvider();
}
return null;
}
private CeylonNavigatorContentProvider getContentProvider() {
return (CeylonNavigatorContentProvider) extensionSite.getExtension().getContentProvider();
}
}
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_navigator_CeylonNavigatorLabelProvider.java
|
220 |
Arrays.sort(passages, new Comparator<Passage>() {
@Override
public int compare(Passage left, Passage right) {
return left.startOffset - right.startOffset;
}
});
| 0true
|
src_main_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighter.java
|
234 |
private class TransactionFactory extends XaTransactionFactory
{
@Override
public XaTransaction create( long lastCommittedTxWhenTransactionStarted, TransactionState state )
{
return new NeoStoreTransaction( lastCommittedTxWhenTransactionStarted, getLogicalLog(), state,
neoStore, cacheAccess, indexingService, labelScanStore, integrityValidator,
(KernelTransactionImplementation)kernel.newTransaction(), locks );
}
@Override
public void recoveryComplete()
{
msgLog.debug( "Recovery complete, "
+ "all transactions have been resolved" );
msgLog.debug( "Rebuilding id generators as needed. "
+ "This can take a while for large stores..." );
forceEverything();
neoStore.makeStoreOk();
neoStore.setVersion( xaContainer.getLogicalLog().getHighestLogVersion() );
msgLog.debug( "Rebuild of id generators complete." );
}
@Override
public long getCurrentVersion()
{
return neoStore.getVersion();
}
@Override
public long getAndSetNewVersion()
{
return neoStore.incrementVersion();
}
@Override
public void setVersion( long version )
{
neoStore.setVersion( version );
}
@Override
public void flushAll()
{
forceEverything();
}
@Override
public long getLastCommittedTx()
{
return neoStore.getLastCommittedTx();
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreXaDataSource.java
|
6,109 |
public class SnapshotsService extends AbstractComponent implements ClusterStateListener {
private final ClusterService clusterService;
private final RepositoriesService repositoriesService;
private final ThreadPool threadPool;
private final IndicesService indicesService;
private final TransportService transportService;
private volatile ImmutableMap<SnapshotId, SnapshotShards> shardSnapshots = ImmutableMap.of();
private final CopyOnWriteArrayList<SnapshotCompletionListener> snapshotCompletionListeners = new CopyOnWriteArrayList<SnapshotCompletionListener>();
@Inject
public SnapshotsService(Settings settings, ClusterService clusterService, RepositoriesService repositoriesService, ThreadPool threadPool,
IndicesService indicesService, TransportService transportService) {
super(settings);
this.clusterService = clusterService;
this.repositoriesService = repositoriesService;
this.threadPool = threadPool;
this.indicesService = indicesService;
this.transportService = transportService;
transportService.registerHandler(UpdateSnapshotStateRequestHandler.ACTION, new UpdateSnapshotStateRequestHandler());
// addLast to make sure that Repository will be created before snapshot
clusterService.addLast(this);
}
/**
* Retrieves snapshot from repository
*
* @param snapshotId snapshot id
* @return snapshot
* @throws SnapshotMissingException if snapshot is not found
*/
public Snapshot snapshot(SnapshotId snapshotId) {
return repositoriesService.repository(snapshotId.getRepository()).readSnapshot(snapshotId);
}
/**
* Returns a list of snapshots from repository sorted by snapshot creation date
*
* @param repositoryName repository name
* @return list of snapshots
*/
public ImmutableList<Snapshot> snapshots(String repositoryName) {
ArrayList<Snapshot> snapshotList = newArrayList();
Repository repository = repositoriesService.repository(repositoryName);
ImmutableList<SnapshotId> snapshotIds = repository.snapshots();
for (SnapshotId snapshotId : snapshotIds) {
snapshotList.add(repository.readSnapshot(snapshotId));
}
CollectionUtil.timSort(snapshotList);
return ImmutableList.copyOf(snapshotList);
}
/**
* Initializes the snapshotting process.
* <p/>
* This method is used by clients to start snapshot. It makes sure that there is no snapshots are currently running and
* creates a snapshot record in cluster state metadata.
*
* @param request snapshot request
* @param listener snapshot creation listener
*/
public void createSnapshot(final SnapshotRequest request, final CreateSnapshotListener listener) {
final SnapshotId snapshotId = new SnapshotId(request.repository(), request.name());
clusterService.submitStateUpdateTask(request.cause(), new TimeoutClusterStateUpdateTask() {
private SnapshotMetaData.Entry newSnapshot = null;
@Override
public ClusterState execute(ClusterState currentState) {
validate(request, currentState);
MetaData metaData = currentState.metaData();
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
SnapshotMetaData snapshots = metaData.custom(SnapshotMetaData.TYPE);
if (snapshots == null || snapshots.entries().isEmpty()) {
// Store newSnapshot here to be processed in clusterStateProcessed
ImmutableList<String> indices = ImmutableList.copyOf(metaData.concreteIndices(request.indices(), request.indicesOptions()));
logger.trace("[{}][{}] creating snapshot for indices [{}]", request.repository(), request.name(), indices);
newSnapshot = new SnapshotMetaData.Entry(snapshotId, request.includeGlobalState(), State.INIT, indices, null);
snapshots = new SnapshotMetaData(newSnapshot);
} else {
// TODO: What should we do if a snapshot is already running?
throw new ConcurrentSnapshotExecutionException(snapshotId, "a snapshot is already running");
}
mdBuilder.putCustom(SnapshotMetaData.TYPE, snapshots);
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.warn("[{}][{}] failed to create snapshot", t, request.repository(), request.name());
newSnapshot = null;
listener.onFailure(t);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, final ClusterState newState) {
if (newSnapshot != null) {
threadPool.executor(ThreadPool.Names.SNAPSHOT).execute(new Runnable() {
@Override
public void run() {
beginSnapshot(newState, newSnapshot, request.partial, listener);
}
});
}
}
@Override
public TimeValue timeout() {
return request.masterNodeTimeout();
}
});
}
/**
* Validates snapshot request
*
* @param request snapshot request
* @param state current cluster state
* @throws org.elasticsearch.ElasticsearchException
*/
private void validate(SnapshotRequest request, ClusterState state) throws ElasticsearchException {
RepositoriesMetaData repositoriesMetaData = state.getMetaData().custom(RepositoriesMetaData.TYPE);
if (repositoriesMetaData == null || repositoriesMetaData.repository(request.repository()) == null) {
throw new RepositoryMissingException(request.repository());
}
if (!Strings.hasLength(request.name())) {
throw new InvalidSnapshotNameException(new SnapshotId(request.repository(), request.name()), "cannot be empty");
}
if (request.name().contains(" ")) {
throw new InvalidSnapshotNameException(new SnapshotId(request.repository(), request.name()), "must not contain whitespace");
}
if (request.name().contains(",")) {
throw new InvalidSnapshotNameException(new SnapshotId(request.repository(), request.name()), "must not contain ','");
}
if (request.name().contains("#")) {
throw new InvalidSnapshotNameException(new SnapshotId(request.repository(), request.name()), "must not contain '#'");
}
if (request.name().charAt(0) == '_') {
throw new InvalidSnapshotNameException(new SnapshotId(request.repository(), request.name()), "must not start with '_'");
}
if (!request.name().toLowerCase(Locale.ROOT).equals(request.name())) {
throw new InvalidSnapshotNameException(new SnapshotId(request.repository(), request.name()), "must be lowercase");
}
if (!Strings.validFileName(request.name())) {
throw new InvalidSnapshotNameException(new SnapshotId(request.repository(), request.name()), "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS);
}
}
/**
* Starts snapshot.
* <p/>
* Creates snapshot in repository and updates snapshot metadata record with list of shards that needs to be processed.
*
* @param clusterState cluster state
* @param snapshot snapshot meta data
* @param partial allow partial snapshots
* @param userCreateSnapshotListener listener
*/
private void beginSnapshot(ClusterState clusterState, final SnapshotMetaData.Entry snapshot, final boolean partial, final CreateSnapshotListener userCreateSnapshotListener) {
boolean snapshotCreated = false;
try {
Repository repository = repositoriesService.repository(snapshot.snapshotId().getRepository());
MetaData metaData = clusterState.metaData();
if (!snapshot.includeGlobalState()) {
// Remove global state from the cluster state
MetaData.Builder builder = MetaData.builder();
for (String index : snapshot.indices()) {
builder.put(metaData.index(index), false);
}
metaData = builder.build();
}
repository.initializeSnapshot(snapshot.snapshotId(), snapshot.indices(), metaData);
snapshotCreated = true;
if (snapshot.indices().isEmpty()) {
// No indices in this snapshot - we are done
userCreateSnapshotListener.onResponse();
endSnapshot(snapshot);
return;
}
clusterService.submitStateUpdateTask("update_snapshot [" + snapshot + "]", new ProcessedClusterStateUpdateTask() {
boolean accepted = false;
SnapshotMetaData.Entry updatedSnapshot;
String failure = null;
@Override
public ClusterState execute(ClusterState currentState) {
MetaData metaData = currentState.metaData();
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
SnapshotMetaData snapshots = metaData.custom(SnapshotMetaData.TYPE);
ImmutableList.Builder<SnapshotMetaData.Entry> entries = ImmutableList.builder();
for (SnapshotMetaData.Entry entry : snapshots.entries()) {
if (entry.snapshotId().equals(snapshot.snapshotId())) {
// Replace the snapshot that was just created
ImmutableMap<ShardId, SnapshotMetaData.ShardSnapshotStatus> shards = shards(snapshot.snapshotId(), currentState, snapshot.indices());
if (!partial) {
Set<String> indicesWithMissingShards = indicesWithMissingShards(shards);
if (indicesWithMissingShards != null) {
updatedSnapshot = new SnapshotMetaData.Entry(snapshot.snapshotId(), snapshot.includeGlobalState(), State.FAILED, snapshot.indices(), shards);
entries.add(updatedSnapshot);
failure = "Indices don't have primary shards +[" + indicesWithMissingShards + "]";
continue;
}
}
updatedSnapshot = new SnapshotMetaData.Entry(snapshot.snapshotId(), snapshot.includeGlobalState(), State.STARTED, snapshot.indices(), shards);
entries.add(updatedSnapshot);
if (!completed(shards.values())) {
accepted = true;
}
} else {
entries.add(entry);
}
}
mdBuilder.putCustom(SnapshotMetaData.TYPE, new SnapshotMetaData(entries.build()));
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.warn("[{}] failed to create snapshot", t, snapshot.snapshotId());
userCreateSnapshotListener.onFailure(t);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
// The userCreateSnapshotListener.onResponse() notifies caller that the snapshot was accepted
// for processing. If client wants to wait for the snapshot completion, it can register snapshot
// completion listener in this method. For the snapshot completion to work properly, the snapshot
// should still exist when listener is registered.
userCreateSnapshotListener.onResponse();
// Now that snapshot completion listener is registered we can end the snapshot if needed
// We should end snapshot only if 1) we didn't accept it for processing (which happens when there
// is nothing to do) and 2) there was a snapshot in metadata that we should end. Otherwise we should
// go ahead and continue working on this snapshot rather then end here.
if (!accepted && updatedSnapshot != null) {
endSnapshot(updatedSnapshot, failure);
}
}
});
} catch (Throwable t) {
logger.warn("failed to create snapshot [{}]", t, snapshot.snapshotId());
clusterService.submitStateUpdateTask("fail_snapshot [" + snapshot.snapshotId() + "]", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
MetaData metaData = currentState.metaData();
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
SnapshotMetaData snapshots = metaData.custom(SnapshotMetaData.TYPE);
ImmutableList.Builder<SnapshotMetaData.Entry> entries = ImmutableList.builder();
for (SnapshotMetaData.Entry entry : snapshots.entries()) {
if (!entry.snapshotId().equals(snapshot.snapshotId())) {
entries.add(entry);
}
}
mdBuilder.putCustom(SnapshotMetaData.TYPE, new SnapshotMetaData(entries.build()));
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.warn("[{}] failed to delete snapshot", t, snapshot.snapshotId());
}
});
if (snapshotCreated) {
try {
repositoriesService.repository(snapshot.snapshotId().getRepository()).finalizeSnapshot(snapshot.snapshotId(), ExceptionsHelper.detailedMessage(t), 0, ImmutableList.<SnapshotShardFailure>of());
} catch (Throwable t2) {
logger.warn("[{}] failed to close snapshot in repository", snapshot.snapshotId());
}
}
userCreateSnapshotListener.onFailure(t);
}
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
try {
if (event.localNodeMaster()) {
if (event.nodesRemoved()) {
processSnapshotsOnRemovedNodes(event);
}
}
SnapshotMetaData prev = event.previousState().metaData().custom(SnapshotMetaData.TYPE);
SnapshotMetaData curr = event.state().metaData().custom(SnapshotMetaData.TYPE);
if (prev == null) {
if (curr != null) {
processIndexShardSnapshots(curr);
}
} else {
if (!prev.equals(curr)) {
processIndexShardSnapshots(curr);
}
}
} catch (Throwable t) {
logger.warn("Failed to update snapshot state ", t);
}
}
/**
* Cleans up shard snapshots that were running on removed nodes
*
* @param event cluster changed event
*/
private void processSnapshotsOnRemovedNodes(ClusterChangedEvent event) {
if (removedNodesCleanupNeeded(event)) {
// Check if we just became the master
final boolean newMaster = !event.previousState().nodes().localNodeMaster();
clusterService.submitStateUpdateTask("update snapshot state after node removal", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
DiscoveryNodes nodes = currentState.nodes();
MetaData metaData = currentState.metaData();
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
SnapshotMetaData snapshots = metaData.custom(SnapshotMetaData.TYPE);
if (snapshots == null) {
return currentState;
}
boolean changed = false;
ArrayList<SnapshotMetaData.Entry> entries = newArrayList();
for (final SnapshotMetaData.Entry snapshot : snapshots.entries()) {
SnapshotMetaData.Entry updatedSnapshot = snapshot;
boolean snapshotChanged = false;
if (snapshot.state() == State.STARTED) {
ImmutableMap.Builder<ShardId, ShardSnapshotStatus> shards = ImmutableMap.builder();
for (ImmutableMap.Entry<ShardId, ShardSnapshotStatus> shardEntry : snapshot.shards().entrySet()) {
ShardSnapshotStatus shardStatus = shardEntry.getValue();
if (!shardStatus.state().completed() && shardStatus.nodeId() != null) {
if (nodes.nodeExists(shardStatus.nodeId())) {
shards.put(shardEntry);
} else {
// TODO: Restart snapshot on another node?
snapshotChanged = true;
logger.warn("failing snapshot of shard [{}] on closed node [{}]", shardEntry.getKey(), shardStatus.nodeId());
shards.put(shardEntry.getKey(), new ShardSnapshotStatus(shardStatus.nodeId(), State.FAILED, "node shutdown"));
}
}
}
if (snapshotChanged) {
changed = true;
ImmutableMap<ShardId, ShardSnapshotStatus> shardsMap = shards.build();
if (!snapshot.state().completed() && completed(shardsMap.values())) {
updatedSnapshot = new SnapshotMetaData.Entry(snapshot.snapshotId(), snapshot.includeGlobalState(), State.SUCCESS, snapshot.indices(), shardsMap);
endSnapshot(updatedSnapshot);
} else {
updatedSnapshot = new SnapshotMetaData.Entry(snapshot.snapshotId(), snapshot.includeGlobalState(), snapshot.state(), snapshot.indices(), shardsMap);
}
}
entries.add(updatedSnapshot);
} else if (snapshot.state() == State.INIT && newMaster) {
// Clean up the snapshot that failed to start from the old master
deleteSnapshot(snapshot.snapshotId(), new DeleteSnapshotListener() {
@Override
public void onResponse() {
logger.debug("cleaned up abandoned snapshot {} in INIT state", snapshot.snapshotId());
}
@Override
public void onFailure(Throwable t) {
logger.warn("failed to clean up abandoned snapshot {} in INIT state", snapshot.snapshotId());
}
});
} else if (snapshot.state() == State.SUCCESS && newMaster) {
// Finalize the snapshot
endSnapshot(snapshot);
}
}
if (changed) {
snapshots = new SnapshotMetaData(entries.toArray(new SnapshotMetaData.Entry[entries.size()]));
mdBuilder.putCustom(SnapshotMetaData.TYPE, snapshots);
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
logger.warn("failed to update snapshot state after node removal");
}
});
}
}
private boolean removedNodesCleanupNeeded(ClusterChangedEvent event) {
// Check if we just became the master
boolean newMaster = !event.previousState().nodes().localNodeMaster();
SnapshotMetaData snapshotMetaData = event.state().getMetaData().custom(SnapshotMetaData.TYPE);
if (snapshotMetaData == null) {
return false;
}
for (SnapshotMetaData.Entry snapshot : snapshotMetaData.entries()) {
if (newMaster && (snapshot.state() == State.SUCCESS || snapshot.state() == State.INIT)) {
// We just replaced old master and snapshots in intermediate states needs to be cleaned
return true;
}
for (DiscoveryNode node : event.nodesDelta().removedNodes()) {
for (ImmutableMap.Entry<ShardId, ShardSnapshotStatus> shardEntry : snapshot.shards().entrySet()) {
ShardSnapshotStatus shardStatus = shardEntry.getValue();
if (!shardStatus.state().completed() && node.getId().equals(shardStatus.nodeId())) {
// At least one shard was running on the removed node - we need to fail it
return true;
}
}
}
}
return false;
}
/**
* Checks if any new shards should be snapshotted on this node
*
* @param snapshotMetaData snapshot metadata to be processed
*/
private void processIndexShardSnapshots(SnapshotMetaData snapshotMetaData) {
Map<SnapshotId, SnapshotShards> survivors = newHashMap();
// First, remove snapshots that are no longer there
for (Map.Entry<SnapshotId, SnapshotShards> entry : shardSnapshots.entrySet()) {
if (snapshotMetaData != null && snapshotMetaData.snapshot(entry.getKey()) != null) {
survivors.put(entry.getKey(), entry.getValue());
}
}
// For now we will be mostly dealing with a single snapshot at a time but might have multiple simultaneously running
// snapshots in the future
HashMap<SnapshotId, SnapshotShards> newSnapshots = null;
// Now go through all snapshots and update existing or create missing
final String localNodeId = clusterService.localNode().id();
for (SnapshotMetaData.Entry entry : snapshotMetaData.entries()) {
HashMap<ShardId, IndexShardSnapshotStatus> startedShards = null;
for (Map.Entry<ShardId, SnapshotMetaData.ShardSnapshotStatus> shard : entry.shards().entrySet()) {
// Check if we have new shards to start processing on
if (localNodeId.equals(shard.getValue().nodeId())) {
if (entry.state() == State.STARTED) {
if (startedShards == null) {
startedShards = newHashMap();
}
startedShards.put(shard.getKey(), new IndexShardSnapshotStatus());
} else if (entry.state() == State.ABORTED) {
SnapshotShards snapshotShards = shardSnapshots.get(entry.snapshotId());
if (snapshotShards != null) {
IndexShardSnapshotStatus snapshotStatus = snapshotShards.shards.get(shard.getKey());
if (snapshotStatus != null) {
snapshotStatus.abort();
}
}
}
}
}
if (startedShards != null) {
if (!survivors.containsKey(entry.snapshotId())) {
if (newSnapshots == null) {
newSnapshots = newHashMapWithExpectedSize(2);
}
newSnapshots.put(entry.snapshotId(), new SnapshotShards(ImmutableMap.copyOf(startedShards)));
}
}
}
if (newSnapshots != null) {
survivors.putAll(newSnapshots);
}
// Update the list of snapshots that we saw and tried to started
// If startup of these shards fails later, we don't want to try starting these shards again
shardSnapshots = ImmutableMap.copyOf(survivors);
// We have new snapshots to process -
if (newSnapshots != null) {
for (final Map.Entry<SnapshotId, SnapshotShards> entry : newSnapshots.entrySet()) {
for (final Map.Entry<ShardId, IndexShardSnapshotStatus> shardEntry : entry.getValue().shards.entrySet()) {
try {
final IndexShardSnapshotAndRestoreService shardSnapshotService = indicesService.indexServiceSafe(shardEntry.getKey().getIndex()).shardInjectorSafe(shardEntry.getKey().id())
.getInstance(IndexShardSnapshotAndRestoreService.class);
threadPool.executor(ThreadPool.Names.SNAPSHOT).execute(new Runnable() {
@Override
public void run() {
try {
shardSnapshotService.snapshot(entry.getKey(), shardEntry.getValue());
updateIndexShardSnapshotStatus(new UpdateIndexShardSnapshotStatusRequest(entry.getKey(), shardEntry.getKey(), new ShardSnapshotStatus(localNodeId, SnapshotMetaData.State.SUCCESS)));
} catch (Throwable t) {
logger.warn("[{}] [{}] failed to create snapshot", t, shardEntry.getKey(), entry.getKey());
updateIndexShardSnapshotStatus(new UpdateIndexShardSnapshotStatusRequest(entry.getKey(), shardEntry.getKey(), new ShardSnapshotStatus(localNodeId, SnapshotMetaData.State.FAILED, ExceptionsHelper.detailedMessage(t))));
}
}
});
} catch (Throwable t) {
updateIndexShardSnapshotStatus(new UpdateIndexShardSnapshotStatusRequest(entry.getKey(), shardEntry.getKey(), new ShardSnapshotStatus(localNodeId, SnapshotMetaData.State.FAILED, ExceptionsHelper.detailedMessage(t))));
}
}
}
}
}
/**
* Updates the shard status
*
* @param request update shard status request
*/
private void updateIndexShardSnapshotStatus(UpdateIndexShardSnapshotStatusRequest request) {
try {
if (clusterService.state().nodes().localNodeMaster()) {
innerUpdateSnapshotState(request);
} else {
transportService.sendRequest(clusterService.state().nodes().masterNode(),
UpdateSnapshotStateRequestHandler.ACTION, request, EmptyTransportResponseHandler.INSTANCE_SAME);
}
} catch (Throwable t) {
logger.warn("[{}] [{}] failed to update snapshot state", t, request.snapshotId(), request.status());
}
}
/**
* Checks if all shards in the list have completed
*
* @param shards list of shard statuses
* @return true if all shards have completed (either successfully or failed), false otherwise
*/
private boolean completed(Collection<SnapshotMetaData.ShardSnapshotStatus> shards) {
for (ShardSnapshotStatus status : shards) {
if (!status.state().completed()) {
return false;
}
}
return true;
}
/**
* Returns list of indices with missing shards
*
* @param shards list of shard statuses
* @return list of failed indices
*/
private Set<String> indicesWithMissingShards(ImmutableMap<ShardId, SnapshotMetaData.ShardSnapshotStatus> shards) {
Set<String> indices = null;
for (ImmutableMap.Entry<ShardId, SnapshotMetaData.ShardSnapshotStatus> entry : shards.entrySet()) {
if (entry.getValue().state() == State.MISSING) {
if (indices == null) {
indices = newHashSet();
}
indices.add(entry.getKey().getIndex());
}
}
return indices;
}
/**
* Updates the shard status on master node
*
* @param request update shard status request
*/
private void innerUpdateSnapshotState(final UpdateIndexShardSnapshotStatusRequest request) {
clusterService.submitStateUpdateTask("update snapshot state", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
MetaData metaData = currentState.metaData();
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
SnapshotMetaData snapshots = metaData.custom(SnapshotMetaData.TYPE);
if (snapshots != null) {
boolean changed = false;
ArrayList<SnapshotMetaData.Entry> entries = newArrayList();
for (SnapshotMetaData.Entry entry : snapshots.entries()) {
if (entry.snapshotId().equals(request.snapshotId())) {
HashMap<ShardId, ShardSnapshotStatus> shards = newHashMap(entry.shards());
logger.trace("[{}] Updating shard [{}] with status [{}]", request.snapshotId(), request.shardId(), request.status().state());
shards.put(request.shardId(), request.status());
if (!completed(shards.values())) {
entries.add(new SnapshotMetaData.Entry(entry.snapshotId(), entry.includeGlobalState(), entry.state(), entry.indices(), ImmutableMap.copyOf(shards)));
} else {
// Snapshot is finished - mark it as done
// TODO: Add PARTIAL_SUCCESS status?
SnapshotMetaData.Entry updatedEntry = new SnapshotMetaData.Entry(entry.snapshotId(), entry.includeGlobalState(), State.SUCCESS, entry.indices(), ImmutableMap.copyOf(shards));
entries.add(updatedEntry);
// Finalize snapshot in the repository
endSnapshot(updatedEntry);
logger.info("snapshot [{}] is done", updatedEntry.snapshotId());
}
changed = true;
} else {
entries.add(entry);
}
}
if (changed) {
snapshots = new SnapshotMetaData(entries.toArray(new SnapshotMetaData.Entry[entries.size()]));
mdBuilder.putCustom(SnapshotMetaData.TYPE, snapshots);
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
}
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
logger.warn("[{}][{}] failed to update snapshot status to [{}]", t, request.snapshotId(), request.shardId(), request.status());
}
});
}
/**
* Finalizes the shard in repository and then removes it from cluster state
* <p/>
* This is non-blocking method that runs on a thread from SNAPSHOT thread pool
*
* @param entry snapshot
*/
private void endSnapshot(SnapshotMetaData.Entry entry) {
endSnapshot(entry, null);
}
/**
* Finalizes the shard in repository and then removes it from cluster state
* <p/>
* This is non-blocking method that runs on a thread from SNAPSHOT thread pool
*
* @param entry snapshot
* @param failure failure reason or null if snapshot was successful
*/
private void endSnapshot(final SnapshotMetaData.Entry entry, final String failure) {
threadPool.executor(ThreadPool.Names.SNAPSHOT).execute(new Runnable() {
@Override
public void run() {
SnapshotId snapshotId = entry.snapshotId();
try {
final Repository repository = repositoriesService.repository(snapshotId.getRepository());
logger.trace("[{}] finalizing snapshot in repository, state: [{}], failure[{}]", snapshotId, entry.state(), failure);
ArrayList<ShardSearchFailure> failures = newArrayList();
ArrayList<SnapshotShardFailure> shardFailures = newArrayList();
for (Map.Entry<ShardId, ShardSnapshotStatus> shardStatus : entry.shards().entrySet()) {
ShardId shardId = shardStatus.getKey();
ShardSnapshotStatus status = shardStatus.getValue();
if (status.state().failed()) {
failures.add(new ShardSearchFailure(status.reason(), new SearchShardTarget(status.nodeId(), shardId.getIndex(), shardId.id())));
shardFailures.add(new SnapshotShardFailure(status.nodeId(), shardId.getIndex(), shardId.id(), status.reason()));
}
}
Snapshot snapshot = repository.finalizeSnapshot(snapshotId, failure, entry.shards().size(), ImmutableList.copyOf(shardFailures));
removeSnapshotFromClusterState(snapshotId, new SnapshotInfo(snapshot), null);
} catch (Throwable t) {
logger.warn("[{}] failed to finalize snapshot", t, snapshotId);
removeSnapshotFromClusterState(snapshotId, null, t);
}
}
});
}
/**
* Removes record of running snapshot from cluster state
*
* @param snapshotId snapshot id
* @param snapshot snapshot info if snapshot was successful
* @param t exception if snapshot failed
*/
private void removeSnapshotFromClusterState(final SnapshotId snapshotId, final SnapshotInfo snapshot, final Throwable t) {
clusterService.submitStateUpdateTask("remove snapshot metadata", new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
MetaData metaData = currentState.metaData();
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
SnapshotMetaData snapshots = metaData.custom(SnapshotMetaData.TYPE);
if (snapshots != null) {
boolean changed = false;
ArrayList<SnapshotMetaData.Entry> entries = newArrayList();
for (SnapshotMetaData.Entry entry : snapshots.entries()) {
if (entry.snapshotId().equals(snapshotId)) {
changed = true;
} else {
entries.add(entry);
}
}
if (changed) {
snapshots = new SnapshotMetaData(entries.toArray(new SnapshotMetaData.Entry[entries.size()]));
mdBuilder.putCustom(SnapshotMetaData.TYPE, snapshots);
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
}
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
logger.warn("[{}][{}] failed to remove snapshot metadata", t, snapshotId);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
for (SnapshotCompletionListener listener : snapshotCompletionListeners) {
try {
if (snapshot != null) {
listener.onSnapshotCompletion(snapshotId, snapshot);
} else {
listener.onSnapshotFailure(snapshotId, t);
}
} catch (Throwable t) {
logger.warn("failed to refresh settings for [{}]", t, listener);
}
}
}
});
}
/**
* Deletes snapshot from repository.
* <p/>
* If the snapshot is still running cancels the snapshot first and then deletes it from the repository.
*
* @param snapshotId snapshot id
* @param listener listener
*/
public void deleteSnapshot(final SnapshotId snapshotId, final DeleteSnapshotListener listener) {
clusterService.submitStateUpdateTask("delete snapshot", new ProcessedClusterStateUpdateTask() {
boolean waitForSnapshot = false;
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
MetaData metaData = currentState.metaData();
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
SnapshotMetaData snapshots = metaData.custom(SnapshotMetaData.TYPE);
if (snapshots == null) {
// No snapshots running - we can continue
return currentState;
}
SnapshotMetaData.Entry snapshot = snapshots.snapshot(snapshotId);
if (snapshot == null) {
// This snapshot is not running - continue
if (!snapshots.entries().isEmpty()) {
// However other snapshots are running - cannot continue
throw new ConcurrentSnapshotExecutionException(snapshotId, "another snapshot is currently running cannot delete");
}
return currentState;
} else {
// This snapshot is currently running - stopping shards first
waitForSnapshot = true;
ImmutableMap<ShardId, ShardSnapshotStatus> shards;
if (snapshot.state() == State.STARTED && snapshot.shards() != null) {
// snapshot is currently running - stop started shards
ImmutableMap.Builder<ShardId, ShardSnapshotStatus> shardsBuilder = ImmutableMap.builder();
for (ImmutableMap.Entry<ShardId, ShardSnapshotStatus> shardEntry : snapshot.shards().entrySet()) {
ShardSnapshotStatus status = shardEntry.getValue();
if (!status.state().completed()) {
shardsBuilder.put(shardEntry.getKey(), new ShardSnapshotStatus(status.nodeId(), State.ABORTED));
} else {
shardsBuilder.put(shardEntry.getKey(), status);
}
}
shards = shardsBuilder.build();
} else if (snapshot.state() == State.INIT) {
// snapshot hasn't started yet - end it
shards = snapshot.shards();
endSnapshot(snapshot);
} else {
// snapshot is being finalized - wait for it
logger.trace("trying to delete completed snapshot - save to delete");
return currentState;
}
SnapshotMetaData.Entry newSnapshot = new SnapshotMetaData.Entry(snapshotId, snapshot.includeGlobalState(), State.ABORTED, snapshot.indices(), shards);
snapshots = new SnapshotMetaData(newSnapshot);
mdBuilder.putCustom(SnapshotMetaData.TYPE, snapshots);
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
}
@Override
public void onFailure(String source, Throwable t) {
listener.onFailure(t);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
if (waitForSnapshot) {
logger.trace("adding snapshot completion listener to wait for deleted snapshot to finish");
addListener(new SnapshotCompletionListener() {
@Override
public void onSnapshotCompletion(SnapshotId snapshotId, SnapshotInfo snapshot) {
logger.trace("deleted snapshot completed - deleting files");
removeListener(this);
deleteSnapshotFromRepository(snapshotId, listener);
}
@Override
public void onSnapshotFailure(SnapshotId snapshotId, Throwable t) {
logger.trace("deleted snapshot failed - deleting files", t);
removeListener(this);
deleteSnapshotFromRepository(snapshotId, listener);
}
});
} else {
logger.trace("deleted snapshot is not running - deleting files");
deleteSnapshotFromRepository(snapshotId, listener);
}
}
});
}
/**
* Checks if a repository is currently in use by one of the snapshots
*
* @param clusterState cluster state
* @param repository repository id
* @return true if repository is currently in use by one of the running snapshots
*/
public static boolean isRepositoryInUse(ClusterState clusterState, String repository) {
MetaData metaData = clusterState.metaData();
SnapshotMetaData snapshots = metaData.custom(SnapshotMetaData.TYPE);
if (snapshots != null) {
for (SnapshotMetaData.Entry snapshot : snapshots.entries()) {
if (repository.equals(snapshot.snapshotId().getRepository())) {
return true;
}
}
}
return false;
}
/**
* Deletes snapshot from repository
*
* @param snapshotId snapshot id
* @param listener listener
*/
private void deleteSnapshotFromRepository(final SnapshotId snapshotId, final DeleteSnapshotListener listener) {
threadPool.executor(ThreadPool.Names.SNAPSHOT).execute(new Runnable() {
@Override
public void run() {
try {
Repository repository = repositoriesService.repository(snapshotId.getRepository());
repository.deleteSnapshot(snapshotId);
listener.onResponse();
} catch (Throwable t) {
listener.onFailure(t);
}
}
});
}
/**
* Calculates the list of shards that should be included into the current snapshot
*
* @param snapshotId snapshot id
* @param clusterState cluster state
* @param indices list of indices to be snapshotted
* @return list of shard to be included into current snapshot
*/
private ImmutableMap<ShardId, SnapshotMetaData.ShardSnapshotStatus> shards(SnapshotId snapshotId, ClusterState clusterState, ImmutableList<String> indices) {
ImmutableMap.Builder<ShardId, SnapshotMetaData.ShardSnapshotStatus> builder = ImmutableMap.builder();
MetaData metaData = clusterState.metaData();
for (String index : indices) {
IndexMetaData indexMetaData = metaData.index(index);
IndexRoutingTable indexRoutingTable = clusterState.getRoutingTable().index(index);
if (indexRoutingTable == null) {
throw new SnapshotCreationException(snapshotId, "Missing routing table for index [" + index + "]");
}
for (int i = 0; i < indexMetaData.numberOfShards(); i++) {
ShardId shardId = new ShardId(index, i);
ShardRouting primary = indexRoutingTable.shard(i).primaryShard();
if (primary == null || !primary.assignedToNode()) {
builder.put(shardId, new SnapshotMetaData.ShardSnapshotStatus(null, State.MISSING, "primary shard is not allocated"));
} else if (!primary.started()) {
builder.put(shardId, new SnapshotMetaData.ShardSnapshotStatus(primary.currentNodeId(), State.MISSING, "primary shard hasn't been started yet"));
} else {
builder.put(shardId, new SnapshotMetaData.ShardSnapshotStatus(primary.currentNodeId()));
}
}
}
return builder.build();
}
/**
* Adds snapshot completion listener
*
* @param listener listener
*/
public void addListener(SnapshotCompletionListener listener) {
this.snapshotCompletionListeners.add(listener);
}
/**
* Removes snapshot completion listener
*
* @param listener listener
*/
public void removeListener(SnapshotCompletionListener listener) {
this.snapshotCompletionListeners.remove(listener);
}
/**
* Listener for create snapshot operation
*/
public static interface CreateSnapshotListener {
/**
* Called when snapshot has successfully started
*/
void onResponse();
/**
* Called if a snapshot operation couldn't start
*/
void onFailure(Throwable t);
}
/**
* Listener for delete snapshot operation
*/
public static interface DeleteSnapshotListener {
/**
* Called if delete operation was successful
*/
void onResponse();
/**
* Called if delete operation failed
*/
void onFailure(Throwable t);
}
public static interface SnapshotCompletionListener {
void onSnapshotCompletion(SnapshotId snapshotId, SnapshotInfo snapshot);
void onSnapshotFailure(SnapshotId snapshotId, Throwable t);
}
/**
* Snapshot creation request
*/
public static class SnapshotRequest {
private String cause;
private String name;
private String repository;
private String[] indices;
private IndicesOptions indicesOptions = IndicesOptions.strict();
private boolean partial;
private Settings settings;
private boolean includeGlobalState;
private TimeValue masterNodeTimeout;
/**
* Constructs new snapshot creation request
*
* @param cause cause for snapshot operation
* @param name name of the snapshot
* @param repository name of the repository
*/
public SnapshotRequest(String cause, String name, String repository) {
this.cause = cause;
this.name = name;
this.repository = repository;
}
/**
* Sets the list of indices to be snapshotted
*
* @param indices list of indices
* @return this request
*/
public SnapshotRequest indices(String[] indices) {
this.indices = indices;
return this;
}
/**
* Sets repository-specific snapshot settings
*
* @param settings snapshot settings
* @return this request
*/
public SnapshotRequest settings(Settings settings) {
this.settings = settings;
return this;
}
/**
* Set to true if global state should be stored as part of the snapshot
*
* @param includeGlobalState true if global state should be stored as part of the snapshot
* @return this request
*/
public SnapshotRequest includeGlobalState(boolean includeGlobalState) {
this.includeGlobalState = includeGlobalState;
return this;
}
/**
* Sets master node timeout
*
* @param masterNodeTimeout master node timeout
* @return this request
*/
public SnapshotRequest masterNodeTimeout(TimeValue masterNodeTimeout) {
this.masterNodeTimeout = masterNodeTimeout;
return this;
}
/**
* Sets the indices options
*
* @param indicesOptions indices options
* @return this request
*/
public SnapshotRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
/**
* Set to true if partial snapshot should be allowed
*
* @param partial true if partial snapshots should be allowed
* @return this request
*/
public SnapshotRequest partial(boolean partial) {
this.partial = partial;
return this;
}
/**
* Returns cause for snapshot operation
*
* @return cause for snapshot operation
*/
public String cause() {
return cause;
}
/**
* Returns snapshot name
*
* @return snapshot name
*/
public String name() {
return name;
}
/**
* Returns snapshot repository
*
* @return snapshot repository
*/
public String repository() {
return repository;
}
/**
* Returns the list of indices to be snapshotted
*
* @return the list of indices
*/
public String[] indices() {
return indices;
}
/**
* Returns indices options
*
* @return indices options
*/
public IndicesOptions indicesOptions() {
return indicesOptions;
}
/**
* Returns repository-specific settings for the snapshot operation
*
* @return repository-specific settings
*/
public Settings settings() {
return settings;
}
/**
* Returns true if global state should be stored as part of the snapshot
*
* @return true if global state should be stored as part of the snapshot
*/
public boolean includeGlobalState() {
return includeGlobalState;
}
/**
* Returns master node timeout
*
* @return master node timeout
*/
public TimeValue masterNodeTimeout() {
return masterNodeTimeout;
}
}
/**
* Stores the list of shards that has to be snapshotted on this node
*/
private static class SnapshotShards {
private final ImmutableMap<ShardId, IndexShardSnapshotStatus> shards;
private SnapshotShards(ImmutableMap<ShardId, IndexShardSnapshotStatus> shards) {
this.shards = shards;
}
}
/**
* Internal request that is used to send changes in snapshot status to master
*/
private static class UpdateIndexShardSnapshotStatusRequest extends TransportRequest {
private SnapshotId snapshotId;
private ShardId shardId;
private SnapshotMetaData.ShardSnapshotStatus status;
private UpdateIndexShardSnapshotStatusRequest() {
}
private UpdateIndexShardSnapshotStatusRequest(SnapshotId snapshotId, ShardId shardId, SnapshotMetaData.ShardSnapshotStatus status) {
this.snapshotId = snapshotId;
this.shardId = shardId;
this.status = status;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
snapshotId = SnapshotId.readSnapshotId(in);
shardId = ShardId.readShardId(in);
status = SnapshotMetaData.ShardSnapshotStatus.readShardSnapshotStatus(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
snapshotId.writeTo(out);
shardId.writeTo(out);
status.writeTo(out);
}
public SnapshotId snapshotId() {
return snapshotId;
}
public ShardId shardId() {
return shardId;
}
public SnapshotMetaData.ShardSnapshotStatus status() {
return status;
}
}
/**
* Transport request handler that is used to send changes in snapshot status to master
*/
private class UpdateSnapshotStateRequestHandler extends BaseTransportRequestHandler<UpdateIndexShardSnapshotStatusRequest> {
static final String ACTION = "cluster/snapshot/update_snapshot";
@Override
public UpdateIndexShardSnapshotStatusRequest newInstance() {
return new UpdateIndexShardSnapshotStatusRequest();
}
@Override
public void messageReceived(UpdateIndexShardSnapshotStatusRequest request, final TransportChannel channel) throws Exception {
innerUpdateSnapshotState(request);
channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_snapshots_SnapshotsService.java
|
957 |
public interface OSerializableStream extends Serializable {
/**
* Marshalls the object. Transforms the current object in byte[] form to being stored or transferred over the network.
*
* @return The byte array representation of the object
* @see #fromStream(byte[])
* @throws OSerializationException
* if the marshalling does not succeed
*/
public byte[] toStream() throws OSerializationException;
/**
* Unmarshalls the object. Fills the current object with the values contained in the byte array representation restoring a
* previous state. Usually byte[] comes from the storage or network.
*
* @param iStream
* byte array representation of the object
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
* @throws OSerializationException
* if the unmarshalling does not succeed
*/
public OSerializableStream fromStream(byte[] iStream) throws OSerializationException;
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_serialization_OSerializableStream.java
|
1,491 |
@SuppressWarnings({ "unchecked" })
public class OObjectLazyListIterator<TYPE> implements Iterator<TYPE>, Serializable {
private static final long serialVersionUID = 3714399452499077452L;
private final ProxyObject sourceRecord;
private final OObjectLazyList<TYPE> list;
private String fetchPlan;
private int cursor = 0;
private int lastRet = -1;
public OObjectLazyListIterator(final OObjectLazyList<TYPE> iSourceList, final ProxyObject iSourceRecord) {
this.list = iSourceList;
this.sourceRecord = iSourceRecord;
}
public TYPE next() {
return next(fetchPlan);
}
public TYPE next(final String iFetchPlan) {
final Object value = list.get(cursor);
lastRet = cursor++;
return (TYPE) value;
}
public boolean hasNext() {
return cursor < (list.size());
}
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
try {
list.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
if (sourceRecord != null) {
((OObjectProxyMethodHandler) sourceRecord.getHandler()).setDirty();
}
}
public String getFetchPlan() {
return fetchPlan;
}
public void setFetchPlan(String fetchPlan) {
this.fetchPlan = fetchPlan;
}
}
| 0true
|
object_src_main_java_com_orientechnologies_orient_object_db_OObjectLazyListIterator.java
|
893 |
public class CountDownOperation extends BackupAwareCountDownLatchOperation implements Notifier, IdentifiedDataSerializable {
private boolean shouldNotify;
public CountDownOperation() {
}
public CountDownOperation(String name) {
super(name);
}
@Override
public void run() throws Exception {
CountDownLatchService service = getService();
service.countDown(name);
int count = service.getCount(name);
shouldNotify = count == 0;
}
@Override
public boolean shouldBackup() {
return true;
}
@Override
public boolean shouldNotify() {
return shouldNotify;
}
@Override
public WaitNotifyKey getNotifiedKey() {
return waitNotifyKey();
}
@Override
public int getFactoryId() {
return CountDownLatchDataSerializerHook.F_ID;
}
@Override
public int getId() {
return CountDownLatchDataSerializerHook.COUNT_DOWN_OPERATION;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_countdownlatch_operations_CountDownOperation.java
|
2,889 |
public final class Predicates {
//we don't want instances.
private Predicates() {
}
public static Predicate instanceOf(final Class klass) {
return new InstanceOfPredicate(klass);
}
private static Comparable readAttribute(Map.Entry entry, String attribute) {
QueryableEntry queryableEntry = (QueryableEntry) entry;
Comparable value = queryableEntry.getAttribute(attribute);
if (value == null) {
return IndexImpl.NULL;
}
return value;
}
public static Predicate and(Predicate x, Predicate y) {
return new AndPredicate(x, y);
}
public static Predicate not(Predicate predicate) {
return new NotPredicate(predicate);
}
public static Predicate or(Predicate x, Predicate y) {
return new OrPredicate(x, y);
}
public static Predicate notEqual(String attribute, Comparable y) {
return new NotEqualPredicate(attribute, y);
}
public static Predicate equal(String attribute, Comparable y) {
return new EqualPredicate(attribute, y);
}
public static Predicate like(String attribute, String pattern) {
return new LikePredicate(attribute, pattern);
}
public static Predicate ilike(String attribute, String pattern) {
return new ILikePredicate(attribute, pattern);
}
public static Predicate regex(String attribute, String pattern) {
return new RegexPredicate(attribute, pattern);
}
public static Predicate greaterThan(String x, Comparable y) {
return new GreaterLessPredicate(x, y, false, false);
}
public static Predicate greaterEqual(String x, Comparable y) {
return new GreaterLessPredicate(x, y, true, false);
}
public static Predicate lessThan(String x, Comparable y) {
return new GreaterLessPredicate(x, y, false, true);
}
public static Predicate lessEqual(String x, Comparable y) {
return new GreaterLessPredicate(x, y, true, true);
}
public static Predicate between(String attribute, Comparable from, Comparable to) {
return new BetweenPredicate(attribute, from, to);
}
public static Predicate in(String attribute, Comparable... values) {
return new InPredicate(attribute, values);
}
public static class BetweenPredicate extends AbstractPredicate {
private Comparable to;
private Comparable from;
public BetweenPredicate() {
}
public BetweenPredicate(String first, Comparable from, Comparable to) {
super(first);
this.from = from;
this.to = to;
}
@Override
public boolean apply(Map.Entry entry) {
Comparable entryValue = readAttribute(entry);
if (entryValue == null) {
return false;
}
Comparable fromConvertedValue = convert(entry, entryValue, from);
Comparable toConvertedValue = convert(entry, entryValue, to);
if (fromConvertedValue == null || toConvertedValue == null) {
return false;
}
return entryValue.compareTo(fromConvertedValue) >= 0 && entryValue.compareTo(toConvertedValue) <= 0;
}
@Override
public Set<QueryableEntry> filter(QueryContext queryContext) {
Index index = getIndex(queryContext);
return index.getSubRecordsBetween(from, to);
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
super.writeData(out);
out.writeObject(to);
out.writeObject(from);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
super.readData(in);
to = in.readObject();
from = in.readObject();
}
@Override
public String toString() {
return attribute + " BETWEEN " + from + " AND " + to;
}
}
public static class NotPredicate implements Predicate, DataSerializable {
private Predicate predicate;
public NotPredicate(Predicate predicate) {
this.predicate = predicate;
}
public NotPredicate() {
}
@Override
public boolean apply(Map.Entry mapEntry) {
return !predicate.apply(mapEntry);
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeObject(predicate);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
predicate = in.readObject();
}
@Override
public String toString() {
return "NOT(" + predicate + ")";
}
}
public static class InPredicate extends AbstractPredicate {
private Comparable[] values;
private volatile Set<Comparable> convertedInValues;
public InPredicate() {
}
public InPredicate(String attribute, Comparable... values) {
super(attribute);
this.values = values;
}
@Override
public boolean apply(Map.Entry entry) {
Comparable entryValue = readAttribute(entry);
Set<Comparable> set = convertedInValues;
if (set == null) {
set = new HashSet<Comparable>(values.length);
for (Comparable value : values) {
set.add(convert(entry, entryValue, value));
}
convertedInValues = set;
}
return entryValue != null && set.contains(entryValue);
}
@Override
public Set<QueryableEntry> filter(QueryContext queryContext) {
Index index = getIndex(queryContext);
if (index != null) {
return index.getRecords(values);
} else {
return null;
}
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
super.writeData(out);
out.writeInt(values.length);
for (Object value : values) {
out.writeObject(value);
}
}
@Override
public void readData(ObjectDataInput in) throws IOException {
super.readData(in);
int len = in.readInt();
values = new Comparable[len];
for (int i = 0; i < len; i++) {
values[i] = in.readObject();
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(attribute);
sb.append(" IN (");
for (int i = 0; i < values.length; i++) {
if (i > 0) {
sb.append(",");
}
sb.append(values[i]);
}
sb.append(")");
return sb.toString();
}
}
public static class RegexPredicate implements Predicate, DataSerializable {
private String attribute;
private String regex;
private volatile Pattern pattern;
public RegexPredicate() {
}
public RegexPredicate(String attribute, String regex) {
this.attribute = attribute;
this.regex = regex;
}
@Override
public boolean apply(Map.Entry entry) {
Comparable attribute = readAttribute(entry, this.attribute);
String firstVal = attribute == IndexImpl.NULL ? null : (String) attribute;
if (firstVal == null) {
return (regex == null);
} else if (regex == null) {
return false;
} else {
if (pattern == null) {
pattern = Pattern.compile(regex);
}
Matcher m = pattern.matcher(firstVal);
return m.matches();
}
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(attribute);
out.writeUTF(regex);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
attribute = in.readUTF();
regex = in.readUTF();
}
@Override
public String toString() {
return attribute + " REGEX '" + regex + "'";
}
}
public static class LikePredicate implements Predicate, DataSerializable {
protected String attribute;
protected String second;
private volatile Pattern pattern;
public LikePredicate() {
}
public LikePredicate(String attribute, String second) {
this.attribute = attribute;
this.second = second;
}
@Override
public boolean apply(Map.Entry entry) {
Comparable attribute = readAttribute(entry, this.attribute);
String firstVal = attribute == IndexImpl.NULL ? null : (String) attribute;
if (firstVal == null) {
return (second == null);
} else if (second == null) {
return false;
} else {
if (pattern == null) {
// we quote the input string then escape then replace % and _
// at the end we have a regex pattern look like : \QSOME_STRING\E.*\QSOME_OTHER_STRING\E
final String quoted = Pattern.quote(second);
String regex = quoted
//escaped %
.replaceAll("(?<!\\\\)[%]", "\\\\E.*\\\\Q")
//escaped _
.replaceAll("(?<!\\\\)[_]", "\\\\E.\\\\Q")
//non escaped %
.replaceAll("\\\\%", "%")
//non escaped _
.replaceAll("\\\\_", "_");
int flags = getFlags();
pattern = Pattern.compile(regex, flags);
}
Matcher m = pattern.matcher(firstVal);
return m.matches();
}
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(attribute);
out.writeUTF(second);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
attribute = in.readUTF();
second = in.readUTF();
}
protected int getFlags() {
//no flags
return 0;
}
@Override
public String toString() {
StringBuffer builder = new StringBuffer(attribute)
.append(" LIKE '")
.append(second)
.append("'");
return builder.toString();
}
}
public static class ILikePredicate extends LikePredicate {
public ILikePredicate() {
}
public ILikePredicate(String attribute, String second) {
super(attribute, second);
}
@Override
public String toString() {
StringBuffer builder = new StringBuffer(attribute)
.append(" ILIKE '")
.append(second)
.append("'");
return builder.toString();
}
@Override
protected int getFlags() {
return Pattern.CASE_INSENSITIVE;
}
}
public static class AndPredicate implements IndexAwarePredicate, DataSerializable {
protected Predicate[] predicates;
public AndPredicate() {
}
public AndPredicate(Predicate... predicates) {
this.predicates = predicates;
}
@Override
public Set<QueryableEntry> filter(QueryContext queryContext) {
Set<QueryableEntry> smallestIndexedResult = null;
List<Set<QueryableEntry>> otherIndexedResults = new LinkedList<Set<QueryableEntry>>();
List<Predicate> lsNoIndexPredicates = null;
for (Predicate predicate : predicates) {
boolean indexed = false;
if (predicate instanceof IndexAwarePredicate) {
IndexAwarePredicate iap = (IndexAwarePredicate) predicate;
if (iap.isIndexed(queryContext)) {
indexed = true;
Set<QueryableEntry> s = iap.filter(queryContext);
if (smallestIndexedResult == null) {
smallestIndexedResult = s;
} else if (s.size() < smallestIndexedResult.size()) {
otherIndexedResults.add(smallestIndexedResult);
smallestIndexedResult = s;
} else {
otherIndexedResults.add(s);
}
} else {
if (lsNoIndexPredicates == null) {
lsNoIndexPredicates = new LinkedList<Predicate>();
lsNoIndexPredicates.add(predicate);
}
}
}
if (!indexed) {
if (lsNoIndexPredicates == null) {
lsNoIndexPredicates = new LinkedList<Predicate>();
}
lsNoIndexPredicates.add(predicate);
}
}
if (smallestIndexedResult == null) {
return null;
}
return new AndResultSet(smallestIndexedResult, otherIndexedResults, lsNoIndexPredicates);
}
@Override
public boolean isIndexed(QueryContext queryContext) {
for (Predicate predicate : predicates) {
if (predicate instanceof IndexAwarePredicate) {
IndexAwarePredicate iap = (IndexAwarePredicate) predicate;
if (iap.isIndexed(queryContext)) {
return true;
}
}
}
return false;
}
@Override
public boolean apply(Map.Entry mapEntry) {
for (Predicate predicate : predicates) {
if (!predicate.apply(mapEntry)) {
return false;
}
}
return true;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("(");
int size = predicates.length;
for (int i = 0; i < size; i++) {
if (i > 0) {
sb.append(" AND ");
}
sb.append(predicates[i]);
}
sb.append(")");
return sb.toString();
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(predicates.length);
for (Predicate predicate : predicates) {
out.writeObject(predicate);
}
}
@Override
public void readData(ObjectDataInput in) throws IOException {
int size = in.readInt();
predicates = new Predicate[size];
for (int i = 0; i < size; i++) {
predicates[i] = in.readObject();
}
}
}
public static class OrPredicate implements IndexAwarePredicate, DataSerializable {
private Predicate[] predicates;
public OrPredicate() {
}
public OrPredicate(Predicate... predicates) {
this.predicates = predicates;
}
@Override
public Set<QueryableEntry> filter(QueryContext queryContext) {
List<Set<QueryableEntry>> indexedResults = new LinkedList<Set<QueryableEntry>>();
for (Predicate predicate : predicates) {
if (predicate instanceof IndexAwarePredicate) {
IndexAwarePredicate iap = (IndexAwarePredicate) predicate;
if (iap.isIndexed(queryContext)) {
Set<QueryableEntry> s = iap.filter(queryContext);
if (s != null) {
indexedResults.add(s);
}
} else {
return null;
}
}
}
return indexedResults.isEmpty() ? null : new OrResultSet(indexedResults);
}
@Override
public boolean isIndexed(QueryContext queryContext) {
for (Predicate predicate : predicates) {
if (predicate instanceof IndexAwarePredicate) {
IndexAwarePredicate iap = (IndexAwarePredicate) predicate;
if (!iap.isIndexed(queryContext)) {
return false;
}
} else {
return false;
}
}
return true;
}
@Override
public boolean apply(Map.Entry mapEntry) {
for (Predicate predicate : predicates) {
if (predicate.apply(mapEntry)) {
return true;
}
}
return false;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(predicates.length);
for (Predicate predicate : predicates) {
out.writeObject(predicate);
}
}
@Override
public void readData(ObjectDataInput in) throws IOException {
int size = in.readInt();
predicates = new Predicate[size];
for (int i = 0; i < size; i++) {
predicates[i] = in.readObject();
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("(");
int size = predicates.length;
for (int i = 0; i < size; i++) {
if (i > 0) {
sb.append(" OR ");
}
sb.append(predicates[i]);
}
sb.append(")");
return sb.toString();
}
}
public static class GreaterLessPredicate extends EqualPredicate {
boolean equal;
boolean less;
public GreaterLessPredicate() {
}
public GreaterLessPredicate(String attribute, Comparable value, boolean equal, boolean less) {
super(attribute, value);
this.equal = equal;
this.less = less;
}
@Override
public boolean apply(Map.Entry mapEntry) {
final Comparable entryValue = readAttribute(mapEntry);
final Comparable attributeValue = convert(mapEntry, entryValue, value);
final int result = entryValue.compareTo(attributeValue);
return equal && result == 0 || (less ? (result < 0) : (result > 0));
}
@Override
public Set<QueryableEntry> filter(QueryContext queryContext) {
Index index = getIndex(queryContext);
final ComparisonType comparisonType;
if (less) {
comparisonType = equal ? ComparisonType.LESSER_EQUAL : ComparisonType.LESSER;
} else {
comparisonType = equal ? ComparisonType.GREATER_EQUAL : ComparisonType.GREATER;
}
return index.getSubRecords(comparisonType, value);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
super.readData(in);
equal = in.readBoolean();
less = in.readBoolean();
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
super.writeData(out);
out.writeBoolean(equal);
out.writeBoolean(less);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(attribute);
sb.append(less ? "<" : ">");
if (equal) {
sb.append("=");
}
sb.append(value);
return sb.toString();
}
}
public static class NotEqualPredicate extends EqualPredicate {
public NotEqualPredicate() {
}
public NotEqualPredicate(String attribute, Comparable value) {
super(attribute, value);
}
@Override
public boolean apply(Map.Entry entry) {
return !super.apply(entry);
}
@Override
public Set<QueryableEntry> filter(QueryContext queryContext) {
Index index = getIndex(queryContext);
if (index != null) {
return index.getSubRecords(ComparisonType.NOT_EQUAL, value);
} else {
return null;
}
}
@Override
public String toString() {
return attribute + " != " + value;
}
}
public static class EqualPredicate extends AbstractPredicate {
protected Comparable value;
public EqualPredicate() {
}
public EqualPredicate(String attribute, Comparable value) {
super(attribute);
this.value = value;
}
@Override
public Set<QueryableEntry> filter(QueryContext queryContext) {
Index index = getIndex(queryContext);
return index.getRecords(value);
}
@Override
public boolean apply(Map.Entry mapEntry) {
Comparable entryValue = readAttribute(mapEntry);
if (entryValue == null) {
return value == null || value == IndexImpl.NULL;
}
value = convert(mapEntry, entryValue, value);
return entryValue.equals(value);
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
super.writeData(out);
out.writeObject(value);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
super.readData(in);
value = in.readObject();
}
@Override
public String toString() {
return attribute + "=" + value;
}
}
public abstract static class AbstractPredicate implements IndexAwarePredicate, DataSerializable {
protected String attribute;
private transient volatile AttributeType attributeType;
protected AbstractPredicate() {
}
protected AbstractPredicate(String attribute) {
this.attribute = attribute;
}
protected Comparable convert(Map.Entry mapEntry, Comparable entryValue, Comparable attributeValue) {
if (attributeValue == null) {
return null;
}
if (attributeValue instanceof IndexImpl.NullObject) {
return IndexImpl.NULL;
}
AttributeType type = attributeType;
if (type == null) {
QueryableEntry queryableEntry = (QueryableEntry) mapEntry;
type = queryableEntry.getAttributeType(attribute);
attributeType = type;
}
if (type == AttributeType.ENUM) {
// if attribute type is enum, convert given attribute to enum string
return type.getConverter().convert(attributeValue);
} else {
// if given attribute value is already in expected type then there's no need for conversion.
if (entryValue != null && entryValue.getClass().isAssignableFrom(attributeValue.getClass())) {
return attributeValue;
} else if (type != null) {
return type.getConverter().convert(attributeValue);
} else {
throw new QueryException("Unknown attribute type: " + attributeValue.getClass());
}
}
}
@Override
public boolean isIndexed(QueryContext queryContext) {
return getIndex(queryContext) != null;
}
protected Index getIndex(QueryContext queryContext) {
return queryContext.getIndex(attribute);
}
protected Comparable readAttribute(Map.Entry entry) {
QueryableEntry queryableEntry = (QueryableEntry) entry;
Comparable val = queryableEntry.getAttribute(attribute);
if (val != null && val.getClass().isEnum()) {
val = val.toString();
}
return val;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(attribute);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
attribute = in.readUTF();
}
}
private static class InstanceOfPredicate implements Predicate, DataSerializable {
private Class klass;
public InstanceOfPredicate(Class klass) {
this.klass = klass;
}
@Override
public boolean apply(Map.Entry mapEntry) {
Object value = mapEntry.getValue();
if (value == null) {
return false;
}
return klass.isAssignableFrom(value.getClass());
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(klass.getName());
}
@Override
public void readData(ObjectDataInput in) throws IOException {
String klassName = in.readUTF();
try {
klass = in.getClassLoader().loadClass(klassName);
} catch (ClassNotFoundException e) {
throw new HazelcastSerializationException("Failed to load class: " + klass, e);
}
}
@Override
public String toString() {
return " instanceOf (" + klass.getName() + ")";
}
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_query_Predicates.java
|
1,556 |
@XmlRootElement(name = "orient-server")
public class OServerConfiguration {
public static final String FILE_NAME = "server-config.xml";
// private static final String HEADER = "OrientDB Server configuration";
@XmlTransient
public String location;
@XmlElementWrapper
@XmlElementRef(type = OServerHandlerConfiguration.class)
public List<OServerHandlerConfiguration> handlers;
@XmlElementWrapper
@XmlElementRef(type = OServerHookConfiguration.class)
public List<OServerHookConfiguration> hooks;
@XmlElementRef(type = OServerNetworkConfiguration.class)
public OServerNetworkConfiguration network;
@XmlElementWrapper
@XmlElementRef(type = OServerStorageConfiguration.class)
public OServerStorageConfiguration[] storages;
@XmlElementWrapper(required = false)
@XmlElementRef(type = OServerUserConfiguration.class)
public OServerUserConfiguration[] users;
@XmlElementRef(type = OServerSecurityConfiguration.class)
public OServerSecurityConfiguration security;
@XmlElementWrapper
@XmlElementRef(type = OServerEntryConfiguration.class)
public OServerEntryConfiguration[] properties;
public static final String DEFAULT_CONFIG_FILE = "config/orientdb-server-config.xml";
public static final String PROPERTY_CONFIG_FILE = "orientdb.config.file";
public static final String SRV_ROOT_ADMIN = "root";
public static final String SRV_ROOT_GUEST = "guest";
/**
* Empty constructor for JAXB
*/
public OServerConfiguration() {
}
public OServerConfiguration(OServerConfigurationLoaderXml iFactory) {
location = FILE_NAME;
network = new OServerNetworkConfiguration(iFactory);
storages = new OServerStorageConfiguration[0];
security = new OServerSecurityConfiguration(iFactory);
}
public String getStoragePath(String iURL) {
if (storages != null)
for (OServerStorageConfiguration stg : storages)
if (stg.name.equals(iURL))
return stg.path;
return null;
}
/**
* Returns the property value configured, if any.
*
* @param iName
* Property name to find
*/
public String getProperty(final String iName) {
return getProperty(iName, null);
}
/**
* Returns the property value configured, if any.
*
* @param iName
* Property name to find
* @param iDefaultValue
* Default value returned if not found
*/
public String getProperty(final String iName, final String iDefaultValue) {
if (properties == null)
return null;
for (OServerEntryConfiguration p : properties) {
if (p.name.equals(iName))
return p.value;
}
return null;
}
public OServerUserConfiguration getUser(final String iName) {
for (OServerUserConfiguration u : users) {
if (u.name.equals(iName))
return u;
}
return null;
}
}
| 0true
|
server_src_main_java_com_orientechnologies_orient_server_config_OServerConfiguration.java
|
2,626 |
public static class PingResponse implements Streamable {
public static PingResponse[] EMPTY = new PingResponse[0];
private ClusterName clusterName;
private DiscoveryNode target;
private DiscoveryNode master;
private PingResponse() {
}
public PingResponse(DiscoveryNode target, DiscoveryNode master, ClusterName clusterName) {
this.target = target;
this.master = master;
this.clusterName = clusterName;
}
public ClusterName clusterName() {
return this.clusterName;
}
public DiscoveryNode target() {
return target;
}
public DiscoveryNode master() {
return master;
}
public static PingResponse readPingResponse(StreamInput in) throws IOException {
PingResponse response = new PingResponse();
response.readFrom(in);
return response;
}
@Override
public void readFrom(StreamInput in) throws IOException {
clusterName = readClusterName(in);
target = readNode(in);
if (in.readBoolean()) {
master = readNode(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
clusterName.writeTo(out);
target.writeTo(out);
if (master == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
master.writeTo(out);
}
}
@Override
public String toString() {
return "ping_response{target [" + target + "], master [" + master + "], cluster_name[" + clusterName.value() + "]}";
}
}
| 1no label
|
src_main_java_org_elasticsearch_discovery_zen_ping_ZenPing.java
|
1,540 |
final Comparator<MutableShardRouting> comparator = new Comparator<MutableShardRouting>() {
@Override
public int compare(MutableShardRouting o1,
MutableShardRouting o2) {
if (o1.primary() ^ o2.primary()) {
return o1.primary() ? -1 : o2.primary() ? 1 : 0;
}
final int indexCmp;
if ((indexCmp = o1.index().compareTo(o2.index())) == 0) {
return o1.getId() - o2.getId();
}
return indexCmp;
}
};
| 0true
|
src_main_java_org_elasticsearch_cluster_routing_allocation_allocator_BalancedShardsAllocator.java
|
890 |
public class PromotableFulfillmentGroupImpl implements PromotableFulfillmentGroup {
private static final long serialVersionUID = 1L;
protected FulfillmentGroup fulfillmentGroup;
protected PromotableOrder promotableOrder;
protected PromotableItemFactory itemFactory;
protected List<PromotableOrderItem> discountableOrderItems;
protected boolean useSaleAdjustments = false;
protected Money adjustedPrice;
public List<PromotableFulfillmentGroupAdjustment> candidateFulfillmentGroupAdjustments = new ArrayList<PromotableFulfillmentGroupAdjustment>();
public PromotableFulfillmentGroupImpl(FulfillmentGroup fulfillmentGroup,
PromotableOrder promotableOrder,
PromotableItemFactory itemFactory) {
this.fulfillmentGroup = fulfillmentGroup;
this.promotableOrder = promotableOrder;
this.itemFactory = itemFactory;
}
@Override
public FulfillmentGroup getFulfillmentGroup() {
return fulfillmentGroup;
}
@Override
public void updateRuleVariables(Map<String, Object> ruleVars) {
ruleVars.put("fulfillmentGroup", fulfillmentGroup);
}
@Override
public List<PromotableOrderItem> getDiscountableOrderItems() {
if (discountableOrderItems != null) {
return discountableOrderItems;
}
discountableOrderItems = new ArrayList<PromotableOrderItem>();
List<Long> discountableOrderItemIds = new ArrayList<Long>();
for (FulfillmentGroupItem fgItem : fulfillmentGroup.getFulfillmentGroupItems()) {
OrderItem orderItem = fgItem.getOrderItem();
if (orderItem.isDiscountingAllowed()) {
discountableOrderItemIds.add(fgItem.getOrderItem().getId());
} else {
if (orderItem instanceof OrderItemContainer) {
OrderItemContainer orderItemContainer = (OrderItemContainer) orderItem;
if (orderItemContainer.getAllowDiscountsOnChildItems()) {
for (OrderItem containedOrderItem : orderItemContainer.getOrderItems()) {
if (!containedOrderItem.isDiscountingAllowed()) {
discountableOrderItemIds.add(containedOrderItem.getId());
}
}
}
}
}
}
for (PromotableOrderItem item : promotableOrder.getDiscountableOrderItems()) {
if (discountableOrderItemIds.contains(item.getOrderItemId())) {
discountableOrderItems.add(item);
}
}
return discountableOrderItems;
}
protected Money getSalePriceBeforeAdjustments() {
Money salePrice = fulfillmentGroup.getSaleFulfillmentPrice();
if (salePrice == null) {
return fulfillmentGroup.getRetailFulfillmentPrice();
} else {
return salePrice;
}
}
protected Money calculateSaleAdjustmentPrice() {
Money returnPrice = getSalePriceBeforeAdjustments();
for (PromotableFulfillmentGroupAdjustment adjustment : candidateFulfillmentGroupAdjustments) {
returnPrice = returnPrice.subtract(adjustment.getSaleAdjustmentValue());
}
return returnPrice;
}
protected Money calculateRetailAdjustmentPrice() {
Money returnPrice = fulfillmentGroup.getRetailFulfillmentPrice();
for (PromotableFulfillmentGroupAdjustment adjustment : candidateFulfillmentGroupAdjustments) {
returnPrice = returnPrice.subtract(adjustment.getRetailAdjustmentValue());
}
return returnPrice;
}
/**
* This method will check to see if the salePriceAdjustments or retailPriceAdjustments are better
* and remove those that should not apply.
* @return
*/
public void chooseSaleOrRetailAdjustments() {
this.useSaleAdjustments = Boolean.FALSE;
Money saleAdjustmentPrice = calculateSaleAdjustmentPrice();
Money retailAdjustmentPrice = calculateRetailAdjustmentPrice();
if (saleAdjustmentPrice.lessThan(retailAdjustmentPrice)) {
this.useSaleAdjustments = Boolean.TRUE;
adjustedPrice = saleAdjustmentPrice;
} else {
adjustedPrice = retailAdjustmentPrice;
}
if (useSaleAdjustments) {
removeRetailOnlyAdjustments();
}
removeZeroDollarAdjustments(useSaleAdjustments);
finalizeAdjustments(useSaleAdjustments);
}
protected void finalizeAdjustments(boolean useSaleAdjustments) {
for (PromotableFulfillmentGroupAdjustment adjustment : candidateFulfillmentGroupAdjustments) {
adjustment.finalizeAdjustment(useSaleAdjustments);
}
}
/**
* Removes retail only adjustments.
*/
protected void removeRetailOnlyAdjustments() {
Iterator<PromotableFulfillmentGroupAdjustment> adjustments = candidateFulfillmentGroupAdjustments.iterator();
while (adjustments.hasNext()) {
PromotableFulfillmentGroupAdjustment adjustment = adjustments.next();
if (adjustment.getPromotableCandidateFulfillmentGroupOffer().getOffer().getApplyDiscountToSalePrice() == false) {
adjustments.remove();
}
}
}
/**
* If removeUnusedAdjustments is s
* @param useSaleAdjustments
*/
protected void removeZeroDollarAdjustments(boolean useSalePrice) {
Iterator<PromotableFulfillmentGroupAdjustment> adjustments = candidateFulfillmentGroupAdjustments.iterator();
while (adjustments.hasNext()) {
PromotableFulfillmentGroupAdjustment adjustment = adjustments.next();
if (useSalePrice) {
if (adjustment.getSaleAdjustmentValue().isZero()) {
adjustments.remove();
}
} else {
if (adjustment.getRetailAdjustmentValue().isZero()) {
adjustments.remove();
}
}
}
}
@Override
public Money getFinalizedPriceWithAdjustments() {
chooseSaleOrRetailAdjustments();
return adjustedPrice;
}
@Override
public Money calculatePriceWithoutAdjustments() {
if (fulfillmentGroup.getSaleFulfillmentPrice() != null) {
return fulfillmentGroup.getSaleFulfillmentPrice();
} else {
return fulfillmentGroup.getRetailFulfillmentPrice();
}
}
@Override
public void addCandidateFulfillmentGroupAdjustment(PromotableFulfillmentGroupAdjustment adjustment) {
candidateFulfillmentGroupAdjustments.add(adjustment);
}
@Override
public List<PromotableFulfillmentGroupAdjustment> getCandidateFulfillmentGroupAdjustments() {
return Collections.unmodifiableList(candidateFulfillmentGroupAdjustments);
}
@Override
public boolean canApplyOffer(PromotableCandidateFulfillmentGroupOffer fulfillmentGroupOffer) {
if (candidateFulfillmentGroupAdjustments.size() > 0) {
if (!fulfillmentGroupOffer.getOffer().isCombinableWithOtherOffers()) {
return false;
}
for (PromotableFulfillmentGroupAdjustment adjustment : candidateFulfillmentGroupAdjustments) {
if (!adjustment.isCombinable()) {
return false;
}
}
}
return true;
}
@Override
public Money calculatePriceWithAdjustments(boolean useSalePrice) {
if (useSalePrice) {
return calculateSaleAdjustmentPrice();
} else {
return calculateRetailAdjustmentPrice();
}
}
@Override
public boolean isTotalitarianOfferApplied() {
for (PromotableFulfillmentGroupAdjustment adjustment : candidateFulfillmentGroupAdjustments) {
if (adjustment.getPromotableCandidateFulfillmentGroupOffer().getOffer().isTotalitarianOffer()) {
return true;
}
}
return false;
}
@Override
public void removeAllCandidateAdjustments() {
candidateFulfillmentGroupAdjustments.clear();
}
}
| 0true
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableFulfillmentGroupImpl.java
|
80 |
class ChangeParametersProposal implements ICompletionProposal,
ICompletionProposalExtension6 {
private final Declaration dec;
private final CeylonEditor editor;
ChangeParametersProposal(Declaration dec, CeylonEditor editor) {
this.dec = dec;
this.editor = editor;
}
@Override
public Point getSelection(IDocument doc) {
return null;
}
@Override
public Image getImage() {
return REORDER;
}
@Override
public String getDisplayString() {
return "Change parameters of '" + dec.getName() + "'";
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument doc) {
new ChangeParametersRefactoringAction(editor).run();
}
@Override
public StyledString getStyledDisplayString() {
return Highlights.styleProposal(getDisplayString(), false);
}
public static void add(Collection<ICompletionProposal> proposals,
CeylonEditor editor) {
ChangeParametersRefactoring cpr = new ChangeParametersRefactoring(editor);
if (cpr.isEnabled()) {
proposals.add(new ChangeParametersProposal(cpr.getDeclaration(),
editor));
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ChangeParametersProposal.java
|
3,656 |
public class AnalyzerMapper implements Mapper, InternalMapper, RootMapper {
public static final String NAME = "_analyzer";
public static final String CONTENT_TYPE = "_analyzer";
public static class Defaults {
public static final String PATH = "_analyzer";
}
public static class Builder extends Mapper.Builder<Builder, AnalyzerMapper> {
private String field = Defaults.PATH;
public Builder() {
super(CONTENT_TYPE);
this.builder = this;
}
public Builder field(String field) {
this.field = field;
return this;
}
@Override
public AnalyzerMapper build(BuilderContext context) {
return new AnalyzerMapper(field);
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
AnalyzerMapper.Builder builder = analyzer();
for (Map.Entry<String, Object> entry : node.entrySet()) {
String fieldName = Strings.toUnderscoreCase(entry.getKey());
Object fieldNode = entry.getValue();
if (fieldName.equals("path")) {
builder.field(fieldNode.toString());
}
}
return builder;
}
}
private final String path;
public AnalyzerMapper() {
this(Defaults.PATH);
}
public AnalyzerMapper(String path) {
this.path = path.intern();
}
@Override
public String name() {
return CONTENT_TYPE;
}
@Override
public void preParse(ParseContext context) throws IOException {
}
@Override
public void postParse(ParseContext context) throws IOException {
Analyzer analyzer = context.docMapper().mappers().indexAnalyzer();
if (path != null) {
String value = null;
List<IndexableField> fields = context.doc().getFields();
for (int i = 0, fieldsSize = fields.size(); i < fieldsSize; i++) {
IndexableField field = fields.get(i);
if (field.name() == path) {
value = field.stringValue();
break;
}
}
if (value == null) {
value = context.ignoredValue(path);
}
if (value != null) {
analyzer = context.analysisService().analyzer(value);
if (analyzer == null) {
throw new MapperParsingException("No analyzer found for [" + value + "] from path [" + path + "]");
}
analyzer = context.docMapper().mappers().indexAnalyzer(analyzer);
}
}
context.analyzer(analyzer);
}
@Override
public void validate(ParseContext context) throws MapperParsingException {
}
@Override
public boolean includeInObject() {
return false;
}
@Override
public void parse(ParseContext context) throws IOException {
}
@Override
public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
}
@Override
public void traverse(FieldMapperListener fieldMapperListener) {
}
@Override
public void traverse(ObjectMapperListener objectMapperListener) {
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (path.equals(Defaults.PATH)) {
return builder;
}
builder.startObject(CONTENT_TYPE);
if (!path.equals(Defaults.PATH)) {
builder.field("path", path);
}
builder.endObject();
return builder;
}
@Override
public void close() {
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_mapper_internal_AnalyzerMapper.java
|
159 |
private class MockedLogLoader implements LogLoader
{
private long version;
private long tx;
private final File baseFile;
private final ByteBuffer activeBuffer;
private final int identifier = 1;
private final LogPruneStrategy pruning;
private final Map<Long, Long> lastCommittedTxs = new HashMap<Long, Long>();
private final Map<Long, Long> timestamps = new HashMap<Long, Long>();
private final int logSize;
MockedLogLoader( LogPruneStrategy pruning )
{
this( MAX_LOG_SIZE, pruning );
}
MockedLogLoader( int logSize, LogPruneStrategy pruning )
{
this.logSize = logSize;
this.pruning = pruning;
activeBuffer = ByteBuffer.allocate( logSize*10 );
baseFile = new File( directory, "log" );
clearAndWriteHeader();
}
public int getLogSize()
{
return logSize;
}
private void clearAndWriteHeader()
{
activeBuffer.clear();
LogIoUtils.writeLogHeader( activeBuffer, version, tx );
// Because writeLogHeader does flip()
activeBuffer.limit( activeBuffer.capacity() );
activeBuffer.position( LogIoUtils.LOG_HEADER_SIZE );
}
@Override
public ReadableByteChannel getLogicalLogOrMyselfCommitted( long version, long position )
throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public long getHighestLogVersion()
{
return version;
}
@Override
public File getFileName( long version )
{
File file = new File( baseFile + ".v" + version );
return file;
}
/**
* @param date start record date.
* @return whether or not this caused a rotation to happen.
* @throws IOException
*/
public boolean addTransaction( int commandSize, long date ) throws IOException
{
InMemoryLogBuffer tempLogBuffer = new InMemoryLogBuffer();
XidImpl xid = new XidImpl( getNewGlobalId( DEFAULT_SEED, 0 ), RESOURCE_XID );
LogIoUtils.writeStart( tempLogBuffer, identifier, xid, -1, -1, date, Long.MAX_VALUE );
LogIoUtils.writeCommand( tempLogBuffer, identifier, new TestXaCommand( commandSize ) );
LogIoUtils.writeCommit( false, tempLogBuffer, identifier, ++tx, date );
LogIoUtils.writeDone( tempLogBuffer, identifier );
tempLogBuffer.read( activeBuffer );
if ( !timestamps.containsKey( version ) )
{
timestamps.put( version, date ); // The first tx timestamp for this version
}
boolean rotate = (activeBuffer.capacity() - activeBuffer.remaining()) >= logSize;
if ( rotate )
{
rotate();
}
return rotate;
}
/**
* @return the total size of the previous log (currently {@link #getHighestLogVersion()}-1
*/
public void addTransactionsUntilRotationHappens() throws IOException
{
int size = 10;
while ( true )
{
if ( addTransaction( size, System.currentTimeMillis() ) )
{
return;
}
size = Math.max( 10, (size + 7)%100 );
}
}
public void rotate() throws IOException
{
lastCommittedTxs.put( version, tx );
writeBufferToFile( activeBuffer, getFileName( version++ ) );
pruning.prune( this );
clearAndWriteHeader();
}
private void writeBufferToFile( ByteBuffer buffer, File fileName ) throws IOException
{
StoreChannel channel = null;
try
{
buffer.flip();
channel = FS.open( fileName, "rw" );
channel.write( buffer );
}
finally
{
if ( channel != null )
{
channel.close();
}
}
}
public int getTotalSizeOfAllExistingLogFiles()
{
int size = 0;
for ( long version = getHighestLogVersion()-1; version >= 0; version-- )
{
File file = getFileName( version );
if ( FS.fileExists( file ) )
{
size += FS.getFileSize( file );
}
else
{
break;
}
}
return size;
}
public int getTotalTransactionCountOfAllExistingLogFiles()
{
if ( getHighestLogVersion() == 0 )
{
return 0;
}
long upper = getHighestLogVersion()-1;
long lower = upper;
while ( lower >= 0 )
{
File file = getFileName( lower-1 );
if ( !FS.fileExists( file ) )
{
break;
}
else
{
lower--;
}
}
return (int) (getLastCommittedTxId() - getFirstCommittedTxId( lower ));
}
@Override
public Long getFirstCommittedTxId( long version )
{
return lastCommittedTxs.get( version );
}
@Override
public Long getFirstStartRecordTimestamp( long version )
{
return timestamps.get( version );
}
@Override
public long getLastCommittedTxId()
{
return tx;
}
}
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestLogPruneStrategy.java
|
460 |
el[6] = StaticArrayEntryList.of(Iterables.transform(entries.entrySet(),new Function<Map.Entry<Integer, Long>, Entry>() {
@Nullable
@Override
public Entry apply(@Nullable Map.Entry<Integer, Long> entry) {
return StaticArrayEntry.ofBytes(entry, ByteEntryGetter.SCHEMA_INSTANCE);
}
}));
| 0true
|
titan-test_src_test_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_StaticArrayEntryTest.java
|
3,319 |
public static class Builder implements IndexFieldData.Builder {
@Override
public IndexFieldData<?> build(Index index, @IndexSettings Settings indexSettings, FieldMapper<?> mapper, IndexFieldDataCache cache,
CircuitBreakerService breakerService) {
return new DoubleArrayIndexFieldData(index, indexSettings, mapper.names(), mapper.fieldDataType(), cache, breakerService);
}
}
| 0true
|
src_main_java_org_elasticsearch_index_fielddata_plain_DoubleArrayIndexFieldData.java
|
1,426 |
public class CategoryHandlerMapping extends BLCAbstractHandlerMapping {
private String controllerName="blCategoryController";
@Resource(name = "blCatalogService")
private CatalogService catalogService;
public static final String CURRENT_CATEGORY_ATTRIBUTE_NAME = "category";
@Override
protected Object getHandlerInternal(HttpServletRequest request)
throws Exception {
BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
if (context != null && context.getRequestURIWithoutContext() != null) {
Category category = catalogService.findCategoryByURI(context.getRequestURIWithoutContext());
if (category != null) {
context.getRequest().setAttribute(CURRENT_CATEGORY_ATTRIBUTE_NAME, category);
return controllerName;
}
}
return null;
}
}
| 0true
|
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_catalog_CategoryHandlerMapping.java
|
1,105 |
public class OrderMultishipOptionDTO {
protected Long id;
protected Long orderItemId;
protected Long addressId;
protected Long fulfillmentOptionId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getOrderItemId() {
return orderItemId;
}
public void setOrderItemId(Long orderItemId) {
this.orderItemId = orderItemId;
}
public Long getAddressId() {
return addressId;
}
public void setAddressId(Long addressId) {
this.addressId = addressId;
}
public Long getFulfillmentOptionId() {
return fulfillmentOptionId;
}
public void setFulfillmentOptionId(Long fulfillmentOptionId) {
this.fulfillmentOptionId = fulfillmentOptionId;
}
}
| 0true
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_call_OrderMultishipOptionDTO.java
|
1,974 |
class TTLReachabilityHandler extends AbstractReachabilityHandler {
public TTLReachabilityHandler() {
}
@Override
public Record handle(Record record, long criteria, long timeInNanos) {
if (record == null) {
return null;
}
boolean result;
final long ttl = record.getTtl();
// when ttl is zero or negative, it should remain eternally.
if (ttl < 1L) {
return record;
}
// expect lastUpdateTime set when creating.
final long lastUpdatedTime = record.getLastUpdateTime();
assert ttl > 0L : log("wrong ttl %d", ttl);
assert lastUpdatedTime > 0L;
assert timeInNanos > 0L;
assert timeInNanos >= lastUpdatedTime : log("time >= lastUpdateTime (%d >= %d)",
timeInNanos, lastUpdatedTime);;
result = timeInNanos - lastUpdatedTime >= ttl;
return result ? null : record;
}
@Override
public short niceNumber() {
return 0;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_map_eviction_TTLReachabilityHandler.java
|
731 |
public class DeleteByQueryAction extends Action<DeleteByQueryRequest, DeleteByQueryResponse, DeleteByQueryRequestBuilder> {
public static final DeleteByQueryAction INSTANCE = new DeleteByQueryAction();
public static final String NAME = "deleteByQuery";
private DeleteByQueryAction() {
super(NAME);
}
@Override
public DeleteByQueryResponse newResponse() {
return new DeleteByQueryResponse();
}
@Override
public DeleteByQueryRequestBuilder newRequestBuilder(Client client) {
return new DeleteByQueryRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_deletebyquery_DeleteByQueryAction.java
|
2,181 |
public abstract class CachedFilter extends Filter {
public static boolean isCached(Filter filter) {
return filter instanceof CachedFilter;
}
}
| 0true
|
src_main_java_org_elasticsearch_common_lucene_search_CachedFilter.java
|
468 |
public interface SandBox extends Serializable {
public Long getId();
public void setId(Long id);
/**
* The name of the sandbox.
* Certain sandbox names are reserved in the system. User created
* sandboxes cannot start with "", "approve_", or "deploy_".
*
* @return String sandbox name
*/
public String getName();
public void setName(String name);
public SandBoxType getSandBoxType();
public void setSandBoxType(SandBoxType sandBoxType);
public Site getSite();
public void setSite(Site site);
public Long getAuthor();
public void setAuthor(Long author);
public SandBox clone();
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_sandbox_domain_SandBox.java
|
877 |
public class CountDownLatchService implements ManagedService, RemoteService, MigrationAwareService {
/**
* The service name of this CountDownLatchService.
*/
public static final String SERVICE_NAME = "hz:impl:countDownLatchService";
private final ConcurrentMap<String, CountDownLatchInfo> latches
= new ConcurrentHashMap<String, CountDownLatchInfo>();
private NodeEngine nodeEngine;
public int getCount(String name) {
CountDownLatchInfo latch = latches.get(name);
return latch != null ? latch.getCount() : 0;
}
public boolean setCount(String name, int count) {
if (count <= 0) {
latches.remove(name);
return false;
} else {
CountDownLatchInfo latch = latches.get(name);
if (latch == null) {
latch = new CountDownLatchInfo(name);
latches.put(name, latch);
}
return latch.setCount(count);
}
}
public void setCountDirect(String name, int count) {
if (count <= 0) {
latches.remove(name);
} else {
CountDownLatchInfo latch = latches.get(name);
if (latch == null) {
latch = new CountDownLatchInfo(name);
latches.put(name, latch);
}
latch.setCountDirect(count);
}
}
public void countDown(String name) {
CountDownLatchInfo latch = latches.get(name);
if (latch != null) {
if (latch.countDown() == 0) {
latches.remove(name);
}
}
}
public boolean shouldWait(String name) {
CountDownLatchInfo latch = latches.get(name);
return latch != null && latch.getCount() > 0;
}
@Override
public void init(NodeEngine nodeEngine, Properties properties) {
this.nodeEngine = nodeEngine;
}
@Override
public void reset() {
latches.clear();
}
@Override
public void shutdown(boolean terminate) {
latches.clear();
}
@Override
public CountDownLatchProxy createDistributedObject(String name) {
return new CountDownLatchProxy(name, nodeEngine);
}
@Override
public void destroyDistributedObject(String name) {
latches.remove(name);
}
@Override
public void beforeMigration(PartitionMigrationEvent partitionMigrationEvent) {
}
@Override
public Operation prepareReplicationOperation(PartitionReplicationEvent event) {
if (event.getReplicaIndex() > 1) {
return null;
}
Collection<CountDownLatchInfo> data = new LinkedList<CountDownLatchInfo>();
for (Map.Entry<String, CountDownLatchInfo> latchEntry : latches.entrySet()) {
String name = latchEntry.getKey();
if (getPartitionId(name) == event.getPartitionId()) {
CountDownLatchInfo value = latchEntry.getValue();
data.add(value);
}
}
return data.isEmpty() ? null : new CountDownLatchReplicationOperation(data);
}
@Override
public void commitMigration(PartitionMigrationEvent event) {
if (event.getMigrationEndpoint() == MigrationEndpoint.SOURCE) {
int partitionId = event.getPartitionId();
clearPartition(partitionId);
}
}
@Override
public void rollbackMigration(PartitionMigrationEvent event) {
if (event.getMigrationEndpoint() == MigrationEndpoint.DESTINATION) {
int partitionId = event.getPartitionId();
clearPartition(partitionId);
}
}
private void clearPartition(int partitionId) {
final Iterator<String> iter = latches.keySet().iterator();
while (iter.hasNext()) {
final String name = iter.next();
if (getPartitionId(name) == partitionId) {
iter.remove();
}
}
}
private int getPartitionId(String name) {
String partitionKey = StringPartitioningStrategy.getPartitionKey(name);
return nodeEngine.getPartitionService().getPartitionId(partitionKey);
}
@Override
public void clearPartitionReplica(int partitionId) {
clearPartition(partitionId);
}
public CountDownLatchInfo getLatch(String name) {
return latches.get(name);
}
// need for testing..
public boolean containsLatch(String name) {
return latches.containsKey(name);
}
public void add(CountDownLatchInfo latch) {
String name = latch.getName();
latches.put(name, latch);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_countdownlatch_CountDownLatchService.java
|
94 |
class ReadOnlyTransactionImpl implements Transaction
{
private static final int RS_ENLISTED = 0;
private static final int RS_SUSPENDED = 1;
private static final int RS_DELISTED = 2;
private static final int RS_READONLY = 3; // set in prepare
private final byte globalId[];
private int status = Status.STATUS_ACTIVE;
private boolean active = true;
private final LinkedList<ResourceElement> resourceList =
new LinkedList<>();
private List<Synchronization> syncHooks =
new ArrayList<>();
private final int eventIdentifier;
private final ReadOnlyTxManager txManager;
private final StringLogger logger;
ReadOnlyTransactionImpl( byte[] xidGlobalId, ReadOnlyTxManager txManager, StringLogger logger )
{
this.txManager = txManager;
this.logger = logger;
globalId = xidGlobalId;
eventIdentifier = txManager.getNextEventIdentifier();
}
@Override
public synchronized String toString()
{
StringBuilder txString = new StringBuilder( "Transaction[Status="
+ txManager.getTxStatusAsString( status ) + ",ResourceList=" );
Iterator<ResourceElement> itr = resourceList.iterator();
while ( itr.hasNext() )
{
txString.append( itr.next().toString() );
if ( itr.hasNext() )
{
txString.append( "," );
}
}
return txString.toString();
}
@Override
public synchronized void commit() throws RollbackException,
HeuristicMixedException, IllegalStateException
{
// make sure tx not suspended
txManager.commit();
}
@Override
public synchronized void rollback() throws IllegalStateException,
SystemException
{
// make sure tx not suspended
txManager.rollback();
}
@Override
public synchronized boolean enlistResource( XAResource xaRes )
throws RollbackException, IllegalStateException
{
if ( xaRes == null )
{
throw new IllegalArgumentException( "Null xa resource" );
}
if ( status == Status.STATUS_ACTIVE ||
status == Status.STATUS_PREPARING )
{
try
{
if ( resourceList.size() == 0 )
{
//
byte branchId[] = txManager.getBranchId( xaRes );
Xid xid = new XidImpl( globalId, branchId );
resourceList.add( new ResourceElement( xid, xaRes ) );
xaRes.start( xid, XAResource.TMNOFLAGS );
return true;
}
Xid sameRmXid = null;
for ( ResourceElement re : resourceList )
{
if ( sameRmXid == null && re.getResource().isSameRM( xaRes ) )
{
sameRmXid = re.getXid();
}
if ( xaRes == re.getResource() )
{
if ( re.getStatus() == RS_SUSPENDED )
{
xaRes.start( re.getXid(), XAResource.TMRESUME );
}
else
{
// either enlisted or delisted
// is TMJOIN correct then?
xaRes.start( re.getXid(), XAResource.TMJOIN );
}
re.setStatus( RS_ENLISTED );
return true;
}
}
if ( sameRmXid != null ) // should we join?
{
resourceList.add( new ResourceElement( sameRmXid, xaRes ) );
xaRes.start( sameRmXid, XAResource.TMJOIN );
}
else
// new branch
{
// ResourceElement re = resourceList.getFirst();
byte branchId[] = txManager.getBranchId( xaRes );
Xid xid = new XidImpl( globalId, branchId );
resourceList.add( new ResourceElement( xid, xaRes ) );
xaRes.start( xid, XAResource.TMNOFLAGS );
}
return true;
}
catch ( XAException e )
{
logger.error( "Unable to enlist resource[" + xaRes + "]", e );
status = Status.STATUS_MARKED_ROLLBACK;
return false;
}
}
else if ( status == Status.STATUS_ROLLING_BACK ||
status == Status.STATUS_ROLLEDBACK ||
status == Status.STATUS_MARKED_ROLLBACK )
{
throw new RollbackException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
throw new IllegalStateException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
@Override
public synchronized boolean delistResource( XAResource xaRes, int flag )
throws IllegalStateException
{
if ( xaRes == null )
{
throw new IllegalArgumentException( "Null xa resource" );
}
if ( flag != XAResource.TMSUCCESS && flag != XAResource.TMSUSPEND &&
flag != XAResource.TMFAIL )
{
throw new IllegalArgumentException( "Illegal flag: " + flag );
}
ResourceElement re = null;
for ( ResourceElement reMatch : resourceList )
{
if ( reMatch.getResource() == xaRes )
{
re = reMatch;
break;
}
}
if ( re == null )
{
return false;
}
if ( status == Status.STATUS_ACTIVE ||
status == Status.STATUS_MARKED_ROLLBACK )
{
try
{
xaRes.end( re.getXid(), flag );
if ( flag == XAResource.TMSUSPEND || flag == XAResource.TMFAIL )
{
re.setStatus( RS_SUSPENDED );
}
else
{
re.setStatus( RS_DELISTED );
}
return true;
}
catch ( XAException e )
{
logger.error("Unable to delist resource[" + xaRes + "]", e );
status = Status.STATUS_MARKED_ROLLBACK;
return false;
}
}
throw new IllegalStateException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
// TODO: figure out if this needs synchronization or make status volatile
public int getStatus()
{
return status;
}
void setStatus( int status )
{
this.status = status;
}
private boolean beforeCompletionRunning = false;
private List<Synchronization> syncHooksAdded = new ArrayList<>();
@Override
public synchronized void registerSynchronization( Synchronization s )
throws RollbackException, IllegalStateException
{
if ( s == null )
{
throw new IllegalArgumentException( "Null parameter" );
}
if ( status == Status.STATUS_ACTIVE ||
status == Status.STATUS_PREPARING ||
status == Status.STATUS_MARKED_ROLLBACK )
{
if ( !beforeCompletionRunning )
{
syncHooks.add( s );
}
else
{
// avoid CME if synchronization is added in before completion
syncHooksAdded.add( s );
}
}
else if ( status == Status.STATUS_ROLLING_BACK ||
status == Status.STATUS_ROLLEDBACK )
{
throw new RollbackException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
else
{
throw new IllegalStateException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
}
synchronized void doBeforeCompletion()
{
beforeCompletionRunning = true;
try
{
for ( Synchronization s : syncHooks )
{
try
{
s.beforeCompletion();
}
catch ( Throwable t )
{
logger.warn( "Caught exception from tx syncronization[" + s
+ "] beforeCompletion()", t );
}
}
// execute any hooks added since we entered doBeforeCompletion
while ( !syncHooksAdded.isEmpty() )
{
List<Synchronization> addedHooks = syncHooksAdded;
syncHooksAdded = new ArrayList<>();
for ( Synchronization s : addedHooks )
{
s.beforeCompletion();
syncHooks.add( s );
}
}
}
finally
{
beforeCompletionRunning = false;
}
}
synchronized void doAfterCompletion()
{
for ( Synchronization s : syncHooks )
{
try
{
s.afterCompletion( status );
}
catch ( Throwable t )
{
logger.warn( "Caught exception from tx syncronization[" + s
+ "] afterCompletion()", t );
}
}
syncHooks = null; // help gc
}
@Override
public void setRollbackOnly() throws IllegalStateException
{
if ( status == Status.STATUS_ACTIVE ||
status == Status.STATUS_PREPARING ||
status == Status.STATUS_PREPARED ||
status == Status.STATUS_MARKED_ROLLBACK ||
status == Status.STATUS_ROLLING_BACK )
{
status = Status.STATUS_MARKED_ROLLBACK;
}
else
{
throw new IllegalStateException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
}
@Override
public boolean equals( Object o )
{
if ( !(o instanceof ReadOnlyTransactionImpl) )
{
return false;
}
ReadOnlyTransactionImpl other = (ReadOnlyTransactionImpl) o;
return this.eventIdentifier == other.eventIdentifier;
}
private volatile int hashCode = 0;
@Override
public int hashCode()
{
if ( hashCode == 0 )
{
hashCode = 3217 * eventIdentifier;
}
return hashCode;
}
int getResourceCount()
{
return resourceList.size();
}
void doRollback() throws XAException
{
status = Status.STATUS_ROLLING_BACK;
LinkedList<Xid> rolledBackXids = new LinkedList<>();
for ( ResourceElement re : resourceList )
{
if ( !rolledBackXids.contains( re.getXid() ) )
{
rolledBackXids.add( re.getXid() );
re.getResource().rollback( re.getXid() );
}
}
status = Status.STATUS_ROLLEDBACK;
}
private static class ResourceElement
{
private Xid xid = null;
private XAResource resource = null;
private int status;
ResourceElement( Xid xid, XAResource resource )
{
this.xid = xid;
this.resource = resource;
status = RS_ENLISTED;
}
Xid getXid()
{
return xid;
}
XAResource getResource()
{
return resource;
}
int getStatus()
{
return status;
}
void setStatus( int status )
{
this.status = status;
}
@Override
public String toString()
{
String statusString;
switch ( status )
{
case RS_ENLISTED:
statusString = "ENLISTED";
break;
case RS_DELISTED:
statusString = "DELISTED";
break;
case RS_SUSPENDED:
statusString = "SUSPENDED";
break;
case RS_READONLY:
statusString = "READONLY";
break;
default:
statusString = "UNKNOWN";
}
return "Xid[" + xid + "] XAResource[" + resource + "] Status["
+ statusString + "]";
}
}
synchronized void markAsActive()
{
if ( active )
{
throw new IllegalStateException( "Transaction[" + this
+ "] already active" );
}
active = true;
}
synchronized void markAsSuspended()
{
if ( !active )
{
throw new IllegalStateException( "Transaction[" + this
+ "] already suspended" );
}
active = false;
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_ReadOnlyTransactionImpl.java
|
611 |
public abstract class OIndexMultiValues extends OIndexAbstract<Set<OIdentifiable>> {
public OIndexMultiValues(final String type, String algorithm, OIndexEngine<Set<OIdentifiable>> indexEngine,
String valueContainerAlgorithm) {
super(type, algorithm, indexEngine, valueContainerAlgorithm);
}
public Set<OIdentifiable> get(Object key) {
checkForRebuild();
key = getCollatingValue(key);
acquireSharedLock();
try {
final Set<OIdentifiable> values = indexEngine.get(key);
if (values == null)
return Collections.emptySet();
return new HashSet<OIdentifiable>(values);
} finally {
releaseSharedLock();
}
}
public long count(Object key) {
checkForRebuild();
key = getCollatingValue(key);
acquireSharedLock();
try {
final Set<OIdentifiable> values = indexEngine.get(key);
if (values == null)
return 0;
return values.size();
} finally {
releaseSharedLock();
}
}
public OIndexMultiValues put(Object key, final OIdentifiable iSingleValue) {
checkForRebuild();
key = getCollatingValue(key);
modificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
checkForKeyType(key);
Set<OIdentifiable> values = indexEngine.get(key);
if (values == null) {
if (ODefaultIndexFactory.SBTREEBONSAI_VALUE_CONTAINER.equals(valueContainerAlgorithm)) {
values = new OIndexRIDContainer(getName());
} else {
values = new OMVRBTreeRIDSet(OGlobalConfiguration.MVRBTREE_RID_BINARY_THRESHOLD.getValueAsInteger());
((OMVRBTreeRIDSet) values).setAutoConvertToRecord(false);
}
}
if (!iSingleValue.getIdentity().isValid())
((ORecord<?>) iSingleValue).save();
values.add(iSingleValue.getIdentity());
indexEngine.put(key, values);
return this;
} finally {
releaseExclusiveLock();
}
} finally {
modificationLock.releaseModificationLock();
}
}
@Override
protected void putInSnapshot(Object key, OIdentifiable value, final Map<Object, Object> snapshot) {
key = getCollatingValue(key);
Object snapshotValue = snapshot.get(key);
Set<OIdentifiable> values;
if (snapshotValue == null)
values = indexEngine.get(key);
else if (snapshotValue.equals(RemovedValue.INSTANCE))
values = null;
else
values = (Set<OIdentifiable>) snapshotValue;
if (values == null) {
if (ODefaultIndexFactory.SBTREEBONSAI_VALUE_CONTAINER.equals(valueContainerAlgorithm)) {
values = new OIndexRIDContainer(getName());
} else {
values = new OMVRBTreeRIDSet(OGlobalConfiguration.MVRBTREE_RID_BINARY_THRESHOLD.getValueAsInteger());
((OMVRBTreeRIDSet) values).setAutoConvertToRecord(false);
}
snapshot.put(key, values);
}
values.add(value.getIdentity());
if (values instanceof OIndexRIDContainer && ((OIndexRIDContainer) values).isEmbedded())
snapshot.put(key, values);
}
@Override
public boolean remove(Object key, final OIdentifiable value) {
checkForRebuild();
key = getCollatingValue(key);
modificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
Set<OIdentifiable> recs = indexEngine.get(key);
if (recs == null)
return false;
if (recs.remove(value)) {
if (recs.isEmpty())
indexEngine.remove(key);
else
indexEngine.put(key, recs);
return true;
}
return false;
} finally {
releaseExclusiveLock();
}
} finally {
modificationLock.releaseModificationLock();
}
}
@Override
protected void removeFromSnapshot(Object key, final OIdentifiable value, final Map<Object, Object> snapshot) {
key = getCollatingValue(key);
final Object snapshotValue = snapshot.get(key);
Set<OIdentifiable> values;
if (snapshotValue == null)
values = indexEngine.get(key);
else if (snapshotValue.equals(RemovedValue.INSTANCE))
values = null;
else
values = (Set<OIdentifiable>) snapshotValue;
if (values == null)
return;
if (values.remove(value)) {
if (values.isEmpty())
snapshot.put(key, RemovedValue.INSTANCE);
else
snapshot.put(key, values);
}
}
@Override
protected void commitSnapshot(Map<Object, Object> snapshot) {
for (Map.Entry<Object, Object> snapshotEntry : snapshot.entrySet()) {
Object key = snapshotEntry.getKey();
Object value = snapshotEntry.getValue();
checkForKeyType(key);
if (value.equals(RemovedValue.INSTANCE))
indexEngine.remove(key);
else
indexEngine.put(key, (Set<OIdentifiable>) value);
}
}
public OIndexMultiValues create(final String name, final OIndexDefinition indexDefinition, final String clusterIndexName,
final Set<String> clustersToIndex, boolean rebuild, final OProgressListener progressListener) {
final OStreamSerializer serializer;
if (ODefaultIndexFactory.SBTREEBONSAI_VALUE_CONTAINER.equals(valueContainerAlgorithm))
serializer = OStreamSerializerSBTreeIndexRIDContainer.INSTANCE;
else
serializer = OStreamSerializerListRID.INSTANCE;
return (OIndexMultiValues) super.create(name, indexDefinition, clusterIndexName, clustersToIndex, rebuild, progressListener,
serializer);
}
public void getValuesBetween(Object iRangeFrom, final boolean fromInclusive, Object iRangeTo, final boolean toInclusive,
final IndexValuesResultListener resultListener) {
checkForRebuild();
iRangeFrom = getCollatingValue(iRangeFrom);
iRangeTo = getCollatingValue(iRangeTo);
acquireSharedLock();
try {
indexEngine.getValuesBetween(iRangeFrom, fromInclusive, iRangeTo, toInclusive, MultiValuesTransformer.INSTANCE,
new OIndexEngine.ValuesResultListener() {
@Override
public boolean addResult(OIdentifiable identifiable) {
return resultListener.addResult(identifiable);
}
});
} finally {
releaseSharedLock();
}
}
public void getValuesMajor(Object iRangeFrom, final boolean isInclusive, final IndexValuesResultListener valuesResultListener) {
checkForRebuild();
iRangeFrom = getCollatingValue(iRangeFrom);
acquireSharedLock();
try {
indexEngine.getValuesMajor(iRangeFrom, isInclusive, MultiValuesTransformer.INSTANCE, new OIndexEngine.ValuesResultListener() {
@Override
public boolean addResult(OIdentifiable identifiable) {
return valuesResultListener.addResult(identifiable);
}
});
} finally {
releaseSharedLock();
}
}
public void getValuesMinor(Object iRangeTo, final boolean isInclusive, final IndexValuesResultListener resultListener) {
checkForRebuild();
iRangeTo = getCollatingValue(iRangeTo);
acquireSharedLock();
try {
indexEngine.getValuesMinor(iRangeTo, isInclusive, MultiValuesTransformer.INSTANCE, new OIndexEngine.ValuesResultListener() {
@Override
public boolean addResult(OIdentifiable identifiable) {
return resultListener.addResult(identifiable);
}
});
} finally {
releaseSharedLock();
}
}
public void getValues(final Collection<?> iKeys, final IndexValuesResultListener resultListener) {
checkForRebuild();
final List<Object> sortedKeys = new ArrayList<Object>(iKeys);
Collections.sort(sortedKeys, ODefaultComparator.INSTANCE);
acquireSharedLock();
try {
for (Object key : sortedKeys) {
key = getCollatingValue(key);
final Set<OIdentifiable> values = indexEngine.get(key);
if (values == null)
continue;
if (!values.isEmpty()) {
for (final OIdentifiable value : values) {
if (!resultListener.addResult(value))
return;
}
}
}
} finally {
releaseSharedLock();
}
}
public void getEntriesMajor(Object iRangeFrom, final boolean isInclusive, final IndexEntriesResultListener entriesResultListener) {
checkForRebuild();
iRangeFrom = getCollatingValue(iRangeFrom);
acquireSharedLock();
try {
indexEngine.getEntriesMajor(iRangeFrom, isInclusive, MultiValuesTransformer.INSTANCE,
new OIndexEngine.EntriesResultListener() {
@Override
public boolean addResult(ODocument entry) {
return entriesResultListener.addResult(entry);
}
});
} finally {
releaseSharedLock();
}
}
public void getEntriesMinor(Object iRangeTo, boolean isInclusive, final IndexEntriesResultListener entriesResultListener) {
checkForRebuild();
iRangeTo = getCollatingValue(iRangeTo);
acquireSharedLock();
try {
indexEngine.getEntriesMinor(iRangeTo, isInclusive, MultiValuesTransformer.INSTANCE, new OIndexEngine.EntriesResultListener() {
@Override
public boolean addResult(ODocument entry) {
return entriesResultListener.addResult(entry);
}
});
} finally {
releaseSharedLock();
}
}
public void getEntriesBetween(Object iRangeFrom, Object iRangeTo, boolean inclusive,
final IndexEntriesResultListener indexEntriesResultListener) {
checkForRebuild();
iRangeFrom = getCollatingValue(iRangeFrom);
iRangeTo = getCollatingValue(iRangeTo);
final OType[] types = getDefinition().getTypes();
if (types.length == 1) {
iRangeFrom = OType.convert(iRangeFrom, types[0].getDefaultJavaType());
iRangeTo = OType.convert(iRangeTo, types[0].getDefaultJavaType());
}
acquireSharedLock();
try {
indexEngine.getEntriesBetween(iRangeFrom, iRangeTo, inclusive, MultiValuesTransformer.INSTANCE,
new OIndexEngine.EntriesResultListener() {
@Override
public boolean addResult(ODocument entry) {
return indexEntriesResultListener.addResult(entry);
}
});
} finally {
releaseSharedLock();
}
}
public long count(Object iRangeFrom, final boolean fromInclusive, Object iRangeTo, final boolean toInclusive,
final int maxValuesToFetch) {
checkForRebuild();
iRangeFrom = getCollatingValue(iRangeFrom);
iRangeTo = getCollatingValue(iRangeTo);
final OType[] types = getDefinition().getTypes();
if (types.length == 1) {
iRangeFrom = OType.convert(iRangeFrom, types[0].getDefaultJavaType());
iRangeTo = OType.convert(iRangeTo, types[0].getDefaultJavaType());
}
if (iRangeFrom != null && iRangeTo != null && iRangeFrom.getClass() != iRangeTo.getClass())
throw new IllegalArgumentException("Range from-to parameters are of different types");
acquireSharedLock();
try {
return indexEngine.count(iRangeFrom, fromInclusive, iRangeTo, toInclusive, maxValuesToFetch, MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public void getEntries(Collection<?> iKeys, IndexEntriesResultListener resultListener) {
checkForRebuild();
final List<Object> sortedKeys = new ArrayList<Object>(iKeys);
Collections.sort(sortedKeys, ODefaultComparator.INSTANCE);
acquireSharedLock();
try {
for (Object key : sortedKeys) {
key = getCollatingValue(key);
final Set<OIdentifiable> values = indexEngine.get(key);
if (values == null)
continue;
if (!values.isEmpty()) {
for (final OIdentifiable value : values) {
final ODocument document = new ODocument();
document.field("key", key);
document.field("rid", value.getIdentity());
document.unsetDirty();
if (!resultListener.addResult(document))
return;
}
}
}
} finally {
releaseSharedLock();
}
}
public long getSize() {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.size(MultiValuesTransformer.INSTANCE);
} finally {
releaseSharedLock();
}
}
public long getKeySize() {
checkForRebuild();
acquireSharedLock();
try {
return indexEngine.size(null);
} finally {
releaseSharedLock();
}
}
public Iterator<OIdentifiable> valuesIterator() {
checkForRebuild();
acquireSharedLock();
try {
return new OSharedResourceIterator<OIdentifiable>(this, new OMultiCollectionIterator<OIdentifiable>(
indexEngine.valuesIterator()));
} finally {
releaseSharedLock();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Iterator<OIdentifiable> valuesInverseIterator() {
checkForRebuild();
acquireSharedLock();
try {
return new OSharedResourceIterator(this, new OMultiCollectionIterator<OIdentifiable>(indexEngine.inverseValuesIterator()));
} finally {
releaseSharedLock();
}
}
private static final class MultiValuesTransformer implements OIndexEngine.ValuesTransformer<Set<OIdentifiable>> {
private static final MultiValuesTransformer INSTANCE = new MultiValuesTransformer();
@Override
public Collection<OIdentifiable> transformFromValue(Set<OIdentifiable> value) {
return value;
}
@Override
public Set<OIdentifiable> transformToValue(Collection<OIdentifiable> collection) {
return (Set<OIdentifiable>) collection;
}
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_index_OIndexMultiValues.java
|
3,339 |
public static class Builder implements IndexFieldData.Builder {
@Override
public IndexFieldData<?> build(Index index, @IndexSettings Settings indexSettings, FieldMapper<?> mapper, IndexFieldDataCache cache,
CircuitBreakerService breakerService) {
return new FloatArrayIndexFieldData(index, indexSettings, mapper.names(), mapper.fieldDataType(), cache, breakerService);
}
}
| 0true
|
src_main_java_org_elasticsearch_index_fielddata_plain_FloatArrayIndexFieldData.java
|
1,646 |
@Component("blPasswordFieldMetadataProvider")
@Scope("prototype")
public class PasswordFieldMetadataProvider extends AbstractFieldMetadataProvider implements FieldMetadataProvider {
@Override
public int getOrder() {
return FieldMetadataProvider.BASIC;
}
@Override
public FieldProviderResponse addMetadataFromFieldType(AddMetadataFromFieldTypeRequest addMetadataFromFieldTypeRequest, Map<String, FieldMetadata> metadata) {
if (addMetadataFromFieldTypeRequest.getPresentationAttribute() instanceof BasicFieldMetadata &&
SupportedFieldType.PASSWORD.equals(((BasicFieldMetadata) addMetadataFromFieldTypeRequest.getPresentationAttribute()).getExplicitFieldType())) {
//build the metadata for the password field
addMetadataFromFieldTypeRequest.getDynamicEntityDao().getDefaultFieldMetadataProvider().addMetadataFromFieldType(addMetadataFromFieldTypeRequest, metadata);
((BasicFieldMetadata)addMetadataFromFieldTypeRequest.getPresentationAttribute()).setFieldType(SupportedFieldType.PASSWORD);
//clone the password field and add in a custom one
BasicFieldMetadata confirmMd = (BasicFieldMetadata) addMetadataFromFieldTypeRequest.getPresentationAttribute().cloneFieldMetadata();
confirmMd.setFieldName("passwordConfirm");
confirmMd.setFriendlyName("AdminUserImpl_Admin_Password_Confirm");
confirmMd.setExplicitFieldType(SupportedFieldType.PASSWORD_CONFIRM);
confirmMd.setValidationConfigurations(new HashMap<String, Map<String,String>>());
metadata.put("passwordConfirm", confirmMd);
return FieldProviderResponse.HANDLED;
} else {
return FieldProviderResponse.NOT_HANDLED;
}
}
@Override
public FieldProviderResponse addMetadata(AddMetadataRequest addMetadataRequest, Map<String, FieldMetadata> metadata) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public FieldProviderResponse lateStageAddMetadata(LateStageAddMetadataRequest addMetadataRequest, Map<String, FieldMetadata> metadata) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public FieldProviderResponse overrideViaAnnotation(OverrideViaAnnotationRequest overrideViaAnnotationRequest, Map<String, FieldMetadata> metadata) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public FieldProviderResponse overrideViaXml(OverrideViaXmlRequest overrideViaXmlRequest, Map<String, FieldMetadata> metadata) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public FieldProviderResponse addMetadataFromMappingData(AddMetadataFromMappingDataRequest addMetadataFromMappingDataRequest, FieldMetadata metadata) {
return FieldProviderResponse.NOT_HANDLED;
}
}
| 0true
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_dao_provider_metadata_PasswordFieldMetadataProvider.java
|
3,754 |
private class RequestWrapper extends HttpServletRequestWrapper {
final ResponseWrapper res;
HazelcastHttpSession hazelcastSession;
String requestedSessionId;
public RequestWrapper(final HttpServletRequest req,
final ResponseWrapper res) {
super(req);
this.res = res;
req.setAttribute(HAZELCAST_REQUEST, this);
}
public void setHazelcastSession(HazelcastHttpSession hazelcastSession, String requestedSessionId) {
this.hazelcastSession = hazelcastSession;
this.requestedSessionId = requestedSessionId;
}
HttpSession getOriginalSession(boolean create) {
return super.getSession(create);
}
@Override
public RequestDispatcher getRequestDispatcher(final String path) {
final ServletRequest original = getRequest();
return new RequestDispatcher() {
public void forward(ServletRequest servletRequest, ServletResponse servletResponse)
throws ServletException, IOException {
original.getRequestDispatcher(path).forward(servletRequest, servletResponse);
}
public void include(ServletRequest servletRequest, ServletResponse servletResponse)
throws ServletException, IOException {
original.getRequestDispatcher(path).include(servletRequest, servletResponse);
}
};
}
public HazelcastHttpSession fetchHazelcastSession() {
if (requestedSessionId == null) {
requestedSessionId = getSessionCookie(this);
}
if (requestedSessionId == null) {
requestedSessionId = getParameter(HAZELCAST_SESSION_COOKIE_NAME);
}
if (requestedSessionId != null) {
hazelcastSession = getSessionWithId(requestedSessionId);
if (hazelcastSession == null) {
final Boolean existing = (Boolean) getClusterMap().get(requestedSessionId);
if (existing != null && existing) {
// we already have the session in the cluster loading it...
hazelcastSession = createNewSession(RequestWrapper.this, requestedSessionId);
}
}
}
return hazelcastSession;
}
@Override
public HttpSession getSession() {
return getSession(true);
}
@Override
public HazelcastHttpSession getSession(final boolean create) {
if (hazelcastSession != null && !hazelcastSession.isValid()) {
LOGGER.finest("Session is invalid!");
destroySession(hazelcastSession, true);
hazelcastSession = null;
} else if (hazelcastSession != null) {
return hazelcastSession;
}
HttpSession originalSession = getOriginalSession(false);
if (originalSession != null) {
String hazelcastSessionId = MAP_ORIGINAL_SESSIONS.get(originalSession.getId());
if (hazelcastSessionId != null) {
hazelcastSession = MAP_SESSIONS.get(hazelcastSessionId);
return hazelcastSession;
}
MAP_ORIGINAL_SESSIONS.remove(originalSession.getId());
originalSession.invalidate();
}
hazelcastSession = fetchHazelcastSession();
if (hazelcastSession == null && create) {
hazelcastSession = createNewSession(RequestWrapper.this, null);
}
if (deferredWrite) {
prepareReloadingSession(hazelcastSession);
}
return hazelcastSession;
}
} // END of RequestWrapper
| 1no label
|
hazelcast-wm_src_main_java_com_hazelcast_web_WebFilter.java
|
138 |
public class DistributedObjectInfo implements Portable {
private String serviceName;
private String name;
DistributedObjectInfo() {
}
DistributedObjectInfo(String serviceName, String name) {
this.serviceName = serviceName;
this.name = name;
}
@Override
public int getFactoryId() {
return ClientPortableHook.ID;
}
@Override
public int getClassId() {
return ClientPortableHook.DISTRIBUTED_OBJECT_INFO;
}
public String getServiceName() {
return serviceName;
}
public String getName() {
return name;
}
@Override
public void writePortable(PortableWriter writer) throws IOException {
writer.writeUTF("sn", serviceName);
writer.writeUTF("n", name);
}
@Override
public void readPortable(PortableReader reader) throws IOException {
serviceName = reader.readUTF("sn");
name = reader.readUTF("n");
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DistributedObjectInfo that = (DistributedObjectInfo) o;
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
if (serviceName != null ? !serviceName.equals(that.serviceName) : that.serviceName != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = serviceName != null ? serviceName.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_DistributedObjectInfo.java
|
3,662 |
public static class Defaults extends NumberFieldMapper.Defaults {
public static final String NAME = "_boost";
public static final Float NULL_VALUE = null;
public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE);
static {
FIELD_TYPE.setIndexed(false);
FIELD_TYPE.setStored(false);
}
}
| 0true
|
src_main_java_org_elasticsearch_index_mapper_internal_BoostFieldMapper.java
|
1,520 |
@Component("blProductOptionDisplayProcessor")
public class ProductOptionDisplayProcessor extends AbstractLocalVariableDefinitionElementProcessor {
/**
* Sets the name of this processor to be used in Thymeleaf template
*/
public ProductOptionDisplayProcessor() {
super("product_option_display");
}
@Override
public int getPrecedence() {
return 100;
}
protected void initServices(Arguments arguments) {
}
@Override
protected Map<String, Object> getNewLocalVariables(Arguments arguments, Element element) {
initServices(arguments);
HashMap<String, String> productOptionDisplayValues = new HashMap<String, String>();
Map<String, Object> newVars = new HashMap<String, Object>();
if (StandardExpressionProcessor.processExpression(arguments,
element.getAttributeValue("orderItem")) instanceof DiscreteOrderItem) {
DiscreteOrderItem orderItem = (DiscreteOrderItem) StandardExpressionProcessor.processExpression(arguments,
element.getAttributeValue("orderItem"));
for (String i : orderItem.getOrderItemAttributes().keySet()) {
for (ProductOption option : orderItem.getProduct().getProductOptions()) {
if (option.getAttributeName().equals(i) && !StringUtils.isEmpty(orderItem.getOrderItemAttributes().get(i).toString())) {
productOptionDisplayValues.put(option.getLabel(), orderItem.getOrderItemAttributes().get(i).toString());
}
}
}
}
newVars.put("productOptionDisplayValues", productOptionDisplayValues);
return newVars;
}
@Override
protected boolean removeHostElement(Arguments arguments, Element element) {
return false;
}
}
| 0true
|
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_processor_ProductOptionDisplayProcessor.java
|
1,084 |
public class OSQLFilterItemFieldAll extends OSQLFilterItemFieldMultiAbstract {
public static final String NAME = "ALL";
public static final String FULL_NAME = "ALL()";
public OSQLFilterItemFieldAll(final OSQLPredicate iQueryCompiled, final String iName) {
super(iQueryCompiled, iName, OStringSerializerHelper.getParameters(iName));
}
@Override
public String getRoot() {
return FULL_NAME;
}
@Override
protected void setRoot(final OBaseParser iQueryToParse, final String iRoot) {
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_sql_filter_OSQLFilterItemFieldAll.java
|
538 |
public class ORemoteFetchListener implements OFetchListener {
final Set<ODocument> recordsToSend;
public ORemoteFetchListener(final Set<ODocument> iRecordsToSend) {
recordsToSend = iRecordsToSend;
}
public void processStandardField(ORecordSchemaAware<?> iRecord, Object iFieldValue, String iFieldName, OFetchContext iContext,
final Object iusObject, final String iFormat) throws OFetchException {
}
public void parseLinked(ORecordSchemaAware<?> iRootRecord, OIdentifiable iLinked, Object iUserObject, String iFieldName,
OFetchContext iContext) throws OFetchException {
}
public void parseLinkedCollectionValue(ORecordSchemaAware<?> iRootRecord, OIdentifiable iLinked, Object iUserObject,
String iFieldName, OFetchContext iContext) throws OFetchException {
}
public Object fetchLinkedMapEntry(ORecordSchemaAware<?> iRoot, Object iUserObject, String iFieldName, String iKey,
ORecordSchemaAware<?> iLinked, OFetchContext iContext) throws OFetchException {
if (iLinked.getIdentity().isValid())
return recordsToSend.add((ODocument) iLinked) ? iLinked : null;
return null;
}
public Object fetchLinkedCollectionValue(ORecordSchemaAware<?> iRoot, Object iUserObject, String iFieldName,
ORecordSchemaAware<?> iLinked, OFetchContext iContext) throws OFetchException {
if (iLinked.getIdentity().isValid())
return recordsToSend.add((ODocument) iLinked) ? iLinked : null;
return null;
}
@SuppressWarnings("unchecked")
public Object fetchLinked(ORecordSchemaAware<?> iRoot, Object iUserObject, String iFieldName, ORecordSchemaAware<?> iLinked,
OFetchContext iContext) throws OFetchException {
if (iLinked instanceof ODocument)
return recordsToSend.add((ODocument) iLinked) ? iLinked : null;
// HOW THIS CODE CAN HAVE SENSE?
else if (iLinked instanceof Collection<?>)
return recordsToSend.addAll((Collection<? extends ODocument>) iLinked) ? iLinked : null;
// HOW THIS CODE CAN HAVE SENSE?
else if (iLinked instanceof Map<?, ?>)
return recordsToSend.addAll(((Map<String, ? extends ODocument>) iLinked).values()) ? iLinked : null;
else
throw new OFetchException("Unrecognized type while fetching records: " + iLinked);
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_fetch_remote_ORemoteFetchListener.java
|
862 |
public class OSecurityShared extends OSharedResourceAdaptive implements OSecurity, OCloseable {
public static final String RESTRICTED_CLASSNAME = "ORestricted";
public static final String IDENTITY_CLASSNAME = "OIdentity";
public static final String ALLOW_ALL_FIELD = "_allow";
public static final String ALLOW_READ_FIELD = "_allowRead";
public static final String ALLOW_UPDATE_FIELD = "_allowUpdate";
public static final String ALLOW_DELETE_FIELD = "_allowDelete";
public static final String ONCREATE_IDENTITY_TYPE = "onCreate.identityType";
public static final String ONCREATE_FIELD = "onCreate.fields";
public OSecurityShared() {
super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean(), OGlobalConfiguration.STORAGE_LOCK_TIMEOUT
.getValueAsInteger(), true);
}
public OIdentifiable allowUser(final ODocument iDocument, final String iAllowFieldName, final String iUserName) {
final OUser user = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSecurity().getUser(iUserName);
if (user == null)
throw new IllegalArgumentException("User '" + iUserName + "' not found");
return allowIdentity(iDocument, iAllowFieldName, user.getDocument().getIdentity());
}
public OIdentifiable allowRole(final ODocument iDocument, final String iAllowFieldName, final String iRoleName) {
final ORole role = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSecurity().getRole(iRoleName);
if (role == null)
throw new IllegalArgumentException("Role '" + iRoleName + "' not found");
return allowIdentity(iDocument, iAllowFieldName, role.getDocument().getIdentity());
}
public OIdentifiable allowIdentity(final ODocument iDocument, final String iAllowFieldName, final OIdentifiable iId) {
Set<OIdentifiable> field = iDocument.field(iAllowFieldName);
if (field == null) {
field = new OMVRBTreeRIDSet(iDocument);
iDocument.field(iAllowFieldName, field);
}
field.add(iId);
return iId;
}
public OIdentifiable disallowUser(final ODocument iDocument, final String iAllowFieldName, final String iUserName) {
final OUser user = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSecurity().getUser(iUserName);
if (user == null)
throw new IllegalArgumentException("User '" + iUserName + "' not found");
return disallowIdentity(iDocument, iAllowFieldName, user.getDocument().getIdentity());
}
public OIdentifiable disallowRole(final ODocument iDocument, final String iAllowFieldName, final String iRoleName) {
final ORole role = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSecurity().getRole(iRoleName);
if (role == null)
throw new IllegalArgumentException("Role '" + iRoleName + "' not found");
return disallowIdentity(iDocument, iAllowFieldName, role.getDocument().getIdentity());
}
public OIdentifiable disallowIdentity(final ODocument iDocument, final String iAllowFieldName, final OIdentifiable iId) {
Set<OIdentifiable> field = iDocument.field(iAllowFieldName);
if (field != null)
field.remove(iId);
return iId;
}
public boolean isAllowed(final Set<OIdentifiable> iAllowAll, final Set<OIdentifiable> iAllowOperation) {
if (iAllowAll == null || iAllowAll.isEmpty())
return true;
final OUser currentUser = ODatabaseRecordThreadLocal.INSTANCE.get().getUser();
if (currentUser != null) {
// CHECK IF CURRENT USER IS ENLISTED
if (!iAllowAll.contains(currentUser.getDocument().getIdentity())) {
// CHECK AGAINST SPECIFIC _ALLOW OPERATION
if (iAllowOperation != null && iAllowOperation.contains(currentUser.getDocument().getIdentity()))
return true;
// CHECK IF AT LEAST ONE OF THE USER'S ROLES IS ENLISTED
for (ORole r : currentUser.getRoles()) {
// CHECK AGAINST GENERIC _ALLOW
if (iAllowAll.contains(r.getDocument().getIdentity()))
return true;
// CHECK AGAINST SPECIFIC _ALLOW OPERATION
if (iAllowOperation != null && iAllowOperation.contains(r.getDocument().getIdentity()))
return true;
}
return false;
}
}
return true;
}
public OUser authenticate(final String iUserName, final String iUserPassword) {
acquireExclusiveLock();
try {
final String dbName = getDatabase().getName();
final OUser user = getUser(iUserName);
if (user == null)
throw new OSecurityAccessException(dbName, "User or password not valid for database: '" + dbName + "'");
if (user.getAccountStatus() != STATUSES.ACTIVE)
throw new OSecurityAccessException(dbName, "User '" + iUserName + "' is not active");
if (!(getDatabase().getStorage() instanceof OStorageProxy)) {
// CHECK USER & PASSWORD
if (!user.checkPassword(iUserPassword)) {
// WAIT A BIT TO AVOID BRUTE FORCE
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
throw new OSecurityAccessException(dbName, "User or password not valid for database: '" + dbName + "'");
}
}
return user;
} finally {
releaseExclusiveLock();
}
}
public OUser getUser(final String iUserName) {
acquireExclusiveLock();
try {
final List<ODocument> result = getDatabase().<OCommandRequest> command(
new OSQLSynchQuery<ODocument>("select from OUser where name = '" + iUserName + "' limit 1").setFetchPlan("roles:1"))
.execute();
if (result != null && !result.isEmpty())
return new OUser(result.get(0));
return null;
} finally {
releaseExclusiveLock();
}
}
public OUser createUser(final String iUserName, final String iUserPassword, final String... iRoles) {
acquireExclusiveLock();
try {
final OUser user = new OUser(iUserName, iUserPassword);
if (iRoles != null)
for (String r : iRoles) {
user.addRole(r);
}
return user.save();
} finally {
releaseExclusiveLock();
}
}
public OUser createUser(final String iUserName, final String iUserPassword, final ORole... iRoles) {
acquireExclusiveLock();
try {
final OUser user = new OUser(iUserName, iUserPassword);
if (iRoles != null)
for (ORole r : iRoles) {
user.addRole(r);
}
return user.save();
} finally {
releaseExclusiveLock();
}
}
public boolean dropUser(final String iUserName) {
acquireExclusiveLock();
try {
final Number removed = getDatabase().<OCommandRequest> command(
new OCommandSQL("delete from OUser where name = '" + iUserName + "'")).execute();
return removed != null && removed.intValue() > 0;
} finally {
releaseExclusiveLock();
}
}
public ORole getRole(final OIdentifiable iRole) {
acquireExclusiveLock();
try {
final ODocument doc = iRole.getRecord();
if ("ORole".equals(doc.getClassName()))
return new ORole(doc);
return null;
} finally {
releaseExclusiveLock();
}
}
public ORole getRole(final String iRoleName) {
acquireExclusiveLock();
try {
final List<ODocument> result = getDatabase().<OCommandRequest> command(
new OSQLSynchQuery<ODocument>("select from ORole where name = '" + iRoleName + "' limit 1")).execute();
if (result != null && !result.isEmpty())
return new ORole(result.get(0));
return null;
} catch (Exception ex) {
OLogManager.instance().error(this, "Failed to get role : " + iRoleName + " " + ex.getMessage());
return null;
} finally {
releaseExclusiveLock();
}
}
public ORole createRole(final String iRoleName, final ORole.ALLOW_MODES iAllowMode) {
return createRole(iRoleName, null, iAllowMode);
}
public ORole createRole(final String iRoleName, final ORole iParent, final ORole.ALLOW_MODES iAllowMode) {
acquireExclusiveLock();
try {
final ORole role = new ORole(iRoleName, iParent, iAllowMode);
return role.save();
} finally {
releaseExclusiveLock();
}
}
public boolean dropRole(final String iRoleName) {
acquireExclusiveLock();
try {
final Number removed = getDatabase().<OCommandRequest> command(
new OCommandSQL("delete from ORole where name = '" + iRoleName + "'")).execute();
return removed != null && removed.intValue() > 0;
} finally {
releaseExclusiveLock();
}
}
public List<ODocument> getAllUsers() {
acquireExclusiveLock();
try {
return getDatabase().<OCommandRequest> command(new OSQLSynchQuery<ODocument>("select from OUser")).execute();
} finally {
releaseExclusiveLock();
}
}
public List<ODocument> getAllRoles() {
acquireExclusiveLock();
try {
return getDatabase().<OCommandRequest> command(new OSQLSynchQuery<ODocument>("select from ORole")).execute();
} finally {
releaseExclusiveLock();
}
}
public OUser create() {
acquireExclusiveLock();
try {
if (!getDatabase().getMetadata().getSchema().getClasses().isEmpty())
return null;
final OUser adminUser = createMetadata();
final ORole readerRole = createRole("reader", ORole.ALLOW_MODES.DENY_ALL_BUT);
readerRole.addRule(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.CLUSTER + "." + OMetadataDefault.CLUSTER_INTERNAL_NAME, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".orole", ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".ouser", ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.ALL_CLASSES, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.ALL_CLUSTERS, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.RECORD_HOOK, ORole.PERMISSION_READ);
readerRole.save();
createUser("reader", "reader", new String[] { readerRole.getName() });
final ORole writerRole = createRole("writer", ORole.ALLOW_MODES.DENY_ALL_BUT);
writerRole.addRule(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_READ);
writerRole.addRule(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ + ORole.PERMISSION_CREATE
+ ORole.PERMISSION_UPDATE);
writerRole.addRule(ODatabaseSecurityResources.CLUSTER + "." + OMetadataDefault.CLUSTER_INTERNAL_NAME, ORole.PERMISSION_READ);
writerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".orole", ORole.PERMISSION_READ);
writerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".ouser", ORole.PERMISSION_READ);
writerRole.addRule(ODatabaseSecurityResources.ALL_CLASSES, ORole.PERMISSION_ALL);
writerRole.addRule(ODatabaseSecurityResources.ALL_CLUSTERS, ORole.PERMISSION_ALL);
writerRole.addRule(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_ALL);
writerRole.addRule(ODatabaseSecurityResources.RECORD_HOOK, ORole.PERMISSION_ALL);
writerRole.save();
createUser("writer", "writer", new String[] { writerRole.getName() });
return adminUser;
} finally {
releaseExclusiveLock();
}
}
/**
* Repairs the security structure if broken by creating the ADMIN role and user with default password.
*
* @return
*/
public OUser repair() {
acquireExclusiveLock();
try {
getDatabase().getMetadata().getIndexManager().dropIndex("OUser.name");
getDatabase().getMetadata().getIndexManager().dropIndex("ORole.name");
return createMetadata();
} finally {
releaseExclusiveLock();
}
}
public OUser createMetadata() {
final ODatabaseRecord database = getDatabase();
OClass identityClass = database.getMetadata().getSchema().getClass(IDENTITY_CLASSNAME); // SINCE 1.2.0
if (identityClass == null)
identityClass = database.getMetadata().getSchema().createAbstractClass(IDENTITY_CLASSNAME);
OClass roleClass = database.getMetadata().getSchema().getClass("ORole");
if (roleClass == null)
roleClass = database.getMetadata().getSchema().createClass("ORole", identityClass);
else if (roleClass.getSuperClass() == null)
// MIGRATE AUTOMATICALLY TO 1.2.0
roleClass.setSuperClass(identityClass);
if (!roleClass.existsProperty("name")) {
roleClass.createProperty("name", OType.STRING).setMandatory(true).setNotNull(true).setCollate("ci");
roleClass.createIndex("ORole.name", INDEX_TYPE.UNIQUE, ONullOutputListener.INSTANCE, "name");
} else {
final Set<OIndex<?>> indexes = roleClass.getInvolvedIndexes("name");
if (indexes.isEmpty())
roleClass.createIndex("ORole.name", INDEX_TYPE.UNIQUE, ONullOutputListener.INSTANCE, "name");
}
if (!roleClass.existsProperty("mode"))
roleClass.createProperty("mode", OType.BYTE);
if (!roleClass.existsProperty("rules"))
roleClass.createProperty("rules", OType.EMBEDDEDMAP, OType.BYTE);
if (!roleClass.existsProperty("inheritedRole"))
roleClass.createProperty("inheritedRole", OType.LINK, roleClass);
OClass userClass = database.getMetadata().getSchema().getClass("OUser");
if (userClass == null)
userClass = database.getMetadata().getSchema().createClass("OUser", identityClass);
else if (userClass.getSuperClass() == null)
// MIGRATE AUTOMATICALLY TO 1.2.0
userClass.setSuperClass(identityClass);
if (!userClass.existsProperty("name")) {
userClass.createProperty("name", OType.STRING).setMandatory(true).setNotNull(true).setCollate("ci");
userClass.createIndex("OUser.name", INDEX_TYPE.UNIQUE, ONullOutputListener.INSTANCE, "name");
}
if (!userClass.existsProperty("password"))
userClass.createProperty("password", OType.STRING).setMandatory(true).setNotNull(true);
if (!userClass.existsProperty("roles"))
userClass.createProperty("roles", OType.LINKSET, roleClass);
if (!userClass.existsProperty("status"))
userClass.createProperty("status", OType.STRING).setMandatory(true).setNotNull(true);
// CREATE ROLES AND USERS
ORole adminRole = getRole(ORole.ADMIN);
if (adminRole == null) {
adminRole = createRole(ORole.ADMIN, ORole.ALLOW_MODES.ALLOW_ALL_BUT);
adminRole.addRule(ODatabaseSecurityResources.BYPASS_RESTRICTED, ORole.PERMISSION_ALL).save();
}
OUser adminUser = getUser(OUser.ADMIN);
if (adminUser == null)
adminUser = createUser(OUser.ADMIN, OUser.ADMIN, adminRole);
// SINCE 1.2.0
OClass restrictedClass = database.getMetadata().getSchema().getClass(RESTRICTED_CLASSNAME);
if (restrictedClass == null)
restrictedClass = database.getMetadata().getSchema().createAbstractClass(RESTRICTED_CLASSNAME);
if (!restrictedClass.existsProperty(ALLOW_ALL_FIELD))
restrictedClass.createProperty(ALLOW_ALL_FIELD, OType.LINKSET, database.getMetadata().getSchema()
.getClass(IDENTITY_CLASSNAME));
if (!restrictedClass.existsProperty(ALLOW_READ_FIELD))
restrictedClass.createProperty(ALLOW_READ_FIELD, OType.LINKSET,
database.getMetadata().getSchema().getClass(IDENTITY_CLASSNAME));
if (!restrictedClass.existsProperty(ALLOW_UPDATE_FIELD))
restrictedClass.createProperty(ALLOW_UPDATE_FIELD, OType.LINKSET,
database.getMetadata().getSchema().getClass(IDENTITY_CLASSNAME));
if (!restrictedClass.existsProperty(ALLOW_DELETE_FIELD))
restrictedClass.createProperty(ALLOW_DELETE_FIELD, OType.LINKSET,
database.getMetadata().getSchema().getClass(IDENTITY_CLASSNAME));
return adminUser;
}
public void close() {
}
public void load() {
final OClass userClass = getDatabase().getMetadata().getSchema().getClass("OUser");
if (userClass != null) {
// @COMPATIBILITY <1.3.0
if (!userClass.existsProperty("status")) {
userClass.createProperty("status", OType.STRING).setMandatory(true).setNotNull(true);
}
OProperty p = userClass.getProperty("name");
if (p == null)
p = userClass.createProperty("name", OType.STRING).setMandatory(true).setNotNull(true);
if (userClass.getInvolvedIndexes("name") == null)
p.createIndex(INDEX_TYPE.UNIQUE);
// ROLE
final OClass roleClass = getDatabase().getMetadata().getSchema().getClass("ORole");
if (!roleClass.existsProperty("inheritedRole")) {
roleClass.createProperty("inheritedRole", OType.LINK, roleClass);
}
p = roleClass.getProperty("name");
if (p == null)
p = roleClass.createProperty("name", OType.STRING).setMandatory(true).setNotNull(true);
if (roleClass.getInvolvedIndexes("name") == null)
p.createIndex(INDEX_TYPE.UNIQUE);
}
}
private ODatabaseRecord getDatabase() {
return ODatabaseRecordThreadLocal.INSTANCE.get();
}
public void createClassTrigger() {
final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.get();
OClass classTrigger = db.getMetadata().getSchema().getClass(OClassTrigger.CLASSNAME);
if (classTrigger == null)
classTrigger = db.getMetadata().getSchema().createAbstractClass(OClassTrigger.CLASSNAME);
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_metadata_security_OSecurityShared.java
|
1,752 |
private static class RemoveEntryProcessor extends AbstractEntryProcessor {
RemoveEntryProcessor() {
}
public Object process(Map.Entry entry) {
entry.setValue(null);
return entry;
}
}
| 0true
|
hazelcast_src_test_java_com_hazelcast_map_EntryProcessorTest.java
|
1,126 |
@Beta
public interface AsyncAtomicLong extends IAtomicLong {
ICompletableFuture<Long> asyncAddAndGet(long delta);
ICompletableFuture<Boolean> asyncCompareAndSet(long expect, long update);
ICompletableFuture<Long> asyncDecrementAndGet();
ICompletableFuture<Long> asyncGet();
ICompletableFuture<Long> asyncGetAndAdd(long delta);
ICompletableFuture<Long> asyncGetAndSet(long newValue);
ICompletableFuture<Long> asyncIncrementAndGet();
ICompletableFuture<Long> asyncGetAndIncrement();
ICompletableFuture<Void> asyncSet(long newValue);
ICompletableFuture<Void> asyncAlter(IFunction<Long, Long> function);
ICompletableFuture<Long> asyncAlterAndGet(IFunction<Long, Long> function);
ICompletableFuture<Long> asyncGetAndAlter(IFunction<Long, Long> function);
<R> ICompletableFuture<R> asyncApply(IFunction<Long, R> function);
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_core_AsyncAtomicLong.java
|
65 |
public interface TitanIndexQuery {
/**
* Specifies the maxium number of elements to return
*
* @param limit
* @return
*/
public TitanIndexQuery limit(int limit);
/**
* Specifies the offset of the query. Query results will be retrieved starting at the given offset.
* @param offset
* @return
*/
public TitanIndexQuery offset(int offset);
/**
* Adds the given parameter to the list of parameters of this query.
* Parameters are passed right through to the indexing backend to modify the query behavior.
* @param para
* @return
*/
public TitanIndexQuery addParameter(Parameter para);
/**
* Adds the given parameters to the list of parameters of this query.
* Parameters are passed right through to the indexing backend to modify the query behavior.
* @param paras
* @return
*/
public TitanIndexQuery addParameters(Iterable<Parameter> paras);
/**
* Adds the given parameters to the list of parameters of this query.
* Parameters are passed right through to the indexing backend to modify the query behavior.
* @param paras
* @return
*/
public TitanIndexQuery addParameters(Parameter... paras);
/**
* Sets the element identifier string that is used by this query builder as the token to identifier key references
* in the query string.
* <p/>
* For example, in the query 'v.name: Tom' the element identifier is 'v.'
*
*
* @param identifier The element identifier which must not be blank
* @return This query builder
*/
public TitanIndexQuery setElementIdentifier(String identifier);
/**
* Returns all vertices that match the query in the indexing backend.
*
* @return
*/
public Iterable<Result<Vertex>> vertices();
/**
* Returns all edges that match the query in the indexing backend.
*
* @return
*/
public Iterable<Result<Edge>> edges();
/**
* Returns all properties that match the query in the indexing backend.
*
* @return
*/
public Iterable<Result<TitanProperty>> properties();
/**
* Container of a query result with its score.
* @param <V>
*/
public interface Result<V extends Element> {
/**
* Returns the element that matches the query
*
* @return
*/
public V getElement();
/**
* Returns the score of the result with respect to the query (if available)
* @return
*/
public double getScore();
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanIndexQuery.java
|
666 |
public class SkuDaoTest extends BaseTest {
private Long skuId;
@Resource
private SkuDao skuDao;
@Resource
private CatalogService catalogService;
@Test(groups = { "createSku" }, dataProvider = "basicSku", dataProviderClass = SkuDaoDataProvider.class, dependsOnGroups = { "readCustomer", "createOrder", "createProducts" })
@Rollback(false)
public void createSku(Sku sku) {
Calendar activeStartCal = Calendar.getInstance();
activeStartCal.add(Calendar.DAY_OF_YEAR, -2);
sku.setSalePrice(new Money(BigDecimal.valueOf(10.0)));
sku.setRetailPrice(new Money(BigDecimal.valueOf(15.0)));
sku.setName("test sku");
sku.setActiveStartDate(activeStartCal.getTime());
assert sku.getId() == null;
sku = catalogService.saveSku(sku);
assert sku.getId() != null;
skuId = sku.getId();
}
@Test(groups = { "readFirstSku" }, dependsOnGroups = { "createSku" })
@Transactional
public void readFirstSku() {
Sku si = skuDao.readFirstSku();
assert si != null;
assert si.getId() != null;
}
@Test(groups = { "readSkuById" }, dependsOnGroups = { "createSku" })
@Transactional
public void readSkuById() {
Sku item = skuDao.readSkuById(skuId);
assert item != null;
assert item.getId() == skuId;
}
}
| 0true
|
integration_src_test_java_org_broadleafcommerce_core_catalog_dao_SkuDaoTest.java
|
1,248 |
public abstract class AbstractClient implements InternalClient {
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> RequestBuilder prepareExecute(final Action<Request, Response, RequestBuilder> action) {
return action.newRequestBuilder(this);
}
@Override
public ActionFuture<IndexResponse> index(final IndexRequest request) {
return execute(IndexAction.INSTANCE, request);
}
@Override
public void index(final IndexRequest request, final ActionListener<IndexResponse> listener) {
execute(IndexAction.INSTANCE, request, listener);
}
@Override
public IndexRequestBuilder prepareIndex() {
return new IndexRequestBuilder(this, null);
}
@Override
public IndexRequestBuilder prepareIndex(String index, String type) {
return prepareIndex(index, type, null);
}
@Override
public IndexRequestBuilder prepareIndex(String index, String type, @Nullable String id) {
return prepareIndex().setIndex(index).setType(type).setId(id);
}
@Override
public ActionFuture<UpdateResponse> update(final UpdateRequest request) {
return execute(UpdateAction.INSTANCE, request);
}
@Override
public void update(final UpdateRequest request, final ActionListener<UpdateResponse> listener) {
execute(UpdateAction.INSTANCE, request, listener);
}
@Override
public UpdateRequestBuilder prepareUpdate() {
return new UpdateRequestBuilder(this, null, null, null);
}
@Override
public UpdateRequestBuilder prepareUpdate(String index, String type, String id) {
return new UpdateRequestBuilder(this, index, type, id);
}
@Override
public ActionFuture<DeleteResponse> delete(final DeleteRequest request) {
return execute(DeleteAction.INSTANCE, request);
}
@Override
public void delete(final DeleteRequest request, final ActionListener<DeleteResponse> listener) {
execute(DeleteAction.INSTANCE, request, listener);
}
@Override
public DeleteRequestBuilder prepareDelete() {
return new DeleteRequestBuilder(this, null);
}
@Override
public DeleteRequestBuilder prepareDelete(String index, String type, String id) {
return prepareDelete().setIndex(index).setType(type).setId(id);
}
@Override
public ActionFuture<BulkResponse> bulk(final BulkRequest request) {
return execute(BulkAction.INSTANCE, request);
}
@Override
public void bulk(final BulkRequest request, final ActionListener<BulkResponse> listener) {
execute(BulkAction.INSTANCE, request, listener);
}
@Override
public BulkRequestBuilder prepareBulk() {
return new BulkRequestBuilder(this);
}
@Override
public ActionFuture<DeleteByQueryResponse> deleteByQuery(final DeleteByQueryRequest request) {
return execute(DeleteByQueryAction.INSTANCE, request);
}
@Override
public void deleteByQuery(final DeleteByQueryRequest request, final ActionListener<DeleteByQueryResponse> listener) {
execute(DeleteByQueryAction.INSTANCE, request, listener);
}
@Override
public DeleteByQueryRequestBuilder prepareDeleteByQuery(String... indices) {
return new DeleteByQueryRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<GetResponse> get(final GetRequest request) {
return execute(GetAction.INSTANCE, request);
}
@Override
public void get(final GetRequest request, final ActionListener<GetResponse> listener) {
execute(GetAction.INSTANCE, request, listener);
}
@Override
public GetRequestBuilder prepareGet() {
return new GetRequestBuilder(this, null);
}
@Override
public GetRequestBuilder prepareGet(String index, String type, String id) {
return prepareGet().setIndex(index).setType(type).setId(id);
}
@Override
public ActionFuture<MultiGetResponse> multiGet(final MultiGetRequest request) {
return execute(MultiGetAction.INSTANCE, request);
}
@Override
public void multiGet(final MultiGetRequest request, final ActionListener<MultiGetResponse> listener) {
execute(MultiGetAction.INSTANCE, request, listener);
}
@Override
public MultiGetRequestBuilder prepareMultiGet() {
return new MultiGetRequestBuilder(this);
}
@Override
public ActionFuture<SearchResponse> search(final SearchRequest request) {
return execute(SearchAction.INSTANCE, request);
}
@Override
public void search(final SearchRequest request, final ActionListener<SearchResponse> listener) {
execute(SearchAction.INSTANCE, request, listener);
}
@Override
public SearchRequestBuilder prepareSearch(String... indices) {
return new SearchRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<SearchResponse> searchScroll(final SearchScrollRequest request) {
return execute(SearchScrollAction.INSTANCE, request);
}
@Override
public void searchScroll(final SearchScrollRequest request, final ActionListener<SearchResponse> listener) {
execute(SearchScrollAction.INSTANCE, request, listener);
}
@Override
public SearchScrollRequestBuilder prepareSearchScroll(String scrollId) {
return new SearchScrollRequestBuilder(this, scrollId);
}
@Override
public ActionFuture<MultiSearchResponse> multiSearch(MultiSearchRequest request) {
return execute(MultiSearchAction.INSTANCE, request);
}
@Override
public void multiSearch(MultiSearchRequest request, ActionListener<MultiSearchResponse> listener) {
execute(MultiSearchAction.INSTANCE, request, listener);
}
@Override
public MultiSearchRequestBuilder prepareMultiSearch() {
return new MultiSearchRequestBuilder(this);
}
@Override
public ActionFuture<CountResponse> count(final CountRequest request) {
return execute(CountAction.INSTANCE, request);
}
@Override
public void count(final CountRequest request, final ActionListener<CountResponse> listener) {
execute(CountAction.INSTANCE, request, listener);
}
@Override
public CountRequestBuilder prepareCount(String... indices) {
return new CountRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<SuggestResponse> suggest(final SuggestRequest request) {
return execute(SuggestAction.INSTANCE, request);
}
@Override
public void suggest(final SuggestRequest request, final ActionListener<SuggestResponse> listener) {
execute(SuggestAction.INSTANCE, request, listener);
}
@Override
public SuggestRequestBuilder prepareSuggest(String... indices) {
return new SuggestRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<SearchResponse> moreLikeThis(final MoreLikeThisRequest request) {
return execute(MoreLikeThisAction.INSTANCE, request);
}
@Override
public void moreLikeThis(final MoreLikeThisRequest request, final ActionListener<SearchResponse> listener) {
execute(MoreLikeThisAction.INSTANCE, request, listener);
}
@Override
public MoreLikeThisRequestBuilder prepareMoreLikeThis(String index, String type, String id) {
return new MoreLikeThisRequestBuilder(this, index, type, id);
}
@Override
public ActionFuture<TermVectorResponse> termVector(final TermVectorRequest request) {
return execute(TermVectorAction.INSTANCE, request);
}
@Override
public void termVector(final TermVectorRequest request, final ActionListener<TermVectorResponse> listener) {
execute(TermVectorAction.INSTANCE, request, listener);
}
@Override
public TermVectorRequestBuilder prepareTermVector(String index, String type, String id) {
return new TermVectorRequestBuilder(this, index, type, id);
}
@Override
public ActionFuture<MultiTermVectorsResponse> multiTermVectors(final MultiTermVectorsRequest request) {
return execute(MultiTermVectorsAction.INSTANCE, request);
}
@Override
public void multiTermVectors(final MultiTermVectorsRequest request, final ActionListener<MultiTermVectorsResponse> listener) {
execute(MultiTermVectorsAction.INSTANCE, request, listener);
}
@Override
public MultiTermVectorsRequestBuilder prepareMultiTermVectors() {
return new MultiTermVectorsRequestBuilder(this);
}
@Override
public ActionFuture<PercolateResponse> percolate(final PercolateRequest request) {
return execute(PercolateAction.INSTANCE, request);
}
@Override
public void percolate(final PercolateRequest request, final ActionListener<PercolateResponse> listener) {
execute(PercolateAction.INSTANCE, request, listener);
}
@Override
public PercolateRequestBuilder preparePercolate() {
return new PercolateRequestBuilder(this);
}
@Override
public MultiPercolateRequestBuilder prepareMultiPercolate() {
return new MultiPercolateRequestBuilder(this);
}
@Override
public void multiPercolate(MultiPercolateRequest request, ActionListener<MultiPercolateResponse> listener) {
execute(MultiPercolateAction.INSTANCE, request, listener);
}
@Override
public ActionFuture<MultiPercolateResponse> multiPercolate(MultiPercolateRequest request) {
return execute(MultiPercolateAction.INSTANCE, request);
}
@Override
public ExplainRequestBuilder prepareExplain(String index, String type, String id) {
return new ExplainRequestBuilder(this, index, type, id);
}
@Override
public ActionFuture<ExplainResponse> explain(ExplainRequest request) {
return execute(ExplainAction.INSTANCE, request);
}
@Override
public void explain(ExplainRequest request, ActionListener<ExplainResponse> listener) {
execute(ExplainAction.INSTANCE, request, listener);
}
@Override
public void clearScroll(ClearScrollRequest request, ActionListener<ClearScrollResponse> listener) {
execute(ClearScrollAction.INSTANCE, request, listener);
}
@Override
public ActionFuture<ClearScrollResponse> clearScroll(ClearScrollRequest request) {
return execute(ClearScrollAction.INSTANCE, request);
}
@Override
public ClearScrollRequestBuilder prepareClearScroll() {
return new ClearScrollRequestBuilder(this);
}
}
| 1no label
|
src_main_java_org_elasticsearch_client_support_AbstractClient.java
|
69 |
public interface TitanRelation extends TitanElement {
/**
* Establishes a unidirectional edge between this relation and the given vertex for the specified label.
* The label must be defined {@link EdgeLabel#isUnidirected()}.
*
* @param label
* @param vertex
*/
public void setProperty(EdgeLabel label, TitanVertex vertex);
/**
* Returns the vertex associated to this relation by a unidirected edge of the given label or NULL if such does not exist.
*
* @param label
* @return
*/
public TitanVertex getProperty(EdgeLabel label);
/**
* Returns the type of this relation.
* <p/>
* The type is either a label ({@link EdgeLabel} if this relation is an edge or a key ({@link PropertyKey}) if this
* relation is a property.
*
* @return Type of this relation
*/
public RelationType getType();
/**
* Returns the direction of this relation from the perspective of the specified vertex.
*
* @param vertex vertex on which the relation is incident
* @return The direction of this relation from the perspective of the specified vertex.
* @throws InvalidElementException if this relation is not incident on the vertex
*/
public Direction getDirection(TitanVertex vertex);
/**
* Checks whether this relation is incident on the specified vertex.
*
* @param vertex vertex to check incidence for
* @return true, if this relation is incident on the vertex, else false
*/
public boolean isIncidentOn(TitanVertex vertex);
/**
* Checks whether this relation is a loop.
* An relation is a loop if it connects a vertex with itself.
*
* @return true, if this relation is a loop, else false.
*/
boolean isLoop();
/**
* Checks whether this relation is a property.
*
* @return true, if this relation is a property, else false.
* @see TitanProperty
*/
boolean isProperty();
/**
* Checks whether this relation is an edge.
*
* @return true, if this relation is an edge, else false.
* @see TitanEdge
*/
boolean isEdge();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanRelation.java
|
161 |
private static final class SingleTargetCallback implements Callback<Object> {
final Address target;
final MultiTargetCallback parent;
private SingleTargetCallback(Address target, MultiTargetCallback parent) {
this.target = target;
this.parent = parent;
}
@Override
public void notify(Object object) {
parent.notify(target, object);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_MultiTargetClientRequest.java
|
1,601 |
public class ODefaultReplicationConflictResolver implements OReplicationConflictResolver {
private static final String DISTRIBUTED_CONFLICT_CLASS = "ODistributedConflict";
private static final String FIELD_RECORD = "record";
private static final String FIELD_NODE = "node";
private static final String FIELD_DATE = "date";
private static final String FIELD_OPERATION = "operation";
private static final String FIELD_OTHER_RID = "otherRID";
private static final String FIELD_CURRENT_VERSION = "currentVersion";
private static final String FIELD_OTHER_VERSION = "otherVersion";
private static final int MAX_RETRIES = 10;
private boolean ignoreIfSameContent;
private boolean ignoreIfMergeOk;
private boolean latestAlwaysWin;
private ODatabaseComplex<?> database;
private OIndex<?> index = null;
private OServer serverInstance;
private ODistributedServerManager cluster;
public ODefaultReplicationConflictResolver() {
}
public void startup(final OServer iServer, final ODistributedServerManager iCluster, final String iDatabaseName) {
serverInstance = iServer;
cluster = iCluster;
synchronized (this) {
if (index != null)
return;
final OServerUserConfiguration replicatorUser = serverInstance.getUser(ODistributedAbstractPlugin.REPLICATOR_USER);
final ODatabaseRecord threadDb = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
if (threadDb != null && !threadDb.isClosed() && threadDb.getStorage().getName().equals(iDatabaseName))
database = threadDb;
else
database = serverInstance.openDatabase("document", iDatabaseName, replicatorUser.name, replicatorUser.password);
if (database.getMetadata() != null) {
OClass cls = database.getMetadata().getSchema().getClass(DISTRIBUTED_CONFLICT_CLASS);
final OProperty p;
if (cls == null) {
cls = database.getMetadata().getSchema().createClass(DISTRIBUTED_CONFLICT_CLASS);
index = cls.createProperty(FIELD_RECORD, OType.LINK).createIndex(INDEX_TYPE.UNIQUE);
} else {
p = cls.getProperty(FIELD_RECORD);
if (p == null)
index = cls.createProperty(FIELD_RECORD, OType.LINK).createIndex(INDEX_TYPE.UNIQUE);
else {
index = p.getIndex();
}
}
}
}
}
public void shutdown() {
if (database != null)
database.close();
if (index != null)
index = null;
}
@Override
public void handleCreateConflict(final String iRemoteNode, final ORecordId iCurrentRID, final int iCurrentVersion,
final ORecordId iOtherRID, final int iOtherVersion) {
if (iCurrentRID.equals(iOtherRID)) {
// PATCH FOR THE CASE THE RECORD WAS DELETED WHILE THE NODE WAS OFFLINE: FORCE THE OTHER VERSION TO THE LOCAL ONE (-1
// BECAUSE IT'S ALWAYS INCREMENTED)
for (int retry = 0; retry < MAX_RETRIES; ++retry) {
ODistributedServerLog
.debug(
this,
cluster.getLocalNodeName(),
iRemoteNode,
DIRECTION.IN,
"Resolved conflict automatically between versions on CREATE record %s/%s v.%d (other RID=%s v.%d). Current record version will be overwritten",
database.getName(), iCurrentRID, iCurrentVersion, iOtherRID, iOtherVersion);
final ORecordInternal<?> record = iCurrentRID.getRecord();
record.setVersion(iOtherVersion - 1);
record.setDirty();
try {
record.save();
return;
} catch (OConcurrentModificationException e) {
// CONCURRENT OPERATION, RETRY AGAIN?
}
}
}
ODistributedServerLog.warn(this, cluster.getLocalNodeName(), iRemoteNode, DIRECTION.IN,
"Conflict on CREATE record %s/%s v.%d (other RID=%s v.%d)...", database.getName(), iCurrentRID, iCurrentVersion, iOtherRID,
iOtherVersion);
if (!existConflictsForRecord(iCurrentRID)) {
final ODocument doc = createConflictDocument(ORecordOperation.CREATED, iCurrentRID, iRemoteNode);
try {
// WRITE THE CONFLICT AS RECORD
doc.field(FIELD_OTHER_RID, iOtherRID);
doc.save();
} catch (Exception e) {
errorOnWriteConflict(iRemoteNode, doc);
}
}
}
@Override
public void handleUpdateConflict(final String iRemoteNode, final ORecordId iCurrentRID, final ORecordVersion iCurrentVersion,
final ORecordVersion iOtherVersion) {
final int otherVersionNumber = iOtherVersion == null ? -1 : iOtherVersion.getCounter();
ODistributedServerLog.warn(this, cluster.getLocalNodeName(), iRemoteNode, DIRECTION.IN,
"Conflict on UDPATE record %s/%s (current=v%d, other=v%d)...", database.getName(), iCurrentRID,
iCurrentVersion.getCounter(), otherVersionNumber);
if (!existConflictsForRecord(iCurrentRID)) {
// WRITE THE CONFLICT AS RECORD
final ODocument doc = createConflictDocument(ORecordOperation.UPDATED, iCurrentRID, iRemoteNode);
try {
doc.field(FIELD_CURRENT_VERSION, iCurrentVersion.getCounter());
doc.field(FIELD_OTHER_VERSION, otherVersionNumber);
doc.save();
} catch (Exception e) {
errorOnWriteConflict(iRemoteNode, doc);
}
}
}
@Override
public void handleDeleteConflict(final String iRemoteNode, final ORecordId iCurrentRID) {
ODistributedServerLog.warn(this, cluster.getLocalNodeName(), iRemoteNode, DIRECTION.IN,
"Conflict on DELETE record %s/%s (cannot be deleted on other node)", database.getName(), iCurrentRID);
if (!existConflictsForRecord(iCurrentRID)) {
// WRITE THE CONFLICT AS RECORD
final ODocument doc = createConflictDocument(ORecordOperation.DELETED, iCurrentRID, iRemoteNode);
try {
doc.save();
} catch (Exception e) {
errorOnWriteConflict(iRemoteNode, doc);
}
}
}
@Override
public void handleCommandConflict(final String iRemoteNode, final Object iCommand, Object iLocalResult, Object iRemoteResult) {
ODistributedServerLog.warn(this, cluster.getLocalNodeName(), iRemoteNode, DIRECTION.IN,
"Conflict on COMMAND execution on db '%s', cmd='%s' result local=%s, remote=%s", database.getName(), iCommand,
iLocalResult, iRemoteResult);
}
@Override
public ODocument getAllConflicts() {
ODatabaseRecordThreadLocal.INSTANCE.set((ODatabaseRecord) database);
final List<OIdentifiable> entries = database.query(new OSQLSynchQuery<OIdentifiable>("select from "
+ DISTRIBUTED_CONFLICT_CLASS));
// EARLY LOAD CONTENT
final ODocument result = new ODocument().field("result", entries);
for (int i = 0; i < entries.size(); ++i) {
final ODocument record = entries.get(i).getRecord();
record.setClassName(null);
record.addOwner(result);
record.getIdentity().reset();
final Byte operation = record.field("operation");
record.field("operation", ORecordOperation.getName(operation));
entries.set(i, record);
}
return result;
}
@Override
public ODocument reset() {
ODatabaseRecordThreadLocal.INSTANCE.set((ODatabaseRecord) database);
final int deleted = (Integer) database.command(new OSQLSynchQuery<OIdentifiable>("delete from " + DISTRIBUTED_CONFLICT_CLASS))
.execute();
return new ODocument().field("result", deleted);
}
/**
* Searches for a conflict by RID.
*
* @param iRID
* RID to search
*/
public boolean existConflictsForRecord(final ORecordId iRID) {
ODatabaseRecordThreadLocal.INSTANCE.set((ODatabaseRecord) database);
if (index == null) {
ODistributedServerLog.warn(this, cluster.getLocalNodeName(), null, DIRECTION.NONE,
"Index against %s is not available right now, searches will be slower", DISTRIBUTED_CONFLICT_CLASS);
final List<?> result = database.query(new OSQLSynchQuery<Object>("select from " + DISTRIBUTED_CONFLICT_CLASS + " where "
+ FIELD_RECORD + " = " + iRID.toString()));
return !result.isEmpty();
}
if (index.contains(iRID)) {
ODistributedServerLog.info(this, cluster.getLocalNodeName(), null, DIRECTION.NONE,
"Conflict already present for record %s, skip it", iRID);
return true;
}
return false;
}
protected ODocument createConflictDocument(final byte iOperation, final ORecordId iRid, final String iServerNode) {
ODatabaseRecordThreadLocal.INSTANCE.set((ODatabaseRecord) database);
final ODocument doc = new ODocument(DISTRIBUTED_CONFLICT_CLASS);
doc.field(FIELD_OPERATION, iOperation);
doc.field(FIELD_DATE, new Date());
doc.field(FIELD_RECORD, iRid);
doc.field(FIELD_NODE, iServerNode);
return doc;
}
protected void errorOnWriteConflict(final String iRemoteNode, final ODocument doc) {
ODistributedServerLog.error(this, cluster.getLocalNodeName(), iRemoteNode, DIRECTION.IN,
"Error on saving CONFLICT for record %s/%s...", database.getName(), doc);
}
protected boolean areRecordContentIdentical(final ORecordInternal<?> rec1, final ORecordInternal<?> rec2) {
final byte[] rec1Stream = rec1.toStream();
final byte[] rec2Stream = rec2.toStream();
if (rec1Stream.length != rec2Stream.length)
return false;
for (int i = 0; i < rec1Stream.length; ++i)
if (rec1Stream[i] != rec2Stream[i])
return false;
return true;
}
}
| 0true
|
server_src_main_java_com_orientechnologies_orient_server_distributed_conflict_ODefaultReplicationConflictResolver.java
|
841 |
return new IAnswer<Order>() {
@Override
public Order answer() throws Throwable {
return (Order) EasyMock.getCurrentArguments()[0];
}
};
| 0true
|
core_broadleaf-framework_src_test_java_org_broadleafcommerce_core_offer_service_OfferDataItemProvider.java
|
2,530 |
new HashMap<String, Object>() {{
put("nested", 2);
put("nested_2", 3);
}}));
| 0true
|
src_test_java_org_elasticsearch_common_xcontent_support_XContentMapValuesTests.java
|
3,507 |
public class MapperService extends AbstractIndexComponent implements Iterable<DocumentMapper> {
public static final String DEFAULT_MAPPING = "_default_";
private static ObjectOpenHashSet<String> META_FIELDS = ObjectOpenHashSet.from(
"_uid", "_id", "_type", "_all", "_analyzer", "_boost", "_parent", "_routing", "_index",
"_size", "_timestamp", "_ttl"
);
private final AnalysisService analysisService;
private final IndexFieldDataService fieldDataService;
/**
* Will create types automatically if they do not exists in the mapping definition yet
*/
private final boolean dynamic;
private volatile String defaultMappingSource;
private volatile String defaultPercolatorMappingSource;
private volatile Map<String, DocumentMapper> mappers = ImmutableMap.of();
private final Object typeMutex = new Object();
private final Object mappersMutex = new Object();
private final FieldMappersLookup fieldMappers = new FieldMappersLookup();
private volatile ImmutableOpenMap<String, ObjectMappers> fullPathObjectMappers = ImmutableOpenMap.of();
private boolean hasNested = false; // updated dynamically to true when a nested object is added
private final DocumentMapperParser documentParser;
private final InternalFieldMapperListener fieldMapperListener = new InternalFieldMapperListener();
private final InternalObjectMapperListener objectMapperListener = new InternalObjectMapperListener();
private final SmartIndexNameSearchAnalyzer searchAnalyzer;
private final SmartIndexNameSearchQuoteAnalyzer searchQuoteAnalyzer;
private final List<DocumentTypeListener> typeListeners = new CopyOnWriteArrayList<DocumentTypeListener>();
@Inject
public MapperService(Index index, @IndexSettings Settings indexSettings, Environment environment, AnalysisService analysisService, IndexFieldDataService fieldDataService,
PostingsFormatService postingsFormatService, DocValuesFormatService docValuesFormatService, SimilarityLookupService similarityLookupService) {
super(index, indexSettings);
this.analysisService = analysisService;
this.fieldDataService = fieldDataService;
this.documentParser = new DocumentMapperParser(index, indexSettings, analysisService, postingsFormatService, docValuesFormatService, similarityLookupService);
this.searchAnalyzer = new SmartIndexNameSearchAnalyzer(analysisService.defaultSearchAnalyzer());
this.searchQuoteAnalyzer = new SmartIndexNameSearchQuoteAnalyzer(analysisService.defaultSearchQuoteAnalyzer());
this.dynamic = componentSettings.getAsBoolean("dynamic", true);
String defaultMappingLocation = componentSettings.get("default_mapping_location");
URL defaultMappingUrl;
if (defaultMappingLocation == null) {
try {
defaultMappingUrl = environment.resolveConfig("default-mapping.json");
} catch (FailedToResolveConfigException e) {
// not there, default to the built in one
defaultMappingUrl = indexSettings.getClassLoader().getResource("org/elasticsearch/index/mapper/default-mapping.json");
if (defaultMappingUrl == null) {
defaultMappingUrl = MapperService.class.getClassLoader().getResource("org/elasticsearch/index/mapper/default-mapping.json");
}
}
} else {
try {
defaultMappingUrl = environment.resolveConfig(defaultMappingLocation);
} catch (FailedToResolveConfigException e) {
// not there, default to the built in one
try {
defaultMappingUrl = new File(defaultMappingLocation).toURI().toURL();
} catch (MalformedURLException e1) {
throw new FailedToResolveConfigException("Failed to resolve dynamic mapping location [" + defaultMappingLocation + "]");
}
}
}
if (defaultMappingUrl == null) {
logger.info("failed to find default-mapping.json in the classpath, using the default template");
defaultMappingSource = "{\n" +
" \"_default_\":{\n" +
" }\n" +
"}";
} else {
try {
defaultMappingSource = Streams.copyToString(new InputStreamReader(defaultMappingUrl.openStream(), Charsets.UTF_8));
} catch (IOException e) {
throw new MapperException("Failed to load default mapping source from [" + defaultMappingLocation + "]", e);
}
}
String percolatorMappingLocation = componentSettings.get("default_percolator_mapping_location");
URL percolatorMappingUrl = null;
if (percolatorMappingLocation != null) {
try {
percolatorMappingUrl = environment.resolveConfig(percolatorMappingLocation);
} catch (FailedToResolveConfigException e) {
// not there, default to the built in one
try {
percolatorMappingUrl = new File(percolatorMappingLocation).toURI().toURL();
} catch (MalformedURLException e1) {
throw new FailedToResolveConfigException("Failed to resolve default percolator mapping location [" + percolatorMappingLocation + "]");
}
}
}
if (percolatorMappingUrl != null) {
try {
defaultPercolatorMappingSource = Streams.copyToString(new InputStreamReader(percolatorMappingUrl.openStream(), Charsets.UTF_8));
} catch (IOException e) {
throw new MapperException("Failed to load default percolator mapping source from [" + percolatorMappingUrl + "]", e);
}
} else {
defaultPercolatorMappingSource = "{\n" +
//" \"" + PercolatorService.TYPE_NAME + "\":{\n" +
" \"" + "_default_" + "\":{\n" +
" \"_id\" : {\"index\": \"not_analyzed\"}," +
" \"properties\" : {\n" +
" \"query\" : {\n" +
" \"type\" : \"object\",\n" +
" \"enabled\" : false\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
}
if (logger.isDebugEnabled()) {
logger.debug("using dynamic[{}], default mapping: default_mapping_location[{}], loaded_from[{}], default percolator mapping: location[{}], loaded_from[{}]", dynamic, defaultMappingLocation, defaultMappingUrl, percolatorMappingLocation, percolatorMappingUrl);
} else if (logger.isTraceEnabled()) {
logger.trace("using dynamic[{}], default mapping: default_mapping_location[{}], loaded_from[{}] and source[{}], default percolator mapping: location[{}], loaded_from[{}] and source[{}]", dynamic, defaultMappingLocation, defaultMappingUrl, defaultMappingSource, percolatorMappingLocation, percolatorMappingUrl, defaultPercolatorMappingSource);
}
}
public void close() {
for (DocumentMapper documentMapper : mappers.values()) {
documentMapper.close();
}
}
public boolean hasNested() {
return this.hasNested;
}
@Override
public UnmodifiableIterator<DocumentMapper> iterator() {
return Iterators.unmodifiableIterator(mappers.values().iterator());
}
public AnalysisService analysisService() {
return this.analysisService;
}
public DocumentMapperParser documentMapperParser() {
return this.documentParser;
}
public void addTypeListener(DocumentTypeListener listener) {
typeListeners.add(listener);
}
public void removeTypeListener(DocumentTypeListener listener) {
typeListeners.remove(listener);
}
public DocumentMapper merge(String type, CompressedString mappingSource, boolean applyDefault) {
if (DEFAULT_MAPPING.equals(type)) {
// verify we can parse it
DocumentMapper mapper = documentParser.parseCompressed(type, mappingSource);
// still add it as a document mapper so we have it registered and, for example, persisted back into
// the cluster meta data if needed, or checked for existence
synchronized (typeMutex) {
mappers = newMapBuilder(mappers).put(type, mapper).map();
}
try {
defaultMappingSource = mappingSource.string();
} catch (IOException e) {
throw new ElasticsearchGenerationException("failed to un-compress", e);
}
return mapper;
} else {
return merge(parse(type, mappingSource, applyDefault));
}
}
// never expose this to the outside world, we need to reparse the doc mapper so we get fresh
// instances of field mappers to properly remove existing doc mapper
private DocumentMapper merge(DocumentMapper mapper) {
synchronized (typeMutex) {
if (mapper.type().length() == 0) {
throw new InvalidTypeNameException("mapping type name is empty");
}
if (mapper.type().charAt(0) == '_') {
throw new InvalidTypeNameException("mapping type name [" + mapper.type() + "] can't start with '_'");
}
if (mapper.type().contains("#")) {
throw new InvalidTypeNameException("mapping type name [" + mapper.type() + "] should not include '#' in it");
}
if (mapper.type().contains(",")) {
throw new InvalidTypeNameException("mapping type name [" + mapper.type() + "] should not include ',' in it");
}
if (mapper.type().contains(".") && !PercolatorService.TYPE_NAME.equals(mapper.type())) {
logger.warn("Type [{}] contains a '.', it is recommended not to include it within a type name", mapper.type());
}
// we can add new field/object mappers while the old ones are there
// since we get new instances of those, and when we remove, we remove
// by instance equality
DocumentMapper oldMapper = mappers.get(mapper.type());
if (oldMapper != null) {
DocumentMapper.MergeResult result = oldMapper.merge(mapper, mergeFlags().simulate(false));
if (result.hasConflicts()) {
// TODO: What should we do???
if (logger.isDebugEnabled()) {
logger.debug("merging mapping for type [{}] resulted in conflicts: [{}]", mapper.type(), Arrays.toString(result.conflicts()));
}
}
fieldDataService.onMappingUpdate();
return oldMapper;
} else {
FieldMapperListener.Aggregator fieldMappersAgg = new FieldMapperListener.Aggregator();
mapper.traverse(fieldMappersAgg);
addFieldMappers(fieldMappersAgg.mappers);
mapper.addFieldMapperListener(fieldMapperListener, false);
ObjectMapperListener.Aggregator objectMappersAgg = new ObjectMapperListener.Aggregator();
mapper.traverse(objectMappersAgg);
addObjectMappers(objectMappersAgg.mappers.toArray(new ObjectMapper[objectMappersAgg.mappers.size()]));
mapper.addObjectMapperListener(objectMapperListener, false);
for (DocumentTypeListener typeListener : typeListeners) {
typeListener.beforeCreate(mapper);
}
mappers = newMapBuilder(mappers).put(mapper.type(), mapper).map();
return mapper;
}
}
}
private void addObjectMappers(ObjectMapper[] objectMappers) {
synchronized (mappersMutex) {
ImmutableOpenMap.Builder<String, ObjectMappers> fullPathObjectMappers = ImmutableOpenMap.builder(this.fullPathObjectMappers);
for (ObjectMapper objectMapper : objectMappers) {
ObjectMappers mappers = fullPathObjectMappers.get(objectMapper.fullPath());
if (mappers == null) {
mappers = new ObjectMappers(objectMapper);
} else {
mappers = mappers.concat(objectMapper);
}
fullPathObjectMappers.put(objectMapper.fullPath(), mappers);
// update the hasNested flag
if (objectMapper.nested().isNested()) {
hasNested = true;
}
}
this.fullPathObjectMappers = fullPathObjectMappers.build();
}
}
private void addFieldMappers(Iterable<FieldMapper> fieldMappers) {
synchronized (mappersMutex) {
this.fieldMappers.addNewMappers(fieldMappers);
}
}
public void remove(String type) {
synchronized (typeMutex) {
DocumentMapper docMapper = mappers.get(type);
if (docMapper == null) {
return;
}
docMapper.close();
mappers = newMapBuilder(mappers).remove(type).map();
removeObjectAndFieldMappers(docMapper);
for (DocumentTypeListener typeListener : typeListeners) {
typeListener.afterRemove(docMapper);
}
}
}
private void removeObjectAndFieldMappers(DocumentMapper docMapper) {
synchronized (mappersMutex) {
fieldMappers.removeMappers(docMapper.mappers());
ImmutableOpenMap.Builder<String, ObjectMappers> fullPathObjectMappers = ImmutableOpenMap.builder(this.fullPathObjectMappers);
for (ObjectMapper mapper : docMapper.objectMappers().values()) {
ObjectMappers mappers = fullPathObjectMappers.get(mapper.fullPath());
if (mappers != null) {
mappers = mappers.remove(mapper);
if (mappers.isEmpty()) {
fullPathObjectMappers.remove(mapper.fullPath());
} else {
fullPathObjectMappers.put(mapper.fullPath(), mappers);
}
}
}
this.fullPathObjectMappers = fullPathObjectMappers.build();
}
}
/**
* Just parses and returns the mapper without adding it, while still applying default mapping.
*/
public DocumentMapper parse(String mappingType, CompressedString mappingSource) throws MapperParsingException {
return parse(mappingType, mappingSource, true);
}
public DocumentMapper parse(String mappingType, CompressedString mappingSource, boolean applyDefault) throws MapperParsingException {
String defaultMappingSource;
if (PercolatorService.TYPE_NAME.equals(mappingType)) {
defaultMappingSource = this.defaultPercolatorMappingSource;
} else {
defaultMappingSource = this.defaultMappingSource;
}
return documentParser.parseCompressed(mappingType, mappingSource, applyDefault ? defaultMappingSource : null);
}
public boolean hasMapping(String mappingType) {
return mappers.containsKey(mappingType);
}
public Collection<String> types() {
return mappers.keySet();
}
public DocumentMapper documentMapper(String type) {
return mappers.get(type);
}
public DocumentMapper documentMapperWithAutoCreate(String type) {
DocumentMapper mapper = mappers.get(type);
if (mapper != null) {
return mapper;
}
if (!dynamic) {
throw new TypeMissingException(index, type, "trying to auto create mapping, but dynamic mapping is disabled");
}
// go ahead and dynamically create it
synchronized (typeMutex) {
mapper = mappers.get(type);
if (mapper != null) {
return mapper;
}
merge(type, null, true);
return mappers.get(type);
}
}
/**
* A filter for search. If a filter is required, will return it, otherwise, will return <tt>null</tt>.
*/
@Nullable
public Filter searchFilter(String... types) {
boolean filterPercolateType = hasMapping(PercolatorService.TYPE_NAME);
if (types != null && filterPercolateType) {
for (String type : types) {
if (PercolatorService.TYPE_NAME.equals(type)) {
filterPercolateType = false;
break;
}
}
}
Filter excludePercolatorType = null;
if (filterPercolateType) {
excludePercolatorType = new NotFilter(documentMapper(PercolatorService.TYPE_NAME).typeFilter());
}
if (types == null || types.length == 0) {
if (hasNested && filterPercolateType) {
return new AndFilter(ImmutableList.of(excludePercolatorType, NonNestedDocsFilter.INSTANCE));
} else if (hasNested) {
return NonNestedDocsFilter.INSTANCE;
} else if (filterPercolateType) {
return excludePercolatorType;
} else {
return null;
}
}
// if we filter by types, we don't need to filter by non nested docs
// since they have different types (starting with __)
if (types.length == 1) {
DocumentMapper docMapper = documentMapper(types[0]);
if (docMapper == null) {
return new TermFilter(new Term(types[0]));
}
return docMapper.typeFilter();
}
// see if we can use terms filter
boolean useTermsFilter = true;
for (String type : types) {
DocumentMapper docMapper = documentMapper(type);
if (docMapper == null) {
useTermsFilter = false;
break;
}
if (!docMapper.typeMapper().fieldType().indexed()) {
useTermsFilter = false;
break;
}
}
if (useTermsFilter) {
BytesRef[] typesBytes = new BytesRef[types.length];
for (int i = 0; i < typesBytes.length; i++) {
typesBytes[i] = new BytesRef(types[i]);
}
TermsFilter termsFilter = new TermsFilter(TypeFieldMapper.NAME, typesBytes);
if (filterPercolateType) {
return new AndFilter(ImmutableList.of(excludePercolatorType, termsFilter));
} else {
return termsFilter;
}
} else {
// Current bool filter requires that at least one should clause matches, even with a must clause.
XBooleanFilter bool = new XBooleanFilter();
for (String type : types) {
DocumentMapper docMapper = documentMapper(type);
if (docMapper == null) {
bool.add(new FilterClause(new TermFilter(new Term(TypeFieldMapper.NAME, type)), BooleanClause.Occur.SHOULD));
} else {
bool.add(new FilterClause(docMapper.typeFilter(), BooleanClause.Occur.SHOULD));
}
}
if (filterPercolateType) {
bool.add(excludePercolatorType, BooleanClause.Occur.MUST);
}
return bool;
}
}
/**
* Returns {@link FieldMappers} for all the {@link FieldMapper}s that are registered
* under the given name across all the different {@link DocumentMapper} types.
*
* @param name The name to return all the {@link FieldMappers} for across all {@link DocumentMapper}s.
* @return All the {@link FieldMappers} for across all {@link DocumentMapper}s
*/
public FieldMappers name(String name) {
return fieldMappers.name(name);
}
/**
* Returns {@link FieldMappers} for all the {@link FieldMapper}s that are registered
* under the given indexName across all the different {@link DocumentMapper} types.
*
* @param indexName The indexName to return all the {@link FieldMappers} for across all {@link DocumentMapper}s.
* @return All the {@link FieldMappers} across all {@link DocumentMapper}s for the given indexName.
*/
public FieldMappers indexName(String indexName) {
return fieldMappers.indexName(indexName);
}
/**
* Returns the {@link FieldMappers} of all the {@link FieldMapper}s that are
* registered under the give fullName across all the different {@link DocumentMapper} types.
*
* @param fullName The full name
* @return All teh {@link FieldMappers} across all the {@link DocumentMapper}s for the given fullName.
*/
public FieldMappers fullName(String fullName) {
return fieldMappers.fullName(fullName);
}
/**
* Returns objects mappers based on the full path of the object.
*/
public ObjectMappers objectMapper(String path) {
return fullPathObjectMappers.get(path);
}
/**
* Returns all the fields that match the given pattern, with an optional narrowing
* based on a list of types.
*/
public Set<String> simpleMatchToIndexNames(String pattern, @Nullable String[] types) {
if (types == null || types.length == 0) {
return simpleMatchToIndexNames(pattern);
}
if (types.length == 1 && types[0].equals("_all")) {
return simpleMatchToIndexNames(pattern);
}
if (!Regex.isSimpleMatchPattern(pattern)) {
return ImmutableSet.of(pattern);
}
Set<String> fields = Sets.newHashSet();
for (String type : types) {
DocumentMapper possibleDocMapper = mappers.get(type);
if (possibleDocMapper != null) {
for (String indexName : possibleDocMapper.mappers().simpleMatchToIndexNames(pattern)) {
fields.add(indexName);
}
}
}
return fields;
}
/**
* Returns all the fields that match the given pattern. If the pattern is prefixed with a type
* then the fields will be returned with a type prefix.
*/
public Set<String> simpleMatchToIndexNames(String pattern) {
if (!Regex.isSimpleMatchPattern(pattern)) {
return ImmutableSet.of(pattern);
}
int dotIndex = pattern.indexOf('.');
if (dotIndex != -1) {
String possibleType = pattern.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
Set<String> typedFields = Sets.newHashSet();
for (String indexName : possibleDocMapper.mappers().simpleMatchToIndexNames(pattern)) {
typedFields.add(possibleType + "." + indexName);
}
return typedFields;
}
}
return fieldMappers.simpleMatchToIndexNames(pattern);
}
public SmartNameObjectMapper smartNameObjectMapper(String smartName, @Nullable String[] types) {
if (types == null || types.length == 0) {
return smartNameObjectMapper(smartName);
}
if (types.length == 1 && types[0].equals("_all")) {
return smartNameObjectMapper(smartName);
}
for (String type : types) {
DocumentMapper possibleDocMapper = mappers.get(type);
if (possibleDocMapper != null) {
ObjectMapper mapper = possibleDocMapper.objectMappers().get(smartName);
if (mapper != null) {
return new SmartNameObjectMapper(mapper, possibleDocMapper);
}
}
}
// did not find one, see if its prefixed by type
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possiblePath = smartName.substring(dotIndex + 1);
ObjectMapper mapper = possibleDocMapper.objectMappers().get(possiblePath);
if (mapper != null) {
return new SmartNameObjectMapper(mapper, possibleDocMapper);
}
}
}
// did not explicitly find one under the types provided, or prefixed by type...
return null;
}
public SmartNameObjectMapper smartNameObjectMapper(String smartName) {
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possiblePath = smartName.substring(dotIndex + 1);
ObjectMapper mapper = possibleDocMapper.objectMappers().get(possiblePath);
if (mapper != null) {
return new SmartNameObjectMapper(mapper, possibleDocMapper);
}
}
}
ObjectMappers mappers = objectMapper(smartName);
if (mappers != null) {
return new SmartNameObjectMapper(mappers.mapper(), null);
}
return null;
}
/**
* Same as {@link #smartNameFieldMappers(String)} but returns the first field mapper for it. Returns
* <tt>null</tt> if there is none.
*/
public FieldMapper smartNameFieldMapper(String smartName) {
FieldMappers fieldMappers = smartNameFieldMappers(smartName);
if (fieldMappers != null) {
return fieldMappers.mapper();
}
return null;
}
public FieldMapper smartNameFieldMapper(String smartName, @Nullable String[] types) {
FieldMappers fieldMappers = smartNameFieldMappers(smartName, types);
if (fieldMappers != null) {
return fieldMappers.mapper();
}
return null;
}
public FieldMappers smartNameFieldMappers(String smartName, @Nullable String[] types) {
if (types == null || types.length == 0) {
return smartNameFieldMappers(smartName);
}
for (String type : types) {
DocumentMapper documentMapper = mappers.get(type);
// we found a mapper
if (documentMapper != null) {
// see if we find a field for it
FieldMappers mappers = documentMapper.mappers().smartName(smartName);
if (mappers != null) {
return mappers;
}
}
}
// did not find explicit field in the type provided, see if its prefixed with type
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possibleName = smartName.substring(dotIndex + 1);
FieldMappers mappers = possibleDocMapper.mappers().smartName(possibleName);
if (mappers != null) {
return mappers;
}
}
}
// we did not find the field mapping in any of the types, so don't go and try to find
// it in other types...
return null;
}
/**
* Same as {@link #smartName(String)}, except it returns just the field mappers.
*/
public FieldMappers smartNameFieldMappers(String smartName) {
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possibleName = smartName.substring(dotIndex + 1);
FieldMappers mappers = possibleDocMapper.mappers().smartName(possibleName);
if (mappers != null) {
return mappers;
}
}
}
FieldMappers mappers = fullName(smartName);
if (mappers != null) {
return mappers;
}
mappers = indexName(smartName);
if (mappers != null) {
return mappers;
}
return name(smartName);
}
public SmartNameFieldMappers smartName(String smartName, @Nullable String[] types) {
if (types == null || types.length == 0) {
return smartName(smartName);
}
if (types.length == 1 && types[0].equals("_all")) {
return smartName(smartName);
}
for (String type : types) {
DocumentMapper documentMapper = mappers.get(type);
// we found a mapper
if (documentMapper != null) {
// see if we find a field for it
FieldMappers mappers = documentMapper.mappers().smartName(smartName);
if (mappers != null) {
return new SmartNameFieldMappers(this, mappers, documentMapper, false);
}
}
}
// did not find explicit field in the type provided, see if its prefixed with type
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possibleName = smartName.substring(dotIndex + 1);
FieldMappers mappers = possibleDocMapper.mappers().smartName(possibleName);
if (mappers != null) {
return new SmartNameFieldMappers(this, mappers, possibleDocMapper, true);
}
}
}
// we did not find the field mapping in any of the types, so don't go and try to find
// it in other types...
return null;
}
/**
* Returns smart field mappers based on a smart name. A smart name is one that can optioannly be prefixed
* with a type (and then a '.'). If it is, then the {@link MapperService.SmartNameFieldMappers}
* will have the doc mapper set.
* <p/>
* <p>It also (without the optional type prefix) try and find the {@link FieldMappers} for the specific
* name. It will first try to find it based on the full name (with the dots if its a compound name). If
* it is not found, will try and find it based on the indexName (which can be controlled in the mapping),
* and last, will try it based no the name itself.
* <p/>
* <p>If nothing is found, returns null.
*/
public SmartNameFieldMappers smartName(String smartName) {
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possibleName = smartName.substring(dotIndex + 1);
FieldMappers mappers = possibleDocMapper.mappers().smartName(possibleName);
if (mappers != null) {
return new SmartNameFieldMappers(this, mappers, possibleDocMapper, true);
}
}
}
FieldMappers fieldMappers = fullName(smartName);
if (fieldMappers != null) {
return new SmartNameFieldMappers(this, fieldMappers, null, false);
}
fieldMappers = indexName(smartName);
if (fieldMappers != null) {
return new SmartNameFieldMappers(this, fieldMappers, null, false);
}
fieldMappers = name(smartName);
if (fieldMappers != null) {
return new SmartNameFieldMappers(this, fieldMappers, null, false);
}
return null;
}
public Analyzer searchAnalyzer() {
return this.searchAnalyzer;
}
public Analyzer searchQuoteAnalyzer() {
return this.searchQuoteAnalyzer;
}
public Analyzer fieldSearchAnalyzer(String field) {
return this.searchAnalyzer.getWrappedAnalyzer(field);
}
public Analyzer fieldSearchQuoteAnalyzer(String field) {
return this.searchQuoteAnalyzer.getWrappedAnalyzer(field);
}
/**
* Resolves the closest inherited {@link ObjectMapper} that is nested.
*/
public ObjectMapper resolveClosestNestedObjectMapper(String fieldName) {
int indexOf = fieldName.lastIndexOf('.');
if (indexOf == -1) {
return null;
} else {
do {
String objectPath = fieldName.substring(0, indexOf);
ObjectMappers objectMappers = objectMapper(objectPath);
if (objectMappers == null) {
return null;
}
if (objectMappers.hasNested()) {
for (ObjectMapper objectMapper : objectMappers) {
if (objectMapper.nested().isNested()) {
return objectMapper;
}
}
}
indexOf = objectPath.lastIndexOf('.');
} while (indexOf != -1);
}
return null;
}
/**
* @return Whether a field is a metadata field.
*/
public static boolean isMetadataField(String fieldName) {
return META_FIELDS.contains(fieldName);
}
public static class SmartNameObjectMapper {
private final ObjectMapper mapper;
private final DocumentMapper docMapper;
public SmartNameObjectMapper(ObjectMapper mapper, @Nullable DocumentMapper docMapper) {
this.mapper = mapper;
this.docMapper = docMapper;
}
public boolean hasMapper() {
return mapper != null;
}
public ObjectMapper mapper() {
return mapper;
}
public boolean hasDocMapper() {
return docMapper != null;
}
public DocumentMapper docMapper() {
return docMapper;
}
}
public static class SmartNameFieldMappers {
private final MapperService mapperService;
private final FieldMappers fieldMappers;
private final DocumentMapper docMapper;
private final boolean explicitTypeInName;
public SmartNameFieldMappers(MapperService mapperService, FieldMappers fieldMappers, @Nullable DocumentMapper docMapper, boolean explicitTypeInName) {
this.mapperService = mapperService;
this.fieldMappers = fieldMappers;
this.docMapper = docMapper;
this.explicitTypeInName = explicitTypeInName;
}
/**
* Has at least one mapper for the field.
*/
public boolean hasMapper() {
return !fieldMappers.isEmpty();
}
/**
* The first mapper for the smart named field.
*/
public FieldMapper mapper() {
return fieldMappers.mapper();
}
/**
* All the field mappers for the smart name field.
*/
public FieldMappers fieldMappers() {
return fieldMappers;
}
/**
* If the smart name was a typed field, with a type that we resolved, will return
* <tt>true</tt>.
*/
public boolean hasDocMapper() {
return docMapper != null;
}
/**
* If the smart name was a typed field, with a type that we resolved, will return
* the document mapper for it.
*/
public DocumentMapper docMapper() {
return docMapper;
}
/**
* Returns <tt>true</tt> if the type is explicitly specified in the name.
*/
public boolean explicitTypeInName() {
return this.explicitTypeInName;
}
public boolean explicitTypeInNameWithDocMapper() {
return explicitTypeInName && docMapper != null;
}
/**
* The best effort search analyzer associated with this field.
*/
public Analyzer searchAnalyzer() {
if (hasMapper()) {
Analyzer analyzer = mapper().searchAnalyzer();
if (analyzer != null) {
return analyzer;
}
}
if (docMapper != null && docMapper.searchAnalyzer() != null) {
return docMapper.searchAnalyzer();
}
return mapperService.searchAnalyzer();
}
public Analyzer searchQuoteAnalyzer() {
if (hasMapper()) {
Analyzer analyzer = mapper().searchQuoteAnalyzer();
if (analyzer != null) {
return analyzer;
}
}
if (docMapper != null && docMapper.searchQuotedAnalyzer() != null) {
return docMapper.searchQuotedAnalyzer();
}
return mapperService.searchQuoteAnalyzer();
}
}
final class SmartIndexNameSearchAnalyzer extends AnalyzerWrapper {
private final Analyzer defaultAnalyzer;
SmartIndexNameSearchAnalyzer(Analyzer defaultAnalyzer) {
this.defaultAnalyzer = defaultAnalyzer;
}
@Override
protected Analyzer getWrappedAnalyzer(String fieldName) {
int dotIndex = fieldName.indexOf('.');
if (dotIndex != -1) {
String possibleType = fieldName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
return possibleDocMapper.mappers().searchAnalyzer();
}
}
FieldMappers mappers = fieldMappers.fullName(fieldName);
if (mappers != null && mappers.mapper() != null && mappers.mapper().searchAnalyzer() != null) {
return mappers.mapper().searchAnalyzer();
}
mappers = fieldMappers.indexName(fieldName);
if (mappers != null && mappers.mapper() != null && mappers.mapper().searchAnalyzer() != null) {
return mappers.mapper().searchAnalyzer();
}
return defaultAnalyzer;
}
@Override
protected TokenStreamComponents wrapComponents(String fieldName, TokenStreamComponents components) {
return components;
}
}
final class SmartIndexNameSearchQuoteAnalyzer extends AnalyzerWrapper {
private final Analyzer defaultAnalyzer;
SmartIndexNameSearchQuoteAnalyzer(Analyzer defaultAnalyzer) {
this.defaultAnalyzer = defaultAnalyzer;
}
@Override
protected Analyzer getWrappedAnalyzer(String fieldName) {
int dotIndex = fieldName.indexOf('.');
if (dotIndex != -1) {
String possibleType = fieldName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
return possibleDocMapper.mappers().searchQuoteAnalyzer();
}
}
FieldMappers mappers = fieldMappers.fullName(fieldName);
if (mappers != null && mappers.mapper() != null && mappers.mapper().searchQuoteAnalyzer() != null) {
return mappers.mapper().searchQuoteAnalyzer();
}
mappers = fieldMappers.indexName(fieldName);
if (mappers != null && mappers.mapper() != null && mappers.mapper().searchQuoteAnalyzer() != null) {
return mappers.mapper().searchQuoteAnalyzer();
}
return defaultAnalyzer;
}
@Override
protected TokenStreamComponents wrapComponents(String fieldName, TokenStreamComponents components) {
return components;
}
}
class InternalFieldMapperListener extends FieldMapperListener {
@Override
public void fieldMapper(FieldMapper fieldMapper) {
addFieldMappers(Arrays.asList(fieldMapper));
}
@Override
public void fieldMappers(Iterable<FieldMapper> fieldMappers) {
addFieldMappers(fieldMappers);
}
}
class InternalObjectMapperListener extends ObjectMapperListener {
@Override
public void objectMapper(ObjectMapper objectMapper) {
addObjectMappers(new ObjectMapper[]{objectMapper});
}
@Override
public void objectMappers(ObjectMapper... objectMappers) {
addObjectMappers(objectMappers);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_mapper_MapperService.java
|
406 |
@SuppressWarnings("serial")
public class OTrackedSet<T> extends HashSet<T> implements ORecordElement, OTrackedMultiValue<T, T>, Serializable {
protected final ORecord<?> sourceRecord;
private STATUS status = STATUS.NOT_LOADED;
private Set<OMultiValueChangeListener<T, T>> changeListeners = Collections
.newSetFromMap(new WeakHashMap<OMultiValueChangeListener<T, T>, Boolean>());
protected Class<?> genericClass;
public OTrackedSet(final ORecord<?> iRecord, final Collection<? extends T> iOrigin, final Class<?> cls) {
this(iRecord);
genericClass = cls;
if (iOrigin != null && !iOrigin.isEmpty())
addAll(iOrigin);
}
public OTrackedSet(final ORecord<?> iSourceRecord) {
this.sourceRecord = iSourceRecord;
}
public boolean add(final T e) {
if (super.add(e)) {
fireCollectionChangedEvent(new OMultiValueChangeEvent<T, T>(OMultiValueChangeEvent.OChangeType.ADD, e, e));
return true;
}
return false;
}
@SuppressWarnings("unchecked")
@Override
public boolean remove(final Object o) {
if (super.remove(o)) {
fireCollectionChangedEvent(new OMultiValueChangeEvent<T, T>(OMultiValueChangeEvent.OChangeType.REMOVE, (T) o, null, (T) o));
return true;
}
return false;
}
@Override
public void clear() {
final Set<T> origValues;
if (changeListeners.isEmpty())
origValues = null;
else
origValues = new HashSet<T>(this);
super.clear();
if (origValues != null) {
for (final T item : origValues)
fireCollectionChangedEvent(new OMultiValueChangeEvent<T, T>(OMultiValueChangeEvent.OChangeType.REMOVE, item, null, item));
} else
setDirty();
}
@SuppressWarnings("unchecked")
public OTrackedSet<T> setDirty() {
if (status != STATUS.UNMARSHALLING && sourceRecord != null && !sourceRecord.isDirty())
sourceRecord.setDirty();
return this;
}
public void onBeforeIdentityChanged(ORID iRID) {
}
public void onAfterIdentityChanged(ORecord<?> iRecord) {
}
public STATUS getInternalStatus() {
return status;
}
public void setInternalStatus(final STATUS iStatus) {
status = iStatus;
}
public void addChangeListener(final OMultiValueChangeListener<T, T> changeListener) {
changeListeners.add(changeListener);
}
public void removeRecordChangeListener(final OMultiValueChangeListener<T, T> changeListener) {
changeListeners.remove(changeListener);
}
public Set<T> returnOriginalState(final List<OMultiValueChangeEvent<T, T>> multiValueChangeEvents) {
final Set<T> reverted = new HashSet<T>(this);
final ListIterator<OMultiValueChangeEvent<T, T>> listIterator = multiValueChangeEvents.listIterator(multiValueChangeEvents
.size());
while (listIterator.hasPrevious()) {
final OMultiValueChangeEvent<T, T> event = listIterator.previous();
switch (event.getChangeType()) {
case ADD:
reverted.remove(event.getKey());
break;
case REMOVE:
reverted.add(event.getOldValue());
break;
default:
throw new IllegalArgumentException("Invalid change type : " + event.getChangeType());
}
}
return reverted;
}
protected void fireCollectionChangedEvent(final OMultiValueChangeEvent<T, T> event) {
if (status == STATUS.UNMARSHALLING)
return;
setDirty();
for (final OMultiValueChangeListener<T, T> changeListener : changeListeners) {
if (changeListener != null)
changeListener.onAfterRecordChanged(event);
}
}
public Class<?> getGenericClass() {
return genericClass;
}
public void setGenericClass(Class<?> genericClass) {
this.genericClass = genericClass;
}
private Object writeReplace() {
return new HashSet<T>(this);
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_record_OTrackedSet.java
|
906 |
private final class OSimpleMultiValueChangeListener<K, V> implements OMultiValueChangeListener<K, V> {
private final String fieldName;
private OSimpleMultiValueChangeListener(final String fieldName) {
this.fieldName = fieldName;
}
public void onAfterRecordChanged(final OMultiValueChangeEvent<K, V> event) {
if (_status != STATUS.UNMARSHALLING)
setDirty();
if (!(_trackingChanges && _recordId.isValid()) || _status == STATUS.UNMARSHALLING)
return;
if (_fieldOriginalValues != null && _fieldOriginalValues.containsKey(fieldName))
return;
if (_fieldCollectionChangeTimeLines == null)
_fieldCollectionChangeTimeLines = new HashMap<String, OMultiValueChangeTimeLine<String, Object>>();
OMultiValueChangeTimeLine<String, Object> timeLine = _fieldCollectionChangeTimeLines.get(fieldName);
if (timeLine == null) {
timeLine = new OMultiValueChangeTimeLine<String, Object>();
_fieldCollectionChangeTimeLines.put(fieldName, timeLine);
}
timeLine.addCollectionChangeEvent((OMultiValueChangeEvent<String, Object>) event);
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocument.java
|
1,451 |
public class CheckoutForm implements Serializable {
private static final long serialVersionUID = 8866879738364589339L;
private String emailAddress;
private Address shippingAddress = new AddressImpl();
private Address billingAddress = new AddressImpl();
private String creditCardNumber;
private String creditCardCvvCode;
private String creditCardExpMonth;
private String creditCardExpYear;
private String selectedCreditCardType;
private boolean isSameAddress;
public CheckoutForm() {
shippingAddress = new AddressImpl();
billingAddress = new AddressImpl();
shippingAddress.setPhonePrimary(new PhoneImpl());
billingAddress.setPhonePrimary(new PhoneImpl());
shippingAddress.setCountry(new CountryImpl());
billingAddress.setCountry(new CountryImpl());
shippingAddress.setState(new StateImpl());
billingAddress.setState(new StateImpl());
isSameAddress = true;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getSelectedCreditCardType() {
return selectedCreditCardType;
}
public void setSelectedCreditCardType(String selectedCreditCardType) {
this.selectedCreditCardType = selectedCreditCardType;
}
public List<CreditCardType> getApprovedCreditCardTypes() {
List<CreditCardType> approvedCCTypes = new ArrayList<CreditCardType>();
approvedCCTypes.add(CreditCardType.VISA);
approvedCCTypes.add(CreditCardType.MASTERCARD);
approvedCCTypes.add(CreditCardType.AMEX);
return approvedCCTypes;
}
public Address getShippingAddress() {
return shippingAddress == null ? new AddressImpl() : shippingAddress;
}
public void setShippingAddress(Address shippingAddress) {
this.shippingAddress = shippingAddress;
}
public Address getBillingAddress() {
return billingAddress == null ? new AddressImpl() : billingAddress;
}
public void setBillingAddress(Address billingAddress) {
this.billingAddress = billingAddress;
}
public String getCreditCardNumber() {
return creditCardNumber;
}
public void setCreditCardNumber(String creditCardNumber) {
this.creditCardNumber = creditCardNumber;
}
public String getCreditCardCvvCode() {
return creditCardCvvCode;
}
public void setCreditCardCvvCode(String creditCardCvvCode) {
this.creditCardCvvCode = creditCardCvvCode;
}
public String getCreditCardExpMonth() {
return creditCardExpMonth;
}
public void setCreditCardExpMonth(String creditCardExpMonth) {
this.creditCardExpMonth = creditCardExpMonth;
}
public String getCreditCardExpYear() {
return creditCardExpYear;
}
public void setCreditCardExpYear(String creditCardExpYear) {
this.creditCardExpYear = creditCardExpYear;
}
public boolean getIsSameAddress() {
return isSameAddress;
}
public void setIsSameAddress(boolean isSameAddress) {
this.isSameAddress = isSameAddress;
}
}
| 0true
|
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_checkout_model_CheckoutForm.java
|
822 |
db.getStorage().callInLock(new Callable<Object>() {
@Override
public Object call() throws Exception {
saveInternal(OMetadataDefault.CLUSTER_INTERNAL_NAME);
return null;
}
}, true);
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OSchemaShared.java
|
1,903 |
public class QueryEventFilter extends EntryEventFilter {
Predicate predicate = null;
public QueryEventFilter(boolean includeValue, Data key, Predicate predicate) {
super(includeValue, key);
this.predicate = predicate;
}
public QueryEventFilter() {
super();
}
public Object getPredicate() {
return predicate;
}
public boolean eval(Object arg) {
final QueryEntry entry = (QueryEntry) arg;
final Data keyData = entry.getKeyData();
return (key == null || key.equals(keyData)) && predicate.apply((Map.Entry)arg);
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
super.writeData(out);
out.writeObject(predicate);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
super.readData(in);
predicate = in.readObject();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_map_QueryEventFilter.java
|
271 |
private static class ThriftGetter implements StaticArrayEntry.GetColVal<ColumnOrSuperColumn,ByteBuffer> {
private final EntryMetaData[] schema;
private ThriftGetter(EntryMetaData[] schema) {
this.schema = schema;
}
@Override
public ByteBuffer getColumn(ColumnOrSuperColumn element) {
return element.getColumn().bufferForName();
}
@Override
public ByteBuffer getValue(ColumnOrSuperColumn element) {
return element.getColumn().bufferForValue();
}
@Override
public EntryMetaData[] getMetaSchema(ColumnOrSuperColumn element) {
return schema;
}
@Override
public Object getMetaData(ColumnOrSuperColumn element, EntryMetaData meta) {
switch(meta) {
case TIMESTAMP:
return element.getColumn().getTimestamp();
case TTL:
return element.getColumn().getTtl();
default:
throw new UnsupportedOperationException("Unsupported meta data: " + meta);
}
}
}
| 0true
|
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_thrift_CassandraThriftKeyColumnValueStore.java
|
361 |
@Deprecated
public class OGraphDatabase extends ODatabaseDocumentTx {
private final boolean preferSBTreeSet = OGlobalConfiguration.PREFER_SBTREE_SET.getValueAsBoolean();
public enum LOCK_MODE {
NO_LOCKING, DATABASE_LEVEL_LOCKING, RECORD_LEVEL_LOCKING
}
public enum DIRECTION {
BOTH, IN, OUT
}
public static final String TYPE = "graph";
public static final String VERTEX_CLASS_NAME = "OGraphVertex";
public static final String VERTEX_ALIAS = "V";
public static final String VERTEX_FIELD_IN = "in_";
public static final String VERTEX_FIELD_OUT = "out_";
public static final String VERTEX_FIELD_IN_OLD = "in";
public static final String VERTEX_FIELD_OUT_OLD = "out";
public static final String EDGE_CLASS_NAME = "OGraphEdge";
public static final String EDGE_ALIAS = "E";
public static final String EDGE_FIELD_IN = "in";
public static final String EDGE_FIELD_OUT = "out";
public static final String LABEL = "label";
private String outV = VERTEX_FIELD_OUT;
private String inV = VERTEX_FIELD_IN;
private boolean useCustomTypes = true;
private boolean safeMode = false;
private LOCK_MODE lockMode = LOCK_MODE.NO_LOCKING;
private boolean retroCompatibility = false;
protected OClass vertexBaseClass;
protected OClass edgeBaseClass;
public OGraphDatabase(final String iURL) {
super(iURL);
}
public OGraphDatabase(final ODatabaseRecordTx iSource) {
super(iSource);
checkForGraphSchema();
}
@Override
@SuppressWarnings("unchecked")
public <THISDB extends ODatabase> THISDB open(final String iUserName, final String iUserPassword) {
super.open(iUserName, iUserPassword);
checkForGraphSchema();
return (THISDB) this;
}
@Override
@SuppressWarnings("unchecked")
public <THISDB extends ODatabase> THISDB create() {
super.create();
checkForGraphSchema();
return (THISDB) this;
}
@Override
public void close() {
super.close();
vertexBaseClass = null;
edgeBaseClass = null;
}
public long countVertexes() {
return countClass(VERTEX_ALIAS);
}
public long countEdges() {
return countClass(EDGE_ALIAS);
}
public Iterable<ODocument> browseVertices() {
return browseElements(VERTEX_ALIAS, true);
}
public Iterable<ODocument> browseVertices(final boolean iPolymorphic) {
return browseElements(VERTEX_ALIAS, iPolymorphic);
}
public Iterable<ODocument> browseEdges() {
return browseElements(EDGE_ALIAS, true);
}
public Iterable<ODocument> browseEdges(final boolean iPolymorphic) {
return browseElements(EDGE_ALIAS, iPolymorphic);
}
public Iterable<ODocument> browseElements(final String iClass, final boolean iPolymorphic) {
return new ORecordIteratorClass<ODocument>(this, (ODatabaseRecordAbstract) getUnderlying(), iClass, iPolymorphic, true, false);
}
public ODocument createVertex() {
return createVertex(null);
}
public ODocument createVertex(final String iClassName) {
return createVertex(iClassName, (Object[]) null);
}
@SuppressWarnings("unchecked")
public ODocument createVertex(final String iClassName, final Object... iFields) {
final OClass cls = checkVertexClass(iClassName);
final ODocument vertex = new ODocument(cls).setOrdered(true);
if (iFields != null)
// SET THE FIELDS
if (iFields != null)
if (iFields.length == 1) {
Object f = iFields[0];
if (f instanceof Map<?, ?>)
vertex.fields((Map<String, Object>) f);
else
throw new IllegalArgumentException(
"Invalid fields: expecting a pairs of fields as String,Object or a single Map<String,Object>, but found: " + f);
} else
// SET THE FIELDS
for (int i = 0; i < iFields.length; i += 2)
vertex.field(iFields[i].toString(), iFields[i + 1]);
return vertex;
}
public ODocument createEdge(final ORID iSourceVertexRid, final ORID iDestVertexRid) {
return createEdge(iSourceVertexRid, iDestVertexRid, null);
}
public ODocument createEdge(final ORID iSourceVertexRid, final ORID iDestVertexRid, final String iClassName) {
final ODocument sourceVertex = load(iSourceVertexRid);
if (sourceVertex == null)
throw new IllegalArgumentException("Source vertex '" + iSourceVertexRid + "' does not exist");
final ODocument destVertex = load(iDestVertexRid);
if (destVertex == null)
throw new IllegalArgumentException("Source vertex '" + iDestVertexRid + "' does not exist");
return createEdge(sourceVertex, destVertex, iClassName);
}
public ODocument createEdge(final ODocument iSourceVertex, final ODocument iDestVertex) {
return createEdge(iSourceVertex, iDestVertex, null);
}
public ODocument createEdge(final ODocument iOutVertex, final ODocument iInVertex, final String iClassName) {
return createEdge(iOutVertex, iInVertex, iClassName, (Object[]) null);
}
@SuppressWarnings("unchecked")
public ODocument createEdge(final ODocument iOutVertex, final ODocument iInVertex, final String iClassName, Object... iFields) {
if (iOutVertex == null)
throw new IllegalArgumentException("iOutVertex is null");
if (iInVertex == null)
throw new IllegalArgumentException("iInVertex is null");
final OClass cls = checkEdgeClass(iClassName);
final boolean safeMode = beginBlock();
try {
final ODocument edge = new ODocument(cls).setOrdered(true);
edge.field(EDGE_FIELD_OUT, iOutVertex);
edge.field(EDGE_FIELD_IN, iInVertex);
if (iFields != null)
if (iFields.length == 1) {
Object f = iFields[0];
if (f instanceof Map<?, ?>)
edge.fields((Map<String, Object>) f);
else
throw new IllegalArgumentException(
"Invalid fields: expecting a pairs of fields as String,Object or a single Map<String,Object>, but found: " + f);
} else
// SET THE FIELDS
for (int i = 0; i < iFields.length; i += 2)
edge.field(iFields[i].toString(), iFields[i + 1]);
// OUT FIELD
updateVertexLinks(iOutVertex, edge, outV);
// IN FIELD
updateVertexLinks(iInVertex, edge, inV);
edge.setDirty();
if (safeMode) {
save(edge);
commitBlock(safeMode);
}
return edge;
} catch (RuntimeException e) {
rollbackBlock(safeMode);
throw e;
}
}
private void updateVertexLinks(ODocument iVertex, ODocument edge, String vertexField) {
acquireWriteLock(iVertex);
try {
final Object field = iVertex.field(vertexField);
final Set<OIdentifiable> links;
if (field instanceof OMVRBTreeRIDSet || field instanceof OSBTreeRIDSet) {
links = (Set<OIdentifiable>) field;
} else if (field instanceof Collection<?>) {
if (preferSBTreeSet)
links = new OSBTreeRIDSet(iVertex, (Collection<OIdentifiable>) field);
else
links = new OMVRBTreeRIDSet(iVertex, (Collection<OIdentifiable>) field);
iVertex.field(vertexField, links);
} else {
links = createRIDSet(iVertex);
iVertex.field(vertexField, links);
}
links.add(edge);
} finally {
releaseWriteLock(iVertex);
}
}
@SuppressWarnings("unchecked")
public boolean removeEdge(final OIdentifiable iEdge) {
if (iEdge == null)
return false;
final ODocument edge = iEdge.getRecord();
if (edge == null)
return false;
final boolean safeMode = beginBlock();
try {
// OUT VERTEX
final ODocument outVertex = edge.field(EDGE_FIELD_OUT);
acquireWriteLock(outVertex);
try {
if (outVertex != null) {
final Set<OIdentifiable> out = getEdgeSet(outVertex, outV);
if (out != null)
out.remove(edge);
save(outVertex);
}
} finally {
releaseWriteLock(outVertex);
}
// IN VERTEX
final ODocument inVertex = edge.field(EDGE_FIELD_IN);
acquireWriteLock(inVertex);
try {
if (inVertex != null) {
final Set<OIdentifiable> in = getEdgeSet(inVertex, inV);
if (in != null)
in.remove(edge);
save(inVertex);
}
} finally {
releaseWriteLock(inVertex);
}
delete(edge);
commitBlock(safeMode);
} catch (RuntimeException e) {
rollbackBlock(safeMode);
throw e;
}
return true;
}
public boolean removeVertex(final OIdentifiable iVertex) {
if (iVertex == null)
return false;
final ODocument vertex = (ODocument) iVertex.getRecord();
if (vertex == null)
return false;
final boolean safeMode = beginBlock();
try {
ODocument otherVertex;
Set<OIdentifiable> otherEdges;
// REMOVE OUT EDGES
acquireWriteLock(vertex);
try {
Set<OIdentifiable> edges = getEdgeSet(vertex, outV);
if (edges != null) {
for (OIdentifiable e : edges) {
if (e != null) {
final ODocument edge = e.getRecord();
if (edge != null) {
otherVertex = edge.field(EDGE_FIELD_IN);
if (otherVertex != null) {
otherEdges = getEdgeSet(otherVertex, inV);
if (otherEdges != null && otherEdges.remove(edge))
save(otherVertex);
}
delete(edge);
}
}
}
}
// REMOVE IN EDGES
edges = getEdgeSet(vertex, inV);
if (edges != null) {
for (OIdentifiable e : edges) {
if (e != null) {
if (e != null) {
final ODocument edge = e.getRecord();
otherVertex = edge.field(EDGE_FIELD_OUT);
if (otherVertex != null) {
otherEdges = getEdgeSet(otherVertex, outV);
if (otherEdges != null && otherEdges.remove(edge))
save(otherVertex);
}
delete(edge);
}
}
}
}
// DELETE VERTEX AS DOCUMENT
delete(vertex);
} finally {
releaseWriteLock(vertex);
}
commitBlock(safeMode);
return true;
} catch (RuntimeException e) {
rollbackBlock(safeMode);
throw e;
}
}
/**
* Returns all the edges between the vertexes iVertex1 and iVertex2.
*
* @param iVertex1
* First Vertex
* @param iVertex2
* Second Vertex
* @return The Set with the common Edges between the two vertexes. If edges aren't found the set is empty
*/
public Set<OIdentifiable> getEdgesBetweenVertexes(final OIdentifiable iVertex1, final OIdentifiable iVertex2) {
return getEdgesBetweenVertexes(iVertex1, iVertex2, null, null);
}
/**
* Returns all the edges between the vertexes iVertex1 and iVertex2 with label between the array of labels passed as iLabels.
*
* @param iVertex1
* First Vertex
* @param iVertex2
* Second Vertex
* @param iLabels
* Array of strings with the labels to get as filter
* @return The Set with the common Edges between the two vertexes. If edges aren't found the set is empty
*/
public Set<OIdentifiable> getEdgesBetweenVertexes(final OIdentifiable iVertex1, final OIdentifiable iVertex2,
final String[] iLabels) {
return getEdgesBetweenVertexes(iVertex1, iVertex2, iLabels, null);
}
/**
* Returns all the edges between the vertexes iVertex1 and iVertex2 with label between the array of labels passed as iLabels and
* with class between the array of class names passed as iClassNames.
*
* @param iVertex1
* First Vertex
* @param iVertex2
* Second Vertex
* @param iLabels
* Array of strings with the labels to get as filter
* @param iClassNames
* Array of strings with the name of the classes to get as filter
* @return The Set with the common Edges between the two vertexes. If edges aren't found the set is empty
*/
public Set<OIdentifiable> getEdgesBetweenVertexes(final OIdentifiable iVertex1, final OIdentifiable iVertex2,
final String[] iLabels, final String[] iClassNames) {
final Set<OIdentifiable> result = new HashSet<OIdentifiable>();
if (iVertex1 != null && iVertex2 != null) {
acquireReadLock(iVertex1);
try {
// CHECK OUT EDGES
for (OIdentifiable e : getOutEdges(iVertex1)) {
final ODocument edge = (ODocument) e.getRecord();
if (checkEdge(edge, iLabels, iClassNames)) {
final OIdentifiable in = edge.<ODocument> field("in");
if (in != null && in.equals(iVertex2))
result.add(edge);
}
}
// CHECK IN EDGES
for (OIdentifiable e : getInEdges(iVertex1)) {
final ODocument edge = (ODocument) e.getRecord();
if (checkEdge(edge, iLabels, iClassNames)) {
final OIdentifiable out = edge.<ODocument> field("out");
if (out != null && out.equals(iVertex2))
result.add(edge);
}
}
} finally {
releaseReadLock(iVertex1);
}
}
return result;
}
public Set<OIdentifiable> getOutEdges(final OIdentifiable iVertex) {
return getOutEdges(iVertex, null);
}
/**
* Retrieves the outgoing edges of vertex iVertex having label equals to iLabel.
*
* @param iVertex
* Target vertex
* @param iLabel
* Label to search
* @return
*/
public Set<OIdentifiable> getOutEdges(final OIdentifiable iVertex, final String iLabel) {
if (iVertex == null)
return null;
final ODocument vertex = iVertex.getRecord();
checkVertexClass(vertex);
Set<OIdentifiable> result = null;
acquireReadLock(iVertex);
try {
final Set<OIdentifiable> set = getEdgeSet(vertex, outV);
if (iLabel == null)
// RETURN THE ENTIRE COLLECTION
if (set != null)
return Collections.unmodifiableSet(set);
else
return Collections.emptySet();
// FILTER BY LABEL
result = new HashSet<OIdentifiable>();
if (set != null)
for (OIdentifiable item : set) {
if (iLabel == null || iLabel.equals(((ODocument) item).field(LABEL)))
result.add(item);
}
} finally {
releaseReadLock(iVertex);
}
return result;
}
@SuppressWarnings("unchecked")
protected Set<OIdentifiable> getEdgeSet(final ODocument iVertex, final String iFieldName) {
final Object value = iVertex.field(iFieldName);
if (value != null && (value instanceof OMVRBTreeRIDSet || value instanceof OSBTreeRIDSet))
return (Set<OIdentifiable>) value;
final Set<OIdentifiable> set = createRIDSet(iVertex);
if (OMultiValue.isMultiValue(value))
// AUTOCONVERT FROM COLLECTION
set.addAll((Collection<? extends OIdentifiable>) value);
else
// AUTOCONVERT FROM SINGLE VALUE
set.add((OIdentifiable) value);
return set;
}
private Set<OIdentifiable> createRIDSet(ODocument iVertex) {
if (preferSBTreeSet)
return new OSBTreeRIDSet(iVertex);
else
return new OMVRBTreeRIDSet(iVertex);
}
/**
* Retrieves the outgoing edges of vertex iVertex having the requested properties iProperties set to the passed values
*
* @param iVertex
* Target vertex
* @param iProperties
* Map where keys are property names and values the expected values
* @return
*/
public Set<OIdentifiable> getOutEdgesHavingProperties(final OIdentifiable iVertex, final Map<String, Object> iProperties) {
if (iVertex == null)
return null;
final ODocument vertex = iVertex.getRecord();
checkVertexClass(vertex);
return filterEdgesByProperties(getEdgeSet(vertex, outV), iProperties);
}
/**
* Retrieves the outgoing edges of vertex iVertex having the requested properties iProperties
*
* @param iVertex
* Target vertex
* @param iProperties
* Map where keys are property names and values the expected values
* @return
*/
public Set<OIdentifiable> getOutEdgesHavingProperties(final OIdentifiable iVertex, Iterable<String> iProperties) {
if (iVertex == null)
return null;
final ODocument vertex = iVertex.getRecord();
checkVertexClass(vertex);
return filterEdgesByProperties(getEdgeSet(vertex, outV), iProperties);
}
public Set<OIdentifiable> getInEdges(final OIdentifiable iVertex) {
return getInEdges(iVertex, null);
}
public Set<OIdentifiable> getInEdges(final OIdentifiable iVertex, final String iLabel) {
if (iVertex == null)
return null;
final ODocument vertex = iVertex.getRecord();
checkVertexClass(vertex);
Set<OIdentifiable> result = null;
acquireReadLock(iVertex);
try {
final Set<OIdentifiable> set = getEdgeSet(vertex, inV);
if (iLabel == null)
// RETURN THE ENTIRE COLLECTION
if (set != null)
return Collections.unmodifiableSet(set);
else
return Collections.emptySet();
// FILTER BY LABEL
result = new HashSet<OIdentifiable>();
if (set != null)
for (OIdentifiable item : set) {
if (iLabel == null || iLabel.equals(((ODocument) item).field(LABEL)))
result.add(item);
}
} finally {
releaseReadLock(iVertex);
}
return result;
}
/**
* Retrieves the incoming edges of vertex iVertex having the requested properties iProperties
*
* @param iVertex
* Target vertex
* @param iProperties
* Map where keys are property names and values the expected values
* @return
*/
public Set<OIdentifiable> getInEdgesHavingProperties(final OIdentifiable iVertex, Iterable<String> iProperties) {
if (iVertex == null)
return null;
final ODocument vertex = iVertex.getRecord();
checkVertexClass(vertex);
return filterEdgesByProperties(getEdgeSet(vertex, inV), iProperties);
}
/**
* Retrieves the incoming edges of vertex iVertex having the requested properties iProperties set to the passed values
*
* @param iVertex
* Target vertex
* @param iProperties
* Map where keys are property names and values the expected values
* @return
*/
public Set<OIdentifiable> getInEdgesHavingProperties(final ODocument iVertex, final Map<String, Object> iProperties) {
if (iVertex == null)
return null;
checkVertexClass(iVertex);
return filterEdgesByProperties(getEdgeSet(iVertex, inV), iProperties);
}
public ODocument getInVertex(final OIdentifiable iEdge) {
if (iEdge == null)
return null;
final ODocument e = (ODocument) iEdge.getRecord();
checkEdgeClass(e);
OIdentifiable v = e.field(EDGE_FIELD_IN);
if (v != null && v instanceof ORID) {
// REPLACE WITH THE DOCUMENT
v = v.getRecord();
final boolean wasDirty = e.isDirty();
e.field(EDGE_FIELD_IN, v);
if (!wasDirty)
e.unsetDirty();
}
return (ODocument) v;
}
public ODocument getOutVertex(final OIdentifiable iEdge) {
if (iEdge == null)
return null;
final ODocument e = (ODocument) iEdge.getRecord();
checkEdgeClass(e);
OIdentifiable v = e.field(EDGE_FIELD_OUT);
if (v != null && v instanceof ORID) {
// REPLACE WITH THE DOCUMENT
v = v.getRecord();
final boolean wasDirty = e.isDirty();
e.field(EDGE_FIELD_OUT, v);
if (!wasDirty)
e.unsetDirty();
}
return (ODocument) v;
}
public Set<OIdentifiable> filterEdgesByProperties(final Set<OIdentifiable> iEdges, final Iterable<String> iPropertyNames) {
acquireReadLock(null);
try {
if (iPropertyNames == null)
// RETURN THE ENTIRE COLLECTION
if (iEdges != null)
return Collections.unmodifiableSet(iEdges);
else
return Collections.emptySet();
// FILTER BY PROPERTY VALUES
final Set<OIdentifiable> result = new HashSet<OIdentifiable>();
if (iEdges != null)
for (OIdentifiable item : iEdges) {
final ODocument doc = (ODocument) item;
for (String propName : iPropertyNames) {
if (doc.containsField(propName))
// FOUND: ADD IT
result.add(item);
}
}
return result;
} finally {
releaseReadLock(null);
}
}
public Set<OIdentifiable> filterEdgesByProperties(final Set<OIdentifiable> iEdges, final Map<String, Object> iProperties) {
acquireReadLock(null);
try {
if (iProperties == null)
// RETURN THE ENTIRE COLLECTION
if (iEdges != null)
return Collections.unmodifiableSet(iEdges);
else
return Collections.emptySet();
// FILTER BY PROPERTY VALUES
final OMVRBTreeRIDSet result;
result = new OMVRBTreeRIDSet();
if (iEdges != null)
for (OIdentifiable item : iEdges) {
final ODocument doc = (ODocument) item;
for (Entry<String, Object> prop : iProperties.entrySet()) {
if (prop.getKey() != null && doc.containsField(prop.getKey())) {
if (prop.getValue() == null) {
if (doc.field(prop.getKey()) == null)
// BOTH NULL: ADD IT
result.add(item);
} else if (prop.getValue().equals(doc.field(prop.getKey())))
// SAME VALUE: ADD IT
result.add(item);
}
}
}
return result;
} finally {
releaseReadLock(null);
}
}
public ODocument getRoot(final String iName) {
return getDictionary().get(iName);
}
public ODocument getRoot(final String iName, final String iFetchPlan) {
return getDictionary().get(iName, iFetchPlan);
}
public OGraphDatabase setRoot(final String iName, final ODocument iNode) {
if (iNode == null)
getDictionary().remove(iName);
else
getDictionary().put(iName, iNode);
return this;
}
public OClass createVertexType(final String iClassName) {
return getMetadata().getSchema().createClass(iClassName, vertexBaseClass);
}
public OClass createVertexType(final String iClassName, final String iSuperClassName) {
return getMetadata().getSchema().createClass(iClassName, checkVertexClass(iSuperClassName));
}
public OClass createVertexType(final String iClassName, final OClass iSuperClass) {
checkVertexClass(iSuperClass);
return getMetadata().getSchema().createClass(iClassName, iSuperClass);
}
public OClass getVertexType(final String iClassName) {
return getMetadata().getSchema().getClass(iClassName);
}
public OClass createEdgeType(final String iClassName) {
return getMetadata().getSchema().createClass(iClassName, edgeBaseClass);
}
public OClass createEdgeType(final String iClassName, final String iSuperClassName) {
return getMetadata().getSchema().createClass(iClassName, checkEdgeClass(iSuperClassName));
}
public OClass createEdgeType(final String iClassName, final OClass iSuperClass) {
checkEdgeClass(iSuperClass);
return getMetadata().getSchema().createClass(iClassName, iSuperClass);
}
public OClass getEdgeType(final String iClassName) {
return getMetadata().getSchema().getClass(iClassName);
}
public boolean isSafeMode() {
return safeMode;
}
public void setSafeMode(boolean safeMode) {
this.safeMode = safeMode;
}
public OClass getVertexBaseClass() {
return vertexBaseClass;
}
public OClass getEdgeBaseClass() {
return edgeBaseClass;
}
public void checkVertexClass(final ODocument iVertex) {
// FORCE EARLY UNMARSHALLING
iVertex.deserializeFields();
if (useCustomTypes && !iVertex.getSchemaClass().isSubClassOf(vertexBaseClass))
throw new IllegalArgumentException("The document received is not a vertex. Found class '" + iVertex.getSchemaClass() + "'");
}
public OClass checkVertexClass(final String iVertexTypeName) {
if (iVertexTypeName == null || !useCustomTypes)
return getVertexBaseClass();
final OClass cls = getMetadata().getSchema().getClass(iVertexTypeName);
if (cls == null)
throw new IllegalArgumentException("The class '" + iVertexTypeName + "' was not found");
if (!cls.isSubClassOf(vertexBaseClass))
throw new IllegalArgumentException("The class '" + iVertexTypeName + "' does not extend the vertex type");
return cls;
}
public void checkVertexClass(final OClass iVertexType) {
if (useCustomTypes && iVertexType != null) {
if (!iVertexType.isSubClassOf(vertexBaseClass))
throw new IllegalArgumentException("The class '" + iVertexType + "' does not extend the vertex type");
}
}
public void checkEdgeClass(final ODocument iEdge) {
// FORCE EARLY UNMARSHALLING
iEdge.deserializeFields();
if (useCustomTypes && !iEdge.getSchemaClass().isSubClassOf(edgeBaseClass))
throw new IllegalArgumentException("The document received is not an edge. Found class '" + iEdge.getSchemaClass() + "'");
}
public OClass checkEdgeClass(final String iEdgeTypeName) {
if (iEdgeTypeName == null || !useCustomTypes)
return getEdgeBaseClass();
final OClass cls = getMetadata().getSchema().getClass(iEdgeTypeName);
if (cls == null)
throw new IllegalArgumentException("The class '" + iEdgeTypeName + "' was not found");
if (!cls.isSubClassOf(edgeBaseClass))
throw new IllegalArgumentException("The class '" + iEdgeTypeName + "' does not extend the edge type");
return cls;
}
public void checkEdgeClass(final OClass iEdgeType) {
if (useCustomTypes && iEdgeType != null) {
if (!iEdgeType.isSubClassOf(edgeBaseClass))
throw new IllegalArgumentException("The class '" + iEdgeType + "' does not extend the edge type");
}
}
public boolean isUseCustomTypes() {
return useCustomTypes;
}
public void setUseCustomTypes(boolean useCustomTypes) {
this.useCustomTypes = useCustomTypes;
}
/**
* Returns true if the document is a vertex (its class is OGraphVertex or any subclasses)
*
* @param iRecord
* Document to analyze.
* @return true if the document is a vertex (its class is OGraphVertex or any subclasses)
*/
public boolean isVertex(final ODocument iRecord) {
return iRecord != null ? iRecord.getSchemaClass().isSubClassOf(vertexBaseClass) : false;
}
/**
* Returns true if the document is an edge (its class is OGraphEdge or any subclasses)
*
* @param iRecord
* Document to analyze.
* @return true if the document is a edge (its class is OGraphEdge or any subclasses)
*/
public boolean isEdge(final ODocument iRecord) {
return iRecord != null ? iRecord.getSchemaClass().isSubClassOf(edgeBaseClass) : false;
}
/**
* Locks the record in exclusive mode to avoid concurrent access.
*
* @param iRecord
* Record to lock
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase acquireWriteLock(final OIdentifiable iRecord) {
switch (lockMode) {
case DATABASE_LEVEL_LOCKING:
((OStorage) getStorage()).getLock().acquireExclusiveLock();
break;
case RECORD_LEVEL_LOCKING:
((OStorageEmbedded) getStorage()).acquireWriteLock(iRecord.getIdentity());
break;
case NO_LOCKING:
break;
}
return this;
}
/**
* Releases the exclusive lock against a record previously acquired by current thread.
*
* @param iRecord
* Record to unlock
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase releaseWriteLock(final OIdentifiable iRecord) {
switch (lockMode) {
case DATABASE_LEVEL_LOCKING:
((OStorage) getStorage()).getLock().releaseExclusiveLock();
break;
case RECORD_LEVEL_LOCKING:
((OStorageEmbedded) getStorage()).releaseWriteLock(iRecord.getIdentity());
break;
case NO_LOCKING:
break;
}
return this;
}
/**
* Locks the record in shared mode to avoid concurrent writes.
*
* @param iRecord
* Record to lock
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase acquireReadLock(final OIdentifiable iRecord) {
switch (lockMode) {
case DATABASE_LEVEL_LOCKING:
((OStorage) getStorage()).getLock().acquireSharedLock();
break;
case RECORD_LEVEL_LOCKING:
((OStorageEmbedded) getStorage()).acquireReadLock(iRecord.getIdentity());
break;
case NO_LOCKING:
break;
}
return this;
}
/**
* Releases the shared lock against a record previously acquired by current thread.
*
* @param iRecord
* Record to unlock
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase releaseReadLock(final OIdentifiable iRecord) {
switch (lockMode) {
case DATABASE_LEVEL_LOCKING:
((OStorage) getStorage()).getLock().releaseSharedLock();
break;
case RECORD_LEVEL_LOCKING:
((OStorageEmbedded) getStorage()).releaseReadLock(iRecord.getIdentity());
break;
case NO_LOCKING:
break;
}
return this;
}
@Override
public String getType() {
return TYPE;
}
public void checkForGraphSchema() {
getMetadata().getSchema().getOrCreateClass(OMVRBTreeRIDProvider.PERSISTENT_CLASS_NAME);
vertexBaseClass = getMetadata().getSchema().getClass(VERTEX_ALIAS);
edgeBaseClass = getMetadata().getSchema().getClass(EDGE_ALIAS);
if (vertexBaseClass == null) {
// CREATE THE META MODEL USING THE ORIENT SCHEMA
vertexBaseClass = getMetadata().getSchema().createClass(VERTEX_ALIAS);
vertexBaseClass.setOverSize(2);
}
if (edgeBaseClass == null) {
edgeBaseClass = getMetadata().getSchema().createClass(EDGE_ALIAS);
edgeBaseClass.setShortName(EDGE_ALIAS);
}
}
protected boolean beginBlock() {
if (safeMode && !(getTransaction() instanceof OTransactionNoTx)) {
begin();
return true;
}
return false;
}
protected void commitBlock(final boolean iOpenTxInSafeMode) {
if (iOpenTxInSafeMode)
commit();
}
protected void rollbackBlock(final boolean iOpenTxInSafeMode) {
if (iOpenTxInSafeMode)
rollback();
}
protected boolean checkEdge(final ODocument iEdge, final String[] iLabels, final String[] iClassNames) {
boolean good = true;
if (iClassNames != null) {
// CHECK AGAINST CLASS NAMES
good = false;
for (String c : iClassNames) {
if (c.equals(iEdge.getClassName())) {
good = true;
break;
}
}
}
if (good && iLabels != null) {
// CHECK AGAINST LABELS
good = false;
for (String c : iLabels) {
if (c.equals(iEdge.field(LABEL))) {
good = true;
break;
}
}
}
return good;
}
public LOCK_MODE getLockMode() {
return lockMode;
}
public void setLockMode(final LOCK_MODE lockMode) {
if (lockMode == LOCK_MODE.RECORD_LEVEL_LOCKING && !(getStorage() instanceof OStorageEmbedded))
// NOT YET SUPPORETD REMOTE LOCKING
throw new IllegalArgumentException("Record leve locking is not supported for remote connections");
this.lockMode = lockMode;
}
public boolean isRetroCompatibility() {
return retroCompatibility;
}
public void setRetroCompatibility(final boolean retroCompatibility) {
this.retroCompatibility = retroCompatibility;
if (retroCompatibility) {
inV = VERTEX_FIELD_IN_OLD;
outV = VERTEX_FIELD_OUT_OLD;
} else {
inV = VERTEX_FIELD_IN;
outV = VERTEX_FIELD_OUT;
}
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_graph_OGraphDatabase.java
|
111 |
class FilterExtendsSatisfiesVisitor extends Visitor {
boolean filter = false;
@Override
public void visit(Tree.ExtendedType that) {
super.visit(that);
if (that.getType()==node) {
filter = true;
}
}
@Override
public void visit(Tree.SatisfiedTypes that) {
super.visit(that);
for (Tree.Type t: that.getTypes()) {
if (t==node) {
filter = true;
}
}
}
@Override
public void visit(Tree.CaseTypes that) {
super.visit(that);
for (Tree.Type t: that.getTypes()) {
if (t==node) {
filter = true;
}
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CreateTypeParameterProposal.java
|
2,208 |
return new Filter() {
@Override
public DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs) {
return null;
}
};
| 0true
|
src_test_java_org_elasticsearch_common_lucene_search_XBooleanFilterLuceneTests.java
|
2,218 |
public static class CustomRandomAccessFilterStrategy extends FilteredQuery.RandomAccessFilterStrategy {
private final int threshold;
public CustomRandomAccessFilterStrategy() {
this.threshold = -1;
}
public CustomRandomAccessFilterStrategy(int threshold) {
this.threshold = threshold;
}
@Override
public Scorer filteredScorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Weight weight, DocIdSet docIdSet) throws IOException {
// CHANGE: If threshold is 0, always pass down the accept docs, don't pay the price of calling nextDoc even...
if (threshold == 0) {
final Bits filterAcceptDocs = docIdSet.bits();
if (filterAcceptDocs != null) {
return weight.scorer(context, scoreDocsInOrder, topScorer, filterAcceptDocs);
} else {
return FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY.filteredScorer(context, scoreDocsInOrder, topScorer, weight, docIdSet);
}
}
// CHANGE: handle "default" value
if (threshold == -1) {
// default value, don't iterate on only apply filter after query if its not a "fast" docIdSet
if (!DocIdSets.isFastIterator(docIdSet)) {
return FilteredQuery.QUERY_FIRST_FILTER_STRATEGY.filteredScorer(context, scoreDocsInOrder, topScorer, weight, docIdSet);
}
}
return super.filteredScorer(context, scoreDocsInOrder, topScorer, weight, docIdSet);
}
/**
* Expert: decides if a filter should be executed as "random-access" or not.
* random-access means the filter "filters" in a similar way as deleted docs are filtered
* in Lucene. This is faster when the filter accepts many documents.
* However, when the filter is very sparse, it can be faster to execute the query+filter
* as a conjunction in some cases.
* <p/>
* The default implementation returns <code>true</code> if the first document accepted by the
* filter is < threshold, if threshold is -1 (the default), then it checks for < 100.
*/
protected boolean useRandomAccess(Bits bits, int firstFilterDoc) {
// "default"
if (threshold == -1) {
return firstFilterDoc < 100;
}
//TODO once we have a cost API on filters and scorers we should rethink this heuristic
return firstFilterDoc < threshold;
}
}
| 0true
|
src_main_java_org_elasticsearch_common_lucene_search_XFilteredQuery.java
|
1,009 |
public class OStreamSerializerString implements OStreamSerializer {
public static final String NAME = "s";
public static final OStreamSerializerString INSTANCE = new OStreamSerializerString();
public String getName() {
return NAME;
}
public Object fromStream(final byte[] iStream) throws IOException {
return OBinaryProtocol.bytes2string(iStream);
}
public byte[] toStream(final Object iObject) throws IOException {
return OBinaryProtocol.string2bytes((String) iObject);
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_stream_OStreamSerializerString.java
|
2,043 |
public class ClearOperationFactory implements OperationFactory {
String name;
public ClearOperationFactory() {
}
public ClearOperationFactory(String name) {
this.name = name;
}
@Override
public Operation createOperation() {
return new ClearOperation(name);
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(name);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
name = in.readUTF();
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_map_operation_ClearOperationFactory.java
|
225 |
private static class HazelcastInstanceAwareObject implements HazelcastInstanceAware {
HazelcastInstance hazelcastInstance;
public HazelcastInstance getHazelcastInstance() {
return hazelcastInstance;
}
@Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hazelcastInstance = hazelcastInstance;
}
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_examples_ClientTestApp.java
|
72 |
public interface TitanVertexQuery<Q extends TitanVertexQuery<Q>> extends BaseVertexQuery<Q>, VertexQuery {
/* ---------------------------------------------------------------
* Query Specification (overwrite to merge BaseVertexQuery with Blueprint's VertexQuery)
* ---------------------------------------------------------------
*/
@Override
public Q adjacent(TitanVertex vertex);
@Override
public Q types(RelationType... type);
@Override
public Q labels(String... labels);
@Override
public Q keys(String... keys);
@Override
public Q direction(Direction d);
@Override
public Q has(PropertyKey key, Object value);
@Override
public Q has(EdgeLabel label, TitanVertex vertex);
@Override
public Q has(String key);
@Override
public Q hasNot(String key);
@Override
public Q has(String type, Object value);
@Override
public Q hasNot(String key, Object value);
@Override
public Q has(PropertyKey key, Predicate predicate, Object value);
@Override
public Q has(String key, Predicate predicate, Object value);
@Override
public <T extends Comparable<?>> Q interval(String key, T start, T end);
@Override
public <T extends Comparable<?>> Q interval(PropertyKey key, T start, T end);
@Override
public Q limit(int limit);
@Override
public Q orderBy(String key, Order order);
@Override
public Q orderBy(PropertyKey key, Order order);
/* ---------------------------------------------------------------
* Query execution
* ---------------------------------------------------------------
*/
/**
* Returns an iterable over all incident edges that match this query
*
* @return Iterable over all incident edges that match this query
*/
public Iterable<Edge> edges();
/**
* Returns an iterable over all incident edges that match this query. Returns edges as {@link TitanEdge}.
*
* @return Iterable over all incident edges that match this query
*/
public Iterable<TitanEdge> titanEdges();
/**
* Returns an iterable over all incident properties that match this query
*
* @return Iterable over all incident properties that match this query
*/
public Iterable<TitanProperty> properties();
/**
* Returns an iterable over all incident relations that match this query
*
* @return Iterable over all incident relations that match this query
*/
public Iterable<TitanRelation> relations();
/**
* Returns the number of edges that match this query
*
* @return Number of edges that match this query
*/
public long count();
/**
* Returns the number of properties that match this query
*
* @return Number of properties that match this query
*/
public long propertyCount();
/**
* Retrieves all vertices connected to this query's base vertex by edges
* matching the conditions defined in this query.
* <p/>
* The query engine will determine the most efficient way to retrieve the vertices that match this query.
*
* @return A list of all vertices connected to this query's base vertex by matching edges
*/
@Override
public VertexList vertexIds();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanVertexQuery.java
|
1,850 |
static class ProviderBindingImpl<T> extends BindingImpl<Provider<T>>
implements ProviderBinding<Provider<T>> {
final BindingImpl<T> providedBinding;
ProviderBindingImpl(InjectorImpl injector, Key<Provider<T>> key, Binding<T> providedBinding) {
super(injector, key, providedBinding.getSource(), createInternalFactory(providedBinding),
Scoping.UNSCOPED);
this.providedBinding = (BindingImpl<T>) providedBinding;
}
static <T> InternalFactory<Provider<T>> createInternalFactory(Binding<T> providedBinding) {
final Provider<T> provider = providedBinding.getProvider();
return new InternalFactory<Provider<T>>() {
public Provider<T> get(Errors errors, InternalContext context, Dependency dependency) {
return provider;
}
};
}
public Key<? extends T> getProvidedKey() {
return providedBinding.getKey();
}
public <V> V acceptTargetVisitor(BindingTargetVisitor<? super Provider<T>, V> visitor) {
return visitor.visit(this);
}
public void applyTo(Binder binder) {
throw new UnsupportedOperationException("This element represents a synthetic binding.");
}
@Override
public String toString() {
return new ToStringBuilder(ProviderKeyBinding.class)
.add("key", getKey())
.add("providedKey", getProvidedKey())
.toString();
}
}
| 0true
|
src_main_java_org_elasticsearch_common_inject_InjectorImpl.java
|
77 |
public final class ClientDataSerializerHook implements DataSerializerHook {
public static final int ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.CLIENT_DS_FACTORY, -3);
public static final int CLIENT_RESPONSE = 1;
@Override
public int getFactoryId() {
return ID;
}
@Override
public DataSerializableFactory createFactory() {
return new DataSerializableFactory() {
@Override
public IdentifiedDataSerializable create(int typeId) {
switch (typeId) {
case CLIENT_RESPONSE:
return new ClientResponse();
default:
return null;
}
}
};
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_ClientDataSerializerHook.java
|
457 |
public class GeneratedResource extends AbstractResource implements Serializable {
private static final long serialVersionUID = 7044543270746433688L;
protected long timeGenerated;
protected String hashRepresentation;
protected final byte[] source;
protected final String description;
/**
* <b>Note: This constructor should not be explicitly used</b>
*
* To properly allow for serialization, we must provide this no-arg constructor that will
* create a "dummy" GeneratedResource. The appropriate fields will be set during deserialization.
*/
public GeneratedResource() {
this(new byte[]{}, null);
}
public GeneratedResource(byte[] source, String description) {
Assert.notNull(source);
this.source = source;
this.description = description;
timeGenerated = System.currentTimeMillis();
}
@Override
public String getFilename() {
return getDescription();
}
@Override
public long lastModified() throws IOException {
return timeGenerated;
}
public String getHashRepresentation() {
return StringUtils.isBlank(hashRepresentation) ? String.valueOf(timeGenerated) : hashRepresentation;
}
public void setHashRepresentation(String hashRepresentation) {
this.hashRepresentation = hashRepresentation;
}
@Override
public String getDescription() {
return description;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(source);
}
@Override
public int hashCode() {
return 1;
}
@Override
public boolean equals(Object res) {
if (!(res instanceof InMemoryResource)) {
return false;
}
return Arrays.equals(source, ((GeneratedResource)res).source);
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_resource_GeneratedResource.java
|
293 |
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientLockTest {
static final String name = "test";
static HazelcastInstance hz;
static ILock l;
@BeforeClass
public static void init() {
Hazelcast.newHazelcastInstance();
hz = HazelcastClient.newHazelcastClient();
l = hz.getLock(name);
}
@AfterClass
public static void destroy() {
hz.shutdown();
Hazelcast.shutdownAll();
}
@Before
@After
public void clear() throws IOException {
l.forceUnlock();
}
@Test
public void testLock() throws Exception {
l.lock();
final CountDownLatch latch = new CountDownLatch(1);
new Thread() {
public void run() {
if (!l.tryLock()) {
latch.countDown();
}
}
}.start();
assertTrue(latch.await(5, TimeUnit.SECONDS));
l.forceUnlock();
}
@Test
public void testLockTtl() throws Exception {
l.lock(3, TimeUnit.SECONDS);
final CountDownLatch latch = new CountDownLatch(2);
new Thread() {
public void run() {
if (!l.tryLock()) {
latch.countDown();
}
try {
if (l.tryLock(5, TimeUnit.SECONDS)) {
latch.countDown();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
assertTrue(latch.await(10, TimeUnit.SECONDS));
l.forceUnlock();
}
@Test
public void testTryLock() throws Exception {
assertTrue(l.tryLock(2, TimeUnit.SECONDS));
final CountDownLatch latch = new CountDownLatch(1);
new Thread() {
public void run() {
try {
if (!l.tryLock(2, TimeUnit.SECONDS)) {
latch.countDown();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
assertTrue(latch.await(100, TimeUnit.SECONDS));
assertTrue(l.isLocked());
final CountDownLatch latch2 = new CountDownLatch(1);
new Thread() {
public void run() {
try {
if (l.tryLock(20, TimeUnit.SECONDS)) {
latch2.countDown();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
Thread.sleep(1000);
l.unlock();
assertTrue(latch2.await(100, TimeUnit.SECONDS));
assertTrue(l.isLocked());
l.forceUnlock();
}
@Test
public void testForceUnlock() throws Exception {
l.lock();
final CountDownLatch latch = new CountDownLatch(1);
new Thread() {
public void run() {
l.forceUnlock();
latch.countDown();
}
}.start();
assertTrue(latch.await(100, TimeUnit.SECONDS));
assertFalse(l.isLocked());
}
@Test
public void testStats() throws InterruptedException {
l.lock();
assertTrue(l.isLocked());
assertTrue(l.isLockedByCurrentThread());
assertEquals(1, l.getLockCount());
l.unlock();
assertFalse(l.isLocked());
assertEquals(0, l.getLockCount());
assertEquals(-1L, l.getRemainingLeaseTime());
l.lock(1, TimeUnit.MINUTES);
assertTrue(l.isLocked());
assertTrue(l.isLockedByCurrentThread());
assertEquals(1, l.getLockCount());
assertTrue(l.getRemainingLeaseTime() > 1000 * 30);
final CountDownLatch latch = new CountDownLatch(1);
new Thread() {
public void run() {
assertTrue(l.isLocked());
assertFalse(l.isLockedByCurrentThread());
assertEquals(1, l.getLockCount());
assertTrue(l.getRemainingLeaseTime() > 1000 * 30);
latch.countDown();
}
}.start();
assertTrue(latch.await(1, TimeUnit.MINUTES));
}
@Test
public void testObtainLock_FromDiffClients() throws InterruptedException {
HazelcastInstance clientA = HazelcastClient.newHazelcastClient();
ILock lockA = clientA.getLock(name);
lockA.lock();
HazelcastInstance clientB = HazelcastClient.newHazelcastClient();
ILock lockB = clientB.getLock(name);
boolean lockObtained = lockB.tryLock();
assertFalse("Lock obtained by 2 client ", lockObtained);
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_lock_ClientLockTest.java
|
2,056 |
public abstract class KeyBasedMapOperation extends Operation implements PartitionAwareOperation {
protected String name;
protected Data dataKey;
protected long threadId;
protected Data dataValue = null;
protected long ttl = -1;
protected transient MapService mapService;
protected transient MapContainer mapContainer;
protected transient PartitionContainer partitionContainer;
protected transient RecordStore recordStore;
public KeyBasedMapOperation() {
}
public KeyBasedMapOperation(String name, Data dataKey) {
super();
this.dataKey = dataKey;
this.name = name;
}
protected KeyBasedMapOperation(String name, Data dataKey, Data dataValue) {
this.name = name;
this.dataKey = dataKey;
this.dataValue = dataValue;
}
protected KeyBasedMapOperation(String name, Data dataKey, long ttl) {
this.name = name;
this.dataKey = dataKey;
this.ttl = ttl;
}
protected KeyBasedMapOperation(String name, Data dataKey, Data dataValue, long ttl) {
this.name = name;
this.dataKey = dataKey;
this.dataValue = dataValue;
this.ttl = ttl;
}
public final String getName() {
return name;
}
public final Data getKey() {
return dataKey;
}
public final long getThreadId() {
return threadId;
}
public final void setThreadId(long threadId) {
this.threadId = threadId;
}
public final Data getValue() {
return dataValue;
}
public final long getTtl() {
return ttl;
}
@Override
public final void beforeRun() throws Exception {
mapService = getService();
mapContainer = mapService.getMapContainer(name);
partitionContainer = mapService.getPartitionContainer(getPartitionId());
recordStore = partitionContainer.getRecordStore(name);
innerBeforeRun();
}
public void innerBeforeRun() {
}
@Override
public void afterRun() throws Exception {
}
@Override
public boolean returnsResponse() {
return true;
}
protected final void invalidateNearCaches() {
if (mapContainer.isNearCacheEnabled()
&& mapContainer.getMapConfig().getNearCacheConfig().isInvalidateOnChange()) {
mapService.invalidateAllNearCaches(name, dataKey);
}
}
protected void writeInternal(ObjectDataOutput out) throws IOException {
out.writeUTF(name);
dataKey.writeData(out);
out.writeLong(threadId);
IOUtil.writeNullableData(out, dataValue);
out.writeLong(ttl);
}
protected void readInternal(ObjectDataInput in) throws IOException {
name = in.readUTF();
dataKey = new Data();
dataKey.readData(in);
threadId = in.readLong();
dataValue = IOUtil.readNullableData(in);
ttl = in.readLong();
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_map_operation_KeyBasedMapOperation.java
|
1,309 |
public interface SearchFacet {
/**
* Returns the internal id
*
* @return the internal id
*/
public Long getId();
/**
* Sets the internal id
*
* @param id
*/
public void setId(Long id);
/**
* Returns the field associated with this facet.
*
* @return the fieldName
*/
public Field getField();
/**
* Sets the field associated with this facet.
*
* @see #getFieldName()
* @param fieldName
*/
public void setField(Field field);
/**
* Gets the label of this SearchFacet. This is the label that will be used for the user-friendly
* display name of this facet
*
* @return the label
*/
public String getLabel();
/**
* Sets the label
*
* @see #getLabel()
* @param label
*/
public void setLabel(String label);
/**
* Gets a boolean that specifies whether or not this SearchFacet should be displayed on search
* result pages in addition to category pages
*
* @return whether or not to display on search result pages
*/
public Boolean getShowOnSearch();
/**
* Sets showOnSearch
*
* @see #getShowOnSearch()
* @param showOnSearch
*/
public void setShowOnSearch(Boolean showOnSearch);
/**
* Gets the display priority of this SearchFacet on search result pages
*
* @return the priority
*/
public Integer getSearchDisplayPriority();
/**
* Sets the display priority on search result pages
*
* @param searchDisplayPriority
*/
public void setSearchDisplayPriority(Integer searchDisplayPriority);
/**
* Sets whether or not you can multiselect values for this Facet.
*
* @param canMultiselect
*/
public void setCanMultiselect(Boolean canMultiselect);
/**
* Gets whether or not you can multiselect values for this Facet
*
* @return the multiselect flag
*/
public Boolean getCanMultiselect();
/**
* Gets the applicable ranges for this search facet, if any are specified. For example, the
* SearchFacet that interacts with "Manufacturers" might not have any ranges defined (as it
* would depend on the manufacturers that are in the result list), but a facet on "Price"
* might have predefined ranges (such as 0-5, 5-10, 10-20).
*
* @return the associated search facet ranges, if any
*/
public List<SearchFacetRange> getSearchFacetRanges();
/**
* Sets the SearchFacetRanges
*
* <b>Note: This method will set ALL search facet ranges</b>
*
* @see #getSearchFacetRanges()
* @param searchFacetRanges
*/
public void setSearchFacetRanges(List<SearchFacetRange> searchFacetRanges);
/**
* @see #getRequiresAllDependentFacets()
*
* @return a list of SearchFacets that must have an active value set for this SearchFacet to be applicable.
*/
public List<RequiredFacet> getRequiredFacets();
/**
* Sets the list of facets which this facet depends on.
*
* @param dependentFacets
*/
public void setRequiredFacets(List<RequiredFacet> requiredFacets);
/**
* This boolean controls whether or not this particular facet requires one of the dependent facets to be active, or if
* it requires all of the dependent facets to be active.
*
* @see #getRequiredFacets()
*
* @return whether the dependent facet list should be AND'ed together
*/
public Boolean getRequiresAllDependentFacets();
/**
* Sets whether or not all dependent facets must be active, or if only one is necessary
*
* @param requiresAllDependentFacets
*/
public void setRequiresAllDependentFacets(Boolean requiresAllDependentFacets);
}
| 0true
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_domain_SearchFacet.java
|
350 |
public enum ElasticSearchSetup {
/**
* Start an ES TransportClient connected to
* {@link com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration#INDEX_HOSTS}.
*/
TRANSPORT_CLIENT {
@Override
public Connection connect(Configuration config) throws IOException {
log.debug("Configuring TransportClient");
ImmutableSettings.Builder settingsBuilder = settingsBuilder(config);
if (config.has(ElasticSearchIndex.CLIENT_SNIFF)) {
String k = "client.transport.sniff";
settingsBuilder.put(k, config.get(ElasticSearchIndex.CLIENT_SNIFF));
log.debug("Set {}: {}", k, config.get(ElasticSearchIndex.CLIENT_SNIFF));
}
TransportClient tc = new TransportClient(settingsBuilder.build());
int defaultPort = config.has(INDEX_PORT) ? config.get(INDEX_PORT) : ElasticSearchIndex.HOST_PORT_DEFAULT;
for (String host : config.get(INDEX_HOSTS)) {
String[] hostparts = host.split(":");
String hostname = hostparts[0];
int hostport = defaultPort;
if (hostparts.length == 2) hostport = Integer.parseInt(hostparts[1]);
log.info("Configured remote host: {} : {}", hostname, hostport);
tc.addTransportAddress(new InetSocketTransportAddress(hostname, hostport));
}
return new Connection(null, tc);
}
},
/**
* Start an ES {@code Node} and use its attached {@code Client}.
*/
NODE {
@Override
public Connection connect(Configuration config) throws IOException {
log.debug("Configuring Node Client");
ImmutableSettings.Builder settingsBuilder = settingsBuilder(config);
if (config.has(ElasticSearchIndex.TTL_INTERVAL)) {
String k = "indices.ttl.interval";
settingsBuilder.put(k, config.get(ElasticSearchIndex.TTL_INTERVAL));
log.debug("Set {}: {}", k, config.get(ElasticSearchIndex.TTL_INTERVAL));
}
makeLocalDirsIfNecessary(settingsBuilder, config);
NodeBuilder nodeBuilder = NodeBuilder.nodeBuilder().settings(settingsBuilder.build());
// Apply explicit Titan properties file overrides (otherwise conf-file or ES defaults apply)
if (config.has(ElasticSearchIndex.CLIENT_ONLY)) {
boolean clientOnly = config.get(ElasticSearchIndex.CLIENT_ONLY);
nodeBuilder.client(clientOnly).data(!clientOnly);
}
if (config.has(ElasticSearchIndex.LOCAL_MODE))
nodeBuilder.local(config.get(ElasticSearchIndex.LOCAL_MODE));
if (config.has(ElasticSearchIndex.LOAD_DEFAULT_NODE_SETTINGS))
nodeBuilder.loadConfigSettings(config.get(ElasticSearchIndex.LOAD_DEFAULT_NODE_SETTINGS));
Node node = nodeBuilder.node();
Client client = node.client();
return new Connection(node, client);
}
};
/**
* Build and setup a new ES settings builder by consulting all Titan config options
* relevant to TransportClient or Node. Options may be specific to a single client,
* but in this case they have no effect/are ignored on the other client.
* <p>
* This method creates a new ES ImmutableSettings.Builder, then carries out the following
* operations on that settings builder in the listed order:
*
* <ol>
* <li>Enable client.transport.ignore_cluster_name in the settings builder</li>
* <li>If conf-file is set, open it using a FileInputStream and load its contents into the settings builder</li>
* <li>Apply any settings in the ext.* meta namespace</li>
* <li>If cluster-name is set, copy that value to cluster.name in the settings builder</li>
* <li>If ignore-cluster-name is set, copy that value to client.transport.ignore_cluster_name in the settings builder</li>
* <li>If client-sniff is set, copy that value to client.transport.sniff in the settings builder</li>
* <li>If ttl-interval is set, copy that volue to indices.ttl.interval in the settings builder</li>
* <li>Unconditionally set script.disable_dynamic to false (i.e. enable dynamic scripting)</li>
* </ol>
*
* This method then returns the builder.
*
* @param config a Titan configuration possibly containing Elasticsearch index settings
* @return ES settings builder configured according to the {@code config} parameter
* @throws java.io.IOException if conf-file was set but could not be read
*/
private static ImmutableSettings.Builder settingsBuilder(Configuration config) throws IOException {
ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder();
// Set Titan defaults
settings.put("client.transport.ignore_cluster_name", true);
// Apply overrides from ES conf file
if (config.has(INDEX_CONF_FILE)) {
String confFile = config.get(INDEX_CONF_FILE);
log.debug("Loading Elasticsearch TransportClient base settings as file {}", confFile);
InputStream confStream = null;
try {
confStream = new FileInputStream(confFile);
settings.loadFromStream(confFile, confStream);
} finally {
IOUtils.closeQuietly(confStream);
}
}
// Apply ext.* overrides from Titan conf file
int keysLoaded = 0;
Map<String,Object> configSub = config.getSubset(ElasticSearchIndex.ES_EXTRAS_NS);
for (Map.Entry<String,Object> entry : configSub.entrySet()) {
String key = entry.getKey();
Object val = entry.getValue();
if (null == val) continue;
if (List.class.isAssignableFrom(val.getClass())) {
// Pretty print lists using comma-separated values and no surrounding square braces for ES
List l = (List) val;
settings.put(key, Joiner.on(",").join(l));
} else if (val.getClass().isArray()) {
// As with Lists, but now for arrays
// The Object copy[] business lets us avoid repetitive primitive array type checking and casting
Object copy[] = new Object[Array.getLength(val)];
for (int i= 0; i < copy.length; i++) {
copy[i] = Array.get(val, i);
}
settings.put(key, Joiner.on(",").join(copy));
} else {
// Copy anything else unmodified
settings.put(key, val.toString());
}
log.debug("[ES ext.* cfg] Set {}: {}", key, val);
keysLoaded++;
}
log.debug("Loaded {} settings from the {} Titan config namespace",
keysLoaded, ElasticSearchIndex.ES_EXTRAS_NS);
// Apply individual Titan ConfigOptions that map to ES settings
if (config.has(ElasticSearchIndex.CLUSTER_NAME)) {
String clustername = config.get(ElasticSearchIndex.CLUSTER_NAME);
Preconditions.checkArgument(StringUtils.isNotBlank(clustername), "Invalid cluster name: %s", clustername);
String k = "cluster.name";
settings.put(k, clustername);
log.debug("Set {}: {}", k, clustername);
}
if (config.has(ElasticSearchIndex.IGNORE_CLUSTER_NAME)) {
boolean ignoreClusterName = config.get(ElasticSearchIndex.IGNORE_CLUSTER_NAME);
String k = "client.transport.ignore_cluster_name";
settings.put(k, ignoreClusterName);
log.debug("Set {}: {}", k, ignoreClusterName);
}
// Force-enable dynamic scripting. This is probably only useful in Node mode.
String disableScriptsKey = "script.disable_dynamic";
String disableScriptsVal = settings.get(disableScriptsKey);
if (null != disableScriptsVal && !"false".equals(disableScriptsVal)) {
log.warn("Titan requires Elasticsearch dynamic scripting. Setting {} to false. " +
"Dynamic scripting must be allowed in the Elasticsearch cluster configuration.",
disableScriptsKey);
}
settings.put(disableScriptsKey, false);
log.debug("Set {}: {}", disableScriptsKey, false);
return settings;
}
private static void makeLocalDirsIfNecessary(ImmutableSettings.Builder settingsBuilder, Configuration config) {
if (config.has(INDEX_DIRECTORY)) {
String dataDirectory = config.get(INDEX_DIRECTORY);
File f = new File(dataDirectory);
if (!f.exists()) {
log.info("Creating ES directory prefix: {}", f);
f.mkdirs();
}
for (String sub : ElasticSearchIndex.DATA_SUBDIRS) {
String subdir = dataDirectory + File.separator + sub;
f = new File(subdir);
if (!f.exists()) {
log.info("Creating ES {} directory: {}", sub, f);
f.mkdirs();
}
settingsBuilder.put("path." + sub, subdir);
log.debug("Set ES {} directory: {}", sub, f);
}
}
}
private static final Logger log = LoggerFactory.getLogger(ElasticSearchSetup.class);
public abstract Connection connect(Configuration config) throws IOException;
public static class Connection {
private final Node node;
private final Client client;
public Connection(Node node, Client client) {
this.node = node;
this.client = client;
Preconditions.checkNotNull(this.client, "Unable to instantiate Elasticsearch Client object");
// node may be null
}
public Node getNode() {
return node;
}
public Client getClient() {
return client;
}
}
}
| 0true
|
titan-es_src_main_java_com_thinkaurelius_titan_diskstorage_es_ElasticSearchSetup.java
|
331 |
fFrameList.addPropertyChangeListener(new IPropertyChangeListener() { // connect after the actions (order of property listener)
public void propertyChange(PropertyChangeEvent event) {
fPart.updateTitle();
fPart.updateToolbar();
}
});
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_PackageExplorerActionGroup.java
|
2,802 |
public static class AnalyzersBindings {
private final Map<String, Class<? extends AnalyzerProvider>> analyzers = Maps.newHashMap();
public AnalyzersBindings() {
}
public void processAnalyzer(String name, Class<? extends AnalyzerProvider> analyzerProvider) {
analyzers.put(name, analyzerProvider);
}
}
| 0true
|
src_main_java_org_elasticsearch_index_analysis_AnalysisModule.java
|
1,288 |
@ClusterScope(scope = Scope.TEST, numNodes = 0)
public class ClusterServiceTests extends ElasticsearchIntegrationTest {
@Test
public void testTimeoutUpdateTask() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "local")
.build();
cluster().startNode(settings);
ClusterService clusterService1 = cluster().getInstance(ClusterService.class);
final CountDownLatch block = new CountDownLatch(1);
clusterService1.submitStateUpdateTask("test1", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
try {
block.await();
} catch (InterruptedException e) {
fail();
}
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
fail();
}
});
final CountDownLatch timedOut = new CountDownLatch(1);
final AtomicBoolean executeCalled = new AtomicBoolean();
clusterService1.submitStateUpdateTask("test2", new TimeoutClusterStateUpdateTask() {
@Override
public TimeValue timeout() {
return TimeValue.timeValueMillis(2);
}
@Override
public void onFailure(String source, Throwable t) {
timedOut.countDown();
}
@Override
public ClusterState execute(ClusterState currentState) {
executeCalled.set(true);
return currentState;
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
});
assertThat(timedOut.await(500, TimeUnit.MILLISECONDS), equalTo(true));
block.countDown();
Thread.sleep(100); // sleep a bit to double check that execute on the timed out update task is not called...
assertThat(executeCalled.get(), equalTo(false));
}
@Test
public void testAckedUpdateTask() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "local")
.build();
cluster().startNode(settings);
ClusterService clusterService = cluster().getInstance(ClusterService.class);
final AtomicBoolean allNodesAcked = new AtomicBoolean(false);
final AtomicBoolean ackTimeout = new AtomicBoolean(false);
final AtomicBoolean onFailure = new AtomicBoolean(false);
final AtomicBoolean executed = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch processedLatch = new CountDownLatch(1);
clusterService.submitStateUpdateTask("test", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return true;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
allNodesAcked.set(true);
latch.countDown();
}
@Override
public void onAckTimeout() {
ackTimeout.set(true);
latch.countDown();
}
@Override
public TimeValue ackTimeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public TimeValue timeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
processedLatch.countDown();
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
executed.set(true);
return ClusterState.builder(currentState).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("failed to execute callback in test {}", t, source);
onFailure.set(true);
latch.countDown();
}
});
assertThat(latch.await(1, TimeUnit.SECONDS), equalTo(true));
assertThat(allNodesAcked.get(), equalTo(true));
assertThat(ackTimeout.get(), equalTo(false));
assertThat(executed.get(), equalTo(true));
assertThat(onFailure.get(), equalTo(false));
assertThat(processedLatch.await(1, TimeUnit.SECONDS), equalTo(true));
}
@Test
public void testAckedUpdateTaskSameClusterState() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "local")
.build();
cluster().startNode(settings);
ClusterService clusterService = cluster().getInstance(ClusterService.class);
final AtomicBoolean allNodesAcked = new AtomicBoolean(false);
final AtomicBoolean ackTimeout = new AtomicBoolean(false);
final AtomicBoolean onFailure = new AtomicBoolean(false);
final AtomicBoolean executed = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch processedLatch = new CountDownLatch(1);
clusterService.submitStateUpdateTask("test", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return true;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
allNodesAcked.set(true);
latch.countDown();
}
@Override
public void onAckTimeout() {
ackTimeout.set(true);
latch.countDown();
}
@Override
public TimeValue ackTimeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public TimeValue timeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
processedLatch.countDown();
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
executed.set(true);
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("failed to execute callback in test {}", t, source);
onFailure.set(true);
latch.countDown();
}
});
assertThat(latch.await(1, TimeUnit.SECONDS), equalTo(true));
assertThat(allNodesAcked.get(), equalTo(true));
assertThat(ackTimeout.get(), equalTo(false));
assertThat(executed.get(), equalTo(true));
assertThat(onFailure.get(), equalTo(false));
assertThat(processedLatch.await(1, TimeUnit.SECONDS), equalTo(true));
}
@Test
public void testAckedUpdateTaskNoAckExpected() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "local")
.build();
cluster().startNode(settings);
ClusterService clusterService = cluster().getInstance(ClusterService.class);
final AtomicBoolean allNodesAcked = new AtomicBoolean(false);
final AtomicBoolean ackTimeout = new AtomicBoolean(false);
final AtomicBoolean onFailure = new AtomicBoolean(false);
final AtomicBoolean executed = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
clusterService.submitStateUpdateTask("test", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return false;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
allNodesAcked.set(true);
latch.countDown();
}
@Override
public void onAckTimeout() {
ackTimeout.set(true);
latch.countDown();
}
@Override
public TimeValue ackTimeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public TimeValue timeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
executed.set(true);
return ClusterState.builder(currentState).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("failed to execute callback in test {}", t, source);
onFailure.set(true);
latch.countDown();
}
});
assertThat(latch.await(1, TimeUnit.SECONDS), equalTo(true));
assertThat(allNodesAcked.get(), equalTo(true));
assertThat(ackTimeout.get(), equalTo(false));
assertThat(executed.get(), equalTo(true));
assertThat(onFailure.get(), equalTo(false));
}
@Test
public void testAckedUpdateTaskTimeoutZero() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "local")
.build();
cluster().startNode(settings);
ClusterService clusterService = cluster().getInstance(ClusterService.class);
final AtomicBoolean allNodesAcked = new AtomicBoolean(false);
final AtomicBoolean ackTimeout = new AtomicBoolean(false);
final AtomicBoolean onFailure = new AtomicBoolean(false);
final AtomicBoolean executed = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch processedLatch = new CountDownLatch(1);
clusterService.submitStateUpdateTask("test", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return false;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
allNodesAcked.set(true);
latch.countDown();
}
@Override
public void onAckTimeout() {
ackTimeout.set(true);
latch.countDown();
}
@Override
public TimeValue ackTimeout() {
return TimeValue.timeValueSeconds(0);
}
@Override
public TimeValue timeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
processedLatch.countDown();
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
executed.set(true);
return ClusterState.builder(currentState).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("failed to execute callback in test {}", t, source);
onFailure.set(true);
latch.countDown();
}
});
assertThat(latch.await(1, TimeUnit.SECONDS), equalTo(true));
assertThat(allNodesAcked.get(), equalTo(false));
assertThat(ackTimeout.get(), equalTo(true));
assertThat(executed.get(), equalTo(true));
assertThat(onFailure.get(), equalTo(false));
assertThat(processedLatch.await(1, TimeUnit.SECONDS), equalTo(true));
}
@Test
public void testPendingUpdateTask() throws Exception {
Settings zenSettings = settingsBuilder()
.put("discovery.type", "zen").build();
String node_0 = cluster().startNode(zenSettings);
cluster().startNodeClient(zenSettings);
ClusterService clusterService = cluster().getInstance(ClusterService.class, node_0);
final CountDownLatch block1 = new CountDownLatch(1);
final CountDownLatch invoked1 = new CountDownLatch(1);
clusterService.submitStateUpdateTask("1", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
invoked1.countDown();
try {
block1.await();
} catch (InterruptedException e) {
fail();
}
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
invoked1.countDown();
fail();
}
});
invoked1.await();
final CountDownLatch invoked2 = new CountDownLatch(9);
for (int i = 2; i <= 10; i++) {
clusterService.submitStateUpdateTask(Integer.toString(i), new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
invoked2.countDown();
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
fail();
}
});
}
// The tasks can be re-ordered, so we need to check out-of-order
Set<String> controlSources = new HashSet<String>(Arrays.asList("2", "3", "4", "5", "6", "7", "8", "9", "10"));
List<PendingClusterTask> pendingClusterTasks = clusterService.pendingTasks();
assertThat(pendingClusterTasks.size(), equalTo(9));
for (PendingClusterTask task : pendingClusterTasks) {
assertTrue(controlSources.remove(task.source().string()));
}
assertTrue(controlSources.isEmpty());
controlSources = new HashSet<String>(Arrays.asList("2", "3", "4", "5", "6", "7", "8", "9", "10"));
PendingClusterTasksResponse response = cluster().clientNodeClient().admin().cluster().preparePendingClusterTasks().execute().actionGet();
assertThat(response.pendingTasks().size(), equalTo(9));
for (PendingClusterTask task : response) {
assertTrue(controlSources.remove(task.source().string()));
}
assertTrue(controlSources.isEmpty());
block1.countDown();
invoked2.await();
pendingClusterTasks = clusterService.pendingTasks();
assertThat(pendingClusterTasks, empty());
response = cluster().clientNodeClient().admin().cluster().preparePendingClusterTasks().execute().actionGet();
assertThat(response.pendingTasks(), empty());
final CountDownLatch block2 = new CountDownLatch(1);
final CountDownLatch invoked3 = new CountDownLatch(1);
clusterService.submitStateUpdateTask("1", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
invoked3.countDown();
try {
block2.await();
} catch (InterruptedException e) {
fail();
}
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
invoked3.countDown();
fail();
}
});
invoked3.await();
for (int i = 2; i <= 5; i++) {
clusterService.submitStateUpdateTask(Integer.toString(i), new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
fail();
}
});
}
Thread.sleep(100);
pendingClusterTasks = clusterService.pendingTasks();
assertThat(pendingClusterTasks.size(), equalTo(4));
controlSources = new HashSet<String>(Arrays.asList("2", "3", "4", "5"));
for (PendingClusterTask task : pendingClusterTasks) {
assertTrue(controlSources.remove(task.source().string()));
}
assertTrue(controlSources.isEmpty());
response = cluster().clientNodeClient().admin().cluster().preparePendingClusterTasks().execute().actionGet();
assertThat(response.pendingTasks().size(), equalTo(4));
controlSources = new HashSet<String>(Arrays.asList("2", "3", "4", "5"));
for (PendingClusterTask task : response) {
assertTrue(controlSources.remove(task.source().string()));
assertThat(task.getTimeInQueueInMillis(), greaterThan(0l));
}
assertTrue(controlSources.isEmpty());
block2.countDown();
}
@Test
public void testListenerCallbacks() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "zen")
.put("discovery.zen.minimum_master_nodes", 1)
.put("discovery.zen.ping_timeout", "200ms")
.put("discovery.initial_state_timeout", "500ms")
.put("plugin.types", TestPlugin.class.getName())
.build();
cluster().startNode(settings);
ClusterService clusterService1 = cluster().getInstance(ClusterService.class);
MasterAwareService testService1 = cluster().getInstance(MasterAwareService.class);
// the first node should be a master as the minimum required is 1
assertThat(clusterService1.state().nodes().masterNode(), notNullValue());
assertThat(clusterService1.state().nodes().localNodeMaster(), is(true));
assertThat(testService1.master(), is(true));
String node_1 = cluster().startNode(settings);
ClusterService clusterService2 = cluster().getInstance(ClusterService.class, node_1);
MasterAwareService testService2 = cluster().getInstance(MasterAwareService.class, node_1);
ClusterHealthResponse clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForNodes("2").execute().actionGet();
assertThat(clusterHealth.isTimedOut(), equalTo(false));
// the second node should not be the master as node1 is already the master.
assertThat(clusterService2.state().nodes().localNodeMaster(), is(false));
assertThat(testService2.master(), is(false));
cluster().stopCurrentMasterNode();
clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForNodes("1").execute().actionGet();
assertThat(clusterHealth.isTimedOut(), equalTo(false));
// now that node1 is closed, node2 should be elected as master
assertThat(clusterService2.state().nodes().localNodeMaster(), is(true));
assertThat(testService2.master(), is(true));
Settings newSettings = settingsBuilder()
.put("discovery.zen.minimum_master_nodes", 2)
.put("discovery.type", "zen")
.build();
client().admin().cluster().prepareUpdateSettings().setTransientSettings(newSettings).execute().actionGet();
Thread.sleep(200);
// there should not be any master as the minimum number of required eligible masters is not met
assertThat(clusterService2.state().nodes().masterNode(), is(nullValue()));
assertThat(testService2.master(), is(false));
String node_2 = cluster().startNode(settings);
clusterService1 = cluster().getInstance(ClusterService.class, node_2);
testService1 = cluster().getInstance(MasterAwareService.class, node_2);
// make sure both nodes see each other otherwise the masternode below could be null if node 2 is master and node 1 did'r receive the updated cluster state...
assertThat(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setLocal(true).setWaitForNodes("2").execute().actionGet().isTimedOut(), is(false));
assertThat(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setLocal(true).setWaitForNodes("2").execute().actionGet().isTimedOut(), is(false));
// now that we started node1 again, a new master should be elected
assertThat(clusterService1.state().nodes().masterNode(), is(notNullValue()));
if (node_2.equals(clusterService1.state().nodes().masterNode().name())) {
assertThat(testService1.master(), is(true));
assertThat(testService2.master(), is(false));
} else {
assertThat(testService1.master(), is(false));
assertThat(testService2.master(), is(true));
}
}
public static class TestPlugin extends AbstractPlugin {
@Override
public String name() {
return "test plugin";
}
@Override
public String description() {
return "test plugin";
}
@Override
public Collection<Class<? extends LifecycleComponent>> services() {
List<Class<? extends LifecycleComponent>> services = new ArrayList<Class<? extends LifecycleComponent>>(1);
services.add(MasterAwareService.class);
return services;
}
}
@Singleton
public static class MasterAwareService extends AbstractLifecycleComponent<MasterAwareService> implements LocalNodeMasterListener {
private final ClusterService clusterService;
private volatile boolean master;
@Inject
public MasterAwareService(Settings settings, ClusterService clusterService) {
super(settings);
clusterService.add(this);
this.clusterService = clusterService;
logger.info("initialized test service");
}
@Override
public void onMaster() {
logger.info("on master [" + clusterService.localNode() + "]");
master = true;
}
@Override
public void offMaster() {
logger.info("off master [" + clusterService.localNode() + "]");
master = false;
}
public boolean master() {
return master;
}
@Override
protected void doStart() throws ElasticsearchException {
}
@Override
protected void doStop() throws ElasticsearchException {
}
@Override
protected void doClose() throws ElasticsearchException {
}
@Override
public String executorName() {
return ThreadPool.Names.SAME;
}
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_ClusterServiceTests.java
|
2,630 |
private static class CompoundPingListener implements PingListener {
private final PingListener listener;
private final AtomicInteger counter;
private ConcurrentMap<DiscoveryNode, PingResponse> responses = ConcurrentCollections.newConcurrentMap();
private CompoundPingListener(PingListener listener, ImmutableList<? extends ZenPing> zenPings) {
this.listener = listener;
this.counter = new AtomicInteger(zenPings.size());
}
@Override
public void onPing(PingResponse[] pings) {
if (pings != null) {
for (PingResponse pingResponse : pings) {
responses.put(pingResponse.target(), pingResponse);
}
}
if (counter.decrementAndGet() == 0) {
listener.onPing(responses.values().toArray(new PingResponse[responses.size()]));
}
}
}
| 0true
|
src_main_java_org_elasticsearch_discovery_zen_ping_ZenPingService.java
|
1,750 |
private static class MyObject implements DataSerializable {
int serializedCount = 0;
int deserializedCount = 0;
public MyObject() {
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(++serializedCount);
out.writeInt(deserializedCount);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
serializedCount = in.readInt();
deserializedCount = in.readInt() + 1;
}
}
| 0true
|
hazelcast_src_test_java_com_hazelcast_map_EntryProcessorTest.java
|
1,443 |
public class ProductLinkTag extends CategoryLinkTag {
private static final long serialVersionUID = 1L;
private Product product;
@Override
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.println(getUrl(product));
}
public void setProduct(Product product) {
this.product = product;
}
protected String getUrl(Product product) {
PageContext pageContext = (PageContext)getJspContext();
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
StringBuffer sb = new StringBuffer();
sb.append("<a class=\"noTextUnderline\" href=\"");
sb.append(request.getContextPath());
sb.append("/");
sb.append(getCategory() == null ? product.getDefaultCategory().getGeneratedUrl() : getCategory().getGeneratedUrl());
sb.append("?productId=" + product.getId());
sb.append("\">");
sb.append(product.getName());
sb.append("</a>");
return sb.toString();
}
}
| 0true
|
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_catalog_taglib_ProductLinkTag.java
|
148 |
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
public sun.misc.Unsafe run() throws Exception {
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
for (java.lang.reflect.Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x))
return k.cast(x);
}
throw new NoSuchFieldError("the Unsafe");
}});
| 0true
|
src_main_java_jsr166e_extra_AtomicDoubleArray.java
|
1,030 |
public class OCommandExecutorSQLCreateFunction extends OCommandExecutorSQLAbstract {
public static final String NAME = "CREATE FUNCTION";
private String name;
private String code;
private String language;
private boolean idempotent = false;
private List<String> parameters = null;
@SuppressWarnings("unchecked")
public OCommandExecutorSQLCreateFunction parse(final OCommandRequest iRequest) {
init((OCommandRequestText) iRequest);
parserRequiredKeyword("CREATE");
parserRequiredKeyword("FUNCTION");
parserNextWord(false);
name = parserGetLastWord();
parserNextWord(false);
code = OStringSerializerHelper.getStringContent(parserGetLastWord());
String temp = parseOptionalWord(true);
while (temp != null) {
if (temp.equals("IDEMPOTENT")) {
parserNextWord(false);
idempotent = Boolean.parseBoolean(parserGetLastWord());
} else if (temp.equals("LANGUAGE")) {
parserNextWord(false);
language = parserGetLastWord();
} else if (temp.equals("PARAMETERS")) {
parserNextWord(false);
parameters = new ArrayList<String>();
OStringSerializerHelper.getCollection(parserGetLastWord(), 0, parameters);
if (parameters.size() == 0)
throw new OCommandExecutionException("Syntax Error. Missing function parameter(s): " + getSyntax());
}
temp = parserOptionalWord(true);
if (parserIsEnded())
break;
}
return this;
}
/**
* Execute the command and return the ODocument object created.
*/
public Object execute(final Map<Object, Object> iArgs) {
if (name == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
if (name.isEmpty())
throw new OCommandExecutionException("Syntax Error. You must specify a function name: " + getSyntax());
if (code == null || code.isEmpty())
throw new OCommandExecutionException("Syntax Error. You must specify the function code: " + getSyntax());
ODatabaseRecord database = getDatabase();
final OFunction f = database.getMetadata().getFunctionLibrary().createFunction(name);
f.setCode(code);
f.setIdempotent(idempotent);
if (parameters != null)
f.setParameters(parameters);
if (language != null)
f.setLanguage(language);
return f.getId();
}
@Override
public String getSyntax() {
return "CREATE FUNCTION <name> <code> [PARAMETERS [<comma-separated list of parameters' name>]] [IDEMPOTENT true|false] [LANGUAGE <language>]";
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLCreateFunction.java
|
1,741 |
map.addEntryListener(new EntryListener<Integer, Integer>() {
@Override
public void entryAdded(EntryEvent<Integer, Integer> event) {
addCount.incrementAndGet();
latch.countDown();
}
@Override
public void entryRemoved(EntryEvent<Integer, Integer> event) {
removeCount.incrementAndGet();
latch.countDown();
}
@Override
public void entryUpdated(EntryEvent<Integer, Integer> event) {
updateCount.incrementAndGet();
latch.countDown();
}
@Override
public void entryEvicted(EntryEvent<Integer, Integer> event) {
}
}, true);
| 0true
|
hazelcast_src_test_java_com_hazelcast_map_EntryProcessorTest.java
|
795 |
private static class FailingFunction implements IFunction<Long, Long> {
@Override
public Long apply(Long input) {
throw new WoohaaException();
}
}
| 0true
|
hazelcast_src_test_java_com_hazelcast_concurrent_atomiclong_AtomicLongTest.java
|
2,498 |
START_OBJECT {
@Override
public boolean isValue() {
return false;
}
},
| 0true
|
src_main_java_org_elasticsearch_common_xcontent_XContentParser.java
|
3,710 |
public class IpFieldMapper extends NumberFieldMapper<Long> {
public static final String CONTENT_TYPE = "ip";
public static String longToIp(long longIp) {
int octet3 = (int) ((longIp >> 24) % 256);
int octet2 = (int) ((longIp >> 16) % 256);
int octet1 = (int) ((longIp >> 8) % 256);
int octet0 = (int) ((longIp) % 256);
return octet3 + "." + octet2 + "." + octet1 + "." + octet0;
}
private static final Pattern pattern = Pattern.compile("\\.");
public static long ipToLong(String ip) throws ElasticsearchIllegalArgumentException {
try {
String[] octets = pattern.split(ip);
if (octets.length != 4) {
throw new ElasticsearchIllegalArgumentException("failed to parse ip [" + ip + "], not full ip address (4 dots)");
}
return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16) +
(Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]);
} catch (Exception e) {
if (e instanceof ElasticsearchIllegalArgumentException) {
throw (ElasticsearchIllegalArgumentException) e;
}
throw new ElasticsearchIllegalArgumentException("failed to parse ip [" + ip + "]", e);
}
}
public static class Defaults extends NumberFieldMapper.Defaults {
public static final String NULL_VALUE = null;
public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE);
static {
FIELD_TYPE.freeze();
}
}
public static class Builder extends NumberFieldMapper.Builder<Builder, IpFieldMapper> {
protected String nullValue = Defaults.NULL_VALUE;
public Builder(String name) {
super(name, new FieldType(Defaults.FIELD_TYPE));
builder = this;
}
public Builder nullValue(String nullValue) {
this.nullValue = nullValue;
return this;
}
@Override
public IpFieldMapper build(BuilderContext context) {
fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f);
IpFieldMapper fieldMapper = new IpFieldMapper(buildNames(context),
precisionStep, boost, fieldType, docValues, nullValue, ignoreMalformed(context), coerce(context),
postingsProvider, docValuesProvider, similarity,
normsLoading, fieldDataSettings, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
fieldMapper.includeInAll(includeInAll);
return fieldMapper;
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
IpFieldMapper.Builder builder = ipField(name);
parseNumberField(builder, name, node, parserContext);
for (Map.Entry<String, Object> entry : node.entrySet()) {
String propName = Strings.toUnderscoreCase(entry.getKey());
Object propNode = entry.getValue();
if (propName.equals("null_value")) {
builder.nullValue(propNode.toString());
}
}
return builder;
}
}
private String nullValue;
protected IpFieldMapper(Names names, int precisionStep, float boost, FieldType fieldType, Boolean docValues,
String nullValue, Explicit<Boolean> ignoreMalformed, Explicit<Boolean> coerce,
PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider,
SimilarityProvider similarity, Loading normsLoading, @Nullable Settings fieldDataSettings,
Settings indexSettings, MultiFields multiFields, CopyTo copyTo) {
super(names, precisionStep, boost, fieldType, docValues,
ignoreMalformed, coerce, new NamedAnalyzer("_ip/" + precisionStep, new NumericIpAnalyzer(precisionStep)),
new NamedAnalyzer("_ip/max", new NumericIpAnalyzer(Integer.MAX_VALUE)), postingsProvider, docValuesProvider,
similarity, normsLoading, fieldDataSettings, indexSettings, multiFields, copyTo);
this.nullValue = nullValue;
}
@Override
public FieldType defaultFieldType() {
return Defaults.FIELD_TYPE;
}
@Override
public FieldDataType defaultFieldDataType() {
return new FieldDataType("long");
}
@Override
protected int maxPrecisionStep() {
return 64;
}
@Override
public Long value(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).longValue();
}
if (value instanceof BytesRef) {
return Numbers.bytesToLong((BytesRef) value);
}
return ipToLong(value.toString());
}
/**
* IPs should return as a string.
*/
@Override
public Object valueForSearch(Object value) {
Long val = value(value);
if (val == null) {
return null;
}
return longToIp(val);
}
@Override
public BytesRef indexedValueForSearch(Object value) {
BytesRef bytesRef = new BytesRef();
NumericUtils.longToPrefixCoded(parseValue(value), 0, bytesRef); // 0 because of exact match
return bytesRef;
}
private long parseValue(Object value) {
if (value instanceof Number) {
return ((Number) value).longValue();
}
if (value instanceof BytesRef) {
return ipToLong(((BytesRef) value).utf8ToString());
}
return ipToLong(value.toString());
}
@Override
public Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) {
long iValue = ipToLong(value);
long iSim;
try {
iSim = ipToLong(fuzziness.asString());
} catch (ElasticsearchIllegalArgumentException e) {
iSim = fuzziness.asLong();
}
return NumericRangeQuery.newLongRange(names.indexName(), precisionStep,
iValue - iSim,
iValue + iSim,
true, true);
}
@Override
public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return NumericRangeQuery.newLongRange(names.indexName(), precisionStep,
lowerTerm == null ? null : parseValue(lowerTerm),
upperTerm == null ? null : parseValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return NumericRangeFilter.newLongRange(names.indexName(), precisionStep,
lowerTerm == null ? null : parseValue(lowerTerm),
upperTerm == null ? null : parseValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Filter rangeFilter(IndexFieldDataService fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return NumericRangeFieldDataFilter.newLongRange((IndexNumericFieldData) fieldData.getForField(this),
lowerTerm == null ? null : parseValue(lowerTerm),
upperTerm == null ? null : parseValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Filter nullValueFilter() {
if (nullValue == null) {
return null;
}
final long value = ipToLong(nullValue);
return NumericRangeFilter.newLongRange(names.indexName(), precisionStep,
value,
value,
true, true);
}
@Override
protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException {
String ipAsString;
if (context.externalValueSet()) {
ipAsString = (String) context.externalValue();
if (ipAsString == null) {
ipAsString = nullValue;
}
} else {
if (context.parser().currentToken() == XContentParser.Token.VALUE_NULL) {
ipAsString = nullValue;
} else {
ipAsString = context.parser().text();
}
}
if (ipAsString == null) {
return;
}
if (context.includeInAll(includeInAll, this)) {
context.allEntries().addText(names.fullName(), ipAsString, boost);
}
final long value = ipToLong(ipAsString);
if (fieldType.indexed() || fieldType.stored()) {
CustomLongNumericField field = new CustomLongNumericField(this, value, fieldType);
field.setBoost(boost);
fields.add(field);
}
if (hasDocValues()) {
addDocValue(context, value);
}
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
super.merge(mergeWith, mergeContext);
if (!this.getClass().equals(mergeWith.getClass())) {
return;
}
if (!mergeContext.mergeFlags().simulate()) {
this.nullValue = ((IpFieldMapper) mergeWith).nullValue;
}
}
@Override
protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
super.doXContentBody(builder, includeDefaults, params);
if (includeDefaults || precisionStep != Defaults.PRECISION_STEP) {
builder.field("precision_step", precisionStep);
}
if (includeDefaults || nullValue != null) {
builder.field("null_value", nullValue);
}
if (includeInAll != null) {
builder.field("include_in_all", includeInAll);
} else if (includeDefaults) {
builder.field("include_in_all", false);
}
}
public static class NumericIpAnalyzer extends NumericAnalyzer<NumericIpTokenizer> {
private final int precisionStep;
public NumericIpAnalyzer() {
this(NumericUtils.PRECISION_STEP_DEFAULT);
}
public NumericIpAnalyzer(int precisionStep) {
this.precisionStep = precisionStep;
}
@Override
protected NumericIpTokenizer createNumericTokenizer(Reader reader, char[] buffer) throws IOException {
return new NumericIpTokenizer(reader, precisionStep, buffer);
}
}
public static class NumericIpTokenizer extends NumericTokenizer {
public NumericIpTokenizer(Reader reader, int precisionStep, char[] buffer) throws IOException {
super(reader, new NumericTokenStream(precisionStep), buffer, null);
}
@Override
protected void setValue(NumericTokenStream tokenStream, String value) {
tokenStream.setLongValue(ipToLong(value));
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_mapper_ip_IpFieldMapper.java
|
286 |
private static final ThreadLocal<Random> THREAD_LOCAL_RANDOM = new ThreadLocal<Random>() {
@Override
public Random initialValue() {
return new Random();
}
};
| 0true
|
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_thrift_thriftpool_CTConnectionFactory.java
|
1,332 |
public class SolrContext {
public static final String PRIMARY = "primary";
public static final String REINDEX = "reindex";
protected static SolrServer primaryServer = null;
protected static SolrServer reindexServer = null;
public static void setPrimaryServer(SolrServer server) {
primaryServer = server;
}
public static void setReindexServer(SolrServer server) {
reindexServer = server;
}
public static SolrServer getServer() {
return primaryServer;
}
public static SolrServer getReindexServer() {
return isSingleCoreMode() ? primaryServer : reindexServer;
}
public static boolean isSingleCoreMode() {
return reindexServer == null;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_service_solr_SolrContext.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.