Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
143k
| target
class label 2
classes | project
stringlengths 33
157
|
---|---|---|---|
2,608 |
= new ConstructorFunction<Address, ConnectionMonitor>() {
public ConnectionMonitor createNew(Address endpoint) {
return new ConnectionMonitor(TcpIpConnectionManager.this, endpoint);
}
};
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_TcpIpConnectionManager.java
|
1,481 |
public class OSQLFunctionOutV extends OSQLFunctionMove {
public static final String NAME = "outV";
public OSQLFunctionOutV() {
super(NAME, 0, 1);
}
@Override
protected Object move(final OrientBaseGraph graph, final OIdentifiable iRecord, final String[] iLabels) {
return e2v(graph, iRecord, Direction.OUT, iLabels);
}
}
| 1no label
|
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_functions_OSQLFunctionOutV.java
|
1,961 |
@Repository("blRoleDao")
public class RoleDaoImpl implements RoleDao {
@PersistenceContext(unitName = "blPU")
protected EntityManager em;
@Resource(name = "blEntityConfiguration")
protected EntityConfiguration entityConfiguration;
public Address readAddressById(Long id) {
return (Address) em.find(AddressImpl.class, id);
}
@SuppressWarnings("unchecked")
public List<CustomerRole> readCustomerRolesByCustomerId(Long customerId) {
Query query = em.createNamedQuery("BC_READ_CUSTOMER_ROLES_BY_CUSTOMER_ID");
query.setParameter("customerId", customerId);
return query.getResultList();
}
public Role readRoleByName(String name) {
Query query = em.createNamedQuery("BC_READ_ROLE_BY_NAME");
query.setParameter("name", name);
return (Role) query.getSingleResult();
}
public void addRoleToCustomer(CustomerRole customerRole) {
em.persist(customerRole);
}
}
| 1no label
|
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_dao_RoleDaoImpl.java
|
747 |
public class GetAction extends Action<GetRequest, GetResponse, GetRequestBuilder> {
public static final GetAction INSTANCE = new GetAction();
public static final String NAME = "get";
private GetAction() {
super(NAME);
}
@Override
public GetResponse newResponse() {
return new GetResponse();
}
@Override
public GetRequestBuilder newRequestBuilder(Client client) {
return new GetRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_get_GetAction.java
|
430 |
public class TransportClusterStateAction extends TransportMasterNodeReadOperationAction<ClusterStateRequest, ClusterStateResponse> {
private final ClusterName clusterName;
@Inject
public TransportClusterStateAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool,
ClusterName clusterName) {
super(settings, transportService, clusterService, threadPool);
this.clusterName = clusterName;
}
@Override
protected String executor() {
// very lightweight operation in memory, no need to fork to a thread
return ThreadPool.Names.SAME;
}
@Override
protected String transportAction() {
return ClusterStateAction.NAME;
}
@Override
protected ClusterStateRequest newRequest() {
return new ClusterStateRequest();
}
@Override
protected ClusterStateResponse newResponse() {
return new ClusterStateResponse();
}
@Override
protected void masterOperation(final ClusterStateRequest request, final ClusterState state, ActionListener<ClusterStateResponse> listener) throws ElasticsearchException {
ClusterState currentState = clusterService.state();
logger.trace("Serving cluster state request using version {}", currentState.version());
ClusterState.Builder builder = ClusterState.builder();
builder.version(currentState.version());
if (request.nodes()) {
builder.nodes(currentState.nodes());
}
if (request.routingTable()) {
if (request.indices().length > 0) {
RoutingTable.Builder routingTableBuilder = RoutingTable.builder();
for (String filteredIndex : request.indices()) {
if (currentState.routingTable().getIndicesRouting().containsKey(filteredIndex)) {
routingTableBuilder.add(currentState.routingTable().getIndicesRouting().get(filteredIndex));
}
}
builder.routingTable(routingTableBuilder);
} else {
builder.routingTable(currentState.routingTable());
}
builder.allocationExplanation(currentState.allocationExplanation());
}
if (request.blocks()) {
builder.blocks(currentState.blocks());
}
if (request.metaData()) {
MetaData.Builder mdBuilder;
if (request.indices().length == 0 && request.indexTemplates().length == 0) {
mdBuilder = MetaData.builder(currentState.metaData());
} else {
mdBuilder = MetaData.builder();
}
if (request.indices().length > 0) {
String[] indices = currentState.metaData().concreteIndicesIgnoreMissing(request.indices());
for (String filteredIndex : indices) {
IndexMetaData indexMetaData = currentState.metaData().index(filteredIndex);
if (indexMetaData != null) {
mdBuilder.put(indexMetaData, false);
}
}
}
if (request.indexTemplates().length > 0) {
for (String templateName : request.indexTemplates()) {
IndexTemplateMetaData indexTemplateMetaData = currentState.metaData().templates().get(templateName);
if (indexTemplateMetaData != null) {
mdBuilder.put(indexTemplateMetaData);
}
}
}
builder.metaData(mdBuilder);
}
listener.onResponse(new ClusterStateResponse(clusterName, builder.build()));
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_state_TransportClusterStateAction.java
|
3,776 |
public class ConcurrentMergeSchedulerProvider extends MergeSchedulerProvider {
private final int maxThreadCount;
private final int maxMergeCount;
private Set<CustomConcurrentMergeScheduler> schedulers = new CopyOnWriteArraySet<CustomConcurrentMergeScheduler>();
@Inject
public ConcurrentMergeSchedulerProvider(ShardId shardId, @IndexSettings Settings indexSettings, ThreadPool threadPool) {
super(shardId, indexSettings, threadPool);
// TODO LUCENE MONITOR this will change in Lucene 4.0
this.maxThreadCount = componentSettings.getAsInt("max_thread_count", Math.max(1, Math.min(3, Runtime.getRuntime().availableProcessors() / 2)));
this.maxMergeCount = componentSettings.getAsInt("max_merge_count", maxThreadCount + 2);
logger.debug("using [concurrent] merge scheduler with max_thread_count[{}]", maxThreadCount);
}
@Override
public MergeScheduler newMergeScheduler() {
CustomConcurrentMergeScheduler concurrentMergeScheduler = new CustomConcurrentMergeScheduler(logger, shardId, this);
concurrentMergeScheduler.setMaxMergesAndThreads(maxMergeCount, maxThreadCount);
schedulers.add(concurrentMergeScheduler);
return concurrentMergeScheduler;
}
@Override
public MergeStats stats() {
MergeStats mergeStats = new MergeStats();
for (CustomConcurrentMergeScheduler scheduler : schedulers) {
mergeStats.add(scheduler.totalMerges(), scheduler.totalMergeTime(), scheduler.totalMergeNumDocs(), scheduler.totalMergeSizeInBytes(),
scheduler.currentMerges(), scheduler.currentMergesNumDocs(), scheduler.currentMergesSizeInBytes());
}
return mergeStats;
}
@Override
public Set<OnGoingMerge> onGoingMerges() {
for (CustomConcurrentMergeScheduler scheduler : schedulers) {
return scheduler.onGoingMerges();
}
return ImmutableSet.of();
}
public static class CustomConcurrentMergeScheduler extends TrackingConcurrentMergeScheduler {
private final ShardId shardId;
private final ConcurrentMergeSchedulerProvider provider;
private CustomConcurrentMergeScheduler(ESLogger logger, ShardId shardId, ConcurrentMergeSchedulerProvider provider) {
super(logger);
this.shardId = shardId;
this.provider = provider;
}
@Override
protected MergeThread getMergeThread(IndexWriter writer, MergePolicy.OneMerge merge) throws IOException {
MergeThread thread = super.getMergeThread(writer, merge);
thread.setName(EsExecutors.threadName(provider.indexSettings(), "[" + shardId.index().name() + "][" + shardId.id() + "]: " + thread.getName()));
return thread;
}
@Override
protected void handleMergeException(Throwable exc) {
logger.warn("failed to merge", exc);
provider.failedMerge(new MergePolicy.MergeException(exc, dir));
super.handleMergeException(exc);
}
@Override
public void close() {
super.close();
provider.schedulers.remove(this);
}
@Override
protected void beforeMerge(OnGoingMerge merge) {
super.beforeMerge(merge);
provider.beforeMerge(merge);
}
@Override
protected void afterMerge(OnGoingMerge merge) {
super.afterMerge(merge);
provider.afterMerge(merge);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_merge_scheduler_ConcurrentMergeSchedulerProvider.java
|
1,382 |
public class IndexTemplateMetaData {
private final String name;
private final int order;
private final String template;
private final Settings settings;
// the mapping source should always include the type as top level
private final ImmutableOpenMap<String, CompressedString> mappings;
private final ImmutableOpenMap<String, IndexMetaData.Custom> customs;
public IndexTemplateMetaData(String name, int order, String template, Settings settings, ImmutableOpenMap<String, CompressedString> mappings, ImmutableOpenMap<String, IndexMetaData.Custom> customs) {
this.name = name;
this.order = order;
this.template = template;
this.settings = settings;
this.mappings = mappings;
this.customs = customs;
}
public String name() {
return this.name;
}
public int order() {
return this.order;
}
public int getOrder() {
return order();
}
public String getName() {
return this.name;
}
public String template() {
return this.template;
}
public String getTemplate() {
return this.template;
}
public Settings settings() {
return this.settings;
}
public Settings getSettings() {
return settings();
}
public ImmutableOpenMap<String, CompressedString> mappings() {
return this.mappings;
}
public ImmutableOpenMap<String, CompressedString> getMappings() {
return this.mappings;
}
public ImmutableOpenMap<String, IndexMetaData.Custom> customs() {
return this.customs;
}
public ImmutableOpenMap<String, IndexMetaData.Custom> getCustoms() {
return this.customs;
}
public <T extends IndexMetaData.Custom> T custom(String type) {
return (T) customs.get(type);
}
public static Builder builder(String name) {
return new Builder(name);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IndexTemplateMetaData that = (IndexTemplateMetaData) o;
if (order != that.order) return false;
if (!mappings.equals(that.mappings)) return false;
if (!name.equals(that.name)) return false;
if (!settings.equals(that.settings)) return false;
if (!template.equals(that.template)) return false;
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + order;
result = 31 * result + template.hashCode();
result = 31 * result + settings.hashCode();
result = 31 * result + mappings.hashCode();
return result;
}
public static class Builder {
private static final Set<String> VALID_FIELDS = Sets.newHashSet("template", "order", "mappings", "settings");
static {
VALID_FIELDS.addAll(IndexMetaData.customFactories.keySet());
}
private String name;
private int order;
private String template;
private Settings settings = ImmutableSettings.Builder.EMPTY_SETTINGS;
private final ImmutableOpenMap.Builder<String, CompressedString> mappings;
private final ImmutableOpenMap.Builder<String, IndexMetaData.Custom> customs;
public Builder(String name) {
this.name = name;
mappings = ImmutableOpenMap.builder();
customs = ImmutableOpenMap.builder();
}
public Builder(IndexTemplateMetaData indexTemplateMetaData) {
this.name = indexTemplateMetaData.name();
order(indexTemplateMetaData.order());
template(indexTemplateMetaData.template());
settings(indexTemplateMetaData.settings());
mappings = ImmutableOpenMap.builder(indexTemplateMetaData.mappings());
customs = ImmutableOpenMap.builder(indexTemplateMetaData.customs());
}
public Builder order(int order) {
this.order = order;
return this;
}
public Builder template(String template) {
this.template = template;
return this;
}
public String template() {
return template;
}
public Builder settings(Settings.Builder settings) {
this.settings = settings.build();
return this;
}
public Builder settings(Settings settings) {
this.settings = settings;
return this;
}
public Builder removeMapping(String mappingType) {
mappings.remove(mappingType);
return this;
}
public Builder putMapping(String mappingType, CompressedString mappingSource) throws IOException {
mappings.put(mappingType, mappingSource);
return this;
}
public Builder putMapping(String mappingType, String mappingSource) throws IOException {
mappings.put(mappingType, new CompressedString(mappingSource));
return this;
}
public Builder putCustom(String type, IndexMetaData.Custom customIndexMetaData) {
this.customs.put(type, customIndexMetaData);
return this;
}
public Builder removeCustom(String type) {
this.customs.remove(type);
return this;
}
public IndexMetaData.Custom getCustom(String type) {
return this.customs.get(type);
}
public IndexTemplateMetaData build() {
return new IndexTemplateMetaData(name, order, template, settings, mappings.build(), customs.build());
}
public static void toXContent(IndexTemplateMetaData indexTemplateMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startObject(indexTemplateMetaData.name(), XContentBuilder.FieldCaseConversion.NONE);
builder.field("order", indexTemplateMetaData.order());
builder.field("template", indexTemplateMetaData.template());
builder.startObject("settings");
for (Map.Entry<String, String> entry : indexTemplateMetaData.settings().getAsMap().entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
builder.endObject();
if (params.paramAsBoolean("reduce_mappings", false)) {
builder.startObject("mappings");
for (ObjectObjectCursor<String, CompressedString> cursor : indexTemplateMetaData.mappings()) {
byte[] mappingSource = cursor.value.uncompressed();
XContentParser parser = XContentFactory.xContent(mappingSource).createParser(mappingSource);
Map<String, Object> mapping = parser.map();
if (mapping.size() == 1 && mapping.containsKey(cursor.key)) {
// the type name is the root value, reduce it
mapping = (Map<String, Object>) mapping.get(cursor.key);
}
builder.field(cursor.key);
builder.map(mapping);
}
builder.endObject();
} else {
builder.startArray("mappings");
for (ObjectObjectCursor<String, CompressedString> cursor : indexTemplateMetaData.mappings()) {
byte[] data = cursor.value.uncompressed();
XContentParser parser = XContentFactory.xContent(data).createParser(data);
Map<String, Object> mapping = parser.mapOrderedAndClose();
builder.map(mapping);
}
builder.endArray();
}
for (ObjectObjectCursor<String, IndexMetaData.Custom> cursor : indexTemplateMetaData.customs()) {
builder.startObject(cursor.key, XContentBuilder.FieldCaseConversion.NONE);
IndexMetaData.lookupFactorySafe(cursor.key).toXContent(cursor.value, builder, params);
builder.endObject();
}
builder.endObject();
}
public static IndexTemplateMetaData fromXContentStandalone(XContentParser parser) throws IOException {
XContentParser.Token token = parser.nextToken();
if (token == null) {
throw new IOException("no data");
}
if (token != XContentParser.Token.START_OBJECT) {
throw new IOException("should start object");
}
token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new IOException("the first field should be the template name");
}
return fromXContent(parser);
}
public static IndexTemplateMetaData fromXContent(XContentParser parser) throws IOException {
Builder builder = new Builder(parser.currentName());
String currentFieldName = skipTemplateName(parser);
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("settings".equals(currentFieldName)) {
ImmutableSettings.Builder templateSettingsBuilder = ImmutableSettings.settingsBuilder();
for (Map.Entry<String, String> entry : SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered()).entrySet()) {
if (!entry.getKey().startsWith("index.")) {
templateSettingsBuilder.put("index." + entry.getKey(), entry.getValue());
} else {
templateSettingsBuilder.put(entry.getKey(), entry.getValue());
}
}
builder.settings(templateSettingsBuilder.build());
} else if ("mappings".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
String mappingType = currentFieldName;
Map<String, Object> mappingSource = MapBuilder.<String, Object>newMapBuilder().put(mappingType, parser.mapOrdered()).map();
builder.putMapping(mappingType, XContentFactory.jsonBuilder().map(mappingSource).string());
}
}
} else {
// check if its a custom index metadata
IndexMetaData.Custom.Factory<IndexMetaData.Custom> factory = IndexMetaData.lookupFactory(currentFieldName);
if (factory == null) {
//TODO warn
parser.skipChildren();
} else {
builder.putCustom(factory.type(), factory.fromXContent(parser));
}
}
} else if (token == XContentParser.Token.START_ARRAY) {
if ("mappings".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
Map<String, Object> mapping = parser.mapOrdered();
if (mapping.size() == 1) {
String mappingType = mapping.keySet().iterator().next();
String mappingSource = XContentFactory.jsonBuilder().map(mapping).string();
if (mappingSource == null) {
// crap, no mapping source, warn?
} else {
builder.putMapping(mappingType, mappingSource);
}
}
}
}
} else if (token.isValue()) {
if ("template".equals(currentFieldName)) {
builder.template(parser.text());
} else if ("order".equals(currentFieldName)) {
builder.order(parser.intValue());
}
}
}
return builder.build();
}
private static String skipTemplateName(XContentParser parser) throws IOException {
XContentParser.Token token = parser.nextToken();
if (token != null && token == XContentParser.Token.START_OBJECT) {
token = parser.nextToken();
if (token == XContentParser.Token.FIELD_NAME) {
String currentFieldName = parser.currentName();
if (VALID_FIELDS.contains(currentFieldName)) {
return currentFieldName;
} else {
// we just hit the template name, which should be ignored and we move on
parser.nextToken();
}
}
}
return null;
}
public static IndexTemplateMetaData readFrom(StreamInput in) throws IOException {
Builder builder = new Builder(in.readString());
builder.order(in.readInt());
builder.template(in.readString());
builder.settings(ImmutableSettings.readSettingsFromStream(in));
int mappingsSize = in.readVInt();
for (int i = 0; i < mappingsSize; i++) {
builder.putMapping(in.readString(), CompressedString.readCompressedString(in));
}
int customSize = in.readVInt();
for (int i = 0; i < customSize; i++) {
String type = in.readString();
IndexMetaData.Custom customIndexMetaData = IndexMetaData.lookupFactorySafe(type).readFrom(in);
builder.putCustom(type, customIndexMetaData);
}
return builder.build();
}
public static void writeTo(IndexTemplateMetaData indexTemplateMetaData, StreamOutput out) throws IOException {
out.writeString(indexTemplateMetaData.name());
out.writeInt(indexTemplateMetaData.order());
out.writeString(indexTemplateMetaData.template());
ImmutableSettings.writeSettingsToStream(indexTemplateMetaData.settings(), out);
out.writeVInt(indexTemplateMetaData.mappings().size());
for (ObjectObjectCursor<String, CompressedString> cursor : indexTemplateMetaData.mappings()) {
out.writeString(cursor.key);
cursor.value.writeTo(out);
}
out.writeVInt(indexTemplateMetaData.customs().size());
for (ObjectObjectCursor<String, IndexMetaData.Custom> cursor : indexTemplateMetaData.customs()) {
out.writeString(cursor.key);
IndexMetaData.lookupFactorySafe(cursor.key).writeTo(cursor.value, out);
}
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_cluster_metadata_IndexTemplateMetaData.java
|
147 |
public abstract class InvocationClientRequest extends ClientRequest {
@Override
final void process() throws Exception {
invoke();
}
protected abstract void invoke();
protected final InvocationBuilder createInvocationBuilder(String serviceName, Operation op, int partitionId) {
return clientEngine.createInvocationBuilder(serviceName, op, partitionId);
}
protected final InvocationBuilder createInvocationBuilder(String serviceName, Operation op, Address target) {
return clientEngine.createInvocationBuilder(serviceName, op, target);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_InvocationClientRequest.java
|
782 |
new OProfilerHookValue() {
public Object getValue() {
return lastGC;
}
});
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_memory_OMemoryWatchDog.java
|
5,920 |
public class GeoDistanceSortParser implements SortParser {
@Override
public String[] names() {
return new String[]{"_geo_distance", "_geoDistance"};
}
@Override
public SortField parse(XContentParser parser, SearchContext context) throws Exception {
String fieldName = null;
GeoPoint point = new GeoPoint();
DistanceUnit unit = DistanceUnit.DEFAULT;
GeoDistance geoDistance = GeoDistance.DEFAULT;
boolean reverse = false;
SortMode sortMode = null;
String nestedPath = null;
Filter nestedFilter = null;
boolean normalizeLon = true;
boolean normalizeLat = true;
XContentParser.Token token;
String currentName = parser.currentName();
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
GeoPoint.parse(parser, point);
fieldName = currentName;
} else if (token == XContentParser.Token.START_OBJECT) {
// the json in the format of -> field : { lat : 30, lon : 12 }
if ("nested_filter".equals(currentName) || "nestedFilter".equals(currentName)) {
ParsedFilter parsedFilter = context.queryParserService().parseInnerFilter(parser);
nestedFilter = parsedFilter == null ? null : parsedFilter.filter();
} else {
fieldName = currentName;
GeoPoint.parse(parser, point);
}
} else if (token.isValue()) {
if ("reverse".equals(currentName)) {
reverse = parser.booleanValue();
} else if ("order".equals(currentName)) {
reverse = "desc".equals(parser.text());
} else if (currentName.equals("unit")) {
unit = DistanceUnit.fromString(parser.text());
} else if (currentName.equals("distance_type") || currentName.equals("distanceType")) {
geoDistance = GeoDistance.fromString(parser.text());
} else if ("normalize".equals(currentName)) {
normalizeLat = parser.booleanValue();
normalizeLon = parser.booleanValue();
} else if ("sort_mode".equals(currentName) || "sortMode".equals(currentName) || "mode".equals(currentName)) {
sortMode = SortMode.fromString(parser.text());
} else if ("nested_path".equals(currentName) || "nestedPath".equals(currentName)) {
nestedPath = parser.text();
} else {
point.resetFromString(parser.text());
fieldName = currentName;
}
}
}
if (normalizeLat || normalizeLon) {
GeoUtils.normalizePoint(point, normalizeLat, normalizeLon);
}
if (sortMode == null) {
sortMode = reverse ? SortMode.MAX : SortMode.MIN;
}
if (sortMode == SortMode.SUM) {
throw new ElasticsearchIllegalArgumentException("sort_mode [sum] isn't supported for sorting by geo distance");
}
FieldMapper mapper = context.smartNameFieldMapper(fieldName);
if (mapper == null) {
throw new ElasticsearchIllegalArgumentException("failed to find mapper for [" + fieldName + "] for geo distance based sort");
}
IndexGeoPointFieldData indexFieldData = context.fieldData().getForField(mapper);
IndexFieldData.XFieldComparatorSource geoDistanceComparatorSource = new GeoDistanceComparatorSource(
indexFieldData, point.lat(), point.lon(), unit, geoDistance, sortMode
);
ObjectMapper objectMapper;
if (nestedPath != null) {
ObjectMappers objectMappers = context.mapperService().objectMapper(nestedPath);
if (objectMappers == null) {
throw new ElasticsearchIllegalArgumentException("failed to find nested object mapping for explicit nested path [" + nestedPath + "]");
}
objectMapper = objectMappers.mapper();
if (!objectMapper.nested().isNested()) {
throw new ElasticsearchIllegalArgumentException("mapping for explicit nested path is not mapped as nested: [" + nestedPath + "]");
}
} else {
objectMapper = context.mapperService().resolveClosestNestedObjectMapper(fieldName);
}
if (objectMapper != null && objectMapper.nested().isNested()) {
Filter rootDocumentsFilter = context.filterCache().cache(NonNestedDocsFilter.INSTANCE);
Filter innerDocumentsFilter;
if (nestedFilter != null) {
innerDocumentsFilter = context.filterCache().cache(nestedFilter);
} else {
innerDocumentsFilter = context.filterCache().cache(objectMapper.nestedTypeFilter());
}
geoDistanceComparatorSource = new NestedFieldComparatorSource(
sortMode, geoDistanceComparatorSource, rootDocumentsFilter, innerDocumentsFilter
);
}
return new SortField(fieldName, geoDistanceComparatorSource, reverse);
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_sort_GeoDistanceSortParser.java
|
596 |
public class IndicesSegmentsRequestBuilder extends BroadcastOperationRequestBuilder<IndicesSegmentsRequest, IndicesSegmentResponse, IndicesSegmentsRequestBuilder> {
public IndicesSegmentsRequestBuilder(IndicesAdminClient indicesClient) {
super((InternalIndicesAdminClient) indicesClient, new IndicesSegmentsRequest());
}
@Override
protected void doExecute(ActionListener<IndicesSegmentResponse> listener) {
((IndicesAdminClient) client).segments(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_segments_IndicesSegmentsRequestBuilder.java
|
517 |
public class IndicesExistsResponse extends ActionResponse {
private boolean exists;
IndicesExistsResponse() {
}
public IndicesExistsResponse(boolean exists) {
this.exists = exists;
}
public boolean isExists() {
return this.exists;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
exists = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(exists);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_exists_indices_IndicesExistsResponse.java
|
3,311 |
public abstract class Operation implements DataSerializable {
// serialized
private String serviceName;
private int partitionId = -1;
private int replicaIndex;
private long callId;
private boolean validateTarget = true;
private long invocationTime = -1;
private long callTimeout = Long.MAX_VALUE;
private long waitTimeout = -1;
private String callerUuid;
private String executorName;
// injected
private transient NodeEngine nodeEngine;
private transient Object service;
private transient Address callerAddress;
private transient Connection connection;
private transient ResponseHandler responseHandler;
private transient long startTime;
public boolean isUrgent() {
return this instanceof UrgentSystemOperation;
}
// runs before wait-support
public abstract void beforeRun() throws Exception;
// runs after wait-support, supposed to do actual operation
public abstract void run() throws Exception;
// runs after backups, before wait-notify
public abstract void afterRun() throws Exception;
public abstract boolean returnsResponse();
public abstract Object getResponse();
public String getServiceName() {
return serviceName;
}
public final Operation setServiceName(String serviceName) {
this.serviceName = serviceName;
return this;
}
public final int getPartitionId() {
return partitionId;
}
public final Operation setPartitionId(int partitionId) {
this.partitionId = partitionId;
return this;
}
public final int getReplicaIndex() {
return replicaIndex;
}
public final Operation setReplicaIndex(int replicaIndex) {
if (replicaIndex < 0 || replicaIndex >= InternalPartition.MAX_REPLICA_COUNT) {
throw new IllegalArgumentException("Replica index is out of range [0-"
+ (InternalPartition.MAX_REPLICA_COUNT - 1) + "]");
}
this.replicaIndex = replicaIndex;
return this;
}
public String getExecutorName() {
return executorName;
}
public void setExecutorName(String executorName) {
this.executorName = executorName;
}
public final long getCallId() {
return callId;
}
// Accessed using OperationAccessor
final Operation setCallId(long callId) {
this.callId = callId;
return this;
}
public boolean validatesTarget() {
return validateTarget;
}
public final Operation setValidateTarget(boolean validateTarget) {
this.validateTarget = validateTarget;
return this;
}
public final NodeEngine getNodeEngine() {
return nodeEngine;
}
public final Operation setNodeEngine(NodeEngine nodeEngine) {
this.nodeEngine = nodeEngine;
return this;
}
public final <T> T getService() {
if (service == null) {
// one might have overridden getServiceName() method...
final String name = serviceName != null ? serviceName : getServiceName();
service = ((NodeEngineImpl) nodeEngine).getService(name);
if (service == null) {
if (nodeEngine.isActive()) {
throw new HazelcastException("Service with name '" + name + "' not found!");
} else {
throw new RetryableHazelcastException("HazelcastInstance[" + nodeEngine.getThisAddress()
+ "] is not active!");
}
}
}
return (T) service;
}
public final Operation setService(Object service) {
this.service = service;
return this;
}
public final Address getCallerAddress() {
return callerAddress;
}
// Accessed using OperationAccessor
final Operation setCallerAddress(Address callerAddress) {
this.callerAddress = callerAddress;
return this;
}
public final Connection getConnection() {
return connection;
}
// Accessed using OperationAccessor
final Operation setConnection(Connection connection) {
this.connection = connection;
return this;
}
public final Operation setResponseHandler(ResponseHandler responseHandler) {
this.responseHandler = responseHandler;
return this;
}
public final ResponseHandler getResponseHandler() {
return responseHandler;
}
public final long getStartTime() {
return startTime;
}
// Accessed using OperationAccessor
final Operation setStartTime(long startTime) {
this.startTime = startTime;
return this;
}
public final long getInvocationTime() {
return invocationTime;
}
// Accessed using OperationAccessor
final Operation setInvocationTime(long invocationTime) {
this.invocationTime = invocationTime;
return this;
}
public final long getCallTimeout() {
return callTimeout;
}
// Accessed using OperationAccessor
final Operation setCallTimeout(long callTimeout) {
this.callTimeout = callTimeout;
return this;
}
public final long getWaitTimeout() {
return waitTimeout;
}
public final void setWaitTimeout(long timeout) {
this.waitTimeout = timeout;
}
public ExceptionAction onException(Throwable throwable) {
return (throwable instanceof RetryableException)
? ExceptionAction.RETRY_INVOCATION : ExceptionAction.THROW_EXCEPTION;
}
public String getCallerUuid() {
return callerUuid;
}
public Operation setCallerUuid(String callerUuid) {
this.callerUuid = callerUuid;
return this;
}
protected final ILogger getLogger() {
final NodeEngine ne = nodeEngine;
return ne != null ? ne.getLogger(getClass()) : Logger.getLogger(getClass());
}
public void logError(Throwable e) {
final ILogger logger = getLogger();
if (e instanceof RetryableException) {
final Level level = returnsResponse() ? Level.FINEST : Level.WARNING;
if (logger.isLoggable(level)) {
logger.log(level, e.getClass().getName() + ": " + e.getMessage());
}
} else if (e instanceof OutOfMemoryError) {
try {
logger.log(Level.SEVERE, e.getMessage(), e);
} catch (Throwable ignored) {
}
} else {
final Level level = nodeEngine != null && nodeEngine.isActive() ? Level.SEVERE : Level.FINEST;
if (logger.isLoggable(level)) {
logger.log(level, e.getMessage(), e);
}
}
}
@Override
public final void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(serviceName);
out.writeInt(partitionId);
out.writeInt(replicaIndex);
out.writeLong(callId);
out.writeBoolean(validateTarget);
out.writeLong(invocationTime);
out.writeLong(callTimeout);
out.writeLong(waitTimeout);
out.writeUTF(callerUuid);
out.writeUTF(executorName);
writeInternal(out);
}
@Override
public final void readData(ObjectDataInput in) throws IOException {
serviceName = in.readUTF();
partitionId = in.readInt();
replicaIndex = in.readInt();
callId = in.readLong();
validateTarget = in.readBoolean();
invocationTime = in.readLong();
callTimeout = in.readLong();
waitTimeout = in.readLong();
callerUuid = in.readUTF();
executorName = in.readUTF();
readInternal(in);
}
protected abstract void writeInternal(ObjectDataOutput out) throws IOException;
protected abstract void readInternal(ObjectDataInput in) throws IOException;
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_spi_Operation.java
|
5,306 |
public class LongTerms extends InternalTerms {
public static final Type TYPE = new Type("terms", "lterms");
public static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public LongTerms readResult(StreamInput in) throws IOException {
LongTerms buckets = new LongTerms();
buckets.readFrom(in);
return buckets;
}
};
public static void registerStreams() {
AggregationStreams.registerStream(STREAM, TYPE.stream());
}
static class Bucket extends InternalTerms.Bucket {
long term;
public Bucket(long term, long docCount, InternalAggregations aggregations) {
super(docCount, aggregations);
this.term = term;
}
@Override
public String getKey() {
return String.valueOf(term);
}
@Override
public Text getKeyAsText() {
return new StringText(String.valueOf(term));
}
@Override
public Number getKeyAsNumber() {
return term;
}
@Override
int compareTerm(Terms.Bucket other) {
return Longs.compare(term, other.getKeyAsNumber().longValue());
}
}
private ValueFormatter valueFormatter;
LongTerms() {} // for serialization
public LongTerms(String name, InternalOrder order, ValueFormatter valueFormatter, int requiredSize, long minDocCount, Collection<InternalTerms.Bucket> buckets) {
super(name, order, requiredSize, minDocCount, buckets);
this.valueFormatter = valueFormatter;
}
@Override
public Type type() {
return TYPE;
}
@Override
public InternalTerms reduce(ReduceContext reduceContext) {
List<InternalAggregation> aggregations = reduceContext.aggregations();
if (aggregations.size() == 1) {
InternalTerms terms = (InternalTerms) aggregations.get(0);
terms.trimExcessEntries(reduceContext.cacheRecycler());
return terms;
}
InternalTerms reduced = null;
Recycler.V<LongObjectOpenHashMap<List<Bucket>>> buckets = null;
for (InternalAggregation aggregation : aggregations) {
InternalTerms terms = (InternalTerms) aggregation;
if (terms instanceof UnmappedTerms) {
continue;
}
if (reduced == null) {
reduced = terms;
}
if (buckets == null) {
buckets = reduceContext.cacheRecycler().longObjectMap(terms.buckets.size());
}
for (Terms.Bucket bucket : terms.buckets) {
List<Bucket> existingBuckets = buckets.v().get(((Bucket) bucket).term);
if (existingBuckets == null) {
existingBuckets = new ArrayList<Bucket>(aggregations.size());
buckets.v().put(((Bucket) bucket).term, existingBuckets);
}
existingBuckets.add((Bucket) bucket);
}
}
if (reduced == null) {
// there are only unmapped terms, so we just return the first one (no need to reduce)
return (UnmappedTerms) aggregations.get(0);
}
// TODO: would it be better to sort the backing array buffer of the hppc map directly instead of using a PQ?
final int size = Math.min(requiredSize, buckets.v().size());
BucketPriorityQueue ordered = new BucketPriorityQueue(size, order.comparator(null));
Object[] internalBuckets = buckets.v().values;
boolean[] states = buckets.v().allocated;
for (int i = 0; i < states.length; i++) {
if (states[i]) {
List<LongTerms.Bucket> sameTermBuckets = (List<LongTerms.Bucket>) internalBuckets[i];
final InternalTerms.Bucket b = sameTermBuckets.get(0).reduce(sameTermBuckets, reduceContext.cacheRecycler());
if (b.getDocCount() >= minDocCount) {
ordered.insertWithOverflow(b);
}
}
}
buckets.release();
InternalTerms.Bucket[] list = new InternalTerms.Bucket[ordered.size()];
for (int i = ordered.size() - 1; i >= 0; i--) {
list[i] = (Bucket) ordered.pop();
}
reduced.buckets = Arrays.asList(list);
return reduced;
}
@Override
public void readFrom(StreamInput in) throws IOException {
this.name = in.readString();
this.order = InternalOrder.Streams.readOrder(in);
this.valueFormatter = ValueFormatterStreams.readOptional(in);
this.requiredSize = readSize(in);
this.minDocCount = in.readVLong();
int size = in.readVInt();
List<InternalTerms.Bucket> buckets = new ArrayList<InternalTerms.Bucket>(size);
for (int i = 0; i < size; i++) {
buckets.add(new Bucket(in.readLong(), in.readVLong(), InternalAggregations.readAggregations(in)));
}
this.buckets = buckets;
this.bucketMap = null;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
InternalOrder.Streams.writeOrder(order, out);
ValueFormatterStreams.writeOptional(valueFormatter, out);
writeSize(requiredSize, out);
out.writeVLong(minDocCount);
out.writeVInt(buckets.size());
for (InternalTerms.Bucket bucket : buckets) {
out.writeLong(((Bucket) bucket).term);
out.writeVLong(bucket.getDocCount());
((InternalAggregations) bucket.getAggregations()).writeTo(out);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
builder.startArray(CommonFields.BUCKETS);
for (InternalTerms.Bucket bucket : buckets) {
builder.startObject();
builder.field(CommonFields.KEY, ((Bucket) bucket).term);
if (valueFormatter != null) {
builder.field(CommonFields.KEY_AS_STRING, valueFormatter.format(((Bucket) bucket).term));
}
builder.field(CommonFields.DOC_COUNT, bucket.getDocCount());
((InternalAggregations) bucket.getAggregations()).toXContentInternal(builder, params);
builder.endObject();
}
builder.endArray();
builder.endObject();
return builder;
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_bucket_terms_LongTerms.java
|
226 |
XPostingsHighlighter highlighter = new XPostingsHighlighter(10000) {
@Override
protected BreakIterator getBreakIterator(String field) {
return new WholeBreakIterator();
}
};
| 0true
|
src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java
|
49 |
public interface QueryDescription {
/**
* Returns a string representation of the entire query
* @return
*/
@Override
public String toString();
/**
* Returns how many individual queries are combined into this query, meaning, how many
* queries will be executed in one batch.
*
* @return
*/
public int getNoCombinedQueries();
/**
* Returns the number of sub-queries this query is comprised of. Each sub-query represents one OR clause, i.e.,
* the union of each sub-query's result is the overall result.
*
* @return
*/
public int getNoSubQueries();
/**
* Returns a list of all sub-queries that comprise this query
* @return
*/
public List<? extends SubQuery> getSubQueries();
/**
* Represents one sub-query of this query. Each sub-query represents one OR clause.
*/
public interface SubQuery {
/**
* Whether this query is fitted, i.e. whether the returned results must be filtered in-memory.
* @return
*/
public boolean isFitted();
/**
* Whether this query respects the sort order of parent query or requires sorting in-memory.
* @return
*/
public boolean isSorted();
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_QueryDescription.java
|
607 |
public class UpdateSettingsAction extends IndicesAction<UpdateSettingsRequest, UpdateSettingsResponse, UpdateSettingsRequestBuilder> {
public static final UpdateSettingsAction INSTANCE = new UpdateSettingsAction();
public static final String NAME = "indices/settings/update";
private UpdateSettingsAction() {
super(NAME);
}
@Override
public UpdateSettingsResponse newResponse() {
return new UpdateSettingsResponse();
}
@Override
public UpdateSettingsRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new UpdateSettingsRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_settings_put_UpdateSettingsAction.java
|
735 |
public class OSBTreeBucket<K, V> extends ODurablePage {
private static final int FREE_POINTER_OFFSET = NEXT_FREE_POSITION;
private static final int SIZE_OFFSET = FREE_POINTER_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int IS_LEAF_OFFSET = SIZE_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int LEFT_SIBLING_OFFSET = IS_LEAF_OFFSET + OByteSerializer.BYTE_SIZE;
private static final int RIGHT_SIBLING_OFFSET = LEFT_SIBLING_OFFSET + OLongSerializer.LONG_SIZE;
private static final int TREE_SIZE_OFFSET = RIGHT_SIBLING_OFFSET + OLongSerializer.LONG_SIZE;
private static final int KEY_SERIALIZER_OFFSET = TREE_SIZE_OFFSET + OLongSerializer.LONG_SIZE;
private static final int VALUE_SERIALIZER_OFFSET = KEY_SERIALIZER_OFFSET + OByteSerializer.BYTE_SIZE;
private static final int FREE_VALUES_LIST_OFFSET = VALUE_SERIALIZER_OFFSET + OByteSerializer.BYTE_SIZE;
private static final int POSITIONS_ARRAY_OFFSET = FREE_VALUES_LIST_OFFSET + OLongSerializer.LONG_SIZE;
private final boolean isLeaf;
private final OBinarySerializer<K> keySerializer;
private final OBinarySerializer<V> valueSerializer;
private final OType[] keyTypes;
private final Comparator<? super K> comparator = ODefaultComparator.INSTANCE;
public OSBTreeBucket(ODirectMemoryPointer cachePointer, boolean isLeaf, OBinarySerializer<K> keySerializer, OType[] keyTypes,
OBinarySerializer<V> valueSerializer, TrackMode trackMode) throws IOException {
super(cachePointer, trackMode);
this.isLeaf = isLeaf;
this.keySerializer = keySerializer;
this.keyTypes = keyTypes;
this.valueSerializer = valueSerializer;
setIntValue(FREE_POINTER_OFFSET, MAX_PAGE_SIZE_BYTES);
setIntValue(SIZE_OFFSET, 0);
setByteValue(IS_LEAF_OFFSET, (byte) (isLeaf ? 1 : 0));
setLongValue(LEFT_SIBLING_OFFSET, -1);
setLongValue(RIGHT_SIBLING_OFFSET, -1);
setLongValue(TREE_SIZE_OFFSET, 0);
setLongValue(FREE_VALUES_LIST_OFFSET, -1);
setByteValue(KEY_SERIALIZER_OFFSET, (byte) -1);
setByteValue(VALUE_SERIALIZER_OFFSET, (byte) -1);
}
public OSBTreeBucket(ODirectMemoryPointer cachePointer, OBinarySerializer<K> keySerializer, OType[] keyTypes,
OBinarySerializer<V> valueSerializer, TrackMode trackMode) {
super(cachePointer, trackMode);
this.keyTypes = keyTypes;
this.isLeaf = getByteValue(IS_LEAF_OFFSET) > 0;
this.keySerializer = keySerializer;
this.valueSerializer = valueSerializer;
}
public byte getKeySerializerId() {
return getByteValue(KEY_SERIALIZER_OFFSET);
}
public void setKeySerializerId(byte keySerializerId) {
setByteValue(KEY_SERIALIZER_OFFSET, keySerializerId);
}
public byte getValueSerializerId() {
return getByteValue(VALUE_SERIALIZER_OFFSET);
}
public void setValueSerializerId(byte valueSerializerId) {
setByteValue(VALUE_SERIALIZER_OFFSET, valueSerializerId);
}
public void setTreeSize(long size) throws IOException {
setLongValue(TREE_SIZE_OFFSET, size);
}
public long getTreeSize() {
return getLongValue(TREE_SIZE_OFFSET);
}
public boolean isEmpty() {
return size() == 0;
}
public long getValuesFreeListFirstIndex() {
return getLongValue(FREE_VALUES_LIST_OFFSET);
}
public void setValuesFreeListFirstIndex(long pageIndex) throws IOException {
setLongValue(FREE_VALUES_LIST_OFFSET, pageIndex);
}
public int find(K key) {
int low = 0;
int high = size() - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
K midVal = getKey(mid);
int cmp = comparator.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
public long remove(int entryIndex) throws IOException {
int entryPosition = getIntValue(POSITIONS_ARRAY_OFFSET + entryIndex * OIntegerSerializer.INT_SIZE);
int keySize = keySerializer.getObjectSizeInDirectMemory(pagePointer, entryPosition);
int entrySize;
long linkValue = -1;
if (isLeaf) {
if (valueSerializer.isFixedLength()) {
entrySize = keySize + valueSerializer.getFixedLength() + OByteSerializer.BYTE_SIZE;
} else {
final boolean isLink = pagePointer.getByte(entryPosition + keySize) > 0;
if (!isLink)
entrySize = keySize
+ valueSerializer.getObjectSizeInDirectMemory(pagePointer, entryPosition + keySize + OByteSerializer.BYTE_SIZE)
+ OByteSerializer.BYTE_SIZE;
else {
entrySize = keySize + OByteSerializer.BYTE_SIZE + OLongSerializer.LONG_SIZE;
linkValue = OLongSerializer.INSTANCE.deserializeFromDirectMemory(pagePointer, entryPosition + keySize
+ OByteSerializer.BYTE_SIZE);
}
}
} else {
throw new IllegalStateException("Remove is applies to leaf buckets only");
}
int size = size();
if (entryIndex < size - 1) {
moveData(POSITIONS_ARRAY_OFFSET + (entryIndex + 1) * OIntegerSerializer.INT_SIZE, POSITIONS_ARRAY_OFFSET + entryIndex
* OIntegerSerializer.INT_SIZE, (size - entryIndex - 1) * OIntegerSerializer.INT_SIZE);
}
size--;
setIntValue(SIZE_OFFSET, size);
int freePointer = getIntValue(FREE_POINTER_OFFSET);
if (size > 0 && entryPosition > freePointer) {
moveData(freePointer, freePointer + entrySize, entryPosition - freePointer);
}
setIntValue(FREE_POINTER_OFFSET, freePointer + entrySize);
int currentPositionOffset = POSITIONS_ARRAY_OFFSET;
for (int i = 0; i < size; i++) {
int currentEntryPosition = getIntValue(currentPositionOffset);
if (currentEntryPosition < entryPosition)
setIntValue(currentPositionOffset, currentEntryPosition + entrySize);
currentPositionOffset += OIntegerSerializer.INT_SIZE;
}
return linkValue;
}
public int size() {
return getIntValue(SIZE_OFFSET);
}
public SBTreeEntry<K, V> getEntry(int entryIndex) {
int entryPosition = getIntValue(entryIndex * OIntegerSerializer.INT_SIZE + POSITIONS_ARRAY_OFFSET);
if (isLeaf) {
K key = keySerializer.deserializeFromDirectMemory(pagePointer, entryPosition);
entryPosition += keySerializer.getObjectSizeInDirectMemory(pagePointer, entryPosition);
boolean isLinkValue = pagePointer.getByte(entryPosition) > 0;
long link = -1;
V value = null;
if (isLinkValue)
link = OLongSerializer.INSTANCE.deserializeFromDirectMemory(pagePointer, entryPosition + OByteSerializer.BYTE_SIZE);
else
value = valueSerializer.deserializeFromDirectMemory(pagePointer, entryPosition + OByteSerializer.BYTE_SIZE);
return new SBTreeEntry<K, V>(-1, -1, key, new OSBTreeValue<V>(link >= 0, link, value));
} else {
long leftChild = getLongValue(entryPosition);
entryPosition += OLongSerializer.LONG_SIZE;
long rightChild = getLongValue(entryPosition);
entryPosition += OLongSerializer.LONG_SIZE;
K key = keySerializer.deserializeFromDirectMemory(pagePointer, entryPosition);
return new SBTreeEntry<K, V>(leftChild, rightChild, key, null);
}
}
public K getKey(int index) {
int entryPosition = getIntValue(index * OIntegerSerializer.INT_SIZE + POSITIONS_ARRAY_OFFSET);
if (!isLeaf)
entryPosition += 2 * OLongSerializer.LONG_SIZE;
return keySerializer.deserializeFromDirectMemory(pagePointer, entryPosition);
}
public boolean isLeaf() {
return isLeaf;
}
public void addAll(List<SBTreeEntry<K, V>> entries) throws IOException {
for (int i = 0; i < entries.size(); i++)
addEntry(i, entries.get(i), false);
}
public void shrink(int newSize) throws IOException {
List<SBTreeEntry<K, V>> treeEntries = new ArrayList<SBTreeEntry<K, V>>(newSize);
for (int i = 0; i < newSize; i++) {
treeEntries.add(getEntry(i));
}
setIntValue(FREE_POINTER_OFFSET, MAX_PAGE_SIZE_BYTES);
setIntValue(SIZE_OFFSET, 0);
int index = 0;
for (SBTreeEntry<K, V> entry : treeEntries) {
addEntry(index, entry, false);
index++;
}
}
public boolean addEntry(int index, SBTreeEntry<K, V> treeEntry, boolean updateNeighbors) throws IOException {
final int keySize = keySerializer.getObjectSize(treeEntry.key, (Object[]) keyTypes);
int valueSize = 0;
int entrySize = keySize;
if (isLeaf) {
if (valueSerializer.isFixedLength())
valueSize = valueSerializer.getFixedLength();
else {
if (treeEntry.value.isLink())
valueSize = OLongSerializer.LONG_SIZE;
else
valueSize = valueSerializer.getObjectSize(treeEntry.value.getValue());
}
entrySize += valueSize + OByteSerializer.BYTE_SIZE;
} else
entrySize += 2 * OLongSerializer.LONG_SIZE;
int size = size();
int freePointer = getIntValue(FREE_POINTER_OFFSET);
if (freePointer - entrySize < (size + 1) * OIntegerSerializer.INT_SIZE + POSITIONS_ARRAY_OFFSET)
return false;
if (index <= size - 1) {
moveData(POSITIONS_ARRAY_OFFSET + index * OIntegerSerializer.INT_SIZE, POSITIONS_ARRAY_OFFSET + (index + 1)
* OIntegerSerializer.INT_SIZE, (size - index) * OIntegerSerializer.INT_SIZE);
}
freePointer -= entrySize;
setIntValue(FREE_POINTER_OFFSET, freePointer);
setIntValue(POSITIONS_ARRAY_OFFSET + index * OIntegerSerializer.INT_SIZE, freePointer);
setIntValue(SIZE_OFFSET, size + 1);
if (isLeaf) {
byte[] serializedKey = new byte[keySize];
keySerializer.serializeNative(treeEntry.key, serializedKey, 0, (Object[]) keyTypes);
setBinaryValue(freePointer, serializedKey);
freePointer += keySize;
setByteValue(freePointer, treeEntry.value.isLink() ? (byte) 1 : (byte) 0);
freePointer += OByteSerializer.BYTE_SIZE;
byte[] serializedValue = new byte[valueSize];
if (treeEntry.value.isLink())
OLongSerializer.INSTANCE.serializeNative(treeEntry.value.getLink(), serializedValue, 0);
else
valueSerializer.serializeNative(treeEntry.value.getValue(), serializedValue, 0);
setBinaryValue(freePointer, serializedValue);
} else {
setLongValue(freePointer, treeEntry.leftChild);
freePointer += OLongSerializer.LONG_SIZE;
setLongValue(freePointer, treeEntry.rightChild);
freePointer += OLongSerializer.LONG_SIZE;
byte[] serializedKey = new byte[keySize];
keySerializer.serializeNative(treeEntry.key, serializedKey, 0, (Object[]) keyTypes);
setBinaryValue(freePointer, serializedKey);
size++;
if (updateNeighbors && size > 1) {
if (index < size - 1) {
final int nextEntryPosition = getIntValue(POSITIONS_ARRAY_OFFSET + (index + 1) * OIntegerSerializer.INT_SIZE);
setLongValue(nextEntryPosition, treeEntry.rightChild);
}
if (index > 0) {
final int prevEntryPosition = getIntValue(POSITIONS_ARRAY_OFFSET + (index - 1) * OIntegerSerializer.INT_SIZE);
setLongValue(prevEntryPosition + OLongSerializer.LONG_SIZE, treeEntry.leftChild);
}
}
}
return true;
}
public int updateValue(int index, OSBTreeValue<V> value) throws IOException {
int entryPosition = getIntValue(index * OIntegerSerializer.INT_SIZE + POSITIONS_ARRAY_OFFSET);
entryPosition += keySerializer.getObjectSizeInDirectMemory(pagePointer, entryPosition) + OByteSerializer.BYTE_SIZE;
final int newSize = valueSerializer.getObjectSize(value.getValue());
final int oldSize = valueSerializer.getObjectSizeInDirectMemory(pagePointer, entryPosition);
if (newSize != oldSize)
return -1;
byte[] serializedValue = new byte[newSize];
valueSerializer.serializeNative(value.getValue(), serializedValue, 0);
byte[] oldSerializedValue = pagePointer.get(entryPosition, oldSize);
if (ODefaultComparator.INSTANCE.compare(oldSerializedValue, serializedValue) == 0)
return 0;
setBinaryValue(entryPosition, serializedValue);
return 1;
}
public void setLeftSibling(long pageIndex) throws IOException {
setLongValue(LEFT_SIBLING_OFFSET, pageIndex);
}
public long getLeftSibling() {
return getLongValue(LEFT_SIBLING_OFFSET);
}
public void setRightSibling(long pageIndex) throws IOException {
setLongValue(RIGHT_SIBLING_OFFSET, pageIndex);
}
public long getRightSibling() {
return getLongValue(RIGHT_SIBLING_OFFSET);
}
public static final class SBTreeEntry<K, V> implements Comparable<SBTreeEntry<K, V>> {
private final Comparator<? super K> comparator = ODefaultComparator.INSTANCE;
public final long leftChild;
public final long rightChild;
public final K key;
public final OSBTreeValue<V> value;
public SBTreeEntry(long leftChild, long rightChild, K key, OSBTreeValue<V> value) {
this.leftChild = leftChild;
this.rightChild = rightChild;
this.key = key;
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final SBTreeEntry<?, ?> that = (SBTreeEntry<?, ?>) o;
if (leftChild != that.leftChild)
return false;
if (rightChild != that.rightChild)
return false;
if (!key.equals(that.key))
return false;
if (value != null ? !value.equals(that.value) : that.value != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (leftChild ^ (leftChild >>> 32));
result = 31 * result + (int) (rightChild ^ (rightChild >>> 32));
result = 31 * result + key.hashCode();
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "SBTreeEntry{" + "leftChild=" + leftChild + ", rightChild=" + rightChild + ", key=" + key + ", value=" + value + '}';
}
@Override
public int compareTo(SBTreeEntry<K, V> other) {
return comparator.compare(key, other.key);
}
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_index_sbtree_local_OSBTreeBucket.java
|
126 |
@Service("blPageService")
public class PageServiceImpl extends AbstractContentService implements PageService, SandBoxItemListener {
protected static final Log LOG = LogFactory.getLog(PageServiceImpl.class);
protected static String AND = " && ";
@Resource(name="blPageDao")
protected PageDao pageDao;
@Resource(name="blSandBoxItemDao")
protected SandBoxItemDao sandBoxItemDao;
@Resource(name="blSandBoxDao")
protected SandBoxDao sandBoxDao;
@Resource(name="blPageRuleProcessors")
protected List<PageRuleProcessor> pageRuleProcessors;
@Resource(name="blLocaleService")
protected LocaleService localeService;
@Resource(name="blStaticAssetService")
protected StaticAssetService staticAssetService;
@Value("${automatically.approve.pages}")
protected boolean automaticallyApproveAndPromotePages=true;
protected Cache pageCache;
protected List<ArchivedPagePublisher> archivedPageListeners;
protected final PageDTO NULL_PAGE = new NullPageDTO();
protected final List<PageDTO> EMPTY_PAGE_DTO = new ArrayList<PageDTO>();
/**
* Returns the page with the passed in id.
*
* @param pageId - The id of the page.
* @return The associated page.
*/
@Override
public Page findPageById(Long pageId) {
return pageDao.readPageById(pageId);
}
@Override
public PageTemplate findPageTemplateById(Long id) {
return pageDao.readPageTemplateById(id);
}
@Override
@Transactional("blTransactionManager")
public PageTemplate savePageTemplate(PageTemplate template) {
return pageDao.savePageTemplate(template);
}
/**
* Returns the page-fields associated with the passed in page-id.
* This is preferred over the direct access from Page so that the
* two items can be cached distinctly
*
* @param pageId - The id of the page.
* @return The associated page.
*/
@Override
public Map<String, PageField> findPageFieldsByPageId(Long pageId) {
Page page = findPageById(pageId);
return pageDao.readPageFieldsByPage(page);
}
/**
* This method is intended to be called from within the CMS
* admin only.
* <p/>
* Adds the passed in page to the DB.
* <p/>
*/
@Override
public Page addPage(Page page, SandBox destinationSandbox) {
if (automaticallyApproveAndPromotePages) {
if (destinationSandbox != null && destinationSandbox.getSite() != null) {
destinationSandbox = destinationSandbox.getSite().getProductionSandbox();
} else {
// Null means production for single-site installations.
destinationSandbox = null;
}
}
page.setSandbox(destinationSandbox);
page.setArchivedFlag(false);
page.setDeletedFlag(false);
Page newPage = pageDao.addPage(page);
if (! isProductionSandBox(destinationSandbox)) {
sandBoxItemDao.addSandBoxItem(destinationSandbox.getId(), SandBoxOperationType.ADD, SandBoxItemType.PAGE, newPage.getFullUrl(), newPage.getId(), null);
}
return newPage;
}
/**
* This method is intended to be called from within the CMS
* admin only.
* <p/>
* Updates the page according to the following rules:
* <p/>
* 1. If sandbox has changed from null to a value
* This means that the user is editing an item in production and
* the edit is taking place in a sandbox.
* <p/>
* Clone the page and add it to the new sandbox and set the cloned
* page's originalPageId to the id of the page being updated.
* <p/>
* 2. If the sandbox has changed from one value to another
* This means that the user is moving the item from one sandbox
* to another.
* <p/>
* Update the siteId for the page to the one associated with the
* new sandbox
* <p/>
* 3. If the sandbox has changed from a value to null
* This means that the item is moving from the sandbox to production.
* <p/>
* If the page has an originalPageId, then update that page by
* setting it's archived flag to true.
* <p/>
* Then, update the siteId of the page being updated to be the
* siteId of the original page.
* <p/>
* 4. If the sandbox is the same then just update the page.
*/
@Override
public Page updatePage(Page page, SandBox destSandbox) {
if (page.getLockedFlag()) {
throw new IllegalArgumentException("Unable to update a locked record");
}
if (automaticallyApproveAndPromotePages) {
if (destSandbox != null && destSandbox.getSite() != null) {
destSandbox = destSandbox.getSite().getProductionSandbox();
} else {
// Null means production for single-site installations.
destSandbox = null;
}
}
if (checkForSandboxMatch(page.getSandbox(), destSandbox)) {
if (page.getDeletedFlag()) {
SandBoxItem item = page.getSandbox()==null?null:sandBoxItemDao.retrieveBySandboxAndTemporaryItemId(page.getSandbox().getId(), SandBoxItemType.PAGE, page.getId());
if (page.getOriginalPageId() == null && item != null) {
// This page was added in this sandbox and now needs to be deleted.
item.setArchivedFlag(true);
page.setArchivedFlag(true);
} else if (item != null) {
// This page was being updated but now is being deleted - so change the
// sandbox operation type to deleted
item.setSandBoxOperationType(SandBoxOperationType.DELETE);
sandBoxItemDao.updateSandBoxItem(item);
} else if (automaticallyApproveAndPromotePages) {
page.setArchivedFlag(true);
}
}
return pageDao.updatePage(page);
} else if (isProductionSandBox(page.getSandbox())) {
// The passed in page is an existing page with updated values.
// Instead, we want to create a clone of this page for the destSandbox
Page clonedPage = page.cloneEntity();
clonedPage.setOriginalPageId(page.getId());
clonedPage.setSandbox(destSandbox);
// Detach the old page from the session so it is not updated.
pageDao.detachPage(page);
// Save the cloned page
Page returnPage = pageDao.addPage(clonedPage);
// Lookup the original page and mark it as locked
Page prod = findPageById(page.getId());
prod.setLockedFlag(true);
pageDao.updatePage(prod);
SandBoxOperationType type = SandBoxOperationType.UPDATE;
if (clonedPage.getDeletedFlag()) {
type = SandBoxOperationType.DELETE;
}
// Add this item to the sandbox.
sandBoxItemDao.addSandBoxItem(destSandbox.getId(), type, SandBoxItemType.PAGE, clonedPage.getFullUrl(), returnPage.getId(), returnPage.getOriginalPageId());
return returnPage;
} else {
// This should happen via a promote, revert, or reject in the sandbox service
throw new IllegalArgumentException("Update called when promote or reject was expected.");
}
}
// Returns true if the src and dest sandbox are the same.
protected boolean checkForSandboxMatch(SandBox src, SandBox dest) {
if (src != null) {
if (dest != null) {
return src.getId().equals(dest.getId());
}
}
return (src == null && dest == null);
}
// Returns true if the dest sandbox is production.
protected boolean isProductionSandBox(SandBox dest) {
if (dest == null) {
return true;
} else {
return SandBoxType.PRODUCTION.equals(dest.getSandBoxType());
}
}
/**
* If deleting and item where page.originalPageId != null
* then the item is deleted from the database.
* <p/>
* If the originalPageId is null, then this method marks
* the items as deleted within the passed in sandbox.
*
* @param page
* @param destinationSandbox
* @return
*/
@Override
public void deletePage(Page page, SandBox destinationSandbox) {
page.setDeletedFlag(true);
updatePage(page, destinationSandbox);
}
/**
* Converts a list of pages to a list of pageDTOs.<br>
* Internally calls buildPageDTO(...).
*
* @param pageList
* @param secure
* @return
*/
protected List<PageDTO> buildPageDTOList(List<Page> pageList, boolean secure) {
List<PageDTO> dtoList = new ArrayList<PageDTO>();
if (pageList != null) {
for(Page page : pageList) {
dtoList.add(buildPageDTOInternal(page, secure));
}
}
return dtoList;
}
protected PageDTO buildPageDTOInternal(Page page, boolean secure) {
PageDTO pageDTO = new PageDTO();
pageDTO.setId(page.getId());
pageDTO.setDescription(page.getDescription());
pageDTO.setUrl(page.getFullUrl());
pageDTO.setPriority(page.getPriority());
if (page.getSandbox() != null) {
pageDTO.setSandboxId(page.getSandbox().getId());
}
if (page.getPageTemplate() != null) {
pageDTO.setTemplatePath(page.getPageTemplate().getTemplatePath());
if (page.getPageTemplate().getLocale() != null) {
pageDTO.setLocaleCode(page.getPageTemplate().getLocale().getLocaleCode());
}
}
String envPrefix = staticAssetService.getStaticAssetEnvironmentUrlPrefix();
if (envPrefix != null && secure) {
envPrefix = staticAssetService.getStaticAssetEnvironmentSecureUrlPrefix();
}
String cmsPrefix = staticAssetService.getStaticAssetUrlPrefix();
for (String fieldKey : page.getPageFields().keySet()) {
PageField pf = page.getPageFields().get(fieldKey);
String originalValue = pf.getValue();
if (StringUtils.isNotBlank(envPrefix) && StringUtils.isNotBlank(originalValue) && StringUtils.isNotBlank(cmsPrefix) && originalValue.contains(cmsPrefix)) {
String fldValue = originalValue.replaceAll(cmsPrefix, envPrefix+cmsPrefix);
pageDTO.getPageFields().put(fieldKey, fldValue);
} else {
pageDTO.getPageFields().put(fieldKey, originalValue);
}
}
pageDTO.setRuleExpression(buildRuleExpression(page));
if (page.getQualifyingItemCriteria() != null && page.getQualifyingItemCriteria().size() > 0) {
pageDTO.setItemCriteriaDTOList(buildItemCriteriaDTOList(page));
}
return pageDTO;
}
protected String buildRuleExpression(Page page) {
StringBuffer ruleExpression = null;
Map<String, PageRule> ruleMap = page.getPageMatchRules();
if (ruleMap != null) {
for (String ruleKey : ruleMap.keySet()) {
if (ruleExpression == null) {
ruleExpression = new StringBuffer(ruleMap.get(ruleKey).getMatchRule());
} else {
ruleExpression.append(AND);
ruleExpression.append(ruleMap.get(ruleKey).getMatchRule());
}
}
}
if (ruleExpression != null) {
return ruleExpression.toString();
} else {
return null;
}
}
protected List<ItemCriteriaDTO> buildItemCriteriaDTOList(Page page) {
List<ItemCriteriaDTO> itemCriteriaDTOList = new ArrayList<ItemCriteriaDTO>();
for(PageItemCriteria criteria : page.getQualifyingItemCriteria()) {
ItemCriteriaDTO criteriaDTO = new ItemCriteriaDTO();
criteriaDTO.setMatchRule(criteria.getMatchRule());
criteriaDTO.setQty(criteria.getQuantity());
itemCriteriaDTOList.add(criteriaDTO);
}
return itemCriteriaDTOList;
}
protected List<PageDTO> mergePages(List<PageDTO> productionPageList, List<Page> sandboxPageList, boolean secure) {
if (sandboxPageList == null || sandboxPageList.size() == 0) {
return productionPageList;
}
Map<Long, PageDTO> pageMap = new LinkedHashMap<Long, PageDTO>();
if (productionPageList != null) {
for(PageDTO page : productionPageList) {
pageMap.put(page.getId(), page);
}
}
for (Page page : sandboxPageList) {
if (page.getOriginalPageId() != null) {
pageMap.remove(page.getOriginalPageId());
}
if (! page.getDeletedFlag() && page.getOfflineFlag() != null && ! page.getOfflineFlag()) {
PageDTO convertedPage = buildPageDTOInternal(page, secure);
pageMap.put(page.getId(), convertedPage);
}
}
ArrayList<PageDTO> returnList = new ArrayList<PageDTO>(pageMap.values());
if (returnList.size() > 1) {
Collections.sort(returnList, new BeanComparator("priority"));
}
return returnList;
}
protected PageDTO evaluatePageRules(List<PageDTO> pageDTOList, Locale locale, Map<String, Object> ruleDTOs) {
if (pageDTOList == null) {
return NULL_PAGE;
}
// First check to see if we have a page that matches on the full locale.
for(PageDTO page : pageDTOList) {
if (locale != null && locale.getLocaleCode() != null) {
if (page.getLocaleCode().equals(locale.getLocaleCode())) {
if (passesPageRules(page, ruleDTOs)) {
return page;
}
}
}
}
// Otherwise, we look for a match using just the language.
for(PageDTO page : pageDTOList) {
if (passesPageRules(page, ruleDTOs)) {
return page;
}
}
return NULL_PAGE;
}
protected boolean passesPageRules(PageDTO page, Map<String, Object> ruleDTOs) {
if (pageRuleProcessors != null) {
for (PageRuleProcessor processor : pageRuleProcessors) {
boolean matchFound = processor.checkForMatch(page, ruleDTOs);
if (! matchFound) {
return false;
}
}
}
return true;
}
protected Locale findLanguageOnlyLocale(Locale locale) {
if (locale != null ) {
Locale languageOnlyLocale = localeService.findLocaleByCode(LocaleUtil.findLanguageCode(locale));
if (languageOnlyLocale != null) {
return languageOnlyLocale;
}
}
return locale;
}
/**
* Retrieve the page if one is available for the passed in uri.
*/
@Override
public PageDTO findPageByURI(SandBox currentSandbox, Locale locale, String uri, Map<String,Object> ruleDTOs, boolean secure) {
List<PageDTO> returnList = null;
if (uri != null) {
SandBox productionSandbox = null;
if (currentSandbox != null && currentSandbox.getSite() != null) {
productionSandbox = currentSandbox.getSite().getProductionSandbox();
}
Locale languageOnlyLocale = findLanguageOnlyLocale(locale);
String key = buildKey(productionSandbox, locale, uri);
key = key + "-" + secure;
returnList = getPageListFromCache(key);
if (returnList == null) {
if (LOG.isTraceEnabled()) {
LOG.trace("Page not found in cache, searching DB for key: " + key);
}
List<Page> productionPages = pageDao.findPageByURI(productionSandbox, locale, languageOnlyLocale, uri);
if (productionPages != null) {
if (LOG.isTraceEnabled()) {
LOG.trace("Pages found, adding pages to cache with key: " + key);
}
returnList = buildPageDTOList(productionPages, secure);
Collections.sort(returnList, new BeanComparator("priority"));
addPageListToCache(returnList, key);
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("No match found for passed in URI, locale, and sandbox. Key = " + key);
}
addPageListToCache(EMPTY_PAGE_DTO, key);
}
}
// If the request is from a non-production SandBox, we need to check to see if the SandBox has an override
// for this page before returning. No caching is used for Sandbox pages.
if (currentSandbox != null && ! currentSandbox.getSandBoxType().equals(SandBoxType.PRODUCTION)) {
List<Page> sandboxPages = pageDao.findPageByURI(currentSandbox, locale, languageOnlyLocale, uri);
if (sandboxPages != null && sandboxPages.size() > 0) {
returnList = mergePages(returnList, sandboxPages, secure);
}
}
}
return evaluatePageRules(returnList, locale, ruleDTOs);
}
@Override
public List<Page> findPages(SandBox sandbox, Criteria c) {
return findItems(sandbox, c, Page.class, PageImpl.class, "originalPageId");
}
@Override
public List<Page> readAllPages() {
return pageDao.readAllPages();
}
@Override
public List<PageTemplate> readAllPageTemplates() {
return pageDao.readAllPageTemplates();
}
@Override
public Long countPages(SandBox sandbox, Criteria c) {
return countItems(sandbox, c, PageImpl.class, "originalPageId");
}
protected void productionItemArchived(Page page) {
// Immediately remove the page from this VM.
removePageFromCache(page);
if (archivedPageListeners != null) {
for (ArchivedPagePublisher listener : archivedPageListeners) {
listener.processPageArchive(page, buildKey(page));
}
}
}
@Override
public void itemPromoted(SandBoxItem sandBoxItem, SandBox destinationSandBox) {
if (! SandBoxItemType.PAGE.equals(sandBoxItem.getSandBoxItemType())) {
return;
}
Page page = pageDao.readPageById(sandBoxItem.getTemporaryItemId());
if (page == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Page not found " + sandBoxItem.getTemporaryItemId());
}
} else {
boolean productionSandBox = isProductionSandBox(destinationSandBox);
if (productionSandBox) {
page.setLockedFlag(false);
} else {
page.setLockedFlag(true);
}
if (productionSandBox && page.getOriginalPageId() != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Page promoted to production. " + page.getId() + ". Archiving original page " + page.getOriginalPageId());
}
Page originalPage = pageDao.readPageById(page.getOriginalPageId());
originalPage.setArchivedFlag(Boolean.TRUE);
pageDao.updatePage(originalPage);
productionItemArchived(originalPage);
// We are archiving the old page and making this the new "production page", so
// null out the original page id before saving.
page.setOriginalPageId(null);
if (page.getDeletedFlag()) {
// If this page is being deleted, set it as archived.
page.setArchivedFlag(true);
}
}
}
if (page.getOriginalSandBox() == null) {
page.setOriginalSandBox(page.getSandbox());
}
page.setSandbox(destinationSandBox);
pageDao.updatePage(page);
}
@Override
public void itemRejected(SandBoxItem sandBoxItem, SandBox destinationSandBox) {
if (! SandBoxItemType.PAGE.equals(sandBoxItem.getSandBoxItemType())) {
return;
}
Page page = pageDao.readPageById(sandBoxItem.getTemporaryItemId());
if (page != null) {
page.setSandbox(destinationSandBox);
page.setOriginalSandBox(null);
page.setLockedFlag(false);
pageDao.updatePage(page);
}
}
@Override
public void itemReverted(SandBoxItem sandBoxItem) {
if (! SandBoxItemType.PAGE.equals(sandBoxItem.getSandBoxItemType())) {
return;
}
Page page = pageDao.readPageById(sandBoxItem.getTemporaryItemId());
if (page != null) {
page.setArchivedFlag(Boolean.TRUE);
page.setLockedFlag(false);
pageDao.updatePage(page);
if (page.getOriginalPageId() != null) {
Page originalPage = pageDao.readPageById(page.getOriginalPageId());
originalPage.setLockedFlag(false);
pageDao.updatePage(originalPage);
}
}
}
protected Cache getPageCache() {
if (pageCache == null) {
pageCache = CacheManager.getInstance().getCache("cmsPageCache");
}
return pageCache;
}
protected String buildKey(SandBox currentSandbox, Locale locale, String uri) {
StringBuffer key = new StringBuffer(uri);
if (locale != null) {
key.append("-").append(locale.getLocaleCode());
}
if (currentSandbox != null) {
key.append("-").append(currentSandbox.getId());
}
return key.toString();
}
protected String buildKey(Page page) {
return buildKey(page.getSandbox(), page.getPageTemplate().getLocale(), page.getFullUrl());
}
protected void addPageListToCache(List<PageDTO> pageList, String key) {
getPageCache().put(new Element(key, pageList));
}
@SuppressWarnings("unchecked")
protected List<PageDTO> getPageListFromCache(String key) {
Element cacheElement = getPageCache().get(key);
if (cacheElement != null && cacheElement.getValue() != null) {
return (List<PageDTO>) cacheElement.getValue();
}
return null;
}
/**
* Call to evict an item from the cache.
* @param p
*/
public void removePageFromCache(Page p) {
// Remove secure and non-secure instances of the page.
// Typically the page will be in one or the other if at all.
removePageFromCache(buildKey(p));
}
/**
* Call to evict both secure and non-secure pages matching
* the passed in key.
*
* @param baseKey
*/
@Override
public void removePageFromCache(String baseKey) {
// Remove secure and non-secure instances of the page.
// Typically the page will be in one or the other if at all.
getPageCache().remove(baseKey+"-"+true);
getPageCache().remove(baseKey+"-"+false);
}
@Override
public List<ArchivedPagePublisher> getArchivedPageListeners() {
return archivedPageListeners;
}
@Override
public void setArchivedPageListeners(List<ArchivedPagePublisher> archivedPageListeners) {
this.archivedPageListeners = archivedPageListeners;
}
@Override
public boolean isAutomaticallyApproveAndPromotePages() {
return automaticallyApproveAndPromotePages;
}
@Override
public void setAutomaticallyApproveAndPromotePages(boolean automaticallyApproveAndPromotePages) {
this.automaticallyApproveAndPromotePages = automaticallyApproveAndPromotePages;
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_service_PageServiceImpl.java
|
195 |
public class MemoryLocker {
/**
* This method disables to using JNA installed in system. Instead of locally installed bundled JNA will be used.
*/
private static void disableUsingSystemJNA() {
if (System.getProperty("jna.nosys") == null || !System.getProperty("jna.nosys").equals("true")) {
System.setProperty("jna.nosys", "true");
}
}
/**
* This method locks memory to prevent swapping. This method provide information about success or problems with locking memory.
* You can reed console output to know if memory locked successfully or not. If system error occurred such as permission any
* specific exception will be thrown.
*
* @param useSystemJNADisabled
* if this parameter is true only bundled JNA will be used.
*/
public static void lockMemory(boolean useSystemJNADisabled) {
if (useSystemJNADisabled)
disableUsingSystemJNA();
try {
int errorCode = MemoryLockerLinux.INSTANCE.mlockall(MemoryLockerLinux.LOCK_CURRENT_MEMORY);
if (errorCode != 0) {
final String errorMessage;
int lastError = Native.getLastError();
switch (lastError) {
case MemoryLockerLinux.EPERM:
errorMessage = "The calling process does not have the appropriate privilege to perform the requested operation(EPERM).";
break;
case MemoryLockerLinux.EAGAIN:
errorMessage = "Some or all of the memory identified by the operation could not be locked when the call was made(EAGAIN).";
break;
case MemoryLockerLinux.ENOMEM:
errorMessage = "Unable to lock JVM memory. This can result in part of the JVM being swapped out, especially if mmapping of files enabled. Increase RLIMIT_MEMLOCK or run OrientDB server as root(ENOMEM).";
break;
case MemoryLockerLinux.EINVAL:
errorMessage = "The flags argument is zero, or includes unimplemented flags(EINVAL).";
break;
case MemoryLockerLinux.ENOSYS:
errorMessage = "The implementation does not support this memory locking interface(ENOSYS).";
break;
default:
errorMessage = "Unexpected exception with code " + lastError + ".";
break;
}
OLogManager.instance().config(null, "[MemoryLocker.lockMemory] Error occurred while locking memory: %s", errorMessage);
} else {
OLogManager.instance().info(null, "[MemoryLocker.lockMemory] Memory locked successfully!");
}
} catch (UnsatisfiedLinkError e) {
OLogManager.instance().config(null,
"[MemoryLocker.lockMemory] Cannot lock virtual memory. It seems that you OS (%s) doesn't support this feature",
System.getProperty("os.name"));
}
}
}
| 0true
|
nativeos_src_main_java_com_orientechnologies_nio_MemoryLocker.java
|
205 |
Callable<Object> response = new Callable<Object>() {
public Object call() throws Exception {
final OClusterPosition result;
try {
OStorageRemoteThreadLocal.INSTANCE.get().sessionId = sessionId;
beginResponse(network);
result = network.readClusterPosition();
if (network.getSrvProtocolVersion() >= 11)
network.readVersion();
} finally {
endResponse(network);
OStorageRemoteThreadLocal.INSTANCE.get().sessionId = -1;
}
iCallback.call(iRid, result);
return null;
}
};
| 0true
|
client_src_main_java_com_orientechnologies_orient_client_remote_OStorageRemote.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
|
678 |
public class TransportGetWarmersAction extends TransportClusterInfoAction<GetWarmersRequest, GetWarmersResponse> {
@Inject
public TransportGetWarmersAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool) {
super(settings, transportService, clusterService, threadPool);
}
@Override
protected String transportAction() {
return GetWarmersAction.NAME;
}
@Override
protected GetWarmersRequest newRequest() {
return new GetWarmersRequest();
}
@Override
protected GetWarmersResponse newResponse() {
return new GetWarmersResponse();
}
@Override
protected void doMasterOperation(final GetWarmersRequest request, final ClusterState state, final ActionListener<GetWarmersResponse> listener) throws ElasticsearchException {
ImmutableOpenMap<String, ImmutableList<IndexWarmersMetaData.Entry>> result = state.metaData().findWarmers(
request.indices(), request.types(), request.warmers()
);
listener.onResponse(new GetWarmersResponse(result));
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_admin_indices_warmer_get_TransportGetWarmersAction.java
|
127 |
public class ImportProposals {
static void addImportProposals(Tree.CompilationUnit cu, Node node,
Collection<ICompletionProposal> proposals, IFile file) {
if (node instanceof Tree.BaseMemberOrTypeExpression ||
node instanceof Tree.SimpleType) {
Node id = getIdentifyingNode(node);
String brokenName = id.getText();
Module module = cu.getUnit().getPackage().getModule();
for (Declaration decl:
findImportCandidates(module, brokenName, cu)) {
ICompletionProposal ip =
createImportProposal(cu, file, decl);
if (ip!=null) {
proposals.add(ip);
}
}
}
}
private static Set<Declaration> findImportCandidates(Module module,
String name, Tree.CompilationUnit cu) {
Set<Declaration> result = new HashSet<Declaration>();
for (Package pkg: module.getAllPackages()) {
if (!pkg.getName().isEmpty()) {
Declaration member =
pkg.getMember(name, null, false);
if (member!=null) {
result.add(member);
}
}
}
/*if (result.isEmpty()) {
for (Package pkg: module.getAllPackages()) {
for (Declaration member: pkg.getMembers()) {
if (!isImported(member, cu)) {
int dist = getLevenshteinDistance(name, member.getName());
//TODO: would it be better to just sort by dist, and
// then select the 3 closest possibilities?
if (dist<=name.length()/3+1) {
result.add(member);
}
}
}
}
}*/
return result;
}
private static ICompletionProposal createImportProposal(Tree.CompilationUnit cu,
IFile file, Declaration declaration) {
TextFileChange change =
new TextFileChange("Add Import", file);
IDocument doc = EditorUtil.getDocument(change);
List<InsertEdit> ies =
importEdits(cu, singleton(declaration),
null, null, doc);
if (ies.isEmpty()) return null;
change.setEdit(new MultiTextEdit());
for (InsertEdit ie: ies) {
change.addEdit(ie);
}
String proposedName = declaration.getName();
/*String brokenName = id.getText();
if (!brokenName.equals(proposedName)) {
change.addEdit(new ReplaceEdit(id.getStartIndex(), brokenName.length(),
proposedName));
}*/
String description = "Add import of '" + proposedName + "'" +
" in package '" + declaration.getUnit().getPackage().getNameAsString() + "'";
return new CorrectionProposal(description, change, null, IMPORT) {
@Override
public StyledString getStyledDisplayString() {
return Highlights.styleProposal(getDisplayString(), true);
}
};
}
public static List<InsertEdit> importEdits(Tree.CompilationUnit cu,
Iterable<Declaration> declarations, Iterable<String> aliases,
Declaration declarationBeingDeleted, IDocument doc) {
String delim = getDefaultLineDelimiter(doc);
List<InsertEdit> result = new ArrayList<InsertEdit>();
Set<Package> packages = new HashSet<Package>();
for (Declaration declaration: declarations) {
packages.add(declaration.getUnit().getPackage());
}
for (Package p: packages) {
StringBuilder text = new StringBuilder();
if (aliases==null) {
for (Declaration d: declarations) {
if (d.getUnit().getPackage().equals(p)) {
text.append(",")
.append(delim).append(getDefaultIndent())
.append(escapeName(d));
}
}
}
else {
Iterator<String> aliasIter = aliases.iterator();
for (Declaration d: declarations) {
String alias = aliasIter.next();
if (d.getUnit().getPackage().equals(p)) {
text.append(",")
.append(delim).append(getDefaultIndent());
if (alias!=null && !alias.equals(d.getName())) {
text.append(alias).append('=');
}
text.append(escapeName(d));
}
}
}
Tree.Import importNode =
findImportNode(cu, p.getNameAsString());
if (importNode!=null) {
Tree.ImportMemberOrTypeList imtl =
importNode.getImportMemberOrTypeList();
if (imtl.getImportWildcard()!=null) {
//Do nothing
}
else {
int insertPosition =
getBestImportMemberInsertPosition(importNode);
if (declarationBeingDeleted!=null &&
imtl.getImportMemberOrTypes().size()==1 &&
imtl.getImportMemberOrTypes().get(0).getDeclarationModel()
.equals(declarationBeingDeleted)) {
text.delete(0, 2);
}
result.add(new InsertEdit(insertPosition,
text.toString()));
}
}
else {
int insertPosition =
getBestImportInsertPosition(cu);
text.delete(0, 2);
text.insert(0, "import " + escapePackageName(p) + " {" + delim)
.append(delim + "}");
if (insertPosition==0) {
text.append(delim);
}
else {
text.insert(0, delim);
}
result.add(new InsertEdit(insertPosition,
text.toString()));
}
}
return result;
}
public static List<TextEdit> importEditForMove(Tree.CompilationUnit cu,
Iterable<Declaration> declarations, Iterable<String> aliases,
String newPackageName, String oldPackageName, IDocument doc) {
String delim = getDefaultLineDelimiter(doc);
List<TextEdit> result = new ArrayList<TextEdit>();
Set<Declaration> set = new HashSet<Declaration>();
for (Declaration d: declarations) {
set.add(d);
}
StringBuilder text = new StringBuilder();
if (aliases==null) {
for (Declaration d: declarations) {
text.append(",")
.append(delim).append(getDefaultIndent())
.append(d.getName());
}
}
else {
Iterator<String> aliasIter = aliases.iterator();
for (Declaration d: declarations) {
String alias = aliasIter.next();
text.append(",")
.append(delim).append(getDefaultIndent());
if (alias!=null && !alias.equals(d.getName())) {
text.append(alias).append('=');
}
text.append(d.getName());
}
}
Tree.Import oldImportNode = findImportNode(cu, oldPackageName);
if (oldImportNode!=null) {
Tree.ImportMemberOrTypeList imtl =
oldImportNode.getImportMemberOrTypeList();
if (imtl!=null) {
int remaining = 0;
for (Tree.ImportMemberOrType imt:
imtl.getImportMemberOrTypes()) {
if (!set.contains(imt.getDeclarationModel())) {
remaining++;
}
}
if (remaining==0) {
result.add(new DeleteEdit(oldImportNode.getStartIndex(),
oldImportNode.getStopIndex()-oldImportNode.getStartIndex()+1));
}
else {
//TODO: format it better!!!!
StringBuilder sb = new StringBuilder("{").append(delim);
for (Tree.ImportMemberOrType imt:
imtl.getImportMemberOrTypes()) {
if (!set.contains(imt.getDeclarationModel())) {
sb.append(getDefaultIndent());
if (imt.getAlias()!=null) {
sb.append(imt.getAlias().getIdentifier().getText())
.append('=');
}
sb.append(imt.getIdentifier().getText())
.append(",")
.append(delim);
}
}
sb.setLength(sb.length()-2);
sb.append(delim).append("}");
result.add(new ReplaceEdit(imtl.getStartIndex(),
imtl.getStopIndex()-imtl.getStartIndex()+1,
sb.toString()));
}
}
}
if (!cu.getUnit().getPackage().getQualifiedNameString()
.equals(newPackageName)) {
Tree.Import importNode = findImportNode(cu, newPackageName);
if (importNode!=null) {
Tree.ImportMemberOrTypeList imtl =
importNode.getImportMemberOrTypeList();
if (imtl.getImportWildcard()!=null) {
//Do nothing
}
else {
int insertPosition =
getBestImportMemberInsertPosition(importNode);
result.add(new InsertEdit(insertPosition, text.toString()));
}
}
else {
int insertPosition = getBestImportInsertPosition(cu);
text.delete(0, 2);
text.insert(0, "import " + newPackageName + " {" + delim)
.append(delim + "}");
if (insertPosition==0) {
text.append(delim);
}
else {
text.insert(0, delim);
}
result.add(new InsertEdit(insertPosition, text.toString()));
}
}
return result;
}
private static int getBestImportInsertPosition(Tree.CompilationUnit cu) {
Integer stopIndex = cu.getImportList().getStopIndex();
if (stopIndex == null) return 0;
return stopIndex+1;
}
public static Tree.Import findImportNode(Tree.CompilationUnit cu,
String packageName) {
FindImportNodeVisitor visitor =
new FindImportNodeVisitor(packageName);
cu.visit(visitor);
return visitor.getResult();
}
private static int getBestImportMemberInsertPosition(Tree.Import importNode) {
Tree.ImportMemberOrTypeList imtl =
importNode.getImportMemberOrTypeList();
if (imtl.getImportWildcard()!=null) {
return imtl.getImportWildcard().getStartIndex();
}
else {
List<Tree.ImportMemberOrType> imts =
imtl.getImportMemberOrTypes();
if (imts.isEmpty()) {
return imtl.getStartIndex()+1;
}
else {
return imts.get(imts.size()-1).getStopIndex()+1;
}
}
}
public static int applyImports(TextChange change,
Set<Declaration> declarations,
Tree.CompilationUnit cu, IDocument doc) {
return applyImports(change, declarations, null, cu, doc);
}
public static int applyImports(TextChange change,
Set<Declaration> declarations,
Declaration declarationBeingDeleted,
Tree.CompilationUnit cu, IDocument doc) {
int il=0;
for (InsertEdit ie:
importEdits(cu, declarations, null,
declarationBeingDeleted, doc)) {
il+=ie.getText().length();
change.addEdit(ie);
}
return il;
}
public static int applyImports(TextChange change,
Map<Declaration,String> declarations,
Tree.CompilationUnit cu, IDocument doc,
Declaration declarationBeingDeleted) {
int il=0;
for (InsertEdit ie:
importEdits(cu, declarations.keySet(),
declarations.values(),
declarationBeingDeleted, doc)) {
il+=ie.getText().length();
change.addEdit(ie);
}
return il;
}
public static void importSignatureTypes(Declaration declaration,
Tree.CompilationUnit rootNode, Set<Declaration> declarations) {
if (declaration instanceof TypedDeclaration) {
importType(declarations,
((TypedDeclaration) declaration).getType(),
rootNode);
}
if (declaration instanceof Functional) {
for (ParameterList pl:
((Functional) declaration).getParameterLists()) {
for (Parameter p: pl.getParameters()) {
importSignatureTypes(p.getModel(),
rootNode, declarations);
}
}
}
}
public static void importTypes(Set<Declaration> declarations,
Collection<ProducedType> types,
Tree.CompilationUnit rootNode) {
if (types==null) return;
for (ProducedType type: types) {
importType(declarations, type, rootNode);
}
}
public static void importType(Set<Declaration> declarations,
ProducedType type,
Tree.CompilationUnit rootNode) {
if (type==null) return;
if (type.getDeclaration() instanceof UnionType) {
for (ProducedType t:
type.getDeclaration().getCaseTypes()) {
importType(declarations, t, rootNode);
}
}
else if (type.getDeclaration() instanceof IntersectionType) {
for (ProducedType t:
type.getDeclaration().getSatisfiedTypes()) {
importType(declarations, t, rootNode);
}
}
else {
importType(declarations, type.getQualifyingType(), rootNode);
TypeDeclaration td = type.getDeclaration();
if (td instanceof ClassOrInterface &&
td.isToplevel()) {
importDeclaration(declarations, td, rootNode);
for (ProducedType arg: type.getTypeArgumentList()) {
importType(declarations, arg, rootNode);
}
}
}
}
public static void importDeclaration(Set<Declaration> declarations,
Declaration declaration, Tree.CompilationUnit rootNode) {
if (!declaration.isParameter()) {
Package p = declaration.getUnit().getPackage();
if (!p.getNameAsString().isEmpty() &&
!p.equals(rootNode.getUnit().getPackage()) &&
!p.getNameAsString().equals(Module.LANGUAGE_MODULE_NAME) &&
(!declaration.isClassOrInterfaceMember() ||
declaration.isStaticallyImportable())) {
if (!isImported(declaration, rootNode)) {
declarations.add(declaration);
}
}
}
}
public static boolean isImported(Declaration declaration,
Tree.CompilationUnit rootNode) {
for (Import i: rootNode.getUnit().getImports()) {
if (i.getDeclaration().equals(getAbstraction(declaration))) {
return true;
}
}
return false;
}
public static void importCallableParameterParamTypes(Declaration declaration,
HashSet<Declaration> decs, Tree.CompilationUnit cu) {
if (declaration instanceof Functional) {
List<ParameterList> pls =
((Functional) declaration).getParameterLists();
if (!pls.isEmpty()) {
for (Parameter p: pls.get(0).getParameters()) {
MethodOrValue pm = p.getModel();
importParameterTypes(pm, cu, decs);
}
}
}
}
public static void importParameterTypes(Declaration pm,
Tree.CompilationUnit cu, HashSet<Declaration> decs) {
if (pm instanceof Method) {
for (ParameterList ppl: ((Method) pm).getParameterLists()) {
for (Parameter pp: ppl.getParameters()) {
importSignatureTypes(pp.getModel(), cu, decs);
}
}
}
}
}
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ImportProposals.java
|
74 |
@SuppressWarnings("serial")
static final class MapReduceKeysToDoubleTask<K,V>
extends BulkTask<K,V,Double> {
final ObjectToDouble<? super K> transformer;
final DoubleByDoubleToDouble reducer;
final double basis;
double result;
MapReduceKeysToDoubleTask<K,V> rights, nextRight;
MapReduceKeysToDoubleTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceKeysToDoubleTask<K,V> nextRight,
ObjectToDouble<? super K> transformer,
double basis,
DoubleByDoubleToDouble reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Double getRawResult() { return result; }
public final void compute() {
final ObjectToDouble<? super K> transformer;
final DoubleByDoubleToDouble reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
double r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceKeysToDoubleTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.apply(r, transformer.apply(p.key));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
t = (MapReduceKeysToDoubleTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.apply(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
3,447 |
public class FsIndexShardGateway extends BlobStoreIndexShardGateway {
private final boolean snapshotLock;
@Inject
public FsIndexShardGateway(ShardId shardId, @IndexSettings Settings indexSettings, ThreadPool threadPool, IndexGateway fsIndexGateway,
IndexShard indexShard, Store store) {
super(shardId, indexSettings, threadPool, fsIndexGateway, indexShard, store);
this.snapshotLock = indexSettings.getAsBoolean("gateway.fs.snapshot_lock", true);
}
@Override
public String type() {
return "fs";
}
@Override
public SnapshotLock obtainSnapshotLock() throws Exception {
if (!snapshotLock) {
return NO_SNAPSHOT_LOCK;
}
AbstractFsBlobContainer fsBlobContainer = (AbstractFsBlobContainer) blobContainer;
NativeFSLockFactory lockFactory = new NativeFSLockFactory(fsBlobContainer.filePath());
Lock lock = lockFactory.makeLock("snapshot.lock");
boolean obtained = lock.obtain();
if (!obtained) {
throw new ElasticsearchIllegalStateException("failed to obtain snapshot lock [" + lock + "]");
}
return new FsSnapshotLock(lock);
}
public class FsSnapshotLock implements SnapshotLock {
private final Lock lock;
public FsSnapshotLock(Lock lock) {
this.lock = lock;
}
@Override
public void release() {
try {
lock.release();
} catch (IOException e) {
logger.warn("failed to release snapshot lock [{}]", e, lock);
}
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_gateway_fs_FsIndexShardGateway.java
|
2,924 |
public class IndexImpl implements Index {
public static final NullObject NULL = new NullObject();
// indexKey -- indexValue
private final ConcurrentMap<Data, Comparable> recordValues = new ConcurrentHashMap<Data, Comparable>(1000);
private final IndexStore indexStore;
private final String attribute;
private final boolean ordered;
private volatile AttributeType attributeType;
public IndexImpl(String attribute, boolean ordered) {
this.attribute = attribute;
this.ordered = ordered;
indexStore = (ordered) ? new SortedIndexStore() : new UnsortedIndexStore();
}
@Override
public void removeEntryIndex(Data indexKey) {
Comparable oldValue = recordValues.remove(indexKey);
if (oldValue != null) {
indexStore.removeIndex(oldValue, indexKey);
}
}
@Override
public void clear() {
recordValues.clear();
indexStore.clear();
}
ConcurrentMap<Data, QueryableEntry> getRecordMap(Comparable indexValue) {
return indexStore.getRecordMap(indexValue);
}
@Override
public void saveEntryIndex(QueryableEntry e) throws QueryException {
Data key = e.getIndexKey();
Comparable oldValue = recordValues.remove(key);
Comparable newValue = e.getAttribute(attribute);
if (newValue == null) {
newValue = NULL;
}
recordValues.put(key, newValue);
if (newValue.getClass().isEnum()) {
newValue = TypeConverters.ENUM_CONVERTER.convert(newValue);
}
if (oldValue == null) {
// new
indexStore.newIndex(newValue, e);
} else {
// update
indexStore.removeIndex(oldValue, key);
indexStore.newIndex(newValue, e);
}
if (attributeType == null) {
attributeType = e.getAttributeType(attribute);
}
}
@Override
public Set<QueryableEntry> getRecords(Comparable[] values) {
if (values.length == 1) {
return indexStore.getRecords(convert(values[0]));
} else {
Set<Comparable> convertedValues = new HashSet<Comparable>(values.length);
for (Comparable value : values) {
convertedValues.add(convert(value));
}
MultiResultSet results = new MultiResultSet();
indexStore.getRecords(results, convertedValues);
return results;
}
}
@Override
public Set<QueryableEntry> getRecords(Comparable value) {
return indexStore.getRecords(convert(value));
}
@Override
public Set<QueryableEntry> getSubRecordsBetween(Comparable from, Comparable to) {
MultiResultSet results = new MultiResultSet();
indexStore.getSubRecordsBetween(results, convert(from), convert(to));
return results;
}
@Override
public Set<QueryableEntry> getSubRecords(ComparisonType comparisonType, Comparable searchedValue) {
MultiResultSet results = new MultiResultSet();
indexStore.getSubRecords(results, comparisonType, convert(searchedValue));
return results;
}
private Comparable convert(Comparable value) {
if (attributeType == null) {
return value;
}
return attributeType.getConverter().convert(value);
}
public ConcurrentMap<Data, Comparable> getRecordValues() {
return recordValues;
}
@Override
public String getAttributeName() {
return attribute;
}
@Override
public boolean isOrdered() {
return ordered;
}
public static final class NullObject implements Comparable {
@Override
public int compareTo(Object o) {
if (o == this || o instanceof NullObject) {
return 0;
}
return -1;
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return true;
}
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_query_impl_IndexImpl.java
|
363 |
public static class TestCollator
implements Collator<Map.Entry<String, Integer>, Integer> {
@Override
public Integer collate(Iterable<Map.Entry<String, Integer>> values) {
int sum = 0;
for (Map.Entry<String, Integer> entry : values) {
sum += entry.getValue();
}
return sum;
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_ClientMapReduceTest.java
|
184 |
public class Phaser {
/*
* This class implements an extension of X10 "clocks". Thanks to
* Vijay Saraswat for the idea, and to Vivek Sarkar for
* enhancements to extend functionality.
*/
/**
* Primary state representation, holding four bit-fields:
*
* unarrived -- the number of parties yet to hit barrier (bits 0-15)
* parties -- the number of parties to wait (bits 16-31)
* phase -- the generation of the barrier (bits 32-62)
* terminated -- set if barrier is terminated (bit 63 / sign)
*
* Except that a phaser with no registered parties is
* distinguished by the otherwise illegal state of having zero
* parties and one unarrived parties (encoded as EMPTY below).
*
* To efficiently maintain atomicity, these values are packed into
* a single (atomic) long. Good performance relies on keeping
* state decoding and encoding simple, and keeping race windows
* short.
*
* All state updates are performed via CAS except initial
* registration of a sub-phaser (i.e., one with a non-null
* parent). In this (relatively rare) case, we use built-in
* synchronization to lock while first registering with its
* parent.
*
* The phase of a subphaser is allowed to lag that of its
* ancestors until it is actually accessed -- see method
* reconcileState.
*/
private volatile long state;
private static final int MAX_PARTIES = 0xffff;
private static final int MAX_PHASE = Integer.MAX_VALUE;
private static final int PARTIES_SHIFT = 16;
private static final int PHASE_SHIFT = 32;
private static final int UNARRIVED_MASK = 0xffff; // to mask ints
private static final long PARTIES_MASK = 0xffff0000L; // to mask longs
private static final long COUNTS_MASK = 0xffffffffL;
private static final long TERMINATION_BIT = 1L << 63;
// some special values
private static final int ONE_ARRIVAL = 1;
private static final int ONE_PARTY = 1 << PARTIES_SHIFT;
private static final int ONE_DEREGISTER = ONE_ARRIVAL|ONE_PARTY;
private static final int EMPTY = 1;
// The following unpacking methods are usually manually inlined
private static int unarrivedOf(long s) {
int counts = (int)s;
return (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
}
private static int partiesOf(long s) {
return (int)s >>> PARTIES_SHIFT;
}
private static int phaseOf(long s) {
return (int)(s >>> PHASE_SHIFT);
}
private static int arrivedOf(long s) {
int counts = (int)s;
return (counts == EMPTY) ? 0 :
(counts >>> PARTIES_SHIFT) - (counts & UNARRIVED_MASK);
}
/**
* The parent of this phaser, or null if none
*/
private final Phaser parent;
/**
* The root of phaser tree. Equals this if not in a tree.
*/
private final Phaser root;
/**
* Heads of Treiber stacks for waiting threads. To eliminate
* contention when releasing some threads while adding others, we
* use two of them, alternating across even and odd phases.
* Subphasers share queues with root to speed up releases.
*/
private final AtomicReference<QNode> evenQ;
private final AtomicReference<QNode> oddQ;
private AtomicReference<QNode> queueFor(int phase) {
return ((phase & 1) == 0) ? evenQ : oddQ;
}
/**
* Returns message string for bounds exceptions on arrival.
*/
private String badArrive(long s) {
return "Attempted arrival of unregistered party for " +
stateToString(s);
}
/**
* Returns message string for bounds exceptions on registration.
*/
private String badRegister(long s) {
return "Attempt to register more than " +
MAX_PARTIES + " parties for " + stateToString(s);
}
/**
* Main implementation for methods arrive and arriveAndDeregister.
* Manually tuned to speed up and minimize race windows for the
* common case of just decrementing unarrived field.
*
* @param adjust value to subtract from state;
* ONE_ARRIVAL for arrive,
* ONE_DEREGISTER for arriveAndDeregister
*/
private int doArrive(int adjust) {
final Phaser root = this.root;
for (;;) {
long s = (root == this) ? state : reconcileState();
int phase = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
return phase;
int counts = (int)s;
int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
if (unarrived <= 0)
throw new IllegalStateException(badArrive(s));
if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adjust)) {
if (unarrived == 1) {
long n = s & PARTIES_MASK; // base of next state
int nextUnarrived = (int)n >>> PARTIES_SHIFT;
if (root == this) {
if (onAdvance(phase, nextUnarrived))
n |= TERMINATION_BIT;
else if (nextUnarrived == 0)
n |= EMPTY;
else
n |= nextUnarrived;
int nextPhase = (phase + 1) & MAX_PHASE;
n |= (long)nextPhase << PHASE_SHIFT;
UNSAFE.compareAndSwapLong(this, stateOffset, s, n);
releaseWaiters(phase);
}
else if (nextUnarrived == 0) { // propagate deregistration
phase = parent.doArrive(ONE_DEREGISTER);
UNSAFE.compareAndSwapLong(this, stateOffset,
s, s | EMPTY);
}
else
phase = parent.doArrive(ONE_ARRIVAL);
}
return phase;
}
}
}
/**
* Implementation of register, bulkRegister
*
* @param registrations number to add to both parties and
* unarrived fields. Must be greater than zero.
*/
private int doRegister(int registrations) {
// adjustment to state
long adjust = ((long)registrations << PARTIES_SHIFT) | registrations;
final Phaser parent = this.parent;
int phase;
for (;;) {
long s = (parent == null) ? state : reconcileState();
int counts = (int)s;
int parties = counts >>> PARTIES_SHIFT;
int unarrived = counts & UNARRIVED_MASK;
if (registrations > MAX_PARTIES - parties)
throw new IllegalStateException(badRegister(s));
phase = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
break;
if (counts != EMPTY) { // not 1st registration
if (parent == null || reconcileState() == s) {
if (unarrived == 0) // wait out advance
root.internalAwaitAdvance(phase, null);
else if (UNSAFE.compareAndSwapLong(this, stateOffset,
s, s + adjust))
break;
}
}
else if (parent == null) { // 1st root registration
long next = ((long)phase << PHASE_SHIFT) | adjust;
if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
break;
}
else {
synchronized (this) { // 1st sub registration
if (state == s) { // recheck under lock
phase = parent.doRegister(1);
if (phase < 0)
break;
// finish registration whenever parent registration
// succeeded, even when racing with termination,
// since these are part of the same "transaction".
while (!UNSAFE.compareAndSwapLong
(this, stateOffset, s,
((long)phase << PHASE_SHIFT) | adjust)) {
s = state;
phase = (int)(root.state >>> PHASE_SHIFT);
// assert (int)s == EMPTY;
}
break;
}
}
}
}
return phase;
}
/**
* Resolves lagged phase propagation from root if necessary.
* Reconciliation normally occurs when root has advanced but
* subphasers have not yet done so, in which case they must finish
* their own advance by setting unarrived to parties (or if
* parties is zero, resetting to unregistered EMPTY state).
*
* @return reconciled state
*/
private long reconcileState() {
final Phaser root = this.root;
long s = state;
if (root != this) {
int phase, p;
// CAS to root phase with current parties, tripping unarrived
while ((phase = (int)(root.state >>> PHASE_SHIFT)) !=
(int)(s >>> PHASE_SHIFT) &&
!UNSAFE.compareAndSwapLong
(this, stateOffset, s,
s = (((long)phase << PHASE_SHIFT) |
((phase < 0) ? (s & COUNTS_MASK) :
(((p = (int)s >>> PARTIES_SHIFT) == 0) ? EMPTY :
((s & PARTIES_MASK) | p))))))
s = state;
}
return s;
}
/**
* Creates a new phaser with no initially registered parties, no
* parent, and initial phase number 0. Any thread using this
* phaser will need to first register for it.
*/
public Phaser() {
this(null, 0);
}
/**
* Creates a new phaser with the given number of registered
* unarrived parties, no parent, and initial phase number 0.
*
* @param parties the number of parties required to advance to the
* next phase
* @throws IllegalArgumentException if parties less than zero
* or greater than the maximum number of parties supported
*/
public Phaser(int parties) {
this(null, parties);
}
/**
* Equivalent to {@link #Phaser(Phaser, int) Phaser(parent, 0)}.
*
* @param parent the parent phaser
*/
public Phaser(Phaser parent) {
this(parent, 0);
}
/**
* Creates a new phaser with the given parent and number of
* registered unarrived parties. When the given parent is non-null
* and the given number of parties is greater than zero, this
* child phaser is registered with its parent.
*
* @param parent the parent phaser
* @param parties the number of parties required to advance to the
* next phase
* @throws IllegalArgumentException if parties less than zero
* or greater than the maximum number of parties supported
*/
public Phaser(Phaser parent, int parties) {
if (parties >>> PARTIES_SHIFT != 0)
throw new IllegalArgumentException("Illegal number of parties");
int phase = 0;
this.parent = parent;
if (parent != null) {
final Phaser root = parent.root;
this.root = root;
this.evenQ = root.evenQ;
this.oddQ = root.oddQ;
if (parties != 0)
phase = parent.doRegister(1);
}
else {
this.root = this;
this.evenQ = new AtomicReference<QNode>();
this.oddQ = new AtomicReference<QNode>();
}
this.state = (parties == 0) ? (long)EMPTY :
((long)phase << PHASE_SHIFT) |
((long)parties << PARTIES_SHIFT) |
((long)parties);
}
/**
* Adds a new unarrived party to this phaser. If an ongoing
* invocation of {@link #onAdvance} is in progress, this method
* may await its completion before returning. If this phaser has
* a parent, and this phaser previously had no registered parties,
* this child phaser is also registered with its parent. If
* this phaser is terminated, the attempt to register has
* no effect, and a negative value is returned.
*
* @return the arrival phase number to which this registration
* applied. If this value is negative, then this phaser has
* terminated, in which case registration has no effect.
* @throws IllegalStateException if attempting to register more
* than the maximum supported number of parties
*/
public int register() {
return doRegister(1);
}
/**
* Adds the given number of new unarrived parties to this phaser.
* If an ongoing invocation of {@link #onAdvance} is in progress,
* this method may await its completion before returning. If this
* phaser has a parent, and the given number of parties is greater
* than zero, and this phaser previously had no registered
* parties, this child phaser is also registered with its parent.
* If this phaser is terminated, the attempt to register has no
* effect, and a negative value is returned.
*
* @param parties the number of additional parties required to
* advance to the next phase
* @return the arrival phase number to which this registration
* applied. If this value is negative, then this phaser has
* terminated, in which case registration has no effect.
* @throws IllegalStateException if attempting to register more
* than the maximum supported number of parties
* @throws IllegalArgumentException if {@code parties < 0}
*/
public int bulkRegister(int parties) {
if (parties < 0)
throw new IllegalArgumentException();
if (parties == 0)
return getPhase();
return doRegister(parties);
}
/**
* Arrives at this phaser, without waiting for others to arrive.
*
* <p>It is a usage error for an unregistered party to invoke this
* method. However, this error may result in an {@code
* IllegalStateException} only upon some subsequent operation on
* this phaser, if ever.
*
* @return the arrival phase number, or a negative value if terminated
* @throws IllegalStateException if not terminated and the number
* of unarrived parties would become negative
*/
public int arrive() {
return doArrive(ONE_ARRIVAL);
}
/**
* Arrives at this phaser and deregisters from it without waiting
* for others to arrive. Deregistration reduces the number of
* parties required to advance in future phases. If this phaser
* has a parent, and deregistration causes this phaser to have
* zero parties, this phaser is also deregistered from its parent.
*
* <p>It is a usage error for an unregistered party to invoke this
* method. However, this error may result in an {@code
* IllegalStateException} only upon some subsequent operation on
* this phaser, if ever.
*
* @return the arrival phase number, or a negative value if terminated
* @throws IllegalStateException if not terminated and the number
* of registered or unarrived parties would become negative
*/
public int arriveAndDeregister() {
return doArrive(ONE_DEREGISTER);
}
/**
* Arrives at this phaser and awaits others. Equivalent in effect
* to {@code awaitAdvance(arrive())}. If you need to await with
* interruption or timeout, you can arrange this with an analogous
* construction using one of the other forms of the {@code
* awaitAdvance} method. If instead you need to deregister upon
* arrival, use {@code awaitAdvance(arriveAndDeregister())}.
*
* <p>It is a usage error for an unregistered party to invoke this
* method. However, this error may result in an {@code
* IllegalStateException} only upon some subsequent operation on
* this phaser, if ever.
*
* @return the arrival phase number, or the (negative)
* {@linkplain #getPhase() current phase} if terminated
* @throws IllegalStateException if not terminated and the number
* of unarrived parties would become negative
*/
public int arriveAndAwaitAdvance() {
// Specialization of doArrive+awaitAdvance eliminating some reads/paths
final Phaser root = this.root;
for (;;) {
long s = (root == this) ? state : reconcileState();
int phase = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
return phase;
int counts = (int)s;
int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
if (unarrived <= 0)
throw new IllegalStateException(badArrive(s));
if (UNSAFE.compareAndSwapLong(this, stateOffset, s,
s -= ONE_ARRIVAL)) {
if (unarrived > 1)
return root.internalAwaitAdvance(phase, null);
if (root != this)
return parent.arriveAndAwaitAdvance();
long n = s & PARTIES_MASK; // base of next state
int nextUnarrived = (int)n >>> PARTIES_SHIFT;
if (onAdvance(phase, nextUnarrived))
n |= TERMINATION_BIT;
else if (nextUnarrived == 0)
n |= EMPTY;
else
n |= nextUnarrived;
int nextPhase = (phase + 1) & MAX_PHASE;
n |= (long)nextPhase << PHASE_SHIFT;
if (!UNSAFE.compareAndSwapLong(this, stateOffset, s, n))
return (int)(state >>> PHASE_SHIFT); // terminated
releaseWaiters(phase);
return nextPhase;
}
}
}
/**
* Awaits the phase of this phaser to advance from the given phase
* value, returning immediately if the current phase is not equal
* to the given phase value or this phaser is terminated.
*
* @param phase an arrival phase number, or negative value if
* terminated; this argument is normally the value returned by a
* previous call to {@code arrive} or {@code arriveAndDeregister}.
* @return the next arrival phase number, or the argument if it is
* negative, or the (negative) {@linkplain #getPhase() current phase}
* if terminated
*/
public int awaitAdvance(int phase) {
final Phaser root = this.root;
long s = (root == this) ? state : reconcileState();
int p = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
return phase;
if (p == phase)
return root.internalAwaitAdvance(phase, null);
return p;
}
/**
* Awaits the phase of this phaser to advance from the given phase
* value, throwing {@code InterruptedException} if interrupted
* while waiting, or returning immediately if the current phase is
* not equal to the given phase value or this phaser is
* terminated.
*
* @param phase an arrival phase number, or negative value if
* terminated; this argument is normally the value returned by a
* previous call to {@code arrive} or {@code arriveAndDeregister}.
* @return the next arrival phase number, or the argument if it is
* negative, or the (negative) {@linkplain #getPhase() current phase}
* if terminated
* @throws InterruptedException if thread interrupted while waiting
*/
public int awaitAdvanceInterruptibly(int phase)
throws InterruptedException {
final Phaser root = this.root;
long s = (root == this) ? state : reconcileState();
int p = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
return phase;
if (p == phase) {
QNode node = new QNode(this, phase, true, false, 0L);
p = root.internalAwaitAdvance(phase, node);
if (node.wasInterrupted)
throw new InterruptedException();
}
return p;
}
/**
* Awaits the phase of this phaser to advance from the given phase
* value or the given timeout to elapse, throwing {@code
* InterruptedException} if interrupted while waiting, or
* returning immediately if the current phase is not equal to the
* given phase value or this phaser is terminated.
*
* @param phase an arrival phase number, or negative value if
* terminated; this argument is normally the value returned by a
* previous call to {@code arrive} or {@code arriveAndDeregister}.
* @param timeout how long to wait before giving up, in units of
* {@code unit}
* @param unit a {@code TimeUnit} determining how to interpret the
* {@code timeout} parameter
* @return the next arrival phase number, or the argument if it is
* negative, or the (negative) {@linkplain #getPhase() current phase}
* if terminated
* @throws InterruptedException if thread interrupted while waiting
* @throws TimeoutException if timed out while waiting
*/
public int awaitAdvanceInterruptibly(int phase,
long timeout, TimeUnit unit)
throws InterruptedException, TimeoutException {
long nanos = unit.toNanos(timeout);
final Phaser root = this.root;
long s = (root == this) ? state : reconcileState();
int p = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
return phase;
if (p == phase) {
QNode node = new QNode(this, phase, true, true, nanos);
p = root.internalAwaitAdvance(phase, node);
if (node.wasInterrupted)
throw new InterruptedException();
else if (p == phase)
throw new TimeoutException();
}
return p;
}
/**
* Forces this phaser to enter termination state. Counts of
* registered parties are unaffected. If this phaser is a member
* of a tiered set of phasers, then all of the phasers in the set
* are terminated. If this phaser is already terminated, this
* method has no effect. This method may be useful for
* coordinating recovery after one or more tasks encounter
* unexpected exceptions.
*/
public void forceTermination() {
// Only need to change root state
final Phaser root = this.root;
long s;
while ((s = root.state) >= 0) {
if (UNSAFE.compareAndSwapLong(root, stateOffset,
s, s | TERMINATION_BIT)) {
// signal all threads
releaseWaiters(0); // Waiters on evenQ
releaseWaiters(1); // Waiters on oddQ
return;
}
}
}
/**
* Returns the current phase number. The maximum phase number is
* {@code Integer.MAX_VALUE}, after which it restarts at
* zero. Upon termination, the phase number is negative,
* in which case the prevailing phase prior to termination
* may be obtained via {@code getPhase() + Integer.MIN_VALUE}.
*
* @return the phase number, or a negative value if terminated
*/
public final int getPhase() {
return (int)(root.state >>> PHASE_SHIFT);
}
/**
* Returns the number of parties registered at this phaser.
*
* @return the number of parties
*/
public int getRegisteredParties() {
return partiesOf(state);
}
/**
* Returns the number of registered parties that have arrived at
* the current phase of this phaser. If this phaser has terminated,
* the returned value is meaningless and arbitrary.
*
* @return the number of arrived parties
*/
public int getArrivedParties() {
return arrivedOf(reconcileState());
}
/**
* Returns the number of registered parties that have not yet
* arrived at the current phase of this phaser. If this phaser has
* terminated, the returned value is meaningless and arbitrary.
*
* @return the number of unarrived parties
*/
public int getUnarrivedParties() {
return unarrivedOf(reconcileState());
}
/**
* Returns the parent of this phaser, or {@code null} if none.
*
* @return the parent of this phaser, or {@code null} if none
*/
public Phaser getParent() {
return parent;
}
/**
* Returns the root ancestor of this phaser, which is the same as
* this phaser if it has no parent.
*
* @return the root ancestor of this phaser
*/
public Phaser getRoot() {
return root;
}
/**
* Returns {@code true} if this phaser has been terminated.
*
* @return {@code true} if this phaser has been terminated
*/
public boolean isTerminated() {
return root.state < 0L;
}
/**
* Overridable method to perform an action upon impending phase
* advance, and to control termination. This method is invoked
* upon arrival of the party advancing this phaser (when all other
* waiting parties are dormant). If this method returns {@code
* true}, this phaser will be set to a final termination state
* upon advance, and subsequent calls to {@link #isTerminated}
* will return true. Any (unchecked) Exception or Error thrown by
* an invocation of this method is propagated to the party
* attempting to advance this phaser, in which case no advance
* occurs.
*
* <p>The arguments to this method provide the state of the phaser
* prevailing for the current transition. The effects of invoking
* arrival, registration, and waiting methods on this phaser from
* within {@code onAdvance} are unspecified and should not be
* relied on.
*
* <p>If this phaser is a member of a tiered set of phasers, then
* {@code onAdvance} is invoked only for its root phaser on each
* advance.
*
* <p>To support the most common use cases, the default
* implementation of this method returns {@code true} when the
* number of registered parties has become zero as the result of a
* party invoking {@code arriveAndDeregister}. You can disable
* this behavior, thus enabling continuation upon future
* registrations, by overriding this method to always return
* {@code false}:
*
* <pre> {@code
* Phaser phaser = new Phaser() {
* protected boolean onAdvance(int phase, int parties) { return false; }
* }}</pre>
*
* @param phase the current phase number on entry to this method,
* before this phaser is advanced
* @param registeredParties the current number of registered parties
* @return {@code true} if this phaser should terminate
*/
protected boolean onAdvance(int phase, int registeredParties) {
return registeredParties == 0;
}
/**
* Returns a string identifying this phaser, as well as its
* state. The state, in brackets, includes the String {@code
* "phase = "} followed by the phase number, {@code "parties = "}
* followed by the number of registered parties, and {@code
* "arrived = "} followed by the number of arrived parties.
*
* @return a string identifying this phaser, as well as its state
*/
public String toString() {
return stateToString(reconcileState());
}
/**
* Implementation of toString and string-based error messages
*/
private String stateToString(long s) {
return super.toString() +
"[phase = " + phaseOf(s) +
" parties = " + partiesOf(s) +
" arrived = " + arrivedOf(s) + "]";
}
// Waiting mechanics
/**
* Removes and signals threads from queue for phase.
*/
private void releaseWaiters(int phase) {
QNode q; // first element of queue
Thread t; // its thread
AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
while ((q = head.get()) != null &&
q.phase != (int)(root.state >>> PHASE_SHIFT)) {
if (head.compareAndSet(q, q.next) &&
(t = q.thread) != null) {
q.thread = null;
LockSupport.unpark(t);
}
}
}
/**
* Variant of releaseWaiters that additionally tries to remove any
* nodes no longer waiting for advance due to timeout or
* interrupt. Currently, nodes are removed only if they are at
* head of queue, which suffices to reduce memory footprint in
* most usages.
*
* @return current phase on exit
*/
private int abortWait(int phase) {
AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
for (;;) {
Thread t;
QNode q = head.get();
int p = (int)(root.state >>> PHASE_SHIFT);
if (q == null || ((t = q.thread) != null && q.phase == p))
return p;
if (head.compareAndSet(q, q.next) && t != null) {
q.thread = null;
LockSupport.unpark(t);
}
}
}
/** The number of CPUs, for spin control */
private static final int NCPU = Runtime.getRuntime().availableProcessors();
/**
* The number of times to spin before blocking while waiting for
* advance, per arrival while waiting. On multiprocessors, fully
* blocking and waking up a large number of threads all at once is
* usually a very slow process, so we use rechargeable spins to
* avoid it when threads regularly arrive: When a thread in
* internalAwaitAdvance notices another arrival before blocking,
* and there appear to be enough CPUs available, it spins
* SPINS_PER_ARRIVAL more times before blocking. The value trades
* off good-citizenship vs big unnecessary slowdowns.
*/
static final int SPINS_PER_ARRIVAL = (NCPU < 2) ? 1 : 1 << 8;
/**
* Possibly blocks and waits for phase to advance unless aborted.
* Call only on root phaser.
*
* @param phase current phase
* @param node if non-null, the wait node to track interrupt and timeout;
* if null, denotes noninterruptible wait
* @return current phase
*/
private int internalAwaitAdvance(int phase, QNode node) {
// assert root == this;
releaseWaiters(phase-1); // ensure old queue clean
boolean queued = false; // true when node is enqueued
int lastUnarrived = 0; // to increase spins upon change
int spins = SPINS_PER_ARRIVAL;
long s;
int p;
while ((p = (int)((s = state) >>> PHASE_SHIFT)) == phase) {
if (node == null) { // spinning in noninterruptible mode
int unarrived = (int)s & UNARRIVED_MASK;
if (unarrived != lastUnarrived &&
(lastUnarrived = unarrived) < NCPU)
spins += SPINS_PER_ARRIVAL;
boolean interrupted = Thread.interrupted();
if (interrupted || --spins < 0) { // need node to record intr
node = new QNode(this, phase, false, false, 0L);
node.wasInterrupted = interrupted;
}
}
else if (node.isReleasable()) // done or aborted
break;
else if (!queued) { // push onto queue
AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
QNode q = node.next = head.get();
if ((q == null || q.phase == phase) &&
(int)(state >>> PHASE_SHIFT) == phase) // avoid stale enq
queued = head.compareAndSet(q, node);
}
else {
try {
ForkJoinPool.managedBlock(node);
} catch (InterruptedException ie) {
node.wasInterrupted = true;
}
}
}
if (node != null) {
if (node.thread != null)
node.thread = null; // avoid need for unpark()
if (node.wasInterrupted && !node.interruptible)
Thread.currentThread().interrupt();
if (p == phase && (p = (int)(state >>> PHASE_SHIFT)) == phase)
return abortWait(phase); // possibly clean up on abort
}
releaseWaiters(phase);
return p;
}
/**
* Wait nodes for Treiber stack representing wait queue
*/
static final class QNode implements ForkJoinPool.ManagedBlocker {
final Phaser phaser;
final int phase;
final boolean interruptible;
final boolean timed;
boolean wasInterrupted;
long nanos;
long lastTime;
volatile Thread thread; // nulled to cancel wait
QNode next;
QNode(Phaser phaser, int phase, boolean interruptible,
boolean timed, long nanos) {
this.phaser = phaser;
this.phase = phase;
this.interruptible = interruptible;
this.nanos = nanos;
this.timed = timed;
this.lastTime = timed ? System.nanoTime() : 0L;
thread = Thread.currentThread();
}
public boolean isReleasable() {
if (thread == null)
return true;
if (phaser.getPhase() != phase) {
thread = null;
return true;
}
if (Thread.interrupted())
wasInterrupted = true;
if (wasInterrupted && interruptible) {
thread = null;
return true;
}
if (timed) {
if (nanos > 0L) {
long now = System.nanoTime();
nanos -= now - lastTime;
lastTime = now;
}
if (nanos <= 0L) {
thread = null;
return true;
}
}
return false;
}
public boolean block() {
if (isReleasable())
return true;
else if (!timed)
LockSupport.park(this);
else if (nanos > 0)
LockSupport.parkNanos(this, nanos);
return isReleasable();
}
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long stateOffset;
static {
try {
UNSAFE = getUnsafe();
Class<?> k = Phaser.class;
stateOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("state"));
} catch (Exception e) {
throw new Error(e);
}
}
/**
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
* Replace with a simple call to Unsafe.getUnsafe when integrating
* into a jdk.
*
* @return a sun.misc.Unsafe
*/
private static sun.misc.Unsafe getUnsafe() {
try {
return sun.misc.Unsafe.getUnsafe();
} catch (SecurityException tryReflectionInstead) {}
try {
return java.security.AccessController.doPrivileged
(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");
}});
} catch (java.security.PrivilegedActionException e) {
throw new RuntimeException("Could not initialize intrinsics",
e.getCause());
}
}
}
| 0true
|
src_main_java_jsr166y_Phaser.java
|
1,517 |
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> {
private final ScriptEngine engine = new FaunusGremlinScriptEngine();
private SafeMapperOutputs outputs;
private Text textWritable = new Text();
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
final FileSystem fs = FileSystem.get(context.getConfiguration());
try {
this.engine.eval(new InputStreamReader(fs.open(new Path(context.getConfiguration().get(SCRIPT_PATH)))));
this.engine.put(ARGS, context.getConfiguration().getStrings(SCRIPT_ARGS));
this.engine.eval(SETUP_ARGS);
} catch (Exception e) {
throw new InterruptedException(e.getMessage());
}
this.outputs = new SafeMapperOutputs(context);
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
if (value.hasPaths()) {
final Object result;
try {
this.engine.put(V, value);
result = engine.eval(MAP_V_ARGS);
} catch (Exception e) {
throw new InterruptedException(e.getMessage());
}
this.textWritable.set((null == result) ? Tokens.NULL : result.toString());
this.outputs.write(Tokens.SIDEEFFECT, NullWritable.get(), this.textWritable);
}
this.outputs.write(Tokens.GRAPH, NullWritable.get(), value);
}
@Override
public void cleanup(final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
try {
this.engine.eval(CLEANUP_ARGS);
} catch (Exception e) {
throw new InterruptedException(e.getMessage());
}
this.outputs.close();
}
}
| 1no label
|
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_ScriptMap.java
|
716 |
class ShardCountResponse extends BroadcastShardOperationResponse {
private long count;
ShardCountResponse() {
}
public ShardCountResponse(String index, int shardId, long count) {
super(index, shardId);
this.count = count;
}
public long getCount() {
return this.count;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
count = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVLong(count);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_count_ShardCountResponse.java
|
886 |
public class TransportSearchScrollQueryThenFetchAction extends AbstractComponent {
private final ThreadPool threadPool;
private final ClusterService clusterService;
private final SearchServiceTransportAction searchService;
private final SearchPhaseController searchPhaseController;
@Inject
public TransportSearchScrollQueryThenFetchAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController) {
super(settings);
this.threadPool = threadPool;
this.clusterService = clusterService;
this.searchService = searchService;
this.searchPhaseController = searchPhaseController;
}
public void execute(SearchScrollRequest request, ParsedScrollId scrollId, ActionListener<SearchResponse> listener) {
new AsyncAction(request, scrollId, listener).start();
}
private class AsyncAction {
private final SearchScrollRequest request;
private final ActionListener<SearchResponse> listener;
private final ParsedScrollId scrollId;
private final DiscoveryNodes nodes;
private volatile AtomicArray<ShardSearchFailure> shardFailures;
final AtomicArray<QuerySearchResult> queryResults;
final AtomicArray<FetchSearchResult> fetchResults;
private volatile ScoreDoc[] sortedShardList;
private final AtomicInteger successfulOps;
private final long startTime = System.currentTimeMillis();
private AsyncAction(SearchScrollRequest request, ParsedScrollId scrollId, ActionListener<SearchResponse> listener) {
this.request = request;
this.listener = listener;
this.scrollId = scrollId;
this.nodes = clusterService.state().nodes();
this.successfulOps = new AtomicInteger(scrollId.getContext().length);
this.queryResults = new AtomicArray<QuerySearchResult>(scrollId.getContext().length);
this.fetchResults = new AtomicArray<FetchSearchResult>(scrollId.getContext().length);
}
protected final ShardSearchFailure[] buildShardFailures() {
if (shardFailures == null) {
return ShardSearchFailure.EMPTY_ARRAY;
}
List<AtomicArray.Entry<ShardSearchFailure>> entries = shardFailures.asList();
ShardSearchFailure[] failures = new ShardSearchFailure[entries.size()];
for (int i = 0; i < failures.length; i++) {
failures[i] = entries.get(i).value;
}
return failures;
}
// we do our best to return the shard failures, but its ok if its not fully concurrently safe
// we simply try and return as much as possible
protected final void addShardFailure(final int shardIndex, ShardSearchFailure failure) {
if (shardFailures == null) {
shardFailures = new AtomicArray<ShardSearchFailure>(scrollId.getContext().length);
}
shardFailures.set(shardIndex, failure);
}
public void start() {
if (scrollId.getContext().length == 0) {
listener.onFailure(new SearchPhaseExecutionException("query", "no nodes to search on", null));
return;
}
final AtomicInteger counter = new AtomicInteger(scrollId.getContext().length);
int localOperations = 0;
Tuple<String, Long>[] context = scrollId.getContext();
for (int i = 0; i < context.length; i++) {
Tuple<String, Long> target = context[i];
DiscoveryNode node = nodes.get(target.v1());
if (node != null) {
if (nodes.localNodeId().equals(node.id())) {
localOperations++;
} else {
executeQueryPhase(i, counter, node, target.v2());
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Node [" + target.v1() + "] not available for scroll request [" + scrollId.getSource() + "]");
}
successfulOps.decrementAndGet();
if (counter.decrementAndGet() == 0) {
executeFetchPhase();
}
}
}
if (localOperations > 0) {
if (request.operationThreading() == SearchOperationThreading.SINGLE_THREAD) {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
Tuple<String, Long>[] context1 = scrollId.getContext();
for (int i = 0; i < context1.length; i++) {
Tuple<String, Long> target = context1[i];
DiscoveryNode node = nodes.get(target.v1());
if (node != null && nodes.localNodeId().equals(node.id())) {
executeQueryPhase(i, counter, node, target.v2());
}
}
}
});
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
Tuple<String, Long>[] context1 = scrollId.getContext();
for (int i = 0; i < context1.length; i++) {
final Tuple<String, Long> target = context1[i];
final int shardIndex = i;
final DiscoveryNode node = nodes.get(target.v1());
if (node != null && nodes.localNodeId().equals(node.id())) {
try {
if (localAsync) {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
executeQueryPhase(shardIndex, counter, node, target.v2());
}
});
} else {
executeQueryPhase(shardIndex, counter, node, target.v2());
}
} catch (Throwable t) {
onQueryPhaseFailure(shardIndex, counter, target.v2(), t);
}
}
}
}
}
}
private void executeQueryPhase(final int shardIndex, final AtomicInteger counter, DiscoveryNode node, final long searchId) {
searchService.sendExecuteQuery(node, internalScrollSearchRequest(searchId, request), new SearchServiceListener<QuerySearchResult>() {
@Override
public void onResult(QuerySearchResult result) {
queryResults.set(shardIndex, result);
if (counter.decrementAndGet() == 0) {
executeFetchPhase();
}
}
@Override
public void onFailure(Throwable t) {
onQueryPhaseFailure(shardIndex, counter, searchId, t);
}
});
}
void onQueryPhaseFailure(final int shardIndex, final AtomicInteger counter, final long searchId, Throwable t) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] Failed to execute query phase", t, searchId);
}
addShardFailure(shardIndex, new ShardSearchFailure(t));
successfulOps.decrementAndGet();
if (counter.decrementAndGet() == 0) {
executeFetchPhase();
}
}
private void executeFetchPhase() {
sortedShardList = searchPhaseController.sortDocs(queryResults);
AtomicArray<IntArrayList> docIdsToLoad = new AtomicArray<IntArrayList>(queryResults.length());
searchPhaseController.fillDocIdsToLoad(docIdsToLoad, sortedShardList);
if (docIdsToLoad.asList().isEmpty()) {
finishHim();
}
final AtomicInteger counter = new AtomicInteger(docIdsToLoad.asList().size());
for (final AtomicArray.Entry<IntArrayList> entry : docIdsToLoad.asList()) {
IntArrayList docIds = entry.value;
final QuerySearchResult querySearchResult = queryResults.get(entry.index);
FetchSearchRequest fetchSearchRequest = new FetchSearchRequest(request, querySearchResult.id(), docIds);
DiscoveryNode node = nodes.get(querySearchResult.shardTarget().nodeId());
searchService.sendExecuteFetch(node, fetchSearchRequest, new SearchServiceListener<FetchSearchResult>() {
@Override
public void onResult(FetchSearchResult result) {
result.shardTarget(querySearchResult.shardTarget());
fetchResults.set(entry.index, result);
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
@Override
public void onFailure(Throwable t) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to execute fetch phase", t);
}
successfulOps.decrementAndGet();
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
});
}
}
private void finishHim() {
try {
innerFinishHim();
} catch (Throwable e) {
listener.onFailure(new ReduceSearchPhaseException("fetch", "", e, buildShardFailures()));
}
}
private void innerFinishHim() {
InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, queryResults, fetchResults);
String scrollId = null;
if (request.scroll() != null) {
scrollId = request.scrollId();
}
listener.onResponse(new SearchResponse(internalResponse, scrollId, this.scrollId.getContext().length, successfulOps.get(),
System.currentTimeMillis() - startTime, buildShardFailures()));
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_search_type_TransportSearchScrollQueryThenFetchAction.java
|
46 |
@Component("blRequestDTOCustomPersistenceHandler")
public class RequestDTOCustomPersistenceHandler extends TimeDTOCustomPersistenceHandler {
private static final Log LOG = LogFactory.getLog(RequestDTOCustomPersistenceHandler.class);
@Override
public Boolean canHandleInspect(PersistencePackage persistencePackage) {
String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
return RequestDTOImpl.class.getName().equals(ceilingEntityFullyQualifiedClassname);
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_admin_server_handler_RequestDTOCustomPersistenceHandler.java
|
4,722 |
public class RepositoriesService extends AbstractComponent implements ClusterStateListener {
private final RepositoryTypesRegistry typesRegistry;
private final Injector injector;
private final ClusterService clusterService;
private volatile ImmutableMap<String, RepositoryHolder> repositories = ImmutableMap.of();
@Inject
public RepositoriesService(Settings settings, ClusterService clusterService, RepositoryTypesRegistry typesRegistry, Injector injector) {
super(settings);
this.typesRegistry = typesRegistry;
this.injector = injector;
this.clusterService = clusterService;
// Doesn't make sense to maintain repositories on non-master and non-data nodes
// Nothing happens there anyway
if (DiscoveryNode.dataNode(settings) || DiscoveryNode.masterNode(settings)) {
clusterService.add(this);
}
}
/**
* Registers new repository in the cluster
* <p/>
* This method can be only called on the master node. It tries to create a new repository on the master
* and if it was successful it adds new repository to cluster metadata.
*
* @param request register repository request
* @param listener register repository listener
*/
public void registerRepository(final RegisterRepositoryRequest request, final ActionListener<RegisterRepositoryResponse> listener) {
final RepositoryMetaData newRepositoryMetaData = new RepositoryMetaData(request.name, request.type, request.settings);
clusterService.submitStateUpdateTask(request.cause, new AckedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
ensureRepositoryNotInUse(currentState, request.name);
// Trying to create the new repository on master to make sure it works
if (!registerRepository(newRepositoryMetaData)) {
// The new repository has the same settings as the old one - ignore
return currentState;
}
MetaData metaData = currentState.metaData();
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
RepositoriesMetaData repositories = metaData.custom(RepositoriesMetaData.TYPE);
if (repositories == null) {
logger.info("put repository [{}]", request.name);
repositories = new RepositoriesMetaData(new RepositoryMetaData(request.name, request.type, request.settings));
} else {
boolean found = false;
List<RepositoryMetaData> repositoriesMetaData = new ArrayList<RepositoryMetaData>(repositories.repositories().size() + 1);
for (RepositoryMetaData repositoryMetaData : repositories.repositories()) {
if (repositoryMetaData.name().equals(newRepositoryMetaData.name())) {
found = true;
repositoriesMetaData.add(newRepositoryMetaData);
} else {
repositoriesMetaData.add(repositoryMetaData);
}
}
if (!found) {
logger.info("put repository [{}]", request.name);
repositoriesMetaData.add(new RepositoryMetaData(request.name, request.type, request.settings));
} else {
logger.info("update repository [{}]", request.name);
}
repositories = new RepositoriesMetaData(repositoriesMetaData.toArray(new RepositoryMetaData[repositoriesMetaData.size()]));
}
mdBuilder.putCustom(RepositoriesMetaData.TYPE, repositories);
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.warn("failed to create repository [{}]", t, request.name);
listener.onFailure(t);
}
@Override
public TimeValue timeout() {
return request.masterNodeTimeout();
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return discoveryNode.masterNode();
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
listener.onResponse(new RegisterRepositoryResponse(true));
}
@Override
public void onAckTimeout() {
listener.onResponse(new RegisterRepositoryResponse(false));
}
@Override
public TimeValue ackTimeout() {
return request.ackTimeout();
}
});
}
/**
* Unregisters repository in the cluster
* <p/>
* This method can be only called on the master node. It removes repository information from cluster metadata.
*
* @param request unregister repository request
* @param listener unregister repository listener
*/
public void unregisterRepository(final UnregisterRepositoryRequest request, final ActionListener<UnregisterRepositoryResponse> listener) {
clusterService.submitStateUpdateTask(request.cause, new AckedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
ensureRepositoryNotInUse(currentState, request.name);
MetaData metaData = currentState.metaData();
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
RepositoriesMetaData repositories = metaData.custom(RepositoriesMetaData.TYPE);
if (repositories != null && repositories.repositories().size() > 0) {
List<RepositoryMetaData> repositoriesMetaData = new ArrayList<RepositoryMetaData>(repositories.repositories().size());
boolean changed = false;
for (RepositoryMetaData repositoryMetaData : repositories.repositories()) {
if (Regex.simpleMatch(request.name, repositoryMetaData.name())) {
logger.info("delete repository [{}]", repositoryMetaData.name());
changed = true;
} else {
repositoriesMetaData.add(repositoryMetaData);
}
}
if (changed) {
repositories = new RepositoriesMetaData(repositoriesMetaData.toArray(new RepositoryMetaData[repositoriesMetaData.size()]));
mdBuilder.putCustom(RepositoriesMetaData.TYPE, repositories);
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
}
throw new RepositoryMissingException(request.name);
}
@Override
public void onFailure(String source, Throwable t) {
listener.onFailure(t);
}
@Override
public TimeValue timeout() {
return request.masterNodeTimeout();
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
// Since operation occurs only on masters, it's enough that only master-eligible nodes acked
return discoveryNode.masterNode();
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
listener.onResponse(new UnregisterRepositoryResponse(true));
}
@Override
public void onAckTimeout() {
listener.onResponse(new UnregisterRepositoryResponse(false));
}
@Override
public TimeValue ackTimeout() {
return request.ackTimeout();
}
});
}
/**
* Checks if new repositories appeared in or disappeared from cluster metadata and updates current list of
* repositories accordingly.
*
* @param event cluster changed event
*/
@Override
public void clusterChanged(ClusterChangedEvent event) {
try {
RepositoriesMetaData oldMetaData = event.previousState().getMetaData().custom(RepositoriesMetaData.TYPE);
RepositoriesMetaData newMetaData = event.state().getMetaData().custom(RepositoriesMetaData.TYPE);
// Check if repositories got changed
if ((oldMetaData == null && newMetaData == null) || (oldMetaData != null && oldMetaData.equals(newMetaData))) {
return;
}
Map<String, RepositoryHolder> survivors = newHashMap();
// First, remove repositories that are no longer there
for (Map.Entry<String, RepositoryHolder> entry : repositories.entrySet()) {
if (newMetaData == null || newMetaData.repository(entry.getKey()) == null) {
closeRepository(entry.getKey(), entry.getValue());
} else {
survivors.put(entry.getKey(), entry.getValue());
}
}
ImmutableMap.Builder<String, RepositoryHolder> builder = ImmutableMap.builder();
if (newMetaData != null) {
// Now go through all repositories and update existing or create missing
for (RepositoryMetaData repositoryMetaData : newMetaData.repositories()) {
RepositoryHolder holder = survivors.get(repositoryMetaData.name());
if (holder != null) {
// Found previous version of this repository
if (!holder.type.equals(repositoryMetaData.type()) || !holder.settings.equals(repositoryMetaData.settings())) {
// Previous version is different from the version in settings
closeRepository(repositoryMetaData.name(), holder);
holder = createRepositoryHolder(repositoryMetaData);
}
} else {
holder = createRepositoryHolder(repositoryMetaData);
}
if (holder != null) {
builder.put(repositoryMetaData.name(), holder);
}
}
}
repositories = builder.build();
} catch (Throwable ex) {
logger.warn("failure updating cluster state ", ex);
}
}
/**
* Returns registered repository
* <p/>
* This method is called only on the master node
*
* @param repository repository name
* @return registered repository
* @throws RepositoryMissingException if repository with such name isn't registered
*/
public Repository repository(String repository) {
RepositoryHolder holder = repositories.get(repository);
if (holder != null) {
return holder.repository;
}
throw new RepositoryMissingException(repository);
}
/**
* Returns registered index shard repository
* <p/>
* This method is called only on data nodes
*
* @param repository repository name
* @return registered repository
* @throws RepositoryMissingException if repository with such name isn't registered
*/
public IndexShardRepository indexShardRepository(String repository) {
RepositoryHolder holder = repositories.get(repository);
if (holder != null) {
return holder.indexShardRepository;
}
throw new RepositoryMissingException(repository);
}
/**
* Creates a new repository and adds it to the list of registered repositories.
* <p/>
* If a repository with the same name but different types or settings already exists, it will be closed and
* replaced with the new repository. If a repository with the same name exists but it has the same type and settings
* the new repository is ignored.
*
* @param repositoryMetaData new repository metadata
* @return {@code true} if new repository was added or {@code false} if it was ignored
*/
private boolean registerRepository(RepositoryMetaData repositoryMetaData) {
RepositoryHolder previous = repositories.get(repositoryMetaData.name());
if (previous != null) {
if (!previous.type.equals(repositoryMetaData.type()) && previous.settings.equals(repositoryMetaData.settings())) {
// Previous version is the same as this one - ignore it
return false;
}
}
RepositoryHolder holder = createRepositoryHolder(repositoryMetaData);
if (previous != null) {
// Closing previous version
closeRepository(repositoryMetaData.name(), previous);
}
Map<String, RepositoryHolder> newRepositories = newHashMap(repositories);
newRepositories.put(repositoryMetaData.name(), holder);
repositories = ImmutableMap.copyOf(newRepositories);
return true;
}
/**
* Closes the repository
*
* @param name repository name
* @param holder repository holder
*/
private void closeRepository(String name, RepositoryHolder holder) {
logger.debug("closing repository [{}][{}]", holder.type, name);
if (holder.injector != null) {
Injectors.close(holder.injector);
}
if (holder.repository != null) {
holder.repository.close();
}
}
/**
* Creates repository holder
*/
private RepositoryHolder createRepositoryHolder(RepositoryMetaData repositoryMetaData) {
logger.debug("creating repository [{}][{}]", repositoryMetaData.type(), repositoryMetaData.name());
Injector repositoryInjector = null;
try {
ModulesBuilder modules = new ModulesBuilder();
RepositoryName name = new RepositoryName(repositoryMetaData.type(), repositoryMetaData.name());
modules.add(new RepositoryNameModule(name));
modules.add(new RepositoryModule(name, repositoryMetaData.settings(), this.settings, typesRegistry));
repositoryInjector = modules.createChildInjector(injector);
Repository repository = repositoryInjector.getInstance(Repository.class);
IndexShardRepository indexShardRepository = repositoryInjector.getInstance(IndexShardRepository.class);
repository.start();
return new RepositoryHolder(repositoryMetaData.type(), repositoryMetaData.settings(), repositoryInjector, repository, indexShardRepository);
} catch (Throwable t) {
if (repositoryInjector != null) {
Injectors.close(repositoryInjector);
}
logger.warn("failed to create repository [{}][{}]", t, repositoryMetaData.type(), repositoryMetaData.name());
throw new RepositoryException(repositoryMetaData.name(), "failed to create repository", t);
}
}
private void ensureRepositoryNotInUse(ClusterState clusterState, String repository) {
if (SnapshotsService.isRepositoryInUse(clusterState, repository) || RestoreService.isRepositoryInUse(clusterState, repository)) {
throw new ElasticsearchIllegalStateException("trying to modify or unregister repository that is currently used ");
}
}
/**
* Internal data structure for holding repository with its configuration information and injector
*/
private static class RepositoryHolder {
private final String type;
private final Settings settings;
private final Injector injector;
private final Repository repository;
private final IndexShardRepository indexShardRepository;
public RepositoryHolder(String type, Settings settings, Injector injector, Repository repository, IndexShardRepository indexShardRepository) {
this.type = type;
this.settings = settings;
this.repository = repository;
this.indexShardRepository = indexShardRepository;
this.injector = injector;
}
}
/**
* Register repository request
*/
public static class RegisterRepositoryRequest extends ClusterStateUpdateRequest<RegisterRepositoryRequest> {
final String cause;
final String name;
final String type;
Settings settings = EMPTY_SETTINGS;
/**
* Constructs new register repository request
*
* @param cause repository registration cause
* @param name repository name
* @param type repository type
*/
public RegisterRepositoryRequest(String cause, String name, String type) {
this.cause = cause;
this.name = name;
this.type = type;
}
/**
* Sets repository settings
*
* @param settings repository settings
* @return this request
*/
public RegisterRepositoryRequest settings(Settings settings) {
this.settings = settings;
return this;
}
}
/**
* Register repository response
*/
public static class RegisterRepositoryResponse extends ClusterStateUpdateResponse {
RegisterRepositoryResponse(boolean acknowledged) {
super(acknowledged);
}
}
/**
* Unregister repository request
*/
public static class UnregisterRepositoryRequest extends ClusterStateUpdateRequest<UnregisterRepositoryRequest> {
final String cause;
final String name;
/**
* Creates a new unregister repository request
*
* @param cause repository unregistration cause
* @param name repository name
*/
public UnregisterRepositoryRequest(String cause, String name) {
this.cause = cause;
this.name = name;
}
}
/**
* Unregister repository response
*/
public static class UnregisterRepositoryResponse extends ClusterStateUpdateResponse {
UnregisterRepositoryResponse(boolean acknowledged) {
super(acknowledged);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_repositories_RepositoriesService.java
|
46 |
public interface Namifiable {
/**
* Returns the unique name of this entity.
*
* @return Name of this entity.
*/
public String getName();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_Namifiable.java
|
4,504 |
public class IndicesStore extends AbstractComponent implements ClusterStateListener {
public static final String INDICES_STORE_THROTTLE_TYPE = "indices.store.throttle.type";
public static final String INDICES_STORE_THROTTLE_MAX_BYTES_PER_SEC = "indices.store.throttle.max_bytes_per_sec";
class ApplySettings implements NodeSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
String rateLimitingType = settings.get(INDICES_STORE_THROTTLE_TYPE, IndicesStore.this.rateLimitingType);
// try and parse the type
StoreRateLimiting.Type.fromString(rateLimitingType);
if (!rateLimitingType.equals(IndicesStore.this.rateLimitingType)) {
logger.info("updating indices.store.throttle.type from [{}] to [{}]", IndicesStore.this.rateLimitingType, rateLimitingType);
IndicesStore.this.rateLimitingType = rateLimitingType;
IndicesStore.this.rateLimiting.setType(rateLimitingType);
}
ByteSizeValue rateLimitingThrottle = settings.getAsBytesSize(INDICES_STORE_THROTTLE_MAX_BYTES_PER_SEC, IndicesStore.this.rateLimitingThrottle);
if (!rateLimitingThrottle.equals(IndicesStore.this.rateLimitingThrottle)) {
logger.info("updating indices.store.throttle.max_bytes_per_sec from [{}] to [{}], note, type is [{}]", IndicesStore.this.rateLimitingThrottle, rateLimitingThrottle, IndicesStore.this.rateLimitingType);
IndicesStore.this.rateLimitingThrottle = rateLimitingThrottle;
IndicesStore.this.rateLimiting.setMaxRate(rateLimitingThrottle);
}
}
}
private final NodeEnvironment nodeEnv;
private final NodeSettingsService nodeSettingsService;
private final IndicesService indicesService;
private final ClusterService clusterService;
private volatile String rateLimitingType;
private volatile ByteSizeValue rateLimitingThrottle;
private final StoreRateLimiting rateLimiting = new StoreRateLimiting();
private final ApplySettings applySettings = new ApplySettings();
@Inject
public IndicesStore(Settings settings, NodeEnvironment nodeEnv, NodeSettingsService nodeSettingsService, IndicesService indicesService, ClusterService clusterService, ThreadPool threadPool) {
super(settings);
this.nodeEnv = nodeEnv;
this.nodeSettingsService = nodeSettingsService;
this.indicesService = indicesService;
this.clusterService = clusterService;
// we limit with 20MB / sec by default with a default type set to merge sice 0.90.1
this.rateLimitingType = componentSettings.get("throttle.type", StoreRateLimiting.Type.MERGE.name());
rateLimiting.setType(rateLimitingType);
this.rateLimitingThrottle = componentSettings.getAsBytesSize("throttle.max_bytes_per_sec", new ByteSizeValue(20, ByteSizeUnit.MB));
rateLimiting.setMaxRate(rateLimitingThrottle);
logger.debug("using indices.store.throttle.type [{}], with index.store.throttle.max_bytes_per_sec [{}]", rateLimitingType, rateLimitingThrottle);
nodeSettingsService.addListener(applySettings);
clusterService.addLast(this);
}
public StoreRateLimiting rateLimiting() {
return this.rateLimiting;
}
public void close() {
nodeSettingsService.removeListener(applySettings);
clusterService.remove(this);
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
if (!event.routingTableChanged()) {
return;
}
if (event.state().blocks().disableStatePersistence()) {
return;
}
for (IndexRoutingTable indexRoutingTable : event.state().routingTable()) {
// Note, closed indices will not have any routing information, so won't be deleted
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
ShardId shardId = indexShardRoutingTable.shardId();
// a shard can be deleted if all its copies are active, and its not allocated on this node
boolean shardCanBeDeleted = true;
if (indexShardRoutingTable.size() == 0) {
// should not really happen, there should always be at least 1 (primary) shard in a
// shard replication group, in any case, protected from deleting something by mistake
shardCanBeDeleted = false;
} else {
for (ShardRouting shardRouting : indexShardRoutingTable) {
// be conservative here, check on started, not even active
if (!shardRouting.started()) {
shardCanBeDeleted = false;
break;
}
// if the allocated or relocation node id doesn't exists in the cluster state, its a stale
// node, make sure we don't do anything with this until the routing table has properly been
// rerouted to reflect the fact that the node does not exists
if (!event.state().nodes().nodeExists(shardRouting.currentNodeId())) {
shardCanBeDeleted = false;
break;
}
if (shardRouting.relocatingNodeId() != null) {
if (!event.state().nodes().nodeExists(shardRouting.relocatingNodeId())) {
shardCanBeDeleted = false;
break;
}
}
// check if shard is active on the current node or is getting relocated to the our node
String localNodeId = clusterService.localNode().id();
if (localNodeId.equals(shardRouting.currentNodeId()) || localNodeId.equals(shardRouting.relocatingNodeId())) {
shardCanBeDeleted = false;
break;
}
}
}
if (shardCanBeDeleted) {
IndexService indexService = indicesService.indexService(indexRoutingTable.index());
if (indexService == null) {
// not physical allocation of the index, delete it from the file system if applicable
if (nodeEnv.hasNodeFile()) {
File[] shardLocations = nodeEnv.shardLocations(shardId);
if (FileSystemUtils.exists(shardLocations)) {
logger.debug("[{}][{}] deleting shard that is no longer used", shardId.index().name(), shardId.id());
FileSystemUtils.deleteRecursively(shardLocations);
}
}
} else {
if (!indexService.hasShard(shardId.id())) {
if (indexService.store().canDeleteUnallocated(shardId)) {
logger.debug("[{}][{}] deleting shard that is no longer used", shardId.index().name(), shardId.id());
try {
indexService.store().deleteUnallocated(indexShardRoutingTable.shardId());
} catch (Exception e) {
logger.debug("[{}][{}] failed to delete unallocated shard, ignoring", e, indexShardRoutingTable.shardId().index().name(), indexShardRoutingTable.shardId().id());
}
}
} else {
// this state is weird, should we log?
// basically, it means that the shard is not allocated on this node using the routing
// but its still physically exists on an IndexService
// Note, this listener should run after IndicesClusterStateService...
}
}
}
}
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_indices_store_IndicesStore.java
|
702 |
public class TransportBulkAction extends TransportAction<BulkRequest, BulkResponse> {
private final AutoCreateIndex autoCreateIndex;
private final boolean allowIdGeneration;
private final ClusterService clusterService;
private final TransportShardBulkAction shardBulkAction;
private final TransportCreateIndexAction createIndexAction;
@Inject
public TransportBulkAction(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterService clusterService,
TransportShardBulkAction shardBulkAction, TransportCreateIndexAction createIndexAction) {
super(settings, threadPool);
this.clusterService = clusterService;
this.shardBulkAction = shardBulkAction;
this.createIndexAction = createIndexAction;
this.autoCreateIndex = new AutoCreateIndex(settings);
this.allowIdGeneration = componentSettings.getAsBoolean("action.allow_id_generation", true);
transportService.registerHandler(BulkAction.NAME, new TransportHandler());
}
@Override
protected void doExecute(final BulkRequest bulkRequest, final ActionListener<BulkResponse> listener) {
final long startTime = System.currentTimeMillis();
Set<String> indices = Sets.newHashSet();
for (ActionRequest request : bulkRequest.requests) {
if (request instanceof IndexRequest) {
IndexRequest indexRequest = (IndexRequest) request;
if (!indices.contains(indexRequest.index())) {
indices.add(indexRequest.index());
}
} else if (request instanceof DeleteRequest) {
DeleteRequest deleteRequest = (DeleteRequest) request;
if (!indices.contains(deleteRequest.index())) {
indices.add(deleteRequest.index());
}
} else if (request instanceof UpdateRequest) {
UpdateRequest updateRequest = (UpdateRequest) request;
if (!indices.contains(updateRequest.index())) {
indices.add(updateRequest.index());
}
}
}
if (autoCreateIndex.needToCheck()) {
final AtomicInteger counter = new AtomicInteger(indices.size());
final AtomicBoolean failed = new AtomicBoolean();
ClusterState state = clusterService.state();
for (String index : indices) {
if (autoCreateIndex.shouldAutoCreate(index, state)) {
createIndexAction.execute(new CreateIndexRequest(index).cause("auto(bulk api)"), new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse result) {
if (counter.decrementAndGet() == 0) {
executeBulk(bulkRequest, startTime, listener);
}
}
@Override
public void onFailure(Throwable e) {
if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) {
// we have the index, do it
if (counter.decrementAndGet() == 0) {
executeBulk(bulkRequest, startTime, listener);
}
} else if (failed.compareAndSet(false, true)) {
listener.onFailure(e);
}
}
});
} else {
if (counter.decrementAndGet() == 0) {
executeBulk(bulkRequest, startTime, listener);
}
}
}
} else {
executeBulk(bulkRequest, startTime, listener);
}
}
private void executeBulk(final BulkRequest bulkRequest, final long startTime, final ActionListener<BulkResponse> listener) {
ClusterState clusterState = clusterService.state();
// TODO use timeout to wait here if its blocked...
clusterState.blocks().globalBlockedRaiseException(ClusterBlockLevel.WRITE);
MetaData metaData = clusterState.metaData();
final AtomicArray<BulkItemResponse> responses = new AtomicArray<BulkItemResponse>(bulkRequest.requests.size());
for (int i = 0; i < bulkRequest.requests.size(); i++) {
ActionRequest request = bulkRequest.requests.get(i);
if (request instanceof IndexRequest) {
IndexRequest indexRequest = (IndexRequest) request;
String aliasOrIndex = indexRequest.index();
indexRequest.index(clusterState.metaData().concreteIndex(indexRequest.index()));
MappingMetaData mappingMd = null;
if (metaData.hasIndex(indexRequest.index())) {
mappingMd = metaData.index(indexRequest.index()).mappingOrDefault(indexRequest.type());
}
try {
indexRequest.process(metaData, aliasOrIndex, mappingMd, allowIdGeneration);
} catch (ElasticsearchParseException e) {
BulkItemResponse.Failure failure = new BulkItemResponse.Failure(indexRequest.index(), indexRequest.type(), indexRequest.id(), e);
BulkItemResponse bulkItemResponse = new BulkItemResponse(i, "index", failure);
responses.set(i, bulkItemResponse);
// make sure the request gets never processed again
bulkRequest.requests.set(i, null);
}
} else if (request instanceof DeleteRequest) {
DeleteRequest deleteRequest = (DeleteRequest) request;
deleteRequest.routing(clusterState.metaData().resolveIndexRouting(deleteRequest.routing(), deleteRequest.index()));
deleteRequest.index(clusterState.metaData().concreteIndex(deleteRequest.index()));
} else if (request instanceof UpdateRequest) {
UpdateRequest updateRequest = (UpdateRequest) request;
updateRequest.routing(clusterState.metaData().resolveIndexRouting(updateRequest.routing(), updateRequest.index()));
updateRequest.index(clusterState.metaData().concreteIndex(updateRequest.index()));
}
}
// first, go over all the requests and create a ShardId -> Operations mapping
Map<ShardId, List<BulkItemRequest>> requestsByShard = Maps.newHashMap();
for (int i = 0; i < bulkRequest.requests.size(); i++) {
ActionRequest request = bulkRequest.requests.get(i);
if (request instanceof IndexRequest) {
IndexRequest indexRequest = (IndexRequest) request;
ShardId shardId = clusterService.operationRouting().indexShards(clusterState, indexRequest.index(), indexRequest.type(), indexRequest.id(), indexRequest.routing()).shardId();
List<BulkItemRequest> list = requestsByShard.get(shardId);
if (list == null) {
list = Lists.newArrayList();
requestsByShard.put(shardId, list);
}
list.add(new BulkItemRequest(i, request));
} else if (request instanceof DeleteRequest) {
DeleteRequest deleteRequest = (DeleteRequest) request;
MappingMetaData mappingMd = clusterState.metaData().index(deleteRequest.index()).mappingOrDefault(deleteRequest.type());
if (mappingMd != null && mappingMd.routing().required() && deleteRequest.routing() == null) {
// if routing is required, and no routing on the delete request, we need to broadcast it....
GroupShardsIterator groupShards = clusterService.operationRouting().broadcastDeleteShards(clusterState, deleteRequest.index());
for (ShardIterator shardIt : groupShards) {
List<BulkItemRequest> list = requestsByShard.get(shardIt.shardId());
if (list == null) {
list = Lists.newArrayList();
requestsByShard.put(shardIt.shardId(), list);
}
list.add(new BulkItemRequest(i, new DeleteRequest(deleteRequest)));
}
} else {
ShardId shardId = clusterService.operationRouting().deleteShards(clusterState, deleteRequest.index(), deleteRequest.type(), deleteRequest.id(), deleteRequest.routing()).shardId();
List<BulkItemRequest> list = requestsByShard.get(shardId);
if (list == null) {
list = Lists.newArrayList();
requestsByShard.put(shardId, list);
}
list.add(new BulkItemRequest(i, request));
}
} else if (request instanceof UpdateRequest) {
UpdateRequest updateRequest = (UpdateRequest) request;
MappingMetaData mappingMd = clusterState.metaData().index(updateRequest.index()).mappingOrDefault(updateRequest.type());
if (mappingMd != null && mappingMd.routing().required() && updateRequest.routing() == null) {
continue; // What to do?
}
ShardId shardId = clusterService.operationRouting().indexShards(clusterState, updateRequest.index(), updateRequest.type(), updateRequest.id(), updateRequest.routing()).shardId();
List<BulkItemRequest> list = requestsByShard.get(shardId);
if (list == null) {
list = Lists.newArrayList();
requestsByShard.put(shardId, list);
}
list.add(new BulkItemRequest(i, request));
}
}
if (requestsByShard.isEmpty()) {
listener.onResponse(new BulkResponse(responses.toArray(new BulkItemResponse[responses.length()]), System.currentTimeMillis() - startTime));
return;
}
final AtomicInteger counter = new AtomicInteger(requestsByShard.size());
for (Map.Entry<ShardId, List<BulkItemRequest>> entry : requestsByShard.entrySet()) {
final ShardId shardId = entry.getKey();
final List<BulkItemRequest> requests = entry.getValue();
BulkShardRequest bulkShardRequest = new BulkShardRequest(shardId.index().name(), shardId.id(), bulkRequest.refresh(), requests.toArray(new BulkItemRequest[requests.size()]));
bulkShardRequest.replicationType(bulkRequest.replicationType());
bulkShardRequest.consistencyLevel(bulkRequest.consistencyLevel());
bulkShardRequest.timeout(bulkRequest.timeout());
shardBulkAction.execute(bulkShardRequest, new ActionListener<BulkShardResponse>() {
@Override
public void onResponse(BulkShardResponse bulkShardResponse) {
for (BulkItemResponse bulkItemResponse : bulkShardResponse.getResponses()) {
responses.set(bulkItemResponse.getItemId(), bulkItemResponse);
}
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
@Override
public void onFailure(Throwable e) {
// create failures for all relevant requests
String message = ExceptionsHelper.detailedMessage(e);
RestStatus status = ExceptionsHelper.status(e);
for (BulkItemRequest request : requests) {
if (request.request() instanceof IndexRequest) {
IndexRequest indexRequest = (IndexRequest) request.request();
responses.set(request.id(), new BulkItemResponse(request.id(), indexRequest.opType().toString().toLowerCase(Locale.ENGLISH),
new BulkItemResponse.Failure(indexRequest.index(), indexRequest.type(), indexRequest.id(), message, status)));
} else if (request.request() instanceof DeleteRequest) {
DeleteRequest deleteRequest = (DeleteRequest) request.request();
responses.set(request.id(), new BulkItemResponse(request.id(), "delete",
new BulkItemResponse.Failure(deleteRequest.index(), deleteRequest.type(), deleteRequest.id(), message, status)));
} else if (request.request() instanceof UpdateRequest) {
UpdateRequest updateRequest = (UpdateRequest) request.request();
responses.set(request.id(), new BulkItemResponse(request.id(), "update",
new BulkItemResponse.Failure(updateRequest.index(), updateRequest.type(), updateRequest.id(), message, status)));
}
}
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
private void finishHim() {
listener.onResponse(new BulkResponse(responses.toArray(new BulkItemResponse[responses.length()]), System.currentTimeMillis() - startTime));
}
});
}
}
class TransportHandler extends BaseTransportRequestHandler<BulkRequest> {
@Override
public BulkRequest newInstance() {
return new BulkRequest();
}
@Override
public void messageReceived(final BulkRequest request, final TransportChannel channel) throws Exception {
// no need to use threaded listener, since we just send a response
request.listenerThreaded(false);
execute(request, new ActionListener<BulkResponse>() {
@Override
public void onResponse(BulkResponse result) {
try {
channel.sendResponse(result);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send error response for action [" + BulkAction.NAME + "] and request [" + request + "]", e1);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_bulk_TransportBulkAction.java
|
424 |
restoreService.restoreSnapshot(restoreRequest, new RestoreSnapshotListener() {
@Override
public void onResponse(RestoreInfo restoreInfo) {
if (restoreInfo == null) {
if (request.waitForCompletion()) {
restoreService.addListener(new RestoreService.RestoreCompletionListener() {
SnapshotId snapshotId = new SnapshotId(request.repository(), request.snapshot());
@Override
public void onRestoreCompletion(SnapshotId snapshotId, RestoreInfo snapshot) {
if (this.snapshotId.equals(snapshotId)) {
listener.onResponse(new RestoreSnapshotResponse(snapshot));
restoreService.removeListener(this);
}
}
});
} else {
listener.onResponse(new RestoreSnapshotResponse(null));
}
} else {
listener.onResponse(new RestoreSnapshotResponse(restoreInfo));
}
}
@Override
public void onFailure(Throwable t) {
listener.onFailure(t);
}
});
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_restore_TransportRestoreSnapshotAction.java
|
645 |
@Component("blAuthenticationSuccessRedirectStrategy")
public class BroadleafAuthenticationSuccessRedirectStrategy implements RedirectStrategy {
private String redirectPath="/redirect";
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
if (BroadleafControllerUtility.isAjaxRequest(request)) {
request.getSession().setAttribute("BLC_REDIRECT_URL", url);
url = getRedirectPath();
}
redirectStrategy.sendRedirect(request, response, url);
}
public String updateLoginErrorUrlForAjax(String url) {
String blcAjax = BroadleafControllerUtility.BLC_AJAX_PARAMETER;
if (url != null && url.indexOf("?") > 0) {
url = url + "&" + blcAjax + "=true";
} else {
url = url + "?" + blcAjax + "=true";
}
return url;
}
public String getRedirectPath() {
return redirectPath;
}
public void setRedirectPath(String redirectPath) {
this.redirectPath = redirectPath;
}
public RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
}
| 1no label
|
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_common_web_security_BroadleafAuthenticationSuccessRedirectStrategy.java
|
614 |
indexEngine.getValuesMinor(iRangeTo, isInclusive, MultiValuesTransformer.INSTANCE, new OIndexEngine.ValuesResultListener() {
@Override
public boolean addResult(OIdentifiable identifiable) {
return resultListener.addResult(identifiable);
}
});
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_index_OIndexMultiValues.java
|
3,697 |
public class TypeFieldMapper extends AbstractFieldMapper<String> implements InternalMapper, RootMapper {
public static final String NAME = "_type";
public static final String CONTENT_TYPE = "_type";
public static class Defaults extends AbstractFieldMapper.Defaults {
public static final String NAME = TypeFieldMapper.NAME;
public static final String INDEX_NAME = TypeFieldMapper.NAME;
public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE);
static {
FIELD_TYPE.setIndexed(true);
FIELD_TYPE.setTokenized(false);
FIELD_TYPE.setStored(false);
FIELD_TYPE.setOmitNorms(true);
FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_ONLY);
FIELD_TYPE.freeze();
}
}
public static class Builder extends AbstractFieldMapper.Builder<Builder, TypeFieldMapper> {
public Builder() {
super(Defaults.NAME, new FieldType(Defaults.FIELD_TYPE));
indexName = Defaults.INDEX_NAME;
}
@Override
public TypeFieldMapper build(BuilderContext context) {
return new TypeFieldMapper(name, indexName, boost, fieldType, postingsProvider, docValuesProvider, fieldDataSettings, context.indexSettings());
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
TypeFieldMapper.Builder builder = type();
parseField(builder, builder.name, node, parserContext);
return builder;
}
}
public TypeFieldMapper() {
this(Defaults.NAME, Defaults.INDEX_NAME);
}
protected TypeFieldMapper(String name, String indexName) {
this(name, indexName, Defaults.BOOST, new FieldType(Defaults.FIELD_TYPE), null, null, null, ImmutableSettings.EMPTY);
}
public TypeFieldMapper(String name, String indexName, float boost, FieldType fieldType, PostingsFormatProvider postingsProvider,
DocValuesFormatProvider docValuesProvider, @Nullable Settings fieldDataSettings, Settings indexSettings) {
super(new Names(name, indexName, indexName, name), boost, fieldType, null, Lucene.KEYWORD_ANALYZER,
Lucene.KEYWORD_ANALYZER, postingsProvider, docValuesProvider, null, null, fieldDataSettings, indexSettings);
}
@Override
public FieldType defaultFieldType() {
return Defaults.FIELD_TYPE;
}
@Override
public FieldDataType defaultFieldDataType() {
return new FieldDataType("string");
}
@Override
public boolean hasDocValues() {
return false;
}
@Override
public String value(Object value) {
if (value == null) {
return null;
}
return value.toString();
}
@Override
public Query termQuery(Object value, @Nullable QueryParseContext context) {
return new XConstantScoreQuery(context.cacheFilter(termFilter(value, context), null));
}
@Override
public Filter termFilter(Object value, @Nullable QueryParseContext context) {
if (!fieldType.indexed()) {
return new PrefixFilter(new Term(UidFieldMapper.NAME, Uid.typePrefixAsBytes(BytesRefs.toBytesRef(value))));
}
return new TermFilter(names().createIndexNameTerm(BytesRefs.toBytesRef(value)));
}
@Override
public boolean useTermQueryWithQueryString() {
return true;
}
@Override
public void preParse(ParseContext context) throws IOException {
super.parse(context);
}
@Override
public void postParse(ParseContext context) throws IOException {
}
@Override
public void parse(ParseContext context) throws IOException {
// we parse in pre parse
}
@Override
public void validate(ParseContext context) throws MapperParsingException {
}
@Override
public boolean includeInObject() {
return false;
}
@Override
protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException {
if (!fieldType.indexed() && !fieldType.stored()) {
return;
}
fields.add(new Field(names.indexName(), context.type(), fieldType));
if (hasDocValues()) {
fields.add(new SortedSetDocValuesField(names.indexName(), new BytesRef(context.type())));
}
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
boolean includeDefaults = params.paramAsBoolean("include_defaults", false);
// if all are defaults, no sense to write it at all
if (!includeDefaults && fieldType.stored() == Defaults.FIELD_TYPE.stored() && fieldType.indexed() == Defaults.FIELD_TYPE.indexed()) {
return builder;
}
builder.startObject(CONTENT_TYPE);
if (includeDefaults || fieldType.stored() != Defaults.FIELD_TYPE.stored()) {
builder.field("store", fieldType.stored());
}
if (includeDefaults || fieldType.indexed() != Defaults.FIELD_TYPE.indexed()) {
builder.field("index", indexTokenizeOptionToString(fieldType.indexed(), fieldType.tokenized()));
}
builder.endObject();
return builder;
}
@Override
public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
// do nothing here, no merging, but also no exception
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_mapper_internal_TypeFieldMapper.java
|
931 |
public final class LockStoreProxy implements LockStore {
private final LockStoreContainer container;
private final ObjectNamespace namespace;
public LockStoreProxy(LockStoreContainer container, ObjectNamespace namespace) {
this.container = container;
this.namespace = namespace;
}
@Override
public boolean lock(Data key, String caller, long threadId, long ttl) {
LockStore lockStore = getLockStore();
return lockStore.lock(key, caller, threadId, ttl);
}
@Override
public boolean txnLock(Data key, String caller, long threadId, long ttl) {
LockStore lockStore = getLockStore();
return lockStore.txnLock(key, caller, threadId, ttl);
}
@Override
public boolean extendLeaseTime(Data key, String caller, long threadId, long ttl) {
LockStore lockStore = getLockStore();
return lockStore.extendLeaseTime(key, caller, threadId, ttl);
}
@Override
public boolean unlock(Data key, String caller, long threadId) {
LockStore lockStore = getLockStore();
return lockStore.unlock(key, caller, threadId);
}
@Override
public boolean isLocked(Data key) {
LockStore lockStore = getLockStore();
return lockStore.isLocked(key);
}
@Override
public boolean isLockedBy(Data key, String caller, long threadId) {
LockStore lockStore = getLockStore();
return lockStore.isLockedBy(key, caller, threadId);
}
@Override
public int getLockCount(Data key) {
LockStore lockStore = getLockStore();
return lockStore.getLockCount(key);
}
@Override
public long getRemainingLeaseTime(Data key) {
LockStore lockStore = getLockStore();
return lockStore.getRemainingLeaseTime(key);
}
@Override
public boolean canAcquireLock(Data key, String caller, long threadId) {
LockStore lockStore = getLockStore();
return lockStore.canAcquireLock(key, caller, threadId);
}
@Override
public Set<Data> getLockedKeys() {
LockStore lockStore = getLockStore();
return lockStore.getLockedKeys();
}
@Override
public boolean forceUnlock(Data key) {
LockStore lockStore = getLockStore();
return lockStore.forceUnlock(key);
}
@Override
public String getOwnerInfo(Data dataKey) {
LockStore lockStore = getLockStore();
return lockStore.getOwnerInfo(dataKey);
}
private LockStore getLockStore() {
return container.getLockStore(namespace);
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockStoreProxy.java
|
212 |
public class ManagerAuthenticator implements Authenticator {
@Override
public void auth(ClientConnection connection) throws AuthenticationException, IOException {
final Object response = authenticate(connection, credentials, principal, true, true);
principal = (ClientPrincipal) response;
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientConnectionManagerImpl.java
|
2,597 |
private class MasterPingRequestHandler extends BaseTransportRequestHandler<MasterPingRequest> {
public static final String ACTION = "discovery/zen/fd/masterPing";
@Override
public MasterPingRequest newInstance() {
return new MasterPingRequest();
}
@Override
public void messageReceived(MasterPingRequest request, TransportChannel channel) throws Exception {
DiscoveryNodes nodes = nodesProvider.nodes();
// check if we are really the same master as the one we seemed to be think we are
// this can happen if the master got "kill -9" and then another node started using the same port
if (!request.masterNodeId.equals(nodes.localNodeId())) {
throw new NotMasterException();
}
// if we are no longer master, fail...
if (!nodes.localNodeMaster()) {
throw new NoLongerMasterException();
}
if (!nodes.nodeExists(request.nodeId)) {
throw new NodeDoesNotExistOnMasterException();
}
// send a response, and note if we are connected to the master or not
channel.sendResponse(new MasterPingResponseResponse(nodes.nodeExists(request.nodeId)));
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
| 1no label
|
src_main_java_org_elasticsearch_discovery_zen_fd_MasterFaultDetection.java
|
5,195 |
public class InternalGeoHashGrid extends InternalAggregation implements GeoHashGrid {
public static final Type TYPE = new Type("geohash_grid", "ghcells");
public static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public InternalGeoHashGrid readResult(StreamInput in) throws IOException {
InternalGeoHashGrid buckets = new InternalGeoHashGrid();
buckets.readFrom(in);
return buckets;
}
};
public static void registerStreams() {
AggregationStreams.registerStream(STREAM, TYPE.stream());
}
static class Bucket implements GeoHashGrid.Bucket, Comparable<Bucket> {
protected long geohashAsLong;
protected long docCount;
protected InternalAggregations aggregations;
public Bucket(long geohashAsLong, long docCount, InternalAggregations aggregations) {
this.docCount = docCount;
this.aggregations = aggregations;
this.geohashAsLong = geohashAsLong;
}
public String getKey() {
return GeoHashUtils.toString(geohashAsLong);
}
@Override
public Text getKeyAsText() {
return new StringText(getKey());
}
public GeoPoint getKeyAsGeoPoint() {
return GeoHashUtils.decode(geohashAsLong);
}
@Override
public long getDocCount() {
return docCount;
}
@Override
public Aggregations getAggregations() {
return aggregations;
}
@Override
public int compareTo(Bucket other) {
if (this.geohashAsLong > other.geohashAsLong) {
return 1;
}
if (this.geohashAsLong < other.geohashAsLong) {
return -1;
}
return 0;
}
public Bucket reduce(List<? extends Bucket> buckets, CacheRecycler cacheRecycler) {
if (buckets.size() == 1) {
// we still need to reduce the sub aggs
Bucket bucket = buckets.get(0);
bucket.aggregations.reduce(cacheRecycler);
return bucket;
}
Bucket reduced = null;
List<InternalAggregations> aggregationsList = new ArrayList<InternalAggregations>(buckets.size());
for (Bucket bucket : buckets) {
if (reduced == null) {
reduced = bucket;
} else {
reduced.docCount += bucket.docCount;
}
aggregationsList.add(bucket.aggregations);
}
reduced.aggregations = InternalAggregations.reduce(aggregationsList, cacheRecycler);
return reduced;
}
@Override
public Number getKeyAsNumber() {
return geohashAsLong;
}
}
private int requiredSize;
private Collection<Bucket> buckets;
protected Map<String, Bucket> bucketMap;
InternalGeoHashGrid() {
} // for serialization
public InternalGeoHashGrid(String name, int requiredSize, Collection<Bucket> buckets) {
super(name);
this.requiredSize = requiredSize;
this.buckets = buckets;
}
@Override
public Type type() {
return TYPE;
}
@Override
public Collection<GeoHashGrid.Bucket> getBuckets() {
Object o = buckets;
return (Collection<GeoHashGrid.Bucket>) o;
}
@Override
public GeoHashGrid.Bucket getBucketByKey(String geohash) {
if (bucketMap == null) {
bucketMap = new HashMap<String, Bucket>(buckets.size());
for (Bucket bucket : buckets) {
bucketMap.put(bucket.getKey(), bucket);
}
}
return bucketMap.get(geohash);
}
@Override
public GeoHashGrid.Bucket getBucketByKey(Number key) {
return getBucketByKey(GeoHashUtils.toString(key.longValue()));
}
@Override
public GeoHashGrid.Bucket getBucketByKey(GeoPoint key) {
return getBucketByKey(key.geohash());
}
@Override
public InternalGeoHashGrid reduce(ReduceContext reduceContext) {
List<InternalAggregation> aggregations = reduceContext.aggregations();
if (aggregations.size() == 1) {
InternalGeoHashGrid grid = (InternalGeoHashGrid) aggregations.get(0);
grid.reduceAndTrimBuckets(reduceContext.cacheRecycler());
return grid;
}
InternalGeoHashGrid reduced = null;
Recycler.V<LongObjectOpenHashMap<List<Bucket>>> buckets = null;
for (InternalAggregation aggregation : aggregations) {
InternalGeoHashGrid grid = (InternalGeoHashGrid) aggregation;
if (reduced == null) {
reduced = grid;
}
if (buckets == null) {
buckets = reduceContext.cacheRecycler().longObjectMap(grid.buckets.size());
}
for (Bucket bucket : grid.buckets) {
List<Bucket> existingBuckets = buckets.v().get(bucket.geohashAsLong);
if (existingBuckets == null) {
existingBuckets = new ArrayList<Bucket>(aggregations.size());
buckets.v().put(bucket.geohashAsLong, existingBuckets);
}
existingBuckets.add(bucket);
}
}
if (reduced == null) {
// there are only unmapped terms, so we just return the first one (no need to reduce)
return (InternalGeoHashGrid) aggregations.get(0);
}
// TODO: would it be better to sort the backing array buffer of the hppc map directly instead of using a PQ?
final int size = Math.min(requiredSize, buckets.v().size());
BucketPriorityQueue ordered = new BucketPriorityQueue(size);
Object[] internalBuckets = buckets.v().values;
boolean[] states = buckets.v().allocated;
for (int i = 0; i < states.length; i++) {
if (states[i]) {
List<Bucket> sameCellBuckets = (List<Bucket>) internalBuckets[i];
ordered.insertWithOverflow(sameCellBuckets.get(0).reduce(sameCellBuckets, reduceContext.cacheRecycler()));
}
}
buckets.release();
Bucket[] list = new Bucket[ordered.size()];
for (int i = ordered.size() - 1; i >= 0; i--) {
list[i] = ordered.pop();
}
reduced.buckets = Arrays.asList(list);
return reduced;
}
protected void reduceAndTrimBuckets(CacheRecycler cacheRecycler) {
if (requiredSize > buckets.size()) { // nothing to trim
for (Bucket bucket : buckets) {
bucket.aggregations.reduce(cacheRecycler);
}
return;
}
List<Bucket> trimmedBuckets = new ArrayList<Bucket>(requiredSize);
for (Bucket bucket : buckets) {
if (trimmedBuckets.size() >= requiredSize) {
break;
}
bucket.aggregations.reduce(cacheRecycler);
trimmedBuckets.add(bucket);
}
buckets = trimmedBuckets;
}
@Override
public void readFrom(StreamInput in) throws IOException {
this.name = in.readString();
this.requiredSize = in.readVInt();
int size = in.readVInt();
List<Bucket> buckets = new ArrayList<Bucket>(size);
for (int i = 0; i < size; i++) {
buckets.add(new Bucket(in.readLong(), in.readVLong(), InternalAggregations.readAggregations(in)));
}
this.buckets = buckets;
this.bucketMap = null;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
out.writeVInt(requiredSize);
out.writeVInt(buckets.size());
for (Bucket bucket : buckets) {
out.writeLong(bucket.geohashAsLong);
out.writeVLong(bucket.getDocCount());
((InternalAggregations) bucket.getAggregations()).writeTo(out);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
builder.startArray(CommonFields.BUCKETS);
for (Bucket bucket : buckets) {
builder.startObject();
builder.field(CommonFields.KEY, bucket.getKeyAsText());
builder.field(CommonFields.DOC_COUNT, bucket.getDocCount());
((InternalAggregations) bucket.getAggregations()).toXContentInternal(builder, params);
builder.endObject();
}
builder.endArray();
builder.endObject();
return builder;
}
static class BucketPriorityQueue extends PriorityQueue<Bucket> {
public BucketPriorityQueue(int size) {
super(size);
}
@Override
protected boolean lessThan(Bucket o1, Bucket o2) {
long i = o2.getDocCount() - o1.getDocCount();
if (i == 0) {
i = o2.compareTo(o1);
if (i == 0) {
i = System.identityHashCode(o2) - System.identityHashCode(o1);
}
}
return i > 0;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_bucket_geogrid_InternalGeoHashGrid.java
|
12 |
static final class AscendingSubMap<K, V> extends NavigableSubMap<K, V> {
private static final long serialVersionUID = 912986545866124060L;
AscendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
K hi, final boolean hiInclusive) {
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
public Comparator<? super K> comparator() {
return m.comparator();
}
public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) {
if (!inRange(fromKey, fromInclusive))
throw new IllegalArgumentException("fromKey out of range");
if (!inRange(toKey, toInclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<K, V>(m, false, fromKey, fromInclusive, false, toKey, toInclusive);
}
public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) {
if (!inRange(toKey, inclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, toKey, inclusive);
}
public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) {
if (!inRange(fromKey, inclusive))
throw new IllegalArgumentException("fromKey out of range");
return new AscendingSubMap<K, V>(m, false, fromKey, inclusive, toEnd, hi, hiInclusive);
}
public ONavigableMap<K, V> descendingMap() {
ONavigableMap<K, V> mv = descendingMapView;
return (mv != null) ? mv : (descendingMapView = new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi,
hiInclusive));
}
@Override
OLazyIterator<K> keyIterator() {
return new SubMapKeyIterator(absLowest(), absHighFence());
}
@Override
OLazyIterator<K> descendingKeyIterator() {
return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
}
final class AscendingEntrySetView extends EntrySetView {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new SubMapEntryIterator(absLowest(), absHighFence());
}
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
EntrySetView es = entrySetView;
return (es != null) ? es : new AscendingEntrySetView();
}
@Override
OMVRBTreeEntry<K, V> subLowest() {
return absLowest().entry;
}
@Override
OMVRBTreeEntry<K, V> subHighest() {
return absHighest().entry;
}
@Override
OMVRBTreeEntry<K, V> subCeiling(final K key) {
return absCeiling(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subHigher(final K key) {
return absHigher(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subFloor(final K key) {
return absFloor(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subLower(final K key) {
return absLower(key).entry;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
|
1,967 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_CHALLENGE_QUESTION")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@AdminPresentationClass(friendlyName = "ChallengeQuestionImpl_baseChallengeQuestion")
public class ChallengeQuestionImpl implements ChallengeQuestion {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "ChallengeQuestionId")
@GenericGenerator(
name="ChallengeQuestionId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="ChallengeQuestionImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.profile.core.domain.ChallengeQuestionImpl")
}
)
@Column(name = "QUESTION_ID")
protected Long id;
@Column(name = "QUESTION", nullable=false)
@AdminPresentation(friendlyName = "ChallengeQuestionImpl_Challenge_Question", group = "ChallengeQuestionImpl_Customer")
protected String question;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getQuestion() {
return question;
}
@Override
public void setQuestion(String question) {
this.question = question;
}
@Override
public String toString() {
return question;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((question == null) ? 0 : question.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ChallengeQuestionImpl other = (ChallengeQuestionImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (question == null) {
if (other.question != null)
return false;
} else if (!question.equals(other.question))
return false;
return true;
}
}
| 1no label
|
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_domain_ChallengeQuestionImpl.java
|
1,341 |
public class OPaginatedClusterFactory {
public static final OPaginatedClusterFactory INSTANCE = new OPaginatedClusterFactory();
public OCluster createCluster(int configurationVersion) {
if (configurationVersion >= 0 && configurationVersion < 6) {
OLogManager.instance().error(
this,
"You use deprecated version of storage cluster, "
+ "this version is not supported in current implementation. Please do export/import or recreate database.");
return new OPaginatedWithoutRidReuseCluster();
}
return new OPaginatedCluster();
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_OPaginatedClusterFactory.java
|
78 |
public class OSharedResourceIterator<T> implements Iterator<T>, OResettable {
protected final OSharedResourceAdaptiveExternal resource;
protected Iterator<?> iterator;
public OSharedResourceIterator(final OSharedResourceAdaptiveExternal iResource, final Iterator<?> iIterator) {
this.resource = iResource;
this.iterator = iIterator;
}
@Override
public boolean hasNext() {
resource.acquireExclusiveLock();
try {
return iterator.hasNext();
} finally {
resource.releaseExclusiveLock();
}
}
@SuppressWarnings("unchecked")
@Override
public T next() {
resource.acquireExclusiveLock();
try {
return (T) iterator.next();
} finally {
resource.releaseExclusiveLock();
}
}
@Override
public void remove() {
resource.acquireExclusiveLock();
try {
iterator.remove();
} finally {
resource.releaseExclusiveLock();
}
}
@Override
public void reset() {
if( !( iterator instanceof OResettable) )
return;
resource.acquireExclusiveLock();
try {
((OResettable) iterator).reset();
} finally {
resource.releaseExclusiveLock();
}
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceIterator.java
|
39 |
public class ModuleCompletions {
static final class ModuleDescriptorProposal extends CompletionProposal {
ModuleDescriptorProposal(int offset, String prefix, String moduleName) {
super(offset, prefix, MODULE,
"module " + moduleName,
"module " + moduleName + " \"1.0.0\" {}");
}
@Override
public Point getSelection(IDocument document) {
return new Point(offset - prefix.length() + text.indexOf('\"')+1, 5);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
}
static final class ModuleProposal extends CompletionProposal {
private final int len;
private final String versioned;
private final ModuleDetails module;
private final boolean withBody;
private final ModuleVersionDetails version;
private final String name;
private Node node;
ModuleProposal(int offset, String prefix, int len,
String versioned, ModuleDetails module,
boolean withBody, ModuleVersionDetails version,
String name, Node node) {
super(offset, prefix, MODULE, versioned,
versioned.substring(len));
this.len = len;
this.versioned = versioned;
this.module = module;
this.withBody = withBody;
this.version = version;
this.name = name;
this.node = node;
}
@Override
public String getDisplayString() {
String str = super.getDisplayString();
/*if (withBody &&
EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
str = str.replaceAll("\".*\"", "\"<...>\"");
}*/
return str;
}
@Override
public Point getSelection(IDocument document) {
final int off = offset+versioned.length()-prefix.length()-len;
if (withBody) {
final int verlen = version.getVersion().length();
return new Point(off-verlen-2, verlen);
}
else {
return new Point(off, 0);
}
}
@Override
public void apply(IDocument document) {
super.apply(document);
if (withBody && //module.getVersions().size()>1 && //TODO: put this back in when sure it works
EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
final LinkedModeModel linkedModeModel = new LinkedModeModel();
final Point selection = getSelection(document);
List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
for (final ModuleVersionDetails d: module.getVersions()) {
proposals.add(new ICompletionProposal() {
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public Image getImage() {
return CeylonResources.VERSION;
}
@Override
public String getDisplayString() {
return d.getVersion();
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return "Repository: " + d.getOrigin();
}
@Override
public void apply(IDocument document) {
try {
document.replace(selection.x, selection.y,
d.getVersion());
}
catch (BadLocationException e) {
e.printStackTrace();
}
linkedModeModel.exit(ILinkedModeListener.UPDATE_CARET);
}
});
}
ProposalPosition linkedPosition =
new ProposalPosition(document, selection.x, selection.y, 0,
proposals.toArray(NO_COMPLETIONS));
try {
LinkedMode.addLinkedPosition(linkedModeModel, linkedPosition);
LinkedMode.installLinkedMode((CeylonEditor) EditorUtil.getCurrentEditor(),
document, linkedModeModel, this, new LinkedMode.NullExitPolicy(),
1, selection.x+selection.y+2);
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
}
@Override
public String getAdditionalProposalInfo() {
Scope scope = node.getScope();
Unit unit = node.getUnit();
return JDKUtils.isJDKModule(name) ?
getDocumentationForModule(name, JDKUtils.jdk.version,
"This module forms part of the Java SDK.",
scope, unit) :
getDocumentationFor(module, version.getVersion(),
scope, unit);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
}
static final class JDKModuleProposal extends CompletionProposal {
private final String name;
JDKModuleProposal(int offset, String prefix, int len,
String versioned, String name) {
super(offset, prefix, MODULE, versioned,
versioned.substring(len));
this.name = name;
}
@Override
public String getAdditionalProposalInfo() {
return getDocumentationForModule(name, JDKUtils.jdk.version,
"This module forms part of the Java SDK.",
null, null);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
}
private static final SortedSet<String> JDK_MODULE_VERSION_SET = new TreeSet<String>();
{
JDK_MODULE_VERSION_SET.add(JDKUtils.jdk.version);
}
static void addModuleCompletions(CeylonParseController cpc,
int offset, String prefix, Tree.ImportPath path, Node node,
List<ICompletionProposal> result, boolean withBody) {
String fullPath = fullPath(offset, prefix, path);
addModuleCompletions(offset, prefix, node, result, fullPath.length(),
fullPath+prefix, cpc, withBody);
}
private static void addModuleCompletions(int offset, String prefix, Node node,
List<ICompletionProposal> result, final int len, String pfp,
final CeylonParseController cpc, final boolean withBody) {
if (pfp.startsWith("java.")) {
for (String name:
new TreeSet<String>(JDKUtils.getJDKModuleNames())) {
if (name.startsWith(pfp) &&
!moduleAlreadyImported(cpc, name)) {
result.add(new JDKModuleProposal(offset, prefix, len,
getModuleString(withBody, name, JDKUtils.jdk.version),
name));
}
}
}
else {
final TypeChecker tc = cpc.getTypeChecker();
if (tc!=null) {
IProject project = cpc.getProject();
for (ModuleDetails module:
getModuleSearchResults(pfp, tc,project).getResults()) {
final String name = module.getName();
if (!name.equals(Module.DEFAULT_MODULE_NAME) &&
!moduleAlreadyImported(cpc, name)) {
if (EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
result.add(new ModuleProposal(offset, prefix, len,
getModuleString(withBody, name,
module.getLastVersion().getVersion()),
module, withBody, module.getLastVersion(),
name, node));
}
else {
for (final ModuleVersionDetails version:
module.getVersions().descendingSet()) {
result.add(new ModuleProposal(offset, prefix, len,
getModuleString(withBody, name, version.getVersion()),
module, withBody, version, name, node));
}
}
}
}
}
}
}
private static boolean moduleAlreadyImported(CeylonParseController cpc, final String mod) {
if (mod.equals(Module.LANGUAGE_MODULE_NAME)) {
return true;
}
List<Tree.ModuleDescriptor> md = cpc.getRootNode().getModuleDescriptors();
if (!md.isEmpty()) {
Tree.ImportModuleList iml = md.get(0).getImportModuleList();
if (iml!=null) {
for (Tree.ImportModule im: iml.getImportModules()) {
if (im.getImportPath()!=null) {
if (formatPath(im.getImportPath().getIdentifiers()).equals(mod)) {
return true;
}
}
}
}
}
//Disabled, because once the module is imported, it hangs around!
// for (ModuleImport mi: node.getUnit().getPackage().getModule().getImports()) {
// if (mi.getModule().getNameAsString().equals(mod)) {
// return true;
// }
// }
return false;
}
private static String getModuleString(boolean withBody,
String name, String version) {
if (!name.matches("^[a-z_]\\w*(\\.[a-z_]\\w*)*$")) {
name = '"' + name + '"';
}
return withBody ? name + " \"" + version + "\";" : name;
}
static void addModuleDescriptorCompletion(CeylonParseController cpc,
int offset, String prefix, List<ICompletionProposal> result) {
if (!"module".startsWith(prefix)) return;
IFile file = cpc.getProject().getFile(cpc.getPath());
String moduleName = getPackageName(file);
if (moduleName!=null) {
result.add(new ModuleDescriptorProposal(offset, prefix, moduleName));
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ModuleCompletions.java
|
423 |
private class ClientCompletableFuture<V>
extends AbstractCompletableFuture<V>
implements JobCompletableFuture<V> {
private final String jobId;
private final CountDownLatch latch;
private volatile boolean cancelled;
protected ClientCompletableFuture(String jobId) {
super(null, Logger.getLogger(ClientCompletableFuture.class));
this.jobId = jobId;
this.latch = new CountDownLatch(1);
}
@Override
public String getJobId() {
return jobId;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
try {
cancelled = (Boolean) invoke(new ClientCancellationRequest(getName(), jobId), jobId);
} catch (Exception ignore) {
}
return cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setResult(Object result) {
super.setResult(result);
latch.countDown();
}
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
ValidationUtil.isNotNull(unit, "unit");
if (!latch.await(timeout, unit) || !isDone()) {
throw new TimeoutException("timeout reached");
}
return getResult();
}
@Override
protected ExecutorService getAsyncExecutor() {
return getContext().getExecutionService().getAsyncExecutor();
}
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientMapReduceProxy.java
|
318 |
public class LateStageMergeBeanPostProcessor extends AbstractMergeBeanPostProcessor implements Ordered {
protected int order = Integer.MAX_VALUE;
/**
* The regular ordering for this post processor in relation to other post processors. The default
* value is Integer.MAX_VALUE.
*/
@Override
public int getOrder() {
return order;
}
/**
* The regular ordering for this post processor in relation to other post processors. The default
* value is Integer.MAX_VALUE.
*
* @param order the regular ordering
*/
public void setOrder(int order) {
this.order = order;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_LateStageMergeBeanPostProcessor.java
|
3,726 |
public class DynamicTemplate {
public static enum MatchType {
SIMPLE,
REGEX;
public static MatchType fromString(String value) {
if ("simple".equals(value)) {
return SIMPLE;
} else if ("regex".equals(value)) {
return REGEX;
}
throw new ElasticsearchIllegalArgumentException("No matching pattern matched on [" + value + "]");
}
}
public static DynamicTemplate parse(String name, Map<String, Object> conf) throws MapperParsingException {
String match = null;
String pathMatch = null;
String unmatch = null;
String pathUnmatch = null;
Map<String, Object> mapping = null;
String matchMappingType = null;
String matchPattern = "simple";
for (Map.Entry<String, Object> entry : conf.entrySet()) {
String propName = Strings.toUnderscoreCase(entry.getKey());
if ("match".equals(propName)) {
match = entry.getValue().toString();
} else if ("path_match".equals(propName)) {
pathMatch = entry.getValue().toString();
} else if ("unmatch".equals(propName)) {
unmatch = entry.getValue().toString();
} else if ("path_unmatch".equals(propName)) {
pathUnmatch = entry.getValue().toString();
} else if ("match_mapping_type".equals(propName)) {
matchMappingType = entry.getValue().toString();
} else if ("match_pattern".equals(propName)) {
matchPattern = entry.getValue().toString();
} else if ("mapping".equals(propName)) {
mapping = (Map<String, Object>) entry.getValue();
}
}
if (match == null && pathMatch == null && matchMappingType == null) {
throw new MapperParsingException("template must have match, path_match or match_mapping_type set");
}
if (mapping == null) {
throw new MapperParsingException("template must have mapping set");
}
return new DynamicTemplate(name, conf, pathMatch, pathUnmatch, match, unmatch, matchMappingType, MatchType.fromString(matchPattern), mapping);
}
private final String name;
private final Map<String, Object> conf;
private final String pathMatch;
private final String pathUnmatch;
private final String match;
private final String unmatch;
private final MatchType matchType;
private final String matchMappingType;
private final Map<String, Object> mapping;
public DynamicTemplate(String name, Map<String, Object> conf, String pathMatch, String pathUnmatch, String match, String unmatch, String matchMappingType, MatchType matchType, Map<String, Object> mapping) {
this.name = name;
this.conf = new TreeMap<String, Object>(conf);
this.pathMatch = pathMatch;
this.pathUnmatch = pathUnmatch;
this.match = match;
this.unmatch = unmatch;
this.matchType = matchType;
this.matchMappingType = matchMappingType;
this.mapping = mapping;
}
public String name() {
return this.name;
}
public Map<String, Object> conf() {
return this.conf;
}
public boolean match(ContentPath path, String name, String dynamicType) {
if (pathMatch != null && !patternMatch(pathMatch, path.fullPathAsText(name))) {
return false;
}
if (match != null && !patternMatch(match, name)) {
return false;
}
if (pathUnmatch != null && patternMatch(pathUnmatch, path.fullPathAsText(name))) {
return false;
}
if (unmatch != null && patternMatch(unmatch, name)) {
return false;
}
if (matchMappingType != null) {
if (dynamicType == null) {
return false;
}
if (!patternMatch(matchMappingType, dynamicType)) {
return false;
}
}
return true;
}
public boolean hasType() {
return mapping.containsKey("type");
}
public String mappingType(String dynamicType) {
return mapping.containsKey("type") ? mapping.get("type").toString() : dynamicType;
}
private boolean patternMatch(String pattern, String str) {
if (matchType == MatchType.SIMPLE) {
return Regex.simpleMatch(pattern, str);
}
return str.matches(pattern);
}
public Map<String, Object> mappingForName(String name, String dynamicType) {
return processMap(mapping, name, dynamicType);
}
private Map<String, Object> processMap(Map<String, Object> map, String name, String dynamicType) {
Map<String, Object> processedMap = Maps.newHashMap();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey().replace("{name}", name).replace("{dynamic_type}", dynamicType).replace("{dynamicType}", dynamicType);
Object value = entry.getValue();
if (value instanceof Map) {
value = processMap((Map<String, Object>) value, name, dynamicType);
} else if (value instanceof List) {
value = processList((List) value, name, dynamicType);
} else if (value instanceof String) {
value = value.toString().replace("{name}", name).replace("{dynamic_type}", dynamicType).replace("{dynamicType}", dynamicType);
}
processedMap.put(key, value);
}
return processedMap;
}
private List processList(List list, String name, String dynamicType) {
List processedList = new ArrayList();
for (Object value : list) {
if (value instanceof Map) {
value = processMap((Map<String, Object>) value, name, dynamicType);
} else if (value instanceof List) {
value = processList((List) value, name, dynamicType);
} else if (value instanceof String) {
value = value.toString().replace("{name}", name).replace("{dynamic_type}", dynamicType).replace("{dynamicType}", dynamicType);
}
processedList.add(value);
}
return processedList;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DynamicTemplate that = (DynamicTemplate) o;
// check if same matching, if so, replace the mapping
if (match != null ? !match.equals(that.match) : that.match != null) {
return false;
}
if (matchMappingType != null ? !matchMappingType.equals(that.matchMappingType) : that.matchMappingType != null) {
return false;
}
if (matchType != that.matchType) {
return false;
}
if (unmatch != null ? !unmatch.equals(that.unmatch) : that.unmatch != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
// check if same matching, if so, replace the mapping
int result = match != null ? match.hashCode() : 0;
result = 31 * result + (unmatch != null ? unmatch.hashCode() : 0);
result = 31 * result + (matchType != null ? matchType.hashCode() : 0);
result = 31 * result + (matchMappingType != null ? matchMappingType.hashCode() : 0);
return result;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_mapper_object_DynamicTemplate.java
|
361 |
static class NodeStatsRequest extends NodeOperationRequest {
NodesStatsRequest request;
NodeStatsRequest() {
}
NodeStatsRequest(String nodeId, NodesStatsRequest request) {
super(request, nodeId);
this.request = request;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
request = new NodesStatsRequest();
request.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
request.writeTo(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_stats_TransportNodesStatsAction.java
|
205 |
public class BigMemoryHydratedCacheManagerImpl extends AbstractHydratedCacheManager {
private static final Log LOG = LogFactory.getLog(BigMemoryHydratedCacheManagerImpl.class);
private static final BigMemoryHydratedCacheManagerImpl MANAGER = new BigMemoryHydratedCacheManagerImpl();
public static BigMemoryHydratedCacheManagerImpl getInstance() {
return MANAGER;
}
private Map<String, List<String>> cacheMemberNamesByEntity = Collections.synchronizedMap(new HashMap<String, List<String>>(100));
private List<String> removeKeys = Collections.synchronizedList(new ArrayList<String>(100));
private Cache offHeap = null;
private BigMemoryHydratedCacheManagerImpl() {
//CacheManager.getInstance() and CacheManager.create() cannot be called in this constructor because it will create two cache manager instances
}
private Cache getHeap() {
if (offHeap == null) {
if (CacheManager.getInstance().cacheExists("hydrated-offheap-cache")) {
offHeap = CacheManager.getInstance().getCache("hydrated-offheap-cache");
} else {
CacheConfiguration config = new CacheConfiguration("hydrated-offheap-cache", 500).eternal(true).overflowToOffHeap(true).maxMemoryOffHeap("1400M");
Cache cache = new Cache(config);
CacheManager.create().addCache(cache);
offHeap = cache;
}
}
return offHeap;
}
@Override
public Object getHydratedCacheElementItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName) {
Element element;
String myKey = cacheRegion + '_' + cacheName + '_' + elementItemName + '_' + elementKey;
if (removeKeys.contains(myKey)) {
return null;
}
Object response = null;
element = getHeap().get(myKey);
if (element != null) {
response = element.getObjectValue();
}
return response;
}
@Override
public void addHydratedCacheElementItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName, Object elementValue) {
String heapKey = cacheRegion + '_' + cacheName + '_' + elementItemName + '_' + elementKey;
String nameKey = cacheRegion + '_' + cacheName + '_' + elementKey;
removeKeys.remove(nameKey);
Element element = new Element(heapKey, elementValue);
if (!cacheMemberNamesByEntity.containsKey(nameKey)) {
List<String> myMembers = new ArrayList<String>(50);
myMembers.add(elementItemName);
cacheMemberNamesByEntity.put(nameKey, myMembers);
} else {
List<String> myMembers = cacheMemberNamesByEntity.get(nameKey);
myMembers.add(elementItemName);
}
getHeap().put(element);
}
protected void removeCache(String cacheRegion, Serializable key) {
String cacheName = cacheRegion;
if (key instanceof CacheKey) {
cacheName = ((CacheKey) key).getEntityOrRoleName();
key = ((CacheKey) key).getKey();
}
String nameKey = cacheRegion + '_' + cacheName + '_' + key;
if (cacheMemberNamesByEntity.containsKey(nameKey)) {
String[] members = new String[cacheMemberNamesByEntity.get(nameKey).size()];
members = cacheMemberNamesByEntity.get(nameKey).toArray(members);
for (String myMember : members) {
String itemKey = cacheRegion + '_' + myMember + '_' + key;
removeKeys.add(itemKey);
}
cacheMemberNamesByEntity.remove(nameKey);
}
}
protected void removeAll(String cacheName) {
//do nothing
}
@Override
public void notifyElementEvicted(Ehcache arg0, Element arg1) {
removeCache(arg0.getName(), arg1.getKey());
}
@Override
public void notifyElementExpired(Ehcache arg0, Element arg1) {
removeCache(arg0.getName(), arg1.getKey());
}
@Override
public void notifyElementPut(Ehcache arg0, Element arg1) throws CacheException {
//do nothing
}
@Override
public void notifyElementRemoved(Ehcache arg0, Element arg1) throws CacheException {
removeCache(arg0.getName(), arg1.getKey());
}
@Override
public void notifyElementUpdated(Ehcache arg0, Element arg1) throws CacheException {
removeCache(arg0.getName(), arg1.getKey());
}
@Override
public void notifyRemoveAll(Ehcache arg0) {
removeAll(arg0.getName());
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_cache_engine_BigMemoryHydratedCacheManagerImpl.java
|
1,374 |
public class OTransactionOptimistic extends OTransactionRealAbstract {
private static final boolean useSBTree = OGlobalConfiguration.INDEX_USE_SBTREE_BY_DEFAULT.getValueAsBoolean();
private boolean usingLog;
private static AtomicInteger txSerial = new AtomicInteger();
private int autoRetries = OGlobalConfiguration.TX_AUTO_RETRY.getValueAsInteger();
public OTransactionOptimistic(final ODatabaseRecordTx iDatabase) {
super(iDatabase, txSerial.incrementAndGet());
usingLog = OGlobalConfiguration.TX_USE_LOG.getValueAsBoolean();
}
public void begin() {
status = TXSTATUS.BEGUN;
}
public void commit() {
checkTransaction();
status = TXSTATUS.COMMITTING;
if (OScenarioThreadLocal.INSTANCE.get() != RUN_MODE.RUNNING_DISTRIBUTED && !(database.getStorage() instanceof OStorageEmbedded))
database.getStorage().commit(this, null);
else {
final List<String> involvedIndexes = getInvolvedIndexes();
if (involvedIndexes != null)
Collections.sort(involvedIndexes);
for (int retry = 1; retry <= autoRetries; ++retry) {
try {
// LOCK INVOLVED INDEXES
List<OIndexAbstract<?>> lockedIndexes = null;
try {
if (involvedIndexes != null)
for (String indexName : involvedIndexes) {
final OIndexAbstract<?> index = (OIndexAbstract<?>) database.getMetadata().getIndexManager()
.getIndexInternal(indexName);
if (lockedIndexes == null)
lockedIndexes = new ArrayList<OIndexAbstract<?>>();
index.acquireModificationLock();
lockedIndexes.add(index);
}
if (!useSBTree) {
// SEARCH FOR INDEX BASED ON DOCUMENT TOUCHED
final Collection<? extends OIndex<?>> indexes = database.getMetadata().getIndexManager().getIndexes();
List<? extends OIndex<?>> indexesToLock = null;
if (indexes != null) {
indexesToLock = new ArrayList<OIndex<?>>(indexes);
Collections.sort(indexesToLock, new Comparator<OIndex<?>>() {
public int compare(final OIndex<?> indexOne, final OIndex<?> indexTwo) {
return indexOne.getName().compareTo(indexTwo.getName());
}
});
}
if (indexesToLock != null && !indexesToLock.isEmpty()) {
if (lockedIndexes == null)
lockedIndexes = new ArrayList<OIndexAbstract<?>>();
for (OIndex<?> index : indexesToLock) {
for (Entry<ORID, ORecordOperation> entry : recordEntries.entrySet()) {
final ORecord<?> record = entry.getValue().record.getRecord();
if (record instanceof ODocument) {
ODocument doc = (ODocument) record;
if (!lockedIndexes.contains(index.getInternal()) && doc.getSchemaClass() != null
&& index.getDefinition() != null
&& doc.getSchemaClass().isSubClassOf(index.getDefinition().getClassName())) {
index.getInternal().acquireModificationLock();
lockedIndexes.add((OIndexAbstract<?>) index.getInternal());
}
}
}
}
for (OIndexAbstract<?> index : lockedIndexes)
index.acquireExclusiveLock();
}
}
final Map<String, OIndex> indexes = new HashMap<String, OIndex>();
for (OIndex index : database.getMetadata().getIndexManager().getIndexes())
indexes.put(index.getName(), index);
final Runnable callback = new Runnable() {
@Override
public void run() {
final ODocument indexEntries = getIndexChanges();
if (indexEntries != null) {
final Map<String, OIndexInternal<?>> indexesToCommit = new HashMap<String, OIndexInternal<?>>();
for (Entry<String, Object> indexEntry : indexEntries) {
final OIndexInternal<?> index = indexes.get(indexEntry.getKey()).getInternal();
indexesToCommit.put(index.getName(), index.getInternal());
}
for (OIndexInternal<?> indexInternal : indexesToCommit.values())
indexInternal.preCommit();
for (Entry<String, Object> indexEntry : indexEntries) {
final OIndexInternal<?> index = indexesToCommit.get(indexEntry.getKey()).getInternal();
if (index == null) {
OLogManager.instance().error(this, "Index with name " + indexEntry.getKey() + " was not found.");
throw new OIndexException("Index with name " + indexEntry.getKey() + " was not found.");
} else
index.addTxOperation((ODocument) indexEntry.getValue());
}
try {
for (OIndexInternal<?> indexInternal : indexesToCommit.values())
indexInternal.commit();
} finally {
for (OIndexInternal<?> indexInternal : indexesToCommit.values())
indexInternal.postCommit();
}
}
}
};
final String storageType = database.getStorage().getType();
if (storageType.equals(OEngineLocal.NAME) || storageType.equals(OEngineLocalPaginated.NAME))
database.getStorage().commit(OTransactionOptimistic.this, callback);
else {
database.getStorage().callInLock(new Callable<Object>() {
@Override
public Object call() throws Exception {
database.getStorage().commit(OTransactionOptimistic.this, null);
callback.run();
return null;
}
}, true);
}
// OK
break;
} finally {
// RELEASE INDEX LOCKS IF ANY
if (lockedIndexes != null) {
if (!useSBTree) {
for (OIndexAbstract<?> index : lockedIndexes)
index.releaseExclusiveLock();
}
for (OIndexAbstract<?> index : lockedIndexes)
index.releaseModificationLock();
}
}
} catch (OTimeoutException e) {
if (autoRetries == 0) {
OLogManager.instance().debug(this, "Caught timeout exception during commit, but no automatic retry has been set", e);
throw e;
} else if (retry == autoRetries) {
OLogManager.instance().debug(this, "Caught timeout exception during %d/%d. Retry limit is exceeded.", retry,
autoRetries);
throw e;
} else {
OLogManager.instance().debug(this, "Caught timeout exception during commit retrying %d/%d...", retry, autoRetries);
}
}
}
}
}
public void rollback() {
checkTransaction();
status = TXSTATUS.ROLLBACKING;
database.getStorage().callInLock(new Callable<Void>() {
public Void call() throws Exception {
database.getStorage().rollback(OTransactionOptimistic.this);
return null;
}
}, true);
// CLEAR THE CACHE MOVING GOOD RECORDS TO LEVEL-2 CACHE
database.getLevel1Cache().clear();
// REMOVE ALL THE ENTRIES AND INVALIDATE THE DOCUMENTS TO AVOID TO BE RE-USED DIRTY AT USER-LEVEL. IN THIS WAY RE-LOADING MUST
// EXECUTED
for (ORecordOperation v : recordEntries.values())
v.getRecord().unload();
for (ORecordOperation v : allEntries.values())
v.getRecord().unload();
indexEntries.clear();
}
public ORecordInternal<?> loadRecord(final ORID iRid, final ORecordInternal<?> iRecord, final String iFetchPlan,
boolean ignoreCache, boolean loadTombstone) {
checkTransaction();
final ORecordInternal<?> txRecord = getRecord(iRid);
if (txRecord == OTransactionRealAbstract.DELETED_RECORD)
// DELETED IN TX
return null;
if (txRecord != null) {
if (iRecord != null && txRecord != iRecord)
OLogManager.instance().warn(
this,
"Found record in transaction with the same RID %s but different instance. "
+ "Probably the record has been loaded from another transaction and reused on the current one: reload it "
+ "from current transaction before to update or delete it", iRecord.getIdentity());
return txRecord;
}
if (iRid.isTemporary())
return null;
// DELEGATE TO THE STORAGE, NO TOMBSTONES SUPPORT IN TX MODE
final ORecordInternal<?> record = database.executeReadRecord((ORecordId) iRid, iRecord, iFetchPlan, ignoreCache, false);
if (record != null)
addRecord(record, ORecordOperation.LOADED, null);
return record;
}
public void deleteRecord(final ORecordInternal<?> iRecord, final OPERATION_MODE iMode) {
if (!iRecord.getIdentity().isValid())
return;
addRecord(iRecord, ORecordOperation.DELETED, null);
}
public void saveRecord(final ORecordInternal<?> iRecord, final String iClusterName, final OPERATION_MODE iMode,
boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback,
ORecordCallback<ORecordVersion> iRecordUpdatedCallback) {
if (iRecord == null)
return;
final byte operation = iForceCreate ? ORecordOperation.CREATED : iRecord.getIdentity().isValid() ? ORecordOperation.UPDATED
: ORecordOperation.CREATED;
addRecord(iRecord, operation, iClusterName);
}
protected void addRecord(final ORecordInternal<?> iRecord, final byte iStatus, final String iClusterName) {
checkTransaction();
switch (iStatus) {
case ORecordOperation.CREATED:
database.callbackHooks(TYPE.BEFORE_CREATE, iRecord);
break;
case ORecordOperation.LOADED:
/**
* Read hooks already invoked in {@link com.orientechnologies.orient.core.db.record.ODatabaseRecordAbstract#executeReadRecord}
* .
*/
break;
case ORecordOperation.UPDATED:
database.callbackHooks(TYPE.BEFORE_UPDATE, iRecord);
break;
case ORecordOperation.DELETED:
database.callbackHooks(TYPE.BEFORE_DELETE, iRecord);
break;
}
try {
if (iRecord.getIdentity().isTemporary())
temp2persistent.put(iRecord.getIdentity().copy(), iRecord);
if ((status == OTransaction.TXSTATUS.COMMITTING) && database.getStorage() instanceof OStorageEmbedded) {
// I'M COMMITTING: BYPASS LOCAL BUFFER
switch (iStatus) {
case ORecordOperation.CREATED:
case ORecordOperation.UPDATED:
final ORID oldRid = iRecord.getIdentity().copy();
database.executeSaveRecord(iRecord, iClusterName, iRecord.getRecordVersion(), iRecord.getRecordType(), false,
OPERATION_MODE.SYNCHRONOUS, false, null, null);
updateIdentityAfterCommit(oldRid, iRecord.getIdentity());
break;
case ORecordOperation.DELETED:
database.executeDeleteRecord(iRecord, iRecord.getRecordVersion(), false, false, OPERATION_MODE.SYNCHRONOUS, false);
break;
}
final ORecordOperation txRecord = getRecordEntry(iRecord.getIdentity());
if (txRecord == null) {
// NOT IN TX, SAVE IT ANYWAY
allEntries.put(iRecord.getIdentity(), new ORecordOperation(iRecord, iStatus));
} else if (txRecord.record != iRecord) {
// UPDATE LOCAL RECORDS TO AVOID MISMATCH OF VERSION/CONTENT
final String clusterName = getDatabase().getClusterNameById(iRecord.getIdentity().getClusterId());
if (!clusterName.equals(OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME)
&& !clusterName.equals(OMetadataDefault.CLUSTER_INDEX_NAME))
OLogManager
.instance()
.warn(
this,
"Found record in transaction with the same RID %s but different instance. Probably the record has been loaded from another transaction and reused on the current one: reload it from current transaction before to update or delete it",
iRecord.getIdentity());
txRecord.record = iRecord;
txRecord.type = iStatus;
}
} else {
final ORecordId rid = (ORecordId) iRecord.getIdentity();
if (!rid.isValid()) {
iRecord.onBeforeIdentityChanged(rid);
// ASSIGN A UNIQUE SERIAL TEMPORARY ID
if (rid.clusterId == ORID.CLUSTER_ID_INVALID)
rid.clusterId = iClusterName != null ? database.getClusterIdByName(iClusterName) : database.getDefaultClusterId();
rid.clusterPosition = OClusterPositionFactory.INSTANCE.valueOf(newObjectCounter--);
iRecord.onAfterIdentityChanged(iRecord);
} else
// REMOVE FROM THE DB'S CACHE
database.getLevel1Cache().freeRecord(rid);
ORecordOperation txEntry = getRecordEntry(rid);
if (txEntry == null) {
if (!(rid.isTemporary() && iStatus != ORecordOperation.CREATED)) {
// NEW ENTRY: JUST REGISTER IT
txEntry = new ORecordOperation(iRecord, iStatus);
recordEntries.put(rid, txEntry);
}
} else {
// UPDATE PREVIOUS STATUS
txEntry.record = iRecord;
switch (txEntry.type) {
case ORecordOperation.LOADED:
switch (iStatus) {
case ORecordOperation.UPDATED:
txEntry.type = ORecordOperation.UPDATED;
break;
case ORecordOperation.DELETED:
txEntry.type = ORecordOperation.DELETED;
break;
}
break;
case ORecordOperation.UPDATED:
switch (iStatus) {
case ORecordOperation.DELETED:
txEntry.type = ORecordOperation.DELETED;
break;
}
break;
case ORecordOperation.DELETED:
break;
case ORecordOperation.CREATED:
switch (iStatus) {
case ORecordOperation.DELETED:
recordEntries.remove(rid);
break;
}
break;
}
}
}
switch (iStatus) {
case ORecordOperation.CREATED:
database.callbackHooks(TYPE.AFTER_CREATE, iRecord);
break;
case ORecordOperation.LOADED:
/**
* Read hooks already invoked in
* {@link com.orientechnologies.orient.core.db.record.ODatabaseRecordAbstract#executeReadRecord}.
*/
break;
case ORecordOperation.UPDATED:
database.callbackHooks(TYPE.AFTER_UPDATE, iRecord);
break;
case ORecordOperation.DELETED:
database.callbackHooks(TYPE.AFTER_DELETE, iRecord);
break;
}
} catch (Throwable t) {
switch (iStatus) {
case ORecordOperation.CREATED:
database.callbackHooks(TYPE.CREATE_FAILED, iRecord);
break;
case ORecordOperation.UPDATED:
database.callbackHooks(TYPE.UPDATE_FAILED, iRecord);
break;
case ORecordOperation.DELETED:
database.callbackHooks(TYPE.DELETE_FAILED, iRecord);
break;
}
if (t instanceof RuntimeException)
throw (RuntimeException) t;
else
throw new ODatabaseException("Error on saving record " + iRecord.getIdentity(), t);
}
}
@Override
public boolean updateReplica(ORecordInternal<?> iRecord) {
throw new UnsupportedOperationException("updateReplica()");
}
@Override
public String toString() {
return "OTransactionOptimistic [id=" + id + ", status=" + status + ", recEntries=" + recordEntries.size() + ", idxEntries="
+ indexEntries.size() + ']';
}
public boolean isUsingLog() {
return usingLog;
}
public void setUsingLog(final boolean useLog) {
this.usingLog = useLog;
}
public int getAutoRetries() {
return autoRetries;
}
public void setAutoRetries(final int autoRetries) {
this.autoRetries = autoRetries;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_tx_OTransactionOptimistic.java
|
1,421 |
public class OChannelBinaryAsynchClient extends OChannelBinary {
private final Condition readCondition = lockRead.getUnderlying().newCondition();
private volatile boolean channelRead = false;
private byte currentStatus;
private int currentSessionId;
private final int maxUnreadResponses;
protected final int socketTimeout; // IN MS
protected final short srvProtocolVersion;
private final String serverURL;
private OAsynchChannelServiceThread serviceThread;
public OChannelBinaryAsynchClient(final String remoteHost, final int remotePort, final OContextConfiguration iConfig,
final int iProtocolVersion) throws IOException {
this(remoteHost, remotePort, iConfig, iProtocolVersion, null);
}
public OChannelBinaryAsynchClient(final String remoteHost, final int remotePort, final OContextConfiguration iConfig,
final int protocolVersion, final ORemoteServerEventListener asynchEventListener) throws IOException {
super(new Socket(), iConfig);
maxUnreadResponses = OGlobalConfiguration.NETWORK_BINARY_READ_RESPONSE_MAX_TIMES.getValueAsInteger();
serverURL = remoteHost + ":" + remotePort;
socketTimeout = iConfig.getValueAsInteger(OGlobalConfiguration.NETWORK_SOCKET_TIMEOUT);
socket.setPerformancePreferences(0, 2, 1);
socket.setKeepAlive(true);
socket.setSendBufferSize(socketBufferSize);
socket.setReceiveBufferSize(socketBufferSize);
try {
socket.connect(new InetSocketAddress(remoteHost, remotePort), socketTimeout);
connected();
} catch (java.net.SocketTimeoutException e) {
throw new IOException("Cannot connect to host " + remoteHost + ":" + remotePort, e);
}
inStream = new BufferedInputStream(socket.getInputStream(), socketBufferSize);
outStream = new BufferedOutputStream(socket.getOutputStream(), socketBufferSize);
in = new DataInputStream(inStream);
out = new DataOutputStream(outStream);
try {
srvProtocolVersion = readShort();
} catch (IOException e) {
throw new ONetworkProtocolException("Cannot read protocol version from remote server " + socket.getRemoteSocketAddress()
+ ": " + e);
}
if (srvProtocolVersion != protocolVersion) {
OLogManager.instance().warn(
this,
"The Client driver version is different than Server version: client=" + protocolVersion + ", server="
+ srvProtocolVersion
+ ". You could not use the full features of the newer version. Assure to have the same versions on both");
}
if (asynchEventListener != null)
serviceThread = new OAsynchChannelServiceThread(asynchEventListener, this);
}
public void beginRequest() {
acquireWriteLock();
}
public void endRequest() throws IOException {
flush();
releaseWriteLock();
}
public void beginResponse(final int iRequesterId) throws IOException {
beginResponse(iRequesterId, timeout);
}
public void beginResponse(final int iRequesterId, final long iTimeout) throws IOException {
try {
int unreadResponse = 0;
final long startClock = iTimeout > 0 ? System.currentTimeMillis() : 0;
// WAIT FOR THE RESPONSE
do {
if (iTimeout <= 0)
acquireReadLock();
else if (!lockRead.tryAcquireLock(iTimeout, TimeUnit.MILLISECONDS))
throw new OTimeoutException("Cannot acquire read lock against channel: " + this);
if (!channelRead) {
channelRead = true;
try {
currentStatus = readByte();
currentSessionId = readInt();
if (debug)
OLogManager.instance().debug(this, "%s - Read response: %d-%d", socket.getLocalAddress(), (int) currentStatus,
currentSessionId);
} catch (IOException e) {
// UNLOCK THE RESOURCE AND PROPAGATES THE EXCEPTION
channelRead = false;
readCondition.signalAll();
releaseReadLock();
throw e;
}
}
if (currentSessionId == iRequesterId)
// IT'S FOR ME
break;
try {
if (debug)
OLogManager.instance().debug(this, "%s - Session %d skip response, it is for %d", socket.getLocalAddress(),
iRequesterId, currentSessionId);
if (iTimeout > 0 && (System.currentTimeMillis() - startClock) > iTimeout) {
// CLOSE THE SOCKET TO CHANNEL TO AVOID FURTHER DIRTY DATA
close();
throw new OTimeoutException("Timeout on reading response from the server "
+ (socket != null ? socket.getRemoteSocketAddress() : "") + " for the request " + iRequesterId);
}
if (unreadResponse > maxUnreadResponses) {
if (debug)
OLogManager.instance().info(this, "Unread responses %d > %d, consider the buffer as dirty: clean it", unreadResponse,
maxUnreadResponses);
close();
throw new IOException("Timeout on reading response");
}
readCondition.signalAll();
if (debug)
OLogManager.instance().debug(this, "Session %d is going to sleep...", iRequesterId);
final long start = System.currentTimeMillis();
// WAIT 1 SECOND AND RETRY
readCondition.await(1, TimeUnit.SECONDS);
final long now = System.currentTimeMillis();
if (debug)
OLogManager.instance().debug(this, "Waked up: slept %dms, checking again from %s for session %d", (now - start),
socket.getLocalAddress(), iRequesterId);
if (now - start >= 1000)
unreadResponse++;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
releaseReadLock();
}
} while (true);
if (debug)
OLogManager.instance().debug(this, "%s - Session %d handle response", socket.getLocalAddress(), iRequesterId);
handleStatus(currentStatus, currentSessionId);
} catch (OLockException e) {
Thread.currentThread().interrupt();
// NEVER HAPPENS?
e.printStackTrace();
}
}
protected int handleStatus(final byte iResult, final int iClientTxId) throws IOException {
if (iResult == OChannelBinaryProtocol.RESPONSE_STATUS_OK || iResult == OChannelBinaryProtocol.PUSH_DATA) {
} else if (iResult == OChannelBinaryProtocol.RESPONSE_STATUS_ERROR) {
StringBuilder buffer = new StringBuilder();
final List<OPair<String, String>> exceptions = new ArrayList<OPair<String, String>>();
// EXCEPTION
while (readByte() == 1) {
final String excClassName = readString();
final String excMessage = readString();
exceptions.add(new OPair<String, String>(excClassName, excMessage));
}
byte[] serializedException = null;
if (srvProtocolVersion >= 19)
serializedException = readBytes();
Exception previous = null;
if (serializedException != null && serializedException.length > 0)
throwSerializedException(serializedException);
for (int i = exceptions.size() - 1; i > -1; --i) {
previous = createException(exceptions.get(i).getKey(), exceptions.get(i).getValue(), previous);
}
if (previous != null) {
throw new RuntimeException(previous);
} else
throw new ONetworkProtocolException("Network response error: " + buffer.toString());
} else {
// PROTOCOL ERROR
// close();
throw new ONetworkProtocolException("Error on reading response from the server");
}
return iClientTxId;
}
private void throwSerializedException(byte[] serializedException) throws IOException {
final OMemoryInputStream inputStream = new OMemoryInputStream(serializedException);
final ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Object throwable = null;
try {
throwable = objectInputStream.readObject();
} catch (ClassNotFoundException e) {
OLogManager.instance().error(this, "Error during exception serialization.", e);
}
objectInputStream.close();
if (throwable instanceof Throwable)
throw new OResponseProcessingException("Exception during response processing.", (Throwable) throwable);
else
OLogManager.instance().error(
this,
"Error during exception serialization, serialized exception is not Throwable, exception type is "
+ (throwable != null ? throwable.getClass().getName() : "null"));
}
@SuppressWarnings("unchecked")
private static RuntimeException createException(final String iClassName, final String iMessage, final Exception iPrevious) {
RuntimeException rootException = null;
Constructor<?> c = null;
try {
final Class<RuntimeException> excClass = (Class<RuntimeException>) Class.forName(iClassName);
if (iPrevious != null) {
try {
c = excClass.getConstructor(String.class, Throwable.class);
} catch (NoSuchMethodException e) {
c = excClass.getConstructor(String.class, Exception.class);
}
}
if (c == null)
c = excClass.getConstructor(String.class);
} catch (Exception e) {
// UNABLE TO REPRODUCE THE SAME SERVER-SIZE EXCEPTION: THROW A STORAGE EXCEPTION
rootException = new OStorageException(iMessage, iPrevious);
}
if (c != null)
try {
final Throwable e;
if (c.getParameterTypes().length > 1)
e = (Throwable) c.newInstance(iMessage, iPrevious);
else
e = (Throwable) c.newInstance(iMessage);
if (e instanceof RuntimeException)
rootException = (RuntimeException) e;
else
rootException = new OException(e);
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
return rootException;
}
public void endResponse() {
channelRead = false;
// WAKE UP ALL THE WAITING THREADS
try {
readCondition.signalAll();
} catch (IllegalMonitorStateException e) {
// IGNORE IT
OLogManager.instance().debug(this, "Error on signaling waiting clients after reading response");
}
try {
releaseReadLock();
} catch (IllegalMonitorStateException e) {
// IGNORE IT
OLogManager.instance().debug(this, "Error on unlocking network channel after reading response");
}
}
@Override
public void close() {
if (lockRead.tryAcquireLock())
try {
readCondition.signalAll();
} finally {
releaseReadLock();
}
super.close();
if (serviceThread != null) {
final OAsynchChannelServiceThread s = serviceThread;
serviceThread = null;
s.sendShutdown();
}
}
@Override
public void clearInput() throws IOException {
acquireReadLock();
try {
super.clearInput();
} finally {
releaseReadLock();
}
}
/**
* Tells if the channel is connected.
*
* @return true if it's connected, otherwise false.
*/
public boolean isConnected() {
if (socket != null && socket.isConnected() && !socket.isInputShutdown() && !socket.isOutputShutdown())
return true;
return false;
}
/**
* Gets the major supported protocol version
*
*/
public short getSrvProtocolVersion() {
return srvProtocolVersion;
}
public OAdaptiveLock getLockRead() {
return lockRead;
}
public OAdaptiveLock getLockWrite() {
return lockWrite;
}
public String getServerURL() {
return serverURL;
}
}
| 1no label
|
enterprise_src_main_java_com_orientechnologies_orient_enterprise_channel_binary_OChannelBinaryAsynchClient.java
|
274 |
public class PortableHelpersFactory implements PortableFactory {
public static final int ID = 666;
public Portable create(int classId) {
if (classId == SimpleClientInterceptor.ID){
return new SimpleClientInterceptor();
}
return null;
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_helpers_PortableHelpersFactory.java
|
237 |
new OProfilerHookValue() {
public Object getValue() {
return getMaxSize();
}
}, profilerMetadataPrefix + "max");
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_cache_OAbstractRecordCache.java
|
470 |
public class ExternalModuleNode implements ModuleNode {
private RepositoryNode repositoryNode;
private List<IPackageFragmentRoot> binaryArchives = new ArrayList<>();
protected String moduleSignature;
public ExternalModuleNode(RepositoryNode repositoryNode, String moduleSignature) {
this.moduleSignature = moduleSignature;
this.repositoryNode = repositoryNode;
}
public List<IPackageFragmentRoot> getBinaryArchives() {
return binaryArchives;
}
public CeylonArchiveFileStore getSourceArchive() {
JDTModule module = getModule();
if (module.isCeylonArchive()) {
String sourcePathString = module.getSourceArchivePath();
if (sourcePathString != null) {
IFolder sourceArchive = getExternalSourceArchiveManager().getSourceArchive(Path.fromOSString(sourcePathString));
if (sourceArchive != null && sourceArchive.exists()) {
return ((CeylonArchiveFileStore) ((Resource)sourceArchive).getStore());
}
}
}
return null;
}
public RepositoryNode getRepositoryNode() {
return repositoryNode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((moduleSignature == null) ? 0 : moduleSignature
.hashCode());
result = prime
* result
+ ((repositoryNode == null) ? 0 : repositoryNode.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ExternalModuleNode other = (ExternalModuleNode) obj;
if (moduleSignature == null) {
if (other.moduleSignature != null)
return false;
} else if (!moduleSignature.equals(other.moduleSignature))
return false;
if (repositoryNode == null) {
if (other.repositoryNode != null)
return false;
} else if (!repositoryNode.equals(other.repositoryNode))
return false;
return true;
}
@Override
public JDTModule getModule() {
for (JDTModule module : CeylonBuilder.getProjectExternalModules(repositoryNode.project)) {
if (module.getSignature().equals(moduleSignature)) {
return module;
}
}
return null;
}
}
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_navigator_ExternalModuleNode.java
|
401 |
public class CreateSnapshotResponse extends ActionResponse implements ToXContent {
@Nullable
private SnapshotInfo snapshotInfo;
CreateSnapshotResponse(@Nullable SnapshotInfo snapshotInfo) {
this.snapshotInfo = snapshotInfo;
}
CreateSnapshotResponse() {
}
/**
* Returns snapshot information if snapshot was completed by the time this method returned or null otherwise.
*
* @return snapshot information or null
*/
public SnapshotInfo getSnapshotInfo() {
return snapshotInfo;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
snapshotInfo = SnapshotInfo.readOptionalSnapshotInfo(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalStreamable(snapshotInfo);
}
/**
* Returns HTTP status
* <p/>
* <ul>
* <li>{@link RestStatus#ACCEPTED}</li> if snapshot is still in progress
* <li>{@link RestStatus#OK}</li> if snapshot was successful or partially successful
* <li>{@link RestStatus#INTERNAL_SERVER_ERROR}</li> if snapshot failed completely
* </ul>
*
* @return
*/
public RestStatus status() {
if (snapshotInfo == null) {
return RestStatus.ACCEPTED;
}
return snapshotInfo.status();
}
static final class Fields {
static final XContentBuilderString SNAPSHOT = new XContentBuilderString("snapshot");
static final XContentBuilderString ACCEPTED = new XContentBuilderString("accepted");
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (snapshotInfo != null) {
builder.field(Fields.SNAPSHOT);
snapshotInfo.toXContent(builder, params);
} else {
builder.field(Fields.ACCEPTED, true);
}
return builder;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_create_CreateSnapshotResponse.java
|
737 |
public class ShardDeleteByQueryRequest extends ShardReplicationOperationRequest<ShardDeleteByQueryRequest> {
private int shardId;
private BytesReference source;
private String[] types = Strings.EMPTY_ARRAY;
@Nullable
private Set<String> routing;
@Nullable
private String[] filteringAliases;
ShardDeleteByQueryRequest(IndexDeleteByQueryRequest request, int shardId) {
super(request);
this.index = request.index();
this.source = request.source();
this.types = request.types();
this.shardId = shardId;
replicationType(request.replicationType());
consistencyLevel(request.consistencyLevel());
timeout = request.timeout();
this.routing = request.routing();
filteringAliases = request.filteringAliases();
}
ShardDeleteByQueryRequest() {
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = super.validate();
if (source == null) {
addValidationError("source is missing", validationException);
}
return validationException;
}
public int shardId() {
return this.shardId;
}
BytesReference source() {
return source;
}
public String[] types() {
return this.types;
}
public Set<String> routing() {
return this.routing;
}
public String[] filteringAliases() {
return filteringAliases;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
source = in.readBytesReference();
shardId = in.readVInt();
types = in.readStringArray();
int routingSize = in.readVInt();
if (routingSize > 0) {
routing = new HashSet<String>(routingSize);
for (int i = 0; i < routingSize; i++) {
routing.add(in.readString());
}
}
int aliasesSize = in.readVInt();
if (aliasesSize > 0) {
filteringAliases = new String[aliasesSize];
for (int i = 0; i < aliasesSize; i++) {
filteringAliases[i] = in.readString();
}
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBytesReference(source);
out.writeVInt(shardId);
out.writeStringArray(types);
if (routing != null) {
out.writeVInt(routing.size());
for (String r : routing) {
out.writeString(r);
}
} else {
out.writeVInt(0);
}
if (filteringAliases != null) {
out.writeVInt(filteringAliases.length);
for (String alias : filteringAliases) {
out.writeString(alias);
}
} else {
out.writeVInt(0);
}
}
@Override
public String toString() {
String sSource = "_na_";
try {
sSource = XContentHelper.convertToJson(source, false);
} catch (Exception e) {
// ignore
}
return "delete_by_query {[" + index + "]" + Arrays.toString(types) + ", query [" + sSource + "]}";
}
}
| 0true
|
src_main_java_org_elasticsearch_action_deletebyquery_ShardDeleteByQueryRequest.java
|
503 |
public class CreateIndexRequest extends AcknowledgedRequest<CreateIndexRequest> {
private String cause = "";
private String index;
private Settings settings = EMPTY_SETTINGS;
private Map<String, String> mappings = newHashMap();
private Map<String, IndexMetaData.Custom> customs = newHashMap();
CreateIndexRequest() {
}
/**
* Constructs a new request to create an index with the specified name.
*/
public CreateIndexRequest(String index) {
this(index, EMPTY_SETTINGS);
}
/**
* Constructs a new request to create an index with the specified name and settings.
*/
public CreateIndexRequest(String index, Settings settings) {
this.index = index;
this.settings = settings;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (index == null) {
validationException = addValidationError("index is missing", validationException);
}
return validationException;
}
/**
* The index name to create.
*/
String index() {
return index;
}
public CreateIndexRequest index(String index) {
this.index = index;
return this;
}
/**
* The settings to create the index with.
*/
Settings settings() {
return settings;
}
/**
* The cause for this index creation.
*/
String cause() {
return cause;
}
/**
* A simplified version of settings that takes key value pairs settings.
*/
public CreateIndexRequest settings(Object... settings) {
this.settings = ImmutableSettings.builder().put(settings).build();
return this;
}
/**
* The settings to create the index with.
*/
public CreateIndexRequest settings(Settings settings) {
this.settings = settings;
return this;
}
/**
* The settings to create the index with.
*/
public CreateIndexRequest settings(Settings.Builder settings) {
this.settings = settings.build();
return this;
}
/**
* The settings to create the index with (either json/yaml/properties format)
*/
public CreateIndexRequest settings(String source) {
this.settings = ImmutableSettings.settingsBuilder().loadFromSource(source).build();
return this;
}
/**
* Allows to set the settings using a json builder.
*/
public CreateIndexRequest settings(XContentBuilder builder) {
try {
settings(builder.string());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate json settings from builder", e);
}
return this;
}
/**
* The settings to create the index with (either json/yaml/properties format)
*/
@SuppressWarnings("unchecked")
public CreateIndexRequest settings(Map source) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.map(source);
settings(builder.string());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
}
return this;
}
/**
* Adds mapping that will be added when the index gets created.
*
* @param type The mapping type
* @param source The mapping source
*/
public CreateIndexRequest mapping(String type, String source) {
mappings.put(type, source);
return this;
}
/**
* The cause for this index creation.
*/
public CreateIndexRequest cause(String cause) {
this.cause = cause;
return this;
}
/**
* Adds mapping that will be added when the index gets created.
*
* @param type The mapping type
* @param source The mapping source
*/
public CreateIndexRequest mapping(String type, XContentBuilder source) {
try {
mappings.put(type, source.string());
} catch (IOException e) {
throw new ElasticsearchIllegalArgumentException("Failed to build json for mapping request", e);
}
return this;
}
/**
* Adds mapping that will be added when the index gets created.
*
* @param type The mapping type
* @param source The mapping source
*/
@SuppressWarnings("unchecked")
public CreateIndexRequest mapping(String type, Map source) {
// wrap it in a type map if its not
if (source.size() != 1 || !source.containsKey(type)) {
source = MapBuilder.<String, Object>newMapBuilder().put(type, source).map();
}
try {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.map(source);
return mapping(type, builder.string());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
}
}
/**
* A specialized simplified mapping source method, takes the form of simple properties definition:
* ("field1", "type=string,store=true").
*/
public CreateIndexRequest mapping(String type, Object... source) {
mapping(type, PutMappingRequest.buildFromSimplifiedDef(type, source));
return this;
}
/**
* Sets the settings and mappings as a single source.
*/
public CreateIndexRequest source(String source) {
return source(source.getBytes(Charsets.UTF_8));
}
/**
* Sets the settings and mappings as a single source.
*/
public CreateIndexRequest source(XContentBuilder source) {
return source(source.bytes());
}
/**
* Sets the settings and mappings as a single source.
*/
public CreateIndexRequest source(byte[] source) {
return source(source, 0, source.length);
}
/**
* Sets the settings and mappings as a single source.
*/
public CreateIndexRequest source(byte[] source, int offset, int length) {
return source(new BytesArray(source, offset, length));
}
/**
* Sets the settings and mappings as a single source.
*/
public CreateIndexRequest source(BytesReference source) {
XContentType xContentType = XContentFactory.xContentType(source);
if (xContentType != null) {
try {
source(XContentFactory.xContent(xContentType).createParser(source).mapAndClose());
} catch (IOException e) {
throw new ElasticsearchParseException("failed to parse source for create index", e);
}
} else {
settings(new String(source.toBytes(), Charsets.UTF_8));
}
return this;
}
/**
* Sets the settings and mappings as a single source.
*/
@SuppressWarnings("unchecked")
public CreateIndexRequest source(Map<String, Object> source) {
boolean found = false;
for (Map.Entry<String, Object> entry : source.entrySet()) {
String name = entry.getKey();
if (name.equals("settings")) {
found = true;
settings((Map<String, Object>) entry.getValue());
} else if (name.equals("mappings")) {
found = true;
Map<String, Object> mappings = (Map<String, Object>) entry.getValue();
for (Map.Entry<String, Object> entry1 : mappings.entrySet()) {
mapping(entry1.getKey(), (Map<String, Object>) entry1.getValue());
}
} else {
// maybe custom?
IndexMetaData.Custom.Factory factory = IndexMetaData.lookupFactory(name);
if (factory != null) {
found = true;
try {
customs.put(name, factory.fromMap((Map<String, Object>) entry.getValue()));
} catch (IOException e) {
throw new ElasticsearchParseException("failed to parse custom metadata for [" + name + "]");
}
}
}
}
if (!found) {
// the top level are settings, use them
settings(source);
}
return this;
}
Map<String, String> mappings() {
return this.mappings;
}
/**
* Adds custom metadata to the index to be created.
*/
public CreateIndexRequest custom(IndexMetaData.Custom custom) {
customs.put(custom.type(), custom);
return this;
}
Map<String, IndexMetaData.Custom> customs() {
return this.customs;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
cause = in.readString();
index = in.readString();
settings = readSettingsFromStream(in);
readTimeout(in);
int size = in.readVInt();
for (int i = 0; i < size; i++) {
mappings.put(in.readString(), in.readString());
}
int customSize = in.readVInt();
for (int i = 0; i < customSize; i++) {
String type = in.readString();
IndexMetaData.Custom customIndexMetaData = IndexMetaData.lookupFactorySafe(type).readFrom(in);
customs.put(type, customIndexMetaData);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(cause);
out.writeString(index);
writeSettingsToStream(settings, out);
writeTimeout(out);
out.writeVInt(mappings.size());
for (Map.Entry<String, String> entry : mappings.entrySet()) {
out.writeString(entry.getKey());
out.writeString(entry.getValue());
}
out.writeVInt(customs.size());
for (Map.Entry<String, IndexMetaData.Custom> entry : customs.entrySet()) {
out.writeString(entry.getKey());
IndexMetaData.lookupFactorySafe(entry.getKey()).writeTo(entry.getValue(), out);
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_create_CreateIndexRequest.java
|
3,735 |
public class RootObjectMapper extends ObjectMapper {
public static class Defaults {
public static final FormatDateTimeFormatter[] DYNAMIC_DATE_TIME_FORMATTERS =
new FormatDateTimeFormatter[]{
DateFieldMapper.Defaults.DATE_TIME_FORMATTER,
Joda.forPattern("yyyy/MM/dd HH:mm:ss||yyyy/MM/dd")
};
public static final boolean DATE_DETECTION = true;
public static final boolean NUMERIC_DETECTION = false;
}
public static class Builder extends ObjectMapper.Builder<Builder, RootObjectMapper> {
protected final List<DynamicTemplate> dynamicTemplates = newArrayList();
// we use this to filter out seen date formats, because we might get duplicates during merging
protected Set<String> seenDateFormats = Sets.newHashSet();
protected List<FormatDateTimeFormatter> dynamicDateTimeFormatters = newArrayList();
protected boolean dateDetection = Defaults.DATE_DETECTION;
protected boolean numericDetection = Defaults.NUMERIC_DETECTION;
public Builder(String name) {
super(name);
this.builder = this;
}
public Builder noDynamicDateTimeFormatter() {
this.dynamicDateTimeFormatters = null;
return builder;
}
public Builder dynamicDateTimeFormatter(Iterable<FormatDateTimeFormatter> dateTimeFormatters) {
for (FormatDateTimeFormatter dateTimeFormatter : dateTimeFormatters) {
if (!seenDateFormats.contains(dateTimeFormatter.format())) {
seenDateFormats.add(dateTimeFormatter.format());
this.dynamicDateTimeFormatters.add(dateTimeFormatter);
}
}
return builder;
}
public Builder add(DynamicTemplate dynamicTemplate) {
this.dynamicTemplates.add(dynamicTemplate);
return this;
}
public Builder add(DynamicTemplate... dynamicTemplate) {
for (DynamicTemplate template : dynamicTemplate) {
this.dynamicTemplates.add(template);
}
return this;
}
@Override
protected ObjectMapper createMapper(String name, String fullPath, boolean enabled, Nested nested, Dynamic dynamic, ContentPath.Type pathType, Map<String, Mapper> mappers) {
assert !nested.isNested();
FormatDateTimeFormatter[] dates = null;
if (dynamicDateTimeFormatters == null) {
dates = new FormatDateTimeFormatter[0];
} else if (dynamicDateTimeFormatters.isEmpty()) {
// add the default one
dates = Defaults.DYNAMIC_DATE_TIME_FORMATTERS;
} else {
dates = dynamicDateTimeFormatters.toArray(new FormatDateTimeFormatter[dynamicDateTimeFormatters.size()]);
}
return new RootObjectMapper(name, enabled, dynamic, pathType, mappers,
dates,
dynamicTemplates.toArray(new DynamicTemplate[dynamicTemplates.size()]),
dateDetection, numericDetection);
}
}
public static class TypeParser extends ObjectMapper.TypeParser {
@Override
protected ObjectMapper.Builder createBuilder(String name) {
return new Builder(name);
}
@Override
protected void processField(ObjectMapper.Builder builder, String fieldName, Object fieldNode) {
if (fieldName.equals("date_formats") || fieldName.equals("dynamic_date_formats")) {
List<FormatDateTimeFormatter> dateTimeFormatters = newArrayList();
if (fieldNode instanceof List) {
for (Object node1 : (List) fieldNode) {
dateTimeFormatters.add(parseDateTimeFormatter(fieldName, node1));
}
} else if ("none".equals(fieldNode.toString())) {
dateTimeFormatters = null;
} else {
dateTimeFormatters.add(parseDateTimeFormatter(fieldName, fieldNode));
}
if (dateTimeFormatters == null) {
((Builder) builder).noDynamicDateTimeFormatter();
} else {
((Builder) builder).dynamicDateTimeFormatter(dateTimeFormatters);
}
} else if (fieldName.equals("dynamic_templates")) {
// "dynamic_templates" : [
// {
// "template_1" : {
// "match" : "*_test",
// "match_mapping_type" : "string",
// "mapping" : { "type" : "string", "store" : "yes" }
// }
// }
// ]
List tmplNodes = (List) fieldNode;
for (Object tmplNode : tmplNodes) {
Map<String, Object> tmpl = (Map<String, Object>) tmplNode;
if (tmpl.size() != 1) {
throw new MapperParsingException("A dynamic template must be defined with a name");
}
Map.Entry<String, Object> entry = tmpl.entrySet().iterator().next();
((Builder) builder).add(DynamicTemplate.parse(entry.getKey(), (Map<String, Object>) entry.getValue()));
}
} else if (fieldName.equals("date_detection")) {
((Builder) builder).dateDetection = nodeBooleanValue(fieldNode);
} else if (fieldName.equals("numeric_detection")) {
((Builder) builder).numericDetection = nodeBooleanValue(fieldNode);
}
}
}
private final FormatDateTimeFormatter[] dynamicDateTimeFormatters;
private final boolean dateDetection;
private final boolean numericDetection;
private volatile DynamicTemplate dynamicTemplates[];
RootObjectMapper(String name, boolean enabled, Dynamic dynamic, ContentPath.Type pathType, Map<String, Mapper> mappers,
FormatDateTimeFormatter[] dynamicDateTimeFormatters, DynamicTemplate dynamicTemplates[], boolean dateDetection, boolean numericDetection) {
super(name, name, enabled, Nested.NO, dynamic, pathType, mappers);
this.dynamicTemplates = dynamicTemplates;
this.dynamicDateTimeFormatters = dynamicDateTimeFormatters;
this.dateDetection = dateDetection;
this.numericDetection = numericDetection;
}
public boolean dateDetection() {
return this.dateDetection;
}
public boolean numericDetection() {
return this.numericDetection;
}
public FormatDateTimeFormatter[] dynamicDateTimeFormatters() {
return dynamicDateTimeFormatters;
}
public Mapper.Builder findTemplateBuilder(ParseContext context, String name, String dynamicType) {
return findTemplateBuilder(context, name, dynamicType, dynamicType);
}
public Mapper.Builder findTemplateBuilder(ParseContext context, String name, String dynamicType, String matchType) {
DynamicTemplate dynamicTemplate = findTemplate(context.path(), name, matchType);
if (dynamicTemplate == null) {
return null;
}
Mapper.TypeParser.ParserContext parserContext = context.docMapperParser().parserContext();
String mappingType = dynamicTemplate.mappingType(dynamicType);
Mapper.TypeParser typeParser = parserContext.typeParser(mappingType);
if (typeParser == null) {
throw new MapperParsingException("failed to find type parsed [" + mappingType + "] for [" + name + "]");
}
return typeParser.parse(name, dynamicTemplate.mappingForName(name, dynamicType), parserContext);
}
public DynamicTemplate findTemplate(ContentPath path, String name, String matchType) {
for (DynamicTemplate dynamicTemplate : dynamicTemplates) {
if (dynamicTemplate.match(path, name, matchType)) {
return dynamicTemplate;
}
}
return null;
}
@Override
protected boolean allowValue() {
return true;
}
@Override
protected void doMerge(ObjectMapper mergeWith, MergeContext mergeContext) {
RootObjectMapper mergeWithObject = (RootObjectMapper) mergeWith;
if (!mergeContext.mergeFlags().simulate()) {
// merge them
List<DynamicTemplate> mergedTemplates = Lists.newArrayList(Arrays.asList(this.dynamicTemplates));
for (DynamicTemplate template : mergeWithObject.dynamicTemplates) {
boolean replaced = false;
for (int i = 0; i < mergedTemplates.size(); i++) {
if (mergedTemplates.get(i).name().equals(template.name())) {
mergedTemplates.set(i, template);
replaced = true;
}
}
if (!replaced) {
mergedTemplates.add(template);
}
}
this.dynamicTemplates = mergedTemplates.toArray(new DynamicTemplate[mergedTemplates.size()]);
}
}
@Override
protected void doXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
if (dynamicDateTimeFormatters != Defaults.DYNAMIC_DATE_TIME_FORMATTERS) {
if (dynamicDateTimeFormatters.length > 0) {
builder.startArray("dynamic_date_formats");
for (FormatDateTimeFormatter dateTimeFormatter : dynamicDateTimeFormatters) {
builder.value(dateTimeFormatter.format());
}
builder.endArray();
}
}
if (dynamicTemplates != null && dynamicTemplates.length > 0) {
builder.startArray("dynamic_templates");
for (DynamicTemplate dynamicTemplate : dynamicTemplates) {
builder.startObject();
builder.field(dynamicTemplate.name());
builder.map(dynamicTemplate.conf());
builder.endObject();
}
builder.endArray();
}
if (dateDetection != Defaults.DATE_DETECTION) {
builder.field("date_detection", dateDetection);
}
if (numericDetection != Defaults.NUMERIC_DETECTION) {
builder.field("numeric_detection", numericDetection);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_mapper_object_RootObjectMapper.java
|
1,678 |
public class FsBlobStore extends AbstractComponent implements BlobStore {
private final Executor executor;
private final File path;
private final int bufferSizeInBytes;
public FsBlobStore(Settings settings, Executor executor, File path) {
super(settings);
this.path = path;
if (!path.exists()) {
boolean b = FileSystemUtils.mkdirs(path);
if (!b) {
throw new BlobStoreException("Failed to create directory at [" + path + "]");
}
}
if (!path.isDirectory()) {
throw new BlobStoreException("Path is not a directory at [" + path + "]");
}
this.bufferSizeInBytes = (int) settings.getAsBytesSize("buffer_size", new ByteSizeValue(100, ByteSizeUnit.KB)).bytes();
this.executor = executor;
}
@Override
public String toString() {
return path.toString();
}
public File path() {
return path;
}
public int bufferSizeInBytes() {
return this.bufferSizeInBytes;
}
public Executor executor() {
return executor;
}
@Override
public ImmutableBlobContainer immutableBlobContainer(BlobPath path) {
return new FsImmutableBlobContainer(this, path, buildAndCreate(path));
}
@Override
public void delete(BlobPath path) {
FileSystemUtils.deleteRecursively(buildPath(path));
}
@Override
public void close() {
// nothing to do here...
}
private synchronized File buildAndCreate(BlobPath path) {
File f = buildPath(path);
FileSystemUtils.mkdirs(f);
return f;
}
private File buildPath(BlobPath path) {
String[] paths = path.toArray();
if (paths.length == 0) {
return path();
}
File blobPath = new File(this.path, paths[0]);
if (paths.length > 1) {
for (int i = 1; i < paths.length; i++) {
blobPath = new File(blobPath, paths[i]);
}
}
return blobPath;
}
}
| 1no label
|
src_main_java_org_elasticsearch_common_blobstore_fs_FsBlobStore.java
|
2,161 |
public class TxnUnlockOperation extends LockAwareOperation implements MapTxnOperation, BackupAwareOperation{
private long version;
private String ownerUuid;
public TxnUnlockOperation() {
}
public TxnUnlockOperation(String name, Data dataKey, long version) {
super(name, dataKey, -1);
this.version = version;
}
@Override
public void run() {
System.out.println( "Owner tid:" + getThreadId() + " pid:"+getPartitionId());
recordStore.unlock(dataKey, ownerUuid, getThreadId());
}
public boolean shouldWait() {
return !recordStore.canAcquireLock(dataKey, ownerUuid, getThreadId());
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
@Override
public Object getResponse() {
return Boolean.TRUE;
}
public boolean shouldNotify() {
return true;
}
public Operation getBackupOperation() {
TxnUnlockBackupOperation txnUnlockOperation = new TxnUnlockBackupOperation(name, dataKey);
txnUnlockOperation.setThreadId(getThreadId());
return txnUnlockOperation;
}
public void onWaitExpire() {
final ResponseHandler responseHandler = getResponseHandler();
responseHandler.sendResponse(false);
}
public final int getAsyncBackupCount() {
return mapContainer.getAsyncBackupCount();
}
public final int getSyncBackupCount() {
return mapContainer.getBackupCount();
}
@Override
public void setOwnerUuid(String ownerUuid) {
this.ownerUuid = ownerUuid;
}
@Override
public boolean shouldBackup() {
return true;
}
public WaitNotifyKey getNotifiedKey() {
return getWaitKey();
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeLong(version);
out.writeUTF(ownerUuid);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
version = in.readLong();
ownerUuid = in.readUTF();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_map_tx_TxnUnlockOperation.java
|
1,097 |
public class OSQLFunctionDifference extends OSQLFunctionMultiValueAbstract<Set<Object>> {
public static final String NAME = "difference";
private Set<Object> rejected;
public OSQLFunctionDifference() {
super(NAME, 1, -1);
}
@SuppressWarnings("unchecked")
public Object execute(OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters, OCommandContext iContext) {
if (iParameters[0] == null)
return null;
Object value = iParameters[0];
if (iParameters.length == 1) {
// AGGREGATION MODE (STATEFULL)
if (context == null) {
context = new HashSet<Object>();
rejected = new HashSet<Object>();
}
if (value instanceof Collection<?>) {
addItemsToResult((Collection<Object>) value, context, rejected);
} else {
addItemToResult(value, context, rejected);
}
return null;
} else {
// IN-LINE MODE (STATELESS)
final Set<Object> result = new HashSet<Object>();
final Set<Object> rejected = new HashSet<Object>();
for (Object iParameter : iParameters) {
if (iParameter instanceof Collection<?>) {
addItemsToResult((Collection<Object>) value, result, rejected);
} else {
addItemToResult(iParameter, result, rejected);
}
}
return result;
}
}
@Override
public Set<Object> getResult() {
if (returnDistributedResult()) {
final Map<String, Object> doc = new HashMap<String, Object>();
doc.put("result", context);
doc.put("rejected", rejected);
return Collections.<Object> singleton(doc);
} else {
return super.getResult();
}
}
private static void addItemToResult(Object o, Set<Object> accepted, Set<Object> rejected) {
if (!accepted.contains(o) && !rejected.contains(o)) {
accepted.add(o);
} else {
accepted.remove(o);
rejected.add(o);
}
}
private static void addItemsToResult(Collection<Object> co, Set<Object> accepted, Set<Object> rejected) {
for (Object o : co) {
addItemToResult(o, accepted, rejected);
}
}
public String getSyntax() {
return "Syntax error: difference(<field>*)";
}
@Override
public Object mergeDistributedResult(List<Object> resultsToMerge) {
final Set<Object> result = new HashSet<Object>();
final Set<Object> rejected = new HashSet<Object>();
for (Object item : resultsToMerge) {
rejected.addAll(unwrap(item, "rejected"));
}
for (Object item : resultsToMerge) {
addItemsToResult(unwrap(item, "result"), result, rejected);
}
return result;
}
@SuppressWarnings("unchecked")
private Set<Object> unwrap(Object obj, String field) {
final Set<Object> objAsSet = (Set<Object>) obj;
final Map<String, Object> objAsMap = (Map<String, Object>) objAsSet.iterator().next();
final Set<Object> objAsField = (Set<Object>) objAsMap.get(field);
return objAsField;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_functions_coll_OSQLFunctionDifference.java
|
3,442 |
public class TraceableIsStillExecutingOperation extends AbstractOperation {
private String serviceName;
private Object identifier;
TraceableIsStillExecutingOperation() {
}
public TraceableIsStillExecutingOperation(String serviceName, Object identifier) {
this.serviceName = serviceName;
this.identifier = identifier;
}
@Override
public void run() throws Exception {
NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine();
BasicOperationService operationService = (BasicOperationService) nodeEngine.operationService;
boolean executing = operationService.isOperationExecuting(getCallerAddress(), getCallerUuid(),
serviceName, identifier);
getResponseHandler().sendResponse(executing);
}
@Override
public boolean returnsResponse() {
return false;
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
serviceName = in.readUTF();
identifier = in.readObject();
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeUTF(serviceName);
out.writeObject(identifier);
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_spi_impl_TraceableIsStillExecutingOperation.java
|
156 |
static final class Sync extends AbstractQueuedLongSynchronizer {
private static final long serialVersionUID = 2540673546047039555L;
/**
* The number of times to spin in lock() and awaitAvailability().
*/
final int spins;
/**
* The number of reentrant holds on this lock. Uses a long for
* compatibility with other AbstractQueuedLongSynchronizer
* operations. Accessed only by lock holder.
*/
long holds;
Sync(int spins) { this.spins = spins; }
// overrides of AQLS methods
public final boolean isHeldExclusively() {
return (getState() & 1L) != 0L &&
getExclusiveOwnerThread() == Thread.currentThread();
}
public final boolean tryAcquire(long acquires) {
Thread current = Thread.currentThread();
long c = getState();
if ((c & 1L) == 0L) {
if (compareAndSetState(c, c + 1L)) {
holds = acquires;
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
holds += acquires;
return true;
}
return false;
}
public final boolean tryRelease(long releases) {
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
if ((holds -= releases) == 0L) {
setExclusiveOwnerThread(null);
setState(getState() + 1L);
return true;
}
return false;
}
public final long tryAcquireShared(long unused) {
return (((getState() & 1L) == 0L) ? 1L :
(getExclusiveOwnerThread() == Thread.currentThread()) ? 0L:
-1L);
}
public final boolean tryReleaseShared(long unused) {
return (getState() & 1L) == 0L;
}
public final Condition newCondition() {
throw new UnsupportedOperationException();
}
// Other methods in support of SequenceLock
final long getSequence() {
return getState();
}
final void lock() {
int k = spins;
while (!tryAcquire(1L)) {
if (k == 0) {
acquire(1L);
break;
}
--k;
}
}
final long awaitAvailability() {
long s;
while (((s = getState()) & 1L) != 0L &&
getExclusiveOwnerThread() != Thread.currentThread()) {
acquireShared(1L);
releaseShared(1L);
}
return s;
}
final long tryAwaitAvailability(long nanos)
throws InterruptedException, TimeoutException {
Thread current = Thread.currentThread();
for (;;) {
long s = getState();
if ((s & 1L) == 0L || getExclusiveOwnerThread() == current) {
releaseShared(1L);
return s;
}
if (!tryAcquireSharedNanos(1L, nanos))
throw new TimeoutException();
// since tryAcquireSharedNanos doesn't return seq
// retry with minimal wait time.
nanos = 1L;
}
}
final boolean isLocked() {
return (getState() & 1L) != 0L;
}
final Thread getOwner() {
return (getState() & 1L) == 0L ? null : getExclusiveOwnerThread();
}
final long getHoldCount() {
return isHeldExclusively() ? holds : 0;
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
holds = 0L;
setState(0L); // reset to unlocked state
}
}
| 0true
|
src_main_java_jsr166e_extra_SequenceLock.java
|
420 |
delegatingFuture.andThen(new ExecutionCallback<V>() {
@Override
public void onResponse(V response) {
if (nearCache != null) {
nearCache.put(keyData, response);
}
}
@Override
public void onFailure(Throwable t) {
}
});
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientMapProxy.java
|
2,079 |
public class EmailOpenTrackingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(EmailOpenTrackingServlet.class);
/*
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest , javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = request.getPathInfo();
Long emailId = null;
String imageUrl = "";
// Parse the URL for the Email ID and Image URL
if (url != null) {
String[] items = url.split("/");
emailId = Long.valueOf(items[1]);
StringBuffer sb = new StringBuffer();
for (int j = 2; j < items.length; j++) {
sb.append("/");
sb.append(items[j]);
}
imageUrl = sb.toString();
}
// Record the open
if (emailId != null && !"null".equals(emailId)) {
if (LOG.isDebugEnabled()) {
LOG.debug("service() => Recording Open for Email[" + emailId + "]");
}
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
EmailTrackingManager emailTrackingManager = (EmailTrackingManager) context.getBean("blEmailTrackingManager");
String userAgent = request.getHeader("USER-AGENT");
Map<String, String> extraValues = new HashMap<String, String>();
extraValues.put("userAgent", userAgent);
emailTrackingManager.recordOpen(emailId, extraValues);
}
if ("".equals(imageUrl)) {
response.setContentType("image/gif");
BufferedInputStream bis = null;
OutputStream out = response.getOutputStream();
try {
bis = new BufferedInputStream(EmailOpenTrackingServlet.class.getResourceAsStream("clear_dot.gif"));
boolean eof = false;
while (!eof) {
int temp = bis.read();
if (temp == -1) {
eof = true;
} else {
out.write(temp);
}
}
} finally {
if (bis != null) {
try{ bis.close(); } catch (Throwable e) {
LOG.error("Unable to close output stream in EmailOpenTrackingServlet", e);
}
}
//Don't close the output stream controlled by the container. The container will
//handle this.
}
} else {
RequestDispatcher dispatcher = request.getRequestDispatcher(imageUrl);
dispatcher.forward(request, response);
}
}
}
| 1no label
|
core_broadleaf-profile-web_src_main_java_org_broadleafcommerce_profile_web_email_EmailOpenTrackingServlet.java
|
915 |
public final class LockEvictionProcessor implements ScheduledEntryProcessor<Data, Object> {
private static final int AWAIT_COMPLETION_TIMEOUT_SECONDS = 30;
private final NodeEngine nodeEngine;
private final ObjectNamespace namespace;
public LockEvictionProcessor(NodeEngine nodeEngine, ObjectNamespace namespace) {
this.nodeEngine = nodeEngine;
this.namespace = namespace;
}
@Override
public void process(EntryTaskScheduler<Data, Object> scheduler, Collection<ScheduledEntry<Data, Object>> entries) {
Collection<Future> futures = sendUnlockOperations(entries);
awaitCompletion(futures);
}
private Collection<Future> sendUnlockOperations(Collection<ScheduledEntry<Data, Object>> entries) {
Collection<Future> futures = new ArrayList<Future>(entries.size());
for (ScheduledEntry<Data, Object> entry : entries) {
Data key = entry.getKey();
sendUnlockOperation(futures, key);
}
return futures;
}
private void sendUnlockOperation(Collection<Future> futures, Data key) {
Operation operation = new UnlockOperation(namespace, key, -1, true);
try {
Future f = invoke(operation, key);
futures.add(f);
} catch (Throwable t) {
ILogger logger = nodeEngine.getLogger(getClass());
logger.warning(t);
}
}
private void awaitCompletion(Collection<Future> futures) {
ILogger logger = nodeEngine.getLogger(getClass());
for (Future future : futures) {
try {
future.get(AWAIT_COMPLETION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (TimeoutException e) {
logger.finest(e);
} catch (Exception e) {
logger.warning(e);
}
}
}
private InternalCompletableFuture invoke(Operation operation, Data key) {
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
OperationService operationService = nodeEngine.getOperationService();
return operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId);
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockEvictionProcessor.java
|
1,472 |
public class OSQLFunctionInE extends OSQLFunctionMove {
public static final String NAME = "inE";
public OSQLFunctionInE() {
super(NAME, 0, 1);
}
@Override
protected Object move(final OrientBaseGraph graph, final OIdentifiable iRecord, final String[] iLabels) {
return v2e(graph, iRecord, Direction.IN, iLabels);
}
}
| 1no label
|
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_functions_OSQLFunctionInE.java
|
342 |
static class TestMapStore extends MapStoreAdapter<Long, String> {
public volatile CountDownLatch latch;
@Override
public void store(Long key, String value) {
if (latch != null) {
latch.countDown();
}
}
@Override
public void storeAll(Map<Long, String> map) {
if (latch != null) {
latch.countDown();
}
}
@Override
public void deleteAll(Collection<Long> keys) {
if (latch != null) {
latch.countDown();
}
}
@Override
public void delete(Long key) {
if (latch != null) {
latch.countDown();
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java
|
288 |
static class TryLockWithTimeOutThread extends LockTestThread {
public TryLockWithTimeOutThread(ILock lock, AtomicInteger upTotal, AtomicInteger downTotal){
super(lock, upTotal, downTotal);
}
public void doRun() throws Exception{
if ( lock.tryLock(1, TimeUnit.MILLISECONDS) ) {
work();
lock.unlock();
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_lock_ClientConcurrentLockTest.java
|
278 |
public abstract class Action<Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>>
extends GenericAction<Request, Response> {
protected Action(String name) {
super(name);
}
public abstract RequestBuilder newRequestBuilder(Client client);
}
| 0true
|
src_main_java_org_elasticsearch_action_Action.java
|
1,113 |
public class OSQLFunctionEval extends OSQLFunctionMathAbstract {
public static final String NAME = "eval";
private OSQLPredicate predicate;
public OSQLFunctionEval() {
super(NAME, 1, 1);
}
public Object execute(final OIdentifiable iRecord, final Object iCurrentResult, final Object[] iParameters,
OCommandContext iContext) {
if (predicate == null)
predicate = new OSQLPredicate((String) iParameters[0].toString());
try {
return predicate.evaluate(iRecord != null ? iRecord.getRecord() : null, (ODocument) iCurrentResult, iContext);
} catch (ArithmeticException e) {
// DIVISION BY 0
return 0;
} catch (Exception e) {
return null;
}
}
public boolean aggregateResults() {
return false;
}
public String getSyntax() {
return "Syntax error: eval(<expression>)";
}
@Override
public Object getResult() {
return null;
}
@Override
public Object mergeDistributedResult(List<Object> resultsToMerge) {
return null;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_functions_math_OSQLFunctionEval.java
|
1,187 |
public class OQueryOperatorMajorEquals extends OQueryOperatorEqualityNotNulls {
public OQueryOperatorMajorEquals() {
super(">=", 5, false);
}
@Override
@SuppressWarnings("unchecked")
protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft,
final Object iRight, OCommandContext iContext) {
final Object right = OType.convert(iRight, iLeft.getClass());
if (right == null)
return false;
return ((Comparable<Object>) iLeft).compareTo(right) >= 0;
}
@Override
public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) {
if (iRight == null || iLeft == null)
return OIndexReuseType.NO_INDEX;
return OIndexReuseType.INDEX_METHOD;
}
@Override
public Object executeIndexQuery(OCommandContext iContext, OIndex<?> index, INDEX_OPERATION_TYPE iOperationType,
List<Object> keyParams, IndexResultListener resultListener, int fetchLimit) {
final OIndexDefinition indexDefinition = index.getDefinition();
final OIndexInternal<?> internalIndex = index.getInternal();
if (!internalIndex.canBeUsedInEqualityOperators() || !internalIndex.hasRangeQuerySupport())
return null;
final Object result;
if (indexDefinition.getParamCount() == 1) {
final Object key;
if (indexDefinition instanceof OIndexDefinitionMultiValue)
key = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(keyParams.get(0));
else
key = indexDefinition.createValue(keyParams);
if (key == null)
return null;
if (INDEX_OPERATION_TYPE.COUNT.equals(iOperationType))
result = index.count(key, true, null, false, fetchLimit);
else if (resultListener != null) {
index.getValuesMajor(key, true, resultListener);
result = resultListener.getResult();
} else
result = index.getValuesMajor(key, true);
} else {
// if we have situation like "field1 = 1 AND field2 >= 2"
// then we fetch collection which left included boundary is the smallest composite key in the
// index that contains keys with values field1=1 and field2=2 and which right included boundary
// is the biggest composite key in the index that contains key with value field1=1.
final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams);
if (keyOne == null)
return null;
final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams.subList(0, keyParams.size() - 1));
if (keyTwo == null)
return null;
if (INDEX_OPERATION_TYPE.COUNT.equals(iOperationType))
result = index.count(keyOne, true, keyTwo, true, fetchLimit);
else if (resultListener != null) {
index.getValuesBetween(keyOne, true, keyTwo, true, resultListener);
result = resultListener.getResult();
} else
result = index.getValuesBetween(keyOne, true, keyTwo, true);
}
updateProfiler(iContext, index, keyParams, indexDefinition);
return result;
}
@Override
public ORID getBeginRidRange(final Object iLeft, final Object iRight) {
if (iLeft instanceof OSQLFilterItemField && ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iLeft).getRoot()))
if (iRight instanceof ORID)
return (ORID) iRight;
else {
if (iRight instanceof OSQLFilterItemParameter && ((OSQLFilterItemParameter) iRight).getValue(null, null) instanceof ORID)
return (ORID) ((OSQLFilterItemParameter) iRight).getValue(null, null);
}
return null;
}
@Override
public ORID getEndRidRange(Object iLeft, Object iRight) {
return null;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorMajorEquals.java
|
265 |
public class ElasticsearchException extends RuntimeException {
/**
* Construct a <code>ElasticsearchException</code> with the specified detail message.
*
* @param msg the detail message
*/
public ElasticsearchException(String msg) {
super(msg);
}
/**
* Construct a <code>ElasticsearchException</code> with the specified detail message
* and nested exception.
*
* @param msg the detail message
* @param cause the nested exception
*/
public ElasticsearchException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Returns the rest status code associated with this exception.
*/
public RestStatus status() {
Throwable cause = unwrapCause();
if (cause == this) {
return RestStatus.INTERNAL_SERVER_ERROR;
} else if (cause instanceof ElasticsearchException) {
return ((ElasticsearchException) cause).status();
} else if (cause instanceof IllegalArgumentException) {
return RestStatus.BAD_REQUEST;
} else {
return RestStatus.INTERNAL_SERVER_ERROR;
}
}
/**
* Unwraps the actual cause from the exception for cases when the exception is a
* {@link ElasticsearchWrapperException}.
*
* @see org.elasticsearch.ExceptionsHelper#unwrapCause(Throwable)
*/
public Throwable unwrapCause() {
return ExceptionsHelper.unwrapCause(this);
}
/**
* Return the detail message, including the message from the nested exception
* if there is one.
*/
public String getDetailedMessage() {
if (getCause() != null) {
StringBuilder sb = new StringBuilder();
sb.append(toString()).append("; ");
if (getCause() instanceof ElasticsearchException) {
sb.append(((ElasticsearchException) getCause()).getDetailedMessage());
} else {
sb.append(getCause());
}
return sb.toString();
} else {
return super.toString();
}
}
/**
* Retrieve the innermost cause of this exception, if none, returns the current exception.
*/
public Throwable getRootCause() {
Throwable rootCause = this;
Throwable cause = getCause();
while (cause != null && cause != rootCause) {
rootCause = cause;
cause = cause.getCause();
}
return rootCause;
}
/**
* Retrieve the most specific cause of this exception, that is,
* either the innermost cause (root cause) or this exception itself.
* <p>Differs from {@link #getRootCause()} in that it falls back
* to the present exception if there is no root cause.
*
* @return the most specific cause (never <code>null</code>)
*/
public Throwable getMostSpecificCause() {
Throwable rootCause = getRootCause();
return (rootCause != null ? rootCause : this);
}
/**
* Check whether this exception contains an exception of the given type:
* either it is of the given class itself or it contains a nested cause
* of the given type.
*
* @param exType the exception type to look for
* @return whether there is a nested exception of the specified type
*/
public boolean contains(Class exType) {
if (exType == null) {
return false;
}
if (exType.isInstance(this)) {
return true;
}
Throwable cause = getCause();
if (cause == this) {
return false;
}
if (cause instanceof ElasticsearchException) {
return ((ElasticsearchException) cause).contains(exType);
} else {
while (cause != null) {
if (exType.isInstance(cause)) {
return true;
}
if (cause.getCause() == cause) {
break;
}
cause = cause.getCause();
}
return false;
}
}
}
| 0true
|
src_main_java_org_elasticsearch_ElasticsearchException.java
|
56 |
public interface OLock {
public void lock();
public void unlock();
public <V> V callInLock(Callable<V> iCallback) throws Exception;
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_concur_lock_OLock.java
|
30 |
static final class ThenApply<T,U> extends Completion {
final CompletableFuture<? extends T> src;
final Fun<? super T,? extends U> fn;
final CompletableFuture<U> dst;
final Executor executor;
ThenApply(CompletableFuture<? extends T> src,
Fun<? super T,? extends U> fn,
CompletableFuture<U> dst,
Executor executor) {
this.src = src; this.fn = fn; this.dst = dst;
this.executor = executor;
}
public final void run() {
final CompletableFuture<? extends T> a;
final Fun<? super T,? extends U> fn;
final CompletableFuture<U> dst;
Object r; T t; Throwable ex;
if ((dst = this.dst) != null &&
(fn = this.fn) != null &&
(a = this.src) != null &&
(r = a.result) != null &&
compareAndSet(0, 1)) {
if (r instanceof AltResult) {
ex = ((AltResult)r).ex;
t = null;
}
else {
ex = null;
@SuppressWarnings("unchecked") T tr = (T) r;
t = tr;
}
Executor e = executor;
U u = null;
if (ex == null) {
try {
if (e != null)
e.execute(new AsyncApply<T,U>(t, fn, dst));
else
u = fn.apply(t);
} catch (Throwable rex) {
ex = rex;
}
}
if (e == null || ex != null)
dst.internalComplete(u, ex);
}
}
private static final long serialVersionUID = 5232453952276885070L;
}
| 0true
|
src_main_java_jsr166e_CompletableFuture.java
|
1,908 |
public class DataDTOToMVELTranslator {
public String createMVEL(String entityKey, DataDTO dataDTO, RuleBuilderFieldService fieldService)
throws MVELTranslationException {
StringBuffer sb = new StringBuffer();
buildMVEL(dataDTO, sb, entityKey, null, fieldService);
String response = sb.toString().trim();
if (response.length() == 0) {
response = null;
}
return response;
}
protected void buildMVEL(DataDTO dataDTO, StringBuffer sb, String entityKey, String groupOperator,
RuleBuilderFieldService fieldService) throws MVELTranslationException {
BLCOperator operator = null;
if (dataDTO instanceof ExpressionDTO) {
operator = BLCOperator.valueOf(((ExpressionDTO) dataDTO).getOperator());
} else {
operator = BLCOperator.valueOf(dataDTO.getGroupOperator());
}
ArrayList<DataDTO> groups = dataDTO.getGroups();
if (sb.length() != 0 && sb.charAt(sb.length() - 1) != '(' && groupOperator != null) {
BLCOperator groupOp = BLCOperator.valueOf(groupOperator);
switch(groupOp) {
default:
sb.append("&&");
break;
case OR:
sb.append("||");
}
}
if (dataDTO instanceof ExpressionDTO) {
buildExpression((ExpressionDTO)dataDTO, sb, entityKey, operator, fieldService);
} else {
boolean includeTopLevelParenthesis = false;
if (sb.length() != 0 || BLCOperator.NOT.equals(operator) || (sb.length() == 0 && groupOperator != null)) {
includeTopLevelParenthesis = true;
}
if (BLCOperator.NOT.equals(operator)) {
sb.append("!");
}
if (includeTopLevelParenthesis) sb.append("(");
for (DataDTO dto : groups) {
buildMVEL(dto, sb, entityKey, dataDTO.getGroupOperator(), fieldService);
}
if (includeTopLevelParenthesis) sb.append(")");
}
}
protected void buildExpression(ExpressionDTO expressionDTO, StringBuffer sb, String entityKey,
BLCOperator operator, RuleBuilderFieldService fieldService)
throws MVELTranslationException {
String field = expressionDTO.getName();
SupportedFieldType type = fieldService.getSupportedFieldType(field);
SupportedFieldType secondaryType = fieldService.getSecondaryFieldType(field);
Object[] value;
if (type == null) {
throw new MVELTranslationException(MVELTranslationException.SPECIFIED_FIELD_NOT_FOUND, "The DataDTO is not compatible with the RuleBuilderFieldService " +
"associated with the current rules builder. Unable to find the field " +
"specified: ("+field+")");
}
if (
SupportedFieldType.DATE.toString().equals(type.toString()) &&
!BLCOperator.CONTAINS_FIELD.equals(operator) &&
!BLCOperator.ENDS_WITH_FIELD.equals(operator) &&
!BLCOperator.EQUALS_FIELD.equals(operator) &&
!BLCOperator.GREATER_OR_EQUAL_FIELD.equals(operator) &&
!BLCOperator.GREATER_THAN_FIELD.equals(operator) &&
!BLCOperator.LESS_OR_EQUAL_FIELD.equals(operator) &&
!BLCOperator.LESS_THAN_FIELD.equals(operator) &&
!BLCOperator.NOT_EQUAL_FIELD.equals(operator) &&
!BLCOperator.STARTS_WITH_FIELD.equals(operator) &&
!BLCOperator.BETWEEN.equals(operator) &&
!BLCOperator.BETWEEN_INCLUSIVE.equals(operator)
) {
value = extractDate(expressionDTO, operator, "value");
} else {
value = extractBasicValues(expressionDTO.getValue());
}
switch(operator) {
case CONTAINS: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".contains",
true, false, false, false, false);
break;
}
case CONTAINS_FIELD: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".contains",
true, true, false, false, false);
break;
}
case ENDS_WITH: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".endsWith",
true, false, false, false, false);
break;
}
case ENDS_WITH_FIELD: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".endsWith",
true, true, false, false, false);
break;
}
case EQUALS: {
buildExpression(sb, entityKey, field, value, type, secondaryType, "==", false, false, false, false, false);
break;
}
case EQUALS_FIELD: {
buildExpression(sb, entityKey, field, value, type, secondaryType, "==", false, true, false, false, false);
break;
}
case GREATER_OR_EQUAL: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ">=", false, false, false, false, false);
break;
}
case GREATER_OR_EQUAL_FIELD: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ">=", false, true, false, false, false);
break;
}
case GREATER_THAN: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ">", false, false, false, false, false);
break;
}
case GREATER_THAN_FIELD: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ">", false, true, false, false, false);
break;
}
case ICONTAINS: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".contains",
true, false, true, false, false);
break;
}
case IENDS_WITH: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".endsWith",
true, false, true, false, false);
break;
}
case IEQUALS: {
buildExpression(sb, entityKey, field, value, type, secondaryType, "==", false, false, true, false, false);
break;
}
case INOT_CONTAINS: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".contains",
true, false, true, true, false);
break;
}
case INOT_ENDS_WITH: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".endsWith",
true, false, true, true, false);
break;
}
case INOT_EQUAL: {
buildExpression(sb, entityKey, field, value, type, secondaryType, "!=", false, false, true, false, false);
break;
}
case INOT_STARTS_WITH: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".startsWith",
true, false, true, true, false);
break;
}
case IS_NULL: {
buildExpression(sb, entityKey, field, new Object[]{"null"}, type, secondaryType, "==",
false, false, false, false, true);
break;
}
case ISTARTS_WITH: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".startsWith",
true, false, true, false, false);
break;
}
case LESS_OR_EQUAL: {
buildExpression(sb, entityKey, field, value, type, secondaryType, "<=", false, false, false, false, false);
break;
}
case LESS_OR_EQUAL_FIELD: {
buildExpression(sb, entityKey, field, value, type, secondaryType, "<=", false, true, false, false, false);
break;
}
case LESS_THAN: {
buildExpression(sb, entityKey, field, value, type, secondaryType, "<", false, false, false, false, false);
break;
}
case LESS_THAN_FIELD: {
buildExpression(sb, entityKey, field, value, type, secondaryType, "<",
false, true, false, false, false);
break;
}
case NOT_CONTAINS: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".contains",
true, false, false, true, false);
break;
}
case NOT_ENDS_WITH: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".endsWith",
true, false, false, true, false);
break;
}
case NOT_EQUAL: {
buildExpression(sb, entityKey, field, value, type, secondaryType, "!=", false, false, false, false, false);
break;
}
case NOT_EQUAL_FIELD: {
buildExpression(sb, entityKey, field, value, type, secondaryType, "!=",
false, true, false, false, false);
break;
}
case NOT_NULL: {
buildExpression(sb, entityKey, field, new Object[]{"null"}, type, secondaryType, "!=",
false, false, false, false, true);
break;
}
case NOT_STARTS_WITH: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".startsWith",
true, false, false, true, false);
break;
}
case STARTS_WITH: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".startsWith",
true, false, false, false, false);
break;
}
case STARTS_WITH_FIELD: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".startsWith",
true, true, false, false, false);
break;
}
case COUNT_GREATER_THAN: {
buildExpression(sb, entityKey, field, value, type, secondaryType, ".size()>", false, false, false, false, true);
break;
}
case COUNT_GREATER_OR_EQUAL:{
buildExpression(sb, entityKey, field, value, type, secondaryType, ".size()>=", false, false, false, false, true);
break;
}
case COUNT_LESS_THAN:{
buildExpression(sb, entityKey, field, value, type, secondaryType, ".size()<", false, false, false, false, true);
break;
}
case COUNT_LESS_OR_EQUAL:{
buildExpression(sb, entityKey, field, value, type, secondaryType, ".size()<=", false, false, false, false, true);
break;
}
case COUNT_EQUALS:{
buildExpression(sb, entityKey, field, value, type, secondaryType, ".size()==", false, false, false, false, true);
break;
}
case BETWEEN: {
if (SupportedFieldType.DATE.toString().equals(type.toString())) {
sb.append("(");
buildExpression(sb, entityKey, field, extractDate(expressionDTO, BLCOperator.GREATER_THAN, "start"),
type, secondaryType, ">", false, false, false, false, false);
sb.append("&&");
buildExpression(sb, entityKey, field, extractDate(expressionDTO, BLCOperator.LESS_THAN, "end"),
type, secondaryType, "<", false, false, false, false, false);
sb.append(")");
} else {
sb.append("(");
buildExpression(sb, entityKey, field, new Object[]{expressionDTO.getStart()}, type, secondaryType, ">",
false, false, false, false, false);
sb.append("&&");
buildExpression(sb, entityKey, field, new Object[]{expressionDTO.getEnd()}, type, secondaryType, "<",
false, false, false, false, false);
sb.append(")");
}
break;
}
case BETWEEN_INCLUSIVE: {
if (
SupportedFieldType.DATE.toString().equals(type.toString())
) {
sb.append("(");
buildExpression(sb, entityKey, field,
extractDate(expressionDTO, BLCOperator.GREATER_OR_EQUAL, "start"), type,
secondaryType, ">=", false, false, false, false, false);
sb.append("&&");
buildExpression(sb, entityKey, field, extractDate(expressionDTO, BLCOperator.LESS_OR_EQUAL, "end"),
type, secondaryType, "<=", false, false, false, false, false);
sb.append(")");
} else {
sb.append("(");
buildExpression(sb, entityKey, field, new Object[]{expressionDTO.getStart()}, type, secondaryType, ">=",
false, false, false, false, false);
sb.append("&&");
buildExpression(sb, entityKey, field, new Object[]{expressionDTO.getEnd()}, type, secondaryType, "<=",
false, false, false, false, false);
sb.append(")");
}
break;
}
}
}
@SuppressWarnings({ "rawtypes", "deprecation", "unchecked" })
protected Object[] extractDate(ExpressionDTO expressionDTO, BLCOperator operator, String key) {
String value;
if ("start".equals(key)) {
value = expressionDTO.getStart();
} else if ("end".equals(key)) {
value = expressionDTO.getEnd();
} else {
value = expressionDTO.getValue();
}
//TODO handle Date Time Format
// if (BLCOperator.GREATER_THAN.equals(operator) || BLCOperator.LESS_OR_EQUAL.equals(operator)) {
// ((Date) value).setHours(23);
// ((Date) value).setMinutes(59);
// } else {
// ((Date) value).setHours(0);
// ((Date) value).setMinutes(0);
// }
return new Object[]{value};
}
protected Object[] extractBasicValues(Object value) {
if (value == null) {
return null;
}
String stringValue = value.toString().trim();
Object[] response = new Object[]{};
if (isProjection(value)) {
List<String> temp = new ArrayList<String>();
int initial = 1;
//assume this is a multi-value phrase
boolean eof = false;
while (!eof) {
int end = stringValue.indexOf(",", initial);
if (end == -1) {
eof = true;
end = stringValue.length() - 1;
}
temp.add(stringValue.substring(initial, end));
initial = end + 1;
}
response = temp.toArray(response);
} else {
response = new Object[]{value};
}
return response;
}
public boolean isProjection(Object value) {
String stringValue = value.toString().trim();
return stringValue.startsWith("[") && stringValue.endsWith("]") && stringValue.indexOf(",") > 0;
}
protected void buildExpression(StringBuffer sb, String entityKey, String field, Object[] value,
SupportedFieldType type, SupportedFieldType secondaryType, String operator,
boolean includeParenthesis, boolean isFieldComparison, boolean ignoreCase,
boolean isNegation, boolean ignoreQuotes)
throws MVELTranslationException {
if (operator.equals("==") && !isFieldComparison && value.length > 1) {
sb.append("(");
sb.append("[");
sb.append(formatValue(field, entityKey, type, secondaryType, value, isFieldComparison,
ignoreCase, ignoreQuotes));
sb.append("] contains ");
sb.append(formatField(entityKey, type, field, ignoreCase, isNegation));
if ((type.equals(SupportedFieldType.ID) && secondaryType != null &&
secondaryType.equals(SupportedFieldType.INTEGER)) || type.equals(SupportedFieldType.INTEGER)) {
sb.append(".intValue()");
}
sb.append(")");
} else {
sb.append(formatField(entityKey, type, field, ignoreCase, isNegation));
sb.append(operator);
if (includeParenthesis) {
sb.append("(");
}
sb.append(formatValue(field, entityKey, type, secondaryType, value,
isFieldComparison, ignoreCase, ignoreQuotes));
if (includeParenthesis) {
sb.append(")");
}
}
}
protected String buildFieldName(String entityKey, String fieldName) {
String response = entityKey + "." + fieldName;
response = response.replaceAll("\\.", ".?");
return response;
}
protected String formatField(String entityKey, SupportedFieldType type, String field,
boolean ignoreCase, boolean isNegation) {
StringBuilder response = new StringBuilder();
if (isNegation) {
response.append("!");
}
String convertedField = field;
boolean isMapField = false;
if (convertedField.contains(FieldManager.MAPFIELDSEPARATOR)) {
//This must be a map field, convert the field name to syntax MVEL can understand for map access
convertedField = convertedField.substring(0, convertedField.indexOf(FieldManager.MAPFIELDSEPARATOR))
+ "[\"" + convertedField.substring(convertedField.indexOf(FieldManager.MAPFIELDSEPARATOR) +
FieldManager.MAPFIELDSEPARATOR.length(), convertedField.length()) + "\"]";
isMapField = true;
}
if (isMapField) {
switch(type) {
case BOOLEAN:
response.append("MvelHelper.convertField(\"BOOLEAN\",");
response.append(buildFieldName(entityKey, convertedField));
response.append(")");
break;
case INTEGER:
response.append("MvelHelper.convertField(\"INTEGER\",");
response.append(buildFieldName(entityKey, convertedField));
response.append(")");
break;
case DECIMAL:
case MONEY:
response.append("MvelHelper.convertField(\"DECIMAL\",");
response.append(buildFieldName(entityKey, convertedField));
response.append(")");
break;
case DATE:
response.append("MvelHelper.convertField(\"DATE\",");
response.append(buildFieldName(entityKey, convertedField));
response.append(")");
break;
case STRING:
if (ignoreCase) {
response.append("MvelHelper.toUpperCase(");
}
response.append(buildFieldName(entityKey, convertedField));
if (ignoreCase) {
response.append(")");
}
break;
case STRING_LIST:
response.append(buildFieldName(entityKey, convertedField));
break;
default:
throw new UnsupportedOperationException(type.toString() + " is not supported for map fields in the rule builder.");
}
} else {
switch(type) {
case BROADLEAF_ENUMERATION:
if (isMapField) {
throw new UnsupportedOperationException("Enumerations are not supported for map fields in the rule builder.");
} else {
response.append(buildFieldName(entityKey, convertedField));
response.append(".getType()");
}
break;
case MONEY:
response.append(buildFieldName(entityKey, convertedField));
response.append(".getAmount()");
break;
case STRING:
if (ignoreCase) {
response.append("MvelHelper.toUpperCase(");
}
response.append(buildFieldName(entityKey, convertedField));
if (ignoreCase) {
response.append(")");
}
break;
default:
response.append(buildFieldName(entityKey, convertedField));
break;
}
}
return response.toString();
}
protected String formatValue(String fieldName, String entityKey, SupportedFieldType type,
SupportedFieldType secondaryType, Object[] value,
boolean isFieldComparison, boolean ignoreCase,
boolean ignoreQuotes) throws MVELTranslationException {
StringBuilder response = new StringBuilder();
if (isFieldComparison) {
switch(type) {
case MONEY:
response.append(entityKey);
response.append(".");
response.append(value[0]);
response.append(".getAmount()");
break;
case STRING:
if (ignoreCase) {
response.append("MvelHelper.toUpperCase(");
}
response.append(entityKey);
response.append(".");
response.append(value[0]);
if (ignoreCase) {
response.append(")");
}
break;
default:
response.append(entityKey);
response.append(".");
response.append(value[0]);
break;
}
} else {
for (int j=0;j<value.length;j++){
switch(type) {
case BOOLEAN:
response.append(value[j]);
break;
case DECIMAL:
try {
Double.parseDouble(value[j].toString());
} catch (Exception e) {
throw new MVELTranslationException(MVELTranslationException.INCOMPATIBLE_DECIMAL_VALUE, "Cannot format value for the field ("
+ fieldName + ") based on field type. The type of field is Decimal, " +
"and you entered: (" + value[j] +")");
}
response.append(value[j]);
break;
case ID:
if (secondaryType != null && secondaryType.toString().equals(
SupportedFieldType.STRING.toString())) {
if (ignoreCase) {
response.append("MvelHelper.toUpperCase(");
}
if (!ignoreQuotes) {
response.append("\"");
}
response.append(value[j]);
if (!ignoreQuotes) {
response.append("\"");
}
if (ignoreCase) {
response.append(")");
}
} else {
try {
Integer.parseInt(value[j].toString());
} catch (Exception e) {
throw new MVELTranslationException(MVELTranslationException.INCOMPATIBLE_INTEGER_VALUE, "Cannot format value for the field (" +
fieldName + ") based on field type. The type of field is Integer, " +
"and you entered: (" + value[j] +")");
}
response.append(value[j]);
}
break;
case INTEGER:
try {
Integer.parseInt(value[j].toString());
} catch (Exception e) {
throw new MVELTranslationException(MVELTranslationException.INCOMPATIBLE_INTEGER_VALUE, "Cannot format value for the field (" +
fieldName + ") based on field type. The type of field is Integer, " +
"and you entered: (" + value[j] +")");
}
response.append(value[j]);
break;
case MONEY:
try {
Double.parseDouble(value[j].toString());
} catch (Exception e) {
throw new MVELTranslationException(MVELTranslationException.INCOMPATIBLE_DECIMAL_VALUE, "Cannot format value for the field (" +
fieldName + ") based on field type. The type of field is Money, " +
"and you entered: (" + value[j] +")");
}
response.append(value[j]);
break;
case DATE:
//convert the date to our standard date/time format
Date temp = null;
try {
temp = RuleBuilderFormatUtil.parseDate(String.valueOf(value[j]));
} catch (ParseException e) {
throw new MVELTranslationException(MVELTranslationException.INCOMPATIBLE_DATE_VALUE, "Cannot format value for the field (" +
fieldName + ") based on field type. The type of field is Date, " +
"and you entered: (" + value[j] +"). Dates must be in the format MM/dd/yyyy HH:mm.");
}
String convertedDate = FormatUtil.getTimeZoneFormat().format(temp);
response.append("MvelHelper.convertField(\"DATE\",\"");
response.append(convertedDate);
response.append("\")");
break;
default:
if (ignoreCase) {
response.append("MvelHelper.toUpperCase(");
}
if (!ignoreQuotes) {
response.append("\"");
}
response.append(value[j]);
if (!ignoreQuotes) {
response.append("\"");
}
if (ignoreCase) {
response.append(")");
}
break;
}
if (j < value.length - 1) {
response.append(",");
}
}
}
return response.toString();
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_web_rulebuilder_DataDTOToMVELTranslator.java
|
761 |
public class TransportGetAction extends TransportShardSingleOperationAction<GetRequest, GetResponse> {
public static boolean REFRESH_FORCE = false;
private final IndicesService indicesService;
private final boolean realtime;
@Inject
public TransportGetAction(Settings settings, ClusterService clusterService, TransportService transportService,
IndicesService indicesService, ThreadPool threadPool) {
super(settings, threadPool, clusterService, transportService);
this.indicesService = indicesService;
this.realtime = settings.getAsBoolean("action.get.realtime", true);
}
@Override
protected String executor() {
return ThreadPool.Names.GET;
}
@Override
protected String transportAction() {
return GetAction.NAME;
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, GetRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.READ);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, GetRequest request) {
return state.blocks().indexBlockedException(ClusterBlockLevel.READ, request.index());
}
@Override
protected ShardIterator shards(ClusterState state, GetRequest request) {
return clusterService.operationRouting()
.getShards(clusterService.state(), request.index(), request.type(), request.id(), request.routing(), request.preference());
}
@Override
protected void resolveRequest(ClusterState state, GetRequest request) {
if (request.realtime == null) {
request.realtime = this.realtime;
}
// update the routing (request#index here is possibly an alias)
request.routing(state.metaData().resolveIndexRouting(request.routing(), request.index()));
request.index(state.metaData().concreteIndex(request.index()));
// Fail fast on the node that received the request.
if (request.routing() == null && state.getMetaData().routingRequired(request.index(), request.type())) {
throw new RoutingMissingException(request.index(), request.type(), request.id());
}
}
@Override
protected GetResponse shardOperation(GetRequest request, int shardId) throws ElasticsearchException {
IndexService indexService = indicesService.indexServiceSafe(request.index());
IndexShard indexShard = indexService.shardSafe(shardId);
if (request.refresh() && !request.realtime()) {
indexShard.refresh(new Engine.Refresh("refresh_flag_get").force(REFRESH_FORCE));
}
GetResult result = indexShard.getService().get(request.type(), request.id(), request.fields(),
request.realtime(), request.version(), request.versionType(), request.fetchSourceContext());
return new GetResponse(result);
}
@Override
protected GetRequest newRequest() {
return new GetRequest();
}
@Override
protected GetResponse newResponse() {
return new GetResponse();
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_get_TransportGetAction.java
|
154 |
public class ODoubleSerializer implements OBinarySerializer<Double> {
private static final OBinaryConverter CONVERTER = OBinaryConverterFactory.getConverter();
public static ODoubleSerializer INSTANCE = new ODoubleSerializer();
public static final byte ID = 6;
/**
* size of double value in bytes
*/
public static final int DOUBLE_SIZE = 8;
public int getObjectSize(Double object, Object... hints) {
return DOUBLE_SIZE;
}
public void serialize(Double object, byte[] stream, int startPosition, Object... hints) {
OLongSerializer.INSTANCE.serialize(Double.doubleToLongBits(object), stream, startPosition);
}
public Double deserialize(byte[] stream, int startPosition) {
return Double.longBitsToDouble(OLongSerializer.INSTANCE.deserialize(stream, startPosition));
}
public int getObjectSize(byte[] stream, int startPosition) {
return DOUBLE_SIZE;
}
public byte getId() {
return ID;
}
public int getObjectSizeNative(byte[] stream, int startPosition) {
return DOUBLE_SIZE;
}
public void serializeNative(Double object, byte[] stream, int startPosition, Object... hints) {
CONVERTER.putLong(stream, startPosition, Double.doubleToLongBits(object), ByteOrder.nativeOrder());
}
public Double deserializeNative(byte[] stream, int startPosition) {
return Double.longBitsToDouble(CONVERTER.getLong(stream, startPosition, ByteOrder.nativeOrder()));
}
@Override
public void serializeInDirectMemory(Double object, ODirectMemoryPointer pointer, long offset, Object... hints) {
pointer.setLong(offset, Double.doubleToLongBits(object));
}
@Override
public Double deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) {
return Double.longBitsToDouble(pointer.getLong(offset));
}
@Override
public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) {
return DOUBLE_SIZE;
}
public boolean isFixedLength() {
return true;
}
public int getFixedLength() {
return DOUBLE_SIZE;
}
@Override
public Double preprocess(Double value, Object... hints) {
return value;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_serialization_types_ODoubleSerializer.java
|
2,598 |
class SocketPacketWriter implements SocketWriter<Packet> {
private static final int CONST_BUFFER_NO = 4;
final TcpIpConnection connection;
final IOService ioService;
final ILogger logger;
private final PacketWriter packetWriter;
SocketPacketWriter(TcpIpConnection connection) {
this.connection = connection;
this.ioService = connection.getConnectionManager().ioService;
this.logger = ioService.getLogger(SocketPacketWriter.class.getName());
boolean symmetricEncryptionEnabled = CipherHelper.isSymmetricEncryptionEnabled(ioService);
if (symmetricEncryptionEnabled) {
packetWriter = new SymmetricCipherPacketWriter();
logger.info("Writer started with SymmetricEncryption");
} else {
packetWriter = new DefaultPacketWriter();
}
}
public boolean write(Packet socketWritable, ByteBuffer socketBuffer) throws Exception {
return packetWriter.writePacket(socketWritable, socketBuffer);
}
private interface PacketWriter {
boolean writePacket(Packet packet, ByteBuffer socketBB) throws Exception;
}
private static class DefaultPacketWriter implements PacketWriter {
public boolean writePacket(Packet packet, ByteBuffer socketBB) {
return packet.writeTo(socketBB);
}
}
private class SymmetricCipherPacketWriter implements PacketWriter {
final Cipher cipher;
ByteBuffer packetBuffer = ByteBuffer.allocate(ioService.getSocketSendBufferSize() * IOService.KILO_BYTE);
boolean packetWritten;
SymmetricCipherPacketWriter() {
cipher = init();
}
private Cipher init() {
Cipher c;
try {
c = CipherHelper.createSymmetricWriterCipher(ioService.getSymmetricEncryptionConfig());
} catch (Exception e) {
logger.severe("Symmetric Cipher for WriteHandler cannot be initialized.", e);
CipherHelper.handleCipherException(e, connection);
throw ExceptionUtil.rethrow(e);
}
return c;
}
public boolean writePacket(Packet packet, ByteBuffer socketBuffer) throws Exception {
if (!packetWritten) {
if (socketBuffer.remaining() < CONST_BUFFER_NO) {
return false;
}
int size = cipher.getOutputSize(packet.size());
socketBuffer.putInt(size);
if (packetBuffer.capacity() < packet.size()) {
packetBuffer = ByteBuffer.allocate(packet.size());
}
if (!packet.writeTo(packetBuffer)) {
throw new HazelcastException("Packet didn't fit into the buffer!");
}
packetBuffer.flip();
packetWritten = true;
}
if (socketBuffer.hasRemaining()) {
int outputSize = cipher.getOutputSize(packetBuffer.remaining());
if (outputSize <= socketBuffer.remaining()) {
cipher.update(packetBuffer, socketBuffer);
} else {
int min = Math.min(packetBuffer.remaining(), socketBuffer.remaining());
int len = min / 2;
if (len > 0) {
int limitOld = packetBuffer.limit();
packetBuffer.limit(packetBuffer.position() + len);
cipher.update(packetBuffer, socketBuffer);
packetBuffer.limit(limitOld);
}
}
if (!packetBuffer.hasRemaining()) {
if (socketBuffer.remaining() >= cipher.getOutputSize(0)) {
socketBuffer.put(cipher.doFinal());
packetWritten = false;
packetBuffer.clear();
return true;
}
}
}
return false;
}
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_SocketPacketWriter.java
|
208 |
public class MissingFieldQueryExtension implements FieldQueryExtension {
public static final String NAME = "_missing_";
@Override
public Query query(QueryParseContext parseContext, String queryText) {
String fieldName = queryText;
Filter filter = null;
MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName);
if (smartNameFieldMappers != null) {
if (smartNameFieldMappers.hasMapper()) {
filter = smartNameFieldMappers.mapper().rangeFilter(null, null, true, true, parseContext);
}
}
if (filter == null) {
filter = new TermRangeFilter(fieldName, null, null, true, true);
}
// we always cache this one, really does not change... (exists)
filter = parseContext.cacheFilter(filter, null);
filter = new NotFilter(filter);
// cache the not filter as well, so it will be faster
filter = parseContext.cacheFilter(filter, null);
filter = wrapSmartNameFilter(filter, smartNameFieldMappers, parseContext);
return new XConstantScoreQuery(filter);
}
}
| 1no label
|
src_main_java_org_apache_lucene_queryparser_classic_MissingFieldQueryExtension.java
|
2,356 |
executorService.submit(new Runnable() {
@Override
public void run() {
processReducerFinished0(notification);
}
});
| 1no label
|
hazelcast_src_main_java_com_hazelcast_mapreduce_impl_task_JobSupervisor.java
|
568 |
public class OpenIndexAction extends IndicesAction<OpenIndexRequest, OpenIndexResponse, OpenIndexRequestBuilder> {
public static final OpenIndexAction INSTANCE = new OpenIndexAction();
public static final String NAME = "indices/open";
private OpenIndexAction() {
super(NAME);
}
@Override
public OpenIndexResponse newResponse() {
return new OpenIndexResponse();
}
@Override
public OpenIndexRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new OpenIndexRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_open_OpenIndexAction.java
|
257 |
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ClientExecutorServiceTest {
static final int CLUSTER_SIZE = 3;
static HazelcastInstance instance1;
static HazelcastInstance instance2;
static HazelcastInstance instance3;
static HazelcastInstance client;
@BeforeClass
public static void init() {
instance1 = Hazelcast.newHazelcastInstance();
instance2 = Hazelcast.newHazelcastInstance();
instance3 = Hazelcast.newHazelcastInstance();
client = HazelcastClient.newHazelcastClient();
}
@AfterClass
public static void destroy() {
client.shutdown();
Hazelcast.shutdownAll();
}
@Test(expected = UnsupportedOperationException.class)
public void testGetLocalExecutorStats() throws Throwable, InterruptedException {
IExecutorService service = client.getExecutorService(randomString());
service.getLocalExecutorStats();
}
@Test
public void testIsTerminated() throws InterruptedException, ExecutionException, TimeoutException {
final IExecutorService service = client.getExecutorService(randomString());
assertFalse(service.isTerminated());
}
@Test
public void testIsShutdown() throws InterruptedException, ExecutionException, TimeoutException {
final IExecutorService service = client.getExecutorService(randomString());
assertFalse(service.isShutdown());
}
@Test
public void testShutdownNow() throws InterruptedException, ExecutionException, TimeoutException {
final IExecutorService service = client.getExecutorService(randomString());
service.shutdownNow();
assertTrueEventually(new AssertTask() {
public void run() throws Exception {
assertTrue(service.isShutdown());
}
});
}
@Test(expected = TimeoutException.class)
public void testCancellationAwareTask_whenTimeOut() throws InterruptedException, ExecutionException, TimeoutException {
IExecutorService service = client.getExecutorService(randomString());
CancellationAwareTask task = new CancellationAwareTask(5000);
Future future = service.submit(task);
future.get(1, TimeUnit.SECONDS);
}
@Test
public void testFutureAfterCancellationAwareTaskTimeOut() throws InterruptedException, ExecutionException, TimeoutException {
IExecutorService service = client.getExecutorService(randomString());
CancellationAwareTask task = new CancellationAwareTask(5000);
Future future = service.submit(task);
try {
future.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
}
assertFalse(future.isDone());
assertFalse(future.isCancelled());
}
@Test
public void testCancelFutureAfterCancellationAwareTaskTimeOut() throws InterruptedException, ExecutionException, TimeoutException {
IExecutorService service = client.getExecutorService(randomString());
CancellationAwareTask task = new CancellationAwareTask(5000);
Future future = service.submit(task);
try {
future.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
}
assertTrue(future.cancel(true));
assertTrue(future.isCancelled());
assertTrue(future.isDone());
}
@Test(expected = CancellationException.class)
public void testGetFutureAfterCancel() throws InterruptedException, ExecutionException, TimeoutException {
IExecutorService service = client.getExecutorService(randomString());
CancellationAwareTask task = new CancellationAwareTask(5000);
Future future = service.submit(task);
try {
future.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
}
future.cancel(true);
future.get();
}
@Test(expected = ExecutionException.class)
public void testSubmitFailingCallableException() throws ExecutionException, InterruptedException {
IExecutorService service = client.getExecutorService(randomString());
final Future<String> f = service.submit(new FailingCallable());
f.get();
}
@Test(expected = IllegalStateException.class)
public void testSubmitFailingCallableReasonExceptionCause() throws Throwable {
IExecutorService service = client.getExecutorService(randomString());
final Future<String> f = service.submit(new FailingCallable());
try {
f.get();
} catch (ExecutionException e) {
throw e.getCause();
}
}
@Test(expected = IllegalStateException.class)
public void testExecute_withNoMemberSelected() {
final IExecutorService service = client.getExecutorService(randomString());
final String mapName = randomString();
final MemberSelector selector = new SelectNoMembers();
service.execute(new MapPutRunnable(mapName), selector);
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceTest.java
|
66 |
public interface OCloseable {
public void close();
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_concur_resource_OCloseable.java
|
316 |
new Thread() {
public void run() {
map.tryPut(key, value, 8, TimeUnit.SECONDS);
tryPutReturned.countDown();
}
}.start();
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapLockTest.java
|
394 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name="BLC_MEDIA")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
public class MediaImpl implements Media {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator= "MediaId")
@GenericGenerator(
name="MediaId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="MediaImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.common.media.domain.MediaImpl")
}
)
@Column(name = "MEDIA_ID")
protected Long id;
@Column(name = "URL", nullable = false)
@Index(name="MEDIA_URL_INDEX", columnNames={"URL"})
@AdminPresentation(friendlyName = "MediaImpl_Media_Url", order = 1, prominent = true,
fieldType = SupportedFieldType.ASSET_LOOKUP)
protected String url;
@Column(name = "TITLE")
@Index(name="MEDIA_TITLE_INDEX", columnNames={"TITLE"})
@AdminPresentation(friendlyName = "MediaImpl_Media_Title", order=2, prominent=true)
protected String title;
@Column(name = "ALT_TEXT")
@AdminPresentation(friendlyName = "MediaImpl_Media_Alt_Text", order=3, prominent=true)
protected String altText;
@Column(name = "TAGS")
@AdminPresentation(friendlyName = "MediaImpl_Media_Tags")
protected String tags;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getUrl() {
return url;
}
@Override
public void setUrl(String url) {
this.url = url;
}
@Override
public String getTitle() {
return title;
}
@Override
public void setTitle(String title) {
this.title = title;
}
@Override
public String getAltText() {
return altText;
}
@Override
public void setAltText(String altText) {
this.altText = altText;
}
@Override
public String getTags() {
return tags;
}
@Override
public void setTags(String tags) {
this.tags = tags;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + ((altText == null) ? 0 : altText.hashCode());
result = prime * result + ((tags == null) ? 0 : tags.hashCode());
result = prime * result + ((url == null) ? 0 : url.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MediaImpl other = (MediaImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (altText == null) {
if (other.altText != null)
return false;
} else if (!altText.equals(other.altText))
return false;
if (tags == null) {
if (other.tags != null)
return false;
} else if (!tags.equals(other.tags))
return false;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
return true;
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_media_domain_MediaImpl.java
|
308 |
new Thread() {
public void run() {
map.lock(key);
lockedLatch.countDown();
}
}.start();
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapLockTest.java
|
17 |
final class EntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> {
EntryIterator(final OMVRBTreeEntry<K, V> first) {
super(first);
}
public Map.Entry<K, V> next() {
return nextEntry();
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
|
143 |
static final class HashCode {
static final Random rng = new Random();
int code;
HashCode() {
int h = rng.nextInt(); // Avoid zero to allow xorShift rehash
code = (h == 0) ? 1 : h;
}
}
| 0true
|
src_main_java_jsr166e_Striped64.java
|
462 |
public class IndicesAliasesAction extends IndicesAction<IndicesAliasesRequest, IndicesAliasesResponse, IndicesAliasesRequestBuilder> {
public static final IndicesAliasesAction INSTANCE = new IndicesAliasesAction();
public static final String NAME = "indices/aliases";
private IndicesAliasesAction() {
super(NAME);
}
@Override
public IndicesAliasesResponse newResponse() {
return new IndicesAliasesResponse();
}
@Override
public IndicesAliasesRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new IndicesAliasesRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_alias_IndicesAliasesAction.java
|
1,787 |
public class FieldPathBuilder {
protected DynamicDaoHelper dynamicDaoHelper = new DynamicDaoHelperImpl();
protected CriteriaQuery criteria;
protected List<Predicate> restrictions;
public FieldPath getFieldPath(From root, String fullPropertyName) {
String[] pieces = fullPropertyName.split("\\.");
List<String> associationPath = new ArrayList<String>();
List<String> basicProperties = new ArrayList<String>();
int j = 0;
for (String piece : pieces) {
checkPiece: {
if (j == 0) {
Path path = root.get(piece);
if (path instanceof PluralAttributePath) {
associationPath.add(piece);
break checkPiece;
}
}
basicProperties.add(piece);
}
j++;
}
FieldPath fieldPath = new FieldPath()
.withAssociationPath(associationPath)
.withTargetPropertyPieces(basicProperties);
return fieldPath;
}
public Path getPath(From root, String fullPropertyName, CriteriaBuilder builder) {
return getPath(root, getFieldPath(root, fullPropertyName), builder);
}
@SuppressWarnings({"rawtypes", "unchecked", "serial"})
public Path getPath(From root, FieldPath fieldPath, final CriteriaBuilder builder) {
FieldPath myFieldPath = fieldPath;
if (!StringUtils.isEmpty(fieldPath.getTargetProperty())) {
myFieldPath = getFieldPath(root, fieldPath.getTargetProperty());
}
From myRoot = root;
for (String pathElement : myFieldPath.getAssociationPath()) {
myRoot = myRoot.join(pathElement);
}
Path path = myRoot;
for (int i = 0; i < myFieldPath.getTargetPropertyPieces().size(); i++) {
String piece = myFieldPath.getTargetPropertyPieces().get(i);
if (path.getJavaType().isAnnotationPresent(Embeddable.class)) {
String original = ((SingularAttributePath) path).getAttribute().getDeclaringType().getJavaType().getName() + "." + ((SingularAttributePath) path).getAttribute().getName() + "." + piece;
String copy = path.getJavaType().getName() + "." + piece;
copyCollectionPersister(original, copy, ((CriteriaBuilderImpl) builder).getEntityManagerFactory().getSessionFactory());
}
try {
path = path.get(piece);
} catch (IllegalArgumentException e) {
// We weren't able to resolve the requested piece, likely because it's in a polymoprhic version
// of the path we're currently on. Let's see if there's any polymoprhic version of our class to
// use instead.
EntityManagerFactoryImpl em = ((CriteriaBuilderImpl) builder).getEntityManagerFactory();
Metamodel mm = em.getMetamodel();
boolean found = false;
Class<?>[] polyClasses = dynamicDaoHelper.getAllPolymorphicEntitiesFromCeiling(
path.getJavaType(), em.getSessionFactory(), true, true);
for (Class<?> clazz : polyClasses) {
ManagedType mt = mm.managedType(clazz);
try {
Attribute attr = mt.getAttribute(piece);
if (attr != null) {
Root additionalRoot = criteria.from(clazz);
restrictions.add(builder.equal(path, additionalRoot));
path = additionalRoot.get(piece);
found = true;
break;
}
} catch (IllegalArgumentException e2) {
// Do nothing - we'll try the next class and see if it has the attribute
}
}
if (!found) {
throw new IllegalArgumentException("Could not resolve requested attribute against path, including" +
" known polymorphic versions of the root", e);
}
}
if (path.getParentPath() != null && path.getParentPath().getJavaType().isAnnotationPresent(Embeddable.class) && path instanceof PluralAttributePath) {
//TODO this code should work, but there still appear to be bugs in Hibernate's JPA criteria handling for lists
//inside Embeddables
Class<?> myClass = ((PluralAttributePath) path).getAttribute().getClass().getInterfaces()[0];
//we don't know which version of "join" to call, so we'll let reflection figure it out
try {
From embeddedJoin = myRoot.join(((SingularAttributePath) path.getParentPath()).getAttribute());
Method join = embeddedJoin.getClass().getMethod("join", myClass);
path = (Path) join.invoke(embeddedJoin, ((PluralAttributePath) path).getAttribute());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return path;
}
/**
* This is a workaround for HHH-6562 (https://hibernate.atlassian.net/browse/HHH-6562)
*/
@SuppressWarnings("unchecked")
private void copyCollectionPersister(String originalKey, String copyKey,
SessionFactoryImpl sessionFactory) {
try {
Field collectionPersistersField = SessionFactoryImpl.class
.getDeclaredField("collectionPersisters");
collectionPersistersField.setAccessible(true);
Map collectionPersisters = (Map) collectionPersistersField.get(sessionFactory);
if (collectionPersisters.containsKey(originalKey)) {
Object collectionPersister = collectionPersisters.get(originalKey);
collectionPersisters.put(copyKey, collectionPersister);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public CriteriaQuery getCriteria() {
return criteria;
}
public void setCriteria(CriteriaQuery criteria) {
this.criteria = criteria;
}
public List<Predicate> getRestrictions() {
return restrictions;
}
public void setRestrictions(List<Predicate> restrictions) {
this.restrictions = restrictions;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_criteria_FieldPathBuilder.java
|
226 |
public class SystemPropertyRuntimeEnvironmentKeyResolver implements RuntimeEnvironmentKeyResolver {
protected String environmentKey = "runtime.environment";
public SystemPropertyRuntimeEnvironmentKeyResolver() {
// EMPTY
}
public String resolveRuntimeEnvironmentKey() {
return System.getProperty(environmentKey);
}
public void setEnvironmentKey(String environmentKey) {
this.environmentKey = environmentKey;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_config_SystemPropertyRuntimeEnvironmentKeyResolver.java
|
41 |
public interface EdgeLabel extends RelationType {
/**
* Checks whether this labels is defined as directed.
*
* @return true, if this label is directed, else false.
*/
public boolean isDirected();
/**
* Checks whether this labels is defined as unidirected.
*
* @return true, if this label is unidirected, else false.
*/
public boolean isUnidirected();
/**
* The {@link Multiplicity} for this edge label.
*
* @return
*/
public Multiplicity getMultiplicity();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_EdgeLabel.java
|
57 |
@SuppressWarnings("serial")
static final class ForEachTransformedKeyTask<K,V,U>
extends BulkTask<K,V,Void> {
final Fun<? super K, ? extends U> transformer;
final Action<? super U> action;
ForEachTransformedKeyTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Fun<? super K, ? extends U> transformer, Action<? super U> action) {
super(p, b, i, f, t);
this.transformer = transformer; this.action = action;
}
public final void compute() {
final Fun<? super K, ? extends U> transformer;
final Action<? super U> action;
if ((transformer = this.transformer) != null &&
(action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachTransformedKeyTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
transformer, action).fork();
}
for (Node<K,V> p; (p = advance()) != null; ) {
U u;
if ((u = transformer.apply(p.key)) != null)
action.apply(u);
}
propagateCompletion();
}
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.