Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
846 | public class StandardSerializer extends StandardAttributeHandling implements Serializer {
private static final Logger log = LoggerFactory.getLogger(StandardSerializer.class);
private final KryoSerializer backupSerializer;
public StandardSerializer(boolean allowCustomSerialization, int maxOutputSize) {
backupSerializer = new KryoSerializer(getDefaultRegistrations(), !allowCustomSerialization, maxOutputSize);
}
public StandardSerializer(boolean allowCustomSerialization) {
backupSerializer = new KryoSerializer(getDefaultRegistrations(), !allowCustomSerialization);
}
public StandardSerializer() {
this(true);
}
private KryoSerializer getBackupSerializer() {
assert backupSerializer!=null;
return backupSerializer;
}
private boolean supportsNullSerialization(Class type) {
return getSerializer(type) instanceof SupportsNullSerializer;
}
@Override
public <T> T readObjectByteOrder(ReadBuffer buffer, Class<T> type) {
return readObjectInternal(buffer,type,true);
}
@Override
public <T> T readObject(ReadBuffer buffer, Class<T> type) {
return readObjectInternal(buffer,type,false);
}
@Override
public <T> T readObjectNotNull(ReadBuffer buffer, Class<T> type) {
return readObjectNotNullInternal(buffer,type,false);
}
private <T> T readObjectInternal(ReadBuffer buffer, Class<T> type, boolean byteOrder) {
if (supportsNullSerialization(type)) {
AttributeSerializer<T> s = getSerializer(type);
if (byteOrder) return ((OrderPreservingSerializer<T>)s).readByteOrder(buffer);
else return s.read(buffer);
} else {
//Read flag for null or not
byte flag = buffer.getByte();
if (flag==-1) {
return null;
} else {
Preconditions.checkArgument(flag==0,"Invalid flag encountered in serialization: %s. Corrupted data.",flag);
return readObjectNotNullInternal(buffer,type,byteOrder);
}
}
}
private <T> T readObjectNotNullInternal(ReadBuffer buffer, Class<T> type, boolean byteOrder) {
AttributeSerializer<T> s = getSerializer(type);
if (byteOrder) {
Preconditions.checkArgument(s!=null && s instanceof OrderPreservingSerializer,"Invalid serializer for class: %s",type);
return ((OrderPreservingSerializer<T>)s).readByteOrder(buffer);
} else {
if (s!=null) return s.read(buffer);
else return getBackupSerializer().readObjectNotNull(buffer,type);
}
}
@Override
public Object readClassAndObject(ReadBuffer buffer) {
return getBackupSerializer().readClassAndObject(buffer);
}
@Override
public DataOutput getDataOutput(int initialCapacity) {
return new StandardDataOutput(initialCapacity);
}
private class StandardDataOutput extends WriteByteBuffer implements DataOutput {
private StandardDataOutput(int initialCapacity) {
super(initialCapacity);
}
@Override
public DataOutput writeObjectByteOrder(Object object, Class type) {
Preconditions.checkArgument(StandardSerializer.this.isOrderPreservingDatatype(type),"Invalid serializer for class: %s",type);
return writeObjectInternal(object,type,true);
}
@Override
public DataOutput writeObject(Object object, Class type) {
return writeObjectInternal(object,type,false);
}
@Override
public DataOutput writeObjectNotNull(Object object) {
return writeObjectNotNullInternal(object,false);
}
private DataOutput writeObjectInternal(Object object, Class type, boolean byteOrder) {
if (supportsNullSerialization(type)) {
AttributeSerializer s = getSerializer(type);
if (byteOrder) ((OrderPreservingSerializer)s).writeByteOrder(this,object);
else s.write(this, object);
} else {
//write flag for null or not
if (object==null) {
putByte((byte)-1);
} else {
putByte((byte)0);
writeObjectNotNullInternal(object,byteOrder);
}
}
return this;
}
private DataOutput writeObjectNotNullInternal(Object object, boolean byteOrder) {
Preconditions.checkNotNull(object);
AttributeSerializer s = getSerializer(object.getClass());
if (byteOrder) {
Preconditions.checkArgument(s!=null && s instanceof OrderPreservingSerializer,"Invalid serializer for class: %s",object.getClass());
((OrderPreservingSerializer)s).writeByteOrder(this,object);
} else {
if (s!=null) s.write(this, object);
else {
try {
getBackupSerializer().writeObjectNotNull(this,object);
} catch (Exception e) {
throw new TitanException("Serializer Restriction: Cannot serialize object of type: " + object.getClass(),e);
}
}
}
return this;
}
@Override
public DataOutput writeClassAndObject(Object object) {
try {
getBackupSerializer().writeClassAndObject(this,object);
} catch (Exception e) {
throw new TitanException("Serializer Restriction: Cannot serialize object of type: " + (object==null?"null":object.getClass()),e);
}
return this;
}
@Override
public DataOutput putLong(long val) {
super.putLong(val);
return this;
}
@Override
public DataOutput putInt(int val) {
super.putInt(val);
return this;
}
@Override
public DataOutput putShort(short val) {
super.putShort(val);
return this;
}
@Override
public WriteBuffer putBoolean(boolean val) {
super.putBoolean(val);
return this;
}
@Override
public DataOutput putByte(byte val) {
super.putByte(val);
return this;
}
@Override
public DataOutput putBytes(byte[] val) {
super.putBytes(val);
return this;
}
@Override
public DataOutput putBytes(final StaticBuffer val) {
super.putBytes(val);
return this;
}
@Override
public DataOutput putChar(char val) {
super.putChar(val);
return this;
}
@Override
public DataOutput putFloat(float val) {
super.putFloat(val);
return this;
}
@Override
public DataOutput putDouble(double val) {
super.putDouble(val);
return this;
}
}
} | 1no label
| titan-core_src_main_java_com_thinkaurelius_titan_graphdb_database_serialize_StandardSerializer.java |
588 | protected static final class IndexTxSnapshot {
public Map<Object, Object> indexSnapshot = new HashMap<Object, Object>();
public boolean clear = false;
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_OIndexAbstract.java |
99 | private static class DeadlockProneTransactionStateFactory extends TransactionStateFactory
{
private DoubleLatch latch;
DeadlockProneTransactionStateFactory( Logging logging )
{
super( logging );
}
public DoubleLatch installDeadlockLatch()
{
return this.latch = new DoubleLatch();
}
@Override
public TransactionState create( javax.transaction.Transaction tx )
{
if ( latch != null )
{
return new DeadlockProneTransactionState(
lockManager, nodeManager, logging, tx, txHook, txIdGenerator, latch );
}
return super.create( tx );
}
} | 0true
| community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestCacheUpdateDeadlock.java |
3,984 | public static abstract class AbstractDistanceScoreFunction extends ScoreFunction {
private final double scale;
protected final double offset;
private final DecayFunction func;
public AbstractDistanceScoreFunction(double userSuppiedScale, double decay, double offset, DecayFunction func) {
super(CombineFunction.MULT);
if (userSuppiedScale <= 0.0) {
throw new ElasticsearchIllegalArgumentException(FunctionScoreQueryParser.NAME + " : scale must be > 0.0.");
}
if (decay <= 0.0 || decay >= 1.0) {
throw new ElasticsearchIllegalArgumentException(FunctionScoreQueryParser.NAME
+ " : decay must be in the range [0..1].");
}
this.scale = func.processScale(userSuppiedScale, decay);
this.func = func;
if (offset < 0.0d) {
throw new ElasticsearchIllegalArgumentException(FunctionScoreQueryParser.NAME + " : offset must be > 0.0");
}
this.offset = offset;
}
@Override
public double score(int docId, float subQueryScore) {
double value = distance(docId);
return func.evaluate(value, scale);
}
/**
* This function computes the distance from a defined origin. Since
* the value of the document is read from the index, it cannot be
* guaranteed that the value actually exists. If it does not, we assume
* the user handles this case in the query and return 0.
* */
protected abstract double distance(int docId);
protected abstract String getDistanceString(int docId);
protected abstract String getFieldName();
@Override
public Explanation explainScore(int docId, Explanation subQueryExpl) {
ComplexExplanation ce = new ComplexExplanation();
ce.setValue(CombineFunction.toFloat(score(docId, subQueryExpl.getValue())));
ce.setMatch(true);
ce.setDescription("Function for field " + getFieldName() + ":");
ce.addDetail(func.explainFunction(getDistanceString(docId), distance(docId), scale));
return ce;
}
} | 1no label
| src_main_java_org_elasticsearch_index_query_functionscore_DecayFunctionParser.java |
1,319 | public class ExecutorDataSerializerHook implements DataSerializerHook {
public static final int F_ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.EXECUTOR_DS_FACTORY, -13);
static final int CALLABLE_TASK = 0;
static final int MEMBER_CALLABLE_TASK = 1;
static final int RUNNABLE_ADAPTER = 2;
@Override
public int getFactoryId() {
return F_ID;
}
@Override
public DataSerializableFactory createFactory() {
return new DataSerializableFactory() {
@Override
public IdentifiedDataSerializable create(int typeId) {
switch (typeId) {
case CALLABLE_TASK:
return new CallableTaskOperation();
case MEMBER_CALLABLE_TASK:
return new MemberCallableTaskOperation();
case RUNNABLE_ADAPTER:
return new RunnableAdapter();
default:
return null;
}
}
};
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_executor_ExecutorDataSerializerHook.java |
436 | public class ClusterStatsNodeResponse extends NodeOperationResponse {
private NodeInfo nodeInfo;
private NodeStats nodeStats;
private ShardStats[] shardsStats;
private ClusterHealthStatus clusterStatus;
ClusterStatsNodeResponse() {
}
public ClusterStatsNodeResponse(DiscoveryNode node, @Nullable ClusterHealthStatus clusterStatus, NodeInfo nodeInfo, NodeStats nodeStats, ShardStats[] shardsStats) {
super(node);
this.nodeInfo = nodeInfo;
this.nodeStats = nodeStats;
this.shardsStats = shardsStats;
this.clusterStatus = clusterStatus;
}
public NodeInfo nodeInfo() {
return this.nodeInfo;
}
public NodeStats nodeStats() {
return this.nodeStats;
}
/**
* Cluster Health Status, only populated on master nodes.
*/
@Nullable
public ClusterHealthStatus clusterStatus() {
return clusterStatus;
}
public ShardStats[] shardsStats() {
return this.shardsStats;
}
public static ClusterStatsNodeResponse readNodeResponse(StreamInput in) throws IOException {
ClusterStatsNodeResponse nodeResponse = new ClusterStatsNodeResponse();
nodeResponse.readFrom(in);
return nodeResponse;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
clusterStatus = null;
if (in.readBoolean()) {
clusterStatus = ClusterHealthStatus.fromValue(in.readByte());
}
this.nodeInfo = NodeInfo.readNodeInfo(in);
this.nodeStats = NodeStats.readNodeStats(in);
int size = in.readVInt();
shardsStats = new ShardStats[size];
for (size--; size >= 0; size--) {
shardsStats[size] = ShardStats.readShardStats(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
if (clusterStatus == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
out.writeByte(clusterStatus.value());
}
nodeInfo.writeTo(out);
nodeStats.writeTo(out);
out.writeVInt(shardsStats.length);
for (ShardStats ss : shardsStats) {
ss.writeTo(out);
}
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsNodeResponse.java |
1,734 | map.addEntryListener(new EntryAdapter<String, String>() {
@Override
public void onEntryEvent(EntryEvent<String, String> event) {
final String val = event.getValue();
final String oldValue = event.getOldValue();
if ("newValue".equals(val) && "value".equals(oldValue)) {
latch.countDown();
}
}
}, true); | 0true
| hazelcast_src_test_java_com_hazelcast_map_EntryProcessorTest.java |
778 | @Entity
@Table(name = "BLC_CATEGORY_MEDIA_MAP")
public class CategoryMediaMap implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
@EmbeddedId
CategoryMediaMapPK categoryMediaMapPK;
@Column(name = "KEY", nullable = false)
private String key;
public void setKey(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public CategoryMediaMapPK getCategoryMediaMapPK() {
return categoryMediaMapPK;
}
public static class CategoryMediaMapPK implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
@Column(name = "CATEGORY_ID", nullable = false)
private Long categoryId;
@Column(name = "MEDIA_ID", nullable = false)
private Long mediaId;
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
public Long getMediaId() {
return mediaId;
}
public void setMediaId(Long mediaId) {
this.mediaId = mediaId;
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
else if (!(obj instanceof CategoryMediaMapPK)) return false;
return categoryId.equals(((CategoryMediaMapPK) obj).getCategoryId()) &&
mediaId.equals(((CategoryMediaMapPK) obj).getMediaId());
}
@Override
public int hashCode() {
return categoryId.hashCode() + mediaId.hashCode();
}
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_media_domain_CategoryMediaMap.java |
1,410 | @XmlRootElement(name = "productAttribute")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class ProductAttributeWrapper extends BaseWrapper implements APIWrapper<ProductAttribute>{
@XmlElement
protected Long id;
@XmlElement
protected Long productId;
@XmlElement
protected String attributeName;
@XmlElement
protected String attributeValue;
@Override
public void wrapDetails(ProductAttribute model, HttpServletRequest request) {
this.id = model.getId();
this.productId = model.getProduct().getId();
this.attributeName = model.getName();
this.attributeValue = model.getValue();
}
@Override
public void wrapSummary(ProductAttribute model, HttpServletRequest request) {
wrapDetails(model, request);
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_ProductAttributeWrapper.java |
1,672 | public interface AdminUserDao {
List<AdminUser> readAllAdminUsers();
AdminUser readAdminUserById(Long id);
AdminUser readAdminUserByUserName(String userName);
AdminUser saveAdminUser(AdminUser user);
void deleteAdminUser(AdminUser user);
List<AdminUser> readAdminUserByEmail(String emailAddress);
} | 0true
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_security_dao_AdminUserDao.java |
621 | new OIndexEngine.ValuesResultListener() {
@Override
public boolean addResult(OIdentifiable identifiable) {
return resultListener.addResult(identifiable);
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_OIndexOneValue.java |
1,958 | public final class MapSQLQueryRequest extends AbstractMapQueryRequest {
private String sql;
public MapSQLQueryRequest() {
}
public MapSQLQueryRequest(String name, String sql, IterationType iterationType) {
super(name, iterationType);
this.sql = sql;
}
@Override
protected Predicate getPredicate() {
return new SqlPredicate(sql);
}
public int getClassId() {
return MapPortableHook.SQL_QUERY;
}
protected void writePortableInner(PortableWriter writer) throws IOException {
writer.writeUTF("sql", sql);
}
protected void readPortableInner(PortableReader reader) throws IOException {
sql = reader.readUTF("sql");
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_client_MapSQLQueryRequest.java |
971 | private class NodeTransportHandler extends BaseTransportRequestHandler<NodeRequest> {
@Override
public NodeRequest newInstance() {
return newNodeRequest();
}
@Override
public void messageReceived(final NodeRequest request, final TransportChannel channel) throws Exception {
channel.sendResponse(nodeOperation(request));
}
@Override
public String toString() {
return transportNodeAction;
}
@Override
public String executor() {
return executor;
}
} | 0true
| src_main_java_org_elasticsearch_action_support_nodes_TransportNodesOperationAction.java |
1,904 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class QueryListenerTest extends HazelcastTestSupport {
@Test
public void testMapQueryListener() throws InterruptedException {
TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);
Config cfg = new Config();
HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(cfg);
HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(cfg);
HazelcastInstance instance3 = nodeFactory.newHazelcastInstance(cfg);
final IMap<Object, Object> map = instance1.getMap("testMapQueryListener");
final Object[] addedKey = new Object[1];
final Object[] addedValue = new Object[1];
final Object[] updatedKey = new Object[1];
final Object[] oldValue = new Object[1];
final Object[] newValue = new Object[1];
final Object[] removedKey = new Object[1];
final Object[] removedValue = new Object[1];
EntryListener<Object, Object> listener = new EntryListener<Object, Object>() {
public void entryAdded(EntryEvent<Object, Object> event) {
addedKey[0] = event.getKey();
addedValue[0] = event.getValue();
}
public void entryRemoved(EntryEvent<Object, Object> event) {
removedKey[0] = event.getKey();
removedValue[0] = event.getOldValue();
}
public void entryUpdated(EntryEvent<Object, Object> event) {
updatedKey[0] = event.getKey();
oldValue[0] = event.getOldValue();
newValue[0] = event.getValue();
}
public void entryEvicted(EntryEvent<Object, Object> event) {
}
};
map.addEntryListener(listener, new StartsWithPredicate("a"), null, true);
map.put("key1", "abc");
map.put("key2", "bcd");
map.put("key2", "axyz");
map.remove("key1");
Thread.sleep(1000);
assertEquals(addedKey[0], "key1");
assertEquals(addedValue[0], "abc");
assertEquals(updatedKey[0], "key2");
assertEquals(oldValue[0], "bcd");
assertEquals(newValue[0], "axyz");
assertEquals(removedKey[0], "key1");
assertEquals(removedValue[0], "abc");
}
static class StartsWithPredicate implements Predicate<Object, Object>, Serializable {
String pref;
StartsWithPredicate(String pref) {
this.pref = pref;
}
public boolean apply(Map.Entry<Object, Object> mapEntry) {
String val = (String) mapEntry.getValue();
if (val == null)
return false;
if (val.startsWith(pref))
return true;
return false;
}
}
@Test
public void testMapQueryListener2() throws InterruptedException {
TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);
Config cfg = new Config();
HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(cfg);
HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(cfg);
HazelcastInstance instance3 = nodeFactory.newHazelcastInstance(cfg);
final IMap<Object, Object> map = instance1.getMap("testMapQueryListener2");
final AtomicInteger addCount = new AtomicInteger(0);
EntryListener<Object, Object> listener = new EntryAdapter<Object, Object>() {
public void entryAdded(EntryEvent<Object, Object> event) {
addCount.incrementAndGet();
}
};
Predicate predicate = new SqlPredicate("age >= 50");
map.addEntryListener(listener, predicate, null, false);
int size = 100;
for (int i = 0; i < size; i++) {
Person person = new Person("name", i);
map.put(i, person);
}
Thread.sleep(1000);
assertEquals(50, addCount.get());
}
static class Person implements Serializable {
String name;
int age;
Person() {
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_map_QueryListenerTest.java |
317 | class GotoRequiredProjectAction extends Action {
private PackageExplorerPart fPackageExplorer;
GotoRequiredProjectAction(PackageExplorerPart part) {
super(PackagesMessages.GotoRequiredProjectAction_label);
setDescription(PackagesMessages.GotoRequiredProjectAction_description);
setToolTipText(PackagesMessages.GotoRequiredProjectAction_tooltip);
fPackageExplorer= part;
}
@Override
public void run() {
IStructuredSelection selection= (IStructuredSelection)fPackageExplorer.getSite().getSelectionProvider().getSelection();
Object element= selection.getFirstElement();
if (element instanceof ClassPathContainer.RequiredProjectWrapper) {
ClassPathContainer.RequiredProjectWrapper wrapper= (ClassPathContainer.RequiredProjectWrapper) element;
fPackageExplorer.tryToReveal(wrapper.getProject());
}
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_GotoRequiredProjectAction.java |
743 | public class ExplainRequest extends SingleShardOperationRequest<ExplainRequest> {
private static final XContentType contentType = Requests.CONTENT_TYPE;
private String type = "_all";
private String id;
private String routing;
private String preference;
private BytesReference source;
private boolean sourceUnsafe;
private String[] fields;
private FetchSourceContext fetchSourceContext;
private String[] filteringAlias = Strings.EMPTY_ARRAY;
long nowInMillis;
ExplainRequest() {
}
public ExplainRequest(String index, String type, String id) {
this.index = index;
this.type = type;
this.id = id;
}
public String type() {
return type;
}
public ExplainRequest type(String type) {
this.type = type;
return this;
}
public String id() {
return id;
}
public ExplainRequest id(String id) {
this.id = id;
return this;
}
public String routing() {
return routing;
}
public ExplainRequest routing(String routing) {
this.routing = routing;
return this;
}
/**
* Simple sets the routing. Since the parent is only used to get to the right shard.
*/
public ExplainRequest parent(String parent) {
this.routing = parent;
return this;
}
public String preference() {
return preference;
}
public ExplainRequest preference(String preference) {
this.preference = preference;
return this;
}
public BytesReference source() {
return source;
}
public boolean sourceUnsafe() {
return sourceUnsafe;
}
public ExplainRequest source(QuerySourceBuilder sourceBuilder) {
this.source = sourceBuilder.buildAsBytes(contentType);
this.sourceUnsafe = false;
return this;
}
public ExplainRequest source(BytesReference source, boolean unsafe) {
this.source = source;
this.sourceUnsafe = unsafe;
return this;
}
/**
* Allows setting the {@link FetchSourceContext} for this request, controlling if and how _source should be returned.
*/
public ExplainRequest fetchSourceContext(FetchSourceContext context) {
this.fetchSourceContext = context;
return this;
}
public FetchSourceContext fetchSourceContext() {
return fetchSourceContext;
}
public String[] fields() {
return fields;
}
public ExplainRequest fields(String[] fields) {
this.fields = fields;
return this;
}
public String[] filteringAlias() {
return filteringAlias;
}
public ExplainRequest filteringAlias(String[] filteringAlias) {
if (filteringAlias != null) {
this.filteringAlias = filteringAlias;
}
return this;
}
@Override
protected void beforeLocalFork() {
if (sourceUnsafe) {
source = source.copyBytesArray();
sourceUnsafe = false;
}
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = super.validate();
if (type == null) {
validationException = ValidateActions.addValidationError("type is missing", validationException);
}
if (id == null) {
validationException = ValidateActions.addValidationError("id is missing", validationException);
}
if (source == null) {
validationException = ValidateActions.addValidationError("source is missing", validationException);
}
return validationException;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
type = in.readString();
id = in.readString();
routing = in.readOptionalString();
preference = in.readOptionalString();
source = in.readBytesReference();
sourceUnsafe = false;
filteringAlias = in.readStringArray();
if (in.readBoolean()) {
fields = in.readStringArray();
}
fetchSourceContext = FetchSourceContext.optionalReadFromStream(in);
nowInMillis = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(type);
out.writeString(id);
out.writeOptionalString(routing);
out.writeOptionalString(preference);
out.writeBytesReference(source);
out.writeStringArray(filteringAlias);
if (fields != null) {
out.writeBoolean(true);
out.writeStringArray(fields);
} else {
out.writeBoolean(false);
}
FetchSourceContext.optionalWriteToStream(fetchSourceContext, out);
out.writeVLong(nowInMillis);
}
} | 0true
| src_main_java_org_elasticsearch_action_explain_ExplainRequest.java |
3,109 | public class IndexEngineModule extends AbstractModule implements SpawnModules {
public static final class EngineSettings {
public static final String ENGINE_TYPE = "index.engine.type";
public static final String INDEX_ENGINE_TYPE = "index.index_engine.type";
public static final Class<? extends Module> DEFAULT_INDEX_ENGINE = InternalIndexEngineModule.class;
public static final Class<? extends Module> DEFAULT_ENGINE = InternalEngineModule.class;
}
private final Settings settings;
public IndexEngineModule(Settings settings) {
this.settings = settings;
}
@Override
public Iterable<? extends Module> spawnModules() {
return ImmutableList.of(createModule(settings.getAsClass(EngineSettings.INDEX_ENGINE_TYPE, EngineSettings.DEFAULT_INDEX_ENGINE, "org.elasticsearch.index.engine.", "IndexEngineModule"), settings));
}
@Override
protected void configure() {
}
} | 0true
| src_main_java_org_elasticsearch_index_engine_IndexEngineModule.java |
1,281 | public class ClusterHealthTests extends ElasticsearchIntegrationTest {
@Test
public void testHealth() {
logger.info("--> running cluster health on an index that does not exists");
ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth("test1").setWaitForYellowStatus().setTimeout("1s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(true));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.RED));
assertThat(healthResponse.getIndices().isEmpty(), equalTo(true));
logger.info("--> running cluster wide health");
healthResponse = client().admin().cluster().prepareHealth().setWaitForYellowStatus().setTimeout("10s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(healthResponse.getIndices().isEmpty(), equalTo(true));
logger.info("--> Creating index test1 with zero replicas");
client().admin().indices().prepareCreate("test1")
.setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_replicas", 0))
.execute().actionGet();
logger.info("--> running cluster health on an index that does exists");
healthResponse = client().admin().cluster().prepareHealth("test1").setWaitForYellowStatus().setTimeout("10s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(healthResponse.getIndices().get("test1").getStatus(), equalTo(ClusterHealthStatus.GREEN));
logger.info("--> running cluster health on an index that does exists and an index that doesn't exists");
healthResponse = client().admin().cluster().prepareHealth("test1", "test2").setWaitForYellowStatus().setTimeout("1s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(true));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.RED));
assertThat(healthResponse.getIndices().get("test1").getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(healthResponse.getIndices().size(), equalTo(1));
}
} | 0true
| src_test_java_org_elasticsearch_cluster_ClusterHealthTests.java |
1,037 | public static class Name {
public static final String Description = "OrderItemImpl_Description";
public static final String Pricing = "OrderItemImpl_Pricing";
public static final String Catalog = "OrderItemImpl_Catalog";
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_OrderItemImpl.java |
761 | @Test
public class OSBTreeBonsaiLeafBucketTest {
public void testInitialization() throws Exception {
ODirectMemoryPointer pointer = new ODirectMemoryPointer(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
OSBTreeBonsaiBucket<Long, OIdentifiable> treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, true,
OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE, ODurablePage.TrackMode.FULL);
Assert.assertEquals(treeBucket.size(), 0);
Assert.assertTrue(treeBucket.isLeaf());
treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE,
ODurablePage.TrackMode.FULL);
Assert.assertEquals(treeBucket.size(), 0);
Assert.assertTrue(treeBucket.isLeaf());
Assert.assertFalse(treeBucket.getLeftSibling().isValid());
Assert.assertFalse(treeBucket.getRightSibling().isValid());
pointer.free();
}
public void testSearch() throws Exception {
long seed = System.currentTimeMillis();
System.out.println("testSearch seed : " + seed);
TreeSet<Long> keys = new TreeSet<Long>();
Random random = new Random(seed);
while (keys.size() < 2 * OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES / OLongSerializer.LONG_SIZE) {
keys.add(random.nextLong());
}
ODirectMemoryPointer pointer = new ODirectMemoryPointer(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
OSBTreeBonsaiBucket<Long, OIdentifiable> treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, true,
OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE, ODurablePage.TrackMode.FULL);
int index = 0;
Map<Long, Integer> keyIndexMap = new HashMap<Long, Integer>();
for (Long key : keys) {
if (!treeBucket.addEntry(index, new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(OBonsaiBucketPointer.NULL,
OBonsaiBucketPointer.NULL, key, new ORecordId(index, OClusterPositionFactory.INSTANCE.valueOf(index))), true))
break;
keyIndexMap.put(key, index);
index++;
}
Assert.assertEquals(treeBucket.size(), keyIndexMap.size());
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
int bucketIndex = treeBucket.find(keyIndexEntry.getKey());
Assert.assertEquals(bucketIndex, (int) keyIndexEntry.getValue());
}
pointer.free();
}
public void testUpdateValue() throws Exception {
long seed = System.currentTimeMillis();
System.out.println("testUpdateValue seed : " + seed);
TreeSet<Long> keys = new TreeSet<Long>();
Random random = new Random(seed);
while (keys.size() < 2 * OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES / OLongSerializer.LONG_SIZE) {
keys.add(random.nextLong());
}
ODirectMemoryPointer pointer = new ODirectMemoryPointer(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
OSBTreeBonsaiBucket<Long, OIdentifiable> treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, true,
OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE, ODurablePage.TrackMode.FULL);
Map<Long, Integer> keyIndexMap = new HashMap<Long, Integer>();
int index = 0;
for (Long key : keys) {
if (!treeBucket.addEntry(index, new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(OBonsaiBucketPointer.NULL,
OBonsaiBucketPointer.NULL, key, new ORecordId(index, OClusterPositionFactory.INSTANCE.valueOf(index))), true))
break;
keyIndexMap.put(key, index);
index++;
}
Assert.assertEquals(keyIndexMap.size(), treeBucket.size());
for (int i = 0; i < treeBucket.size(); i++)
treeBucket.updateValue(i, new ORecordId(i + 5, OClusterPositionFactory.INSTANCE.valueOf(i + 5)));
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable> entry = treeBucket.getEntry(keyIndexEntry.getValue());
Assert.assertEquals(entry, new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(OBonsaiBucketPointer.NULL,
OBonsaiBucketPointer.NULL, keyIndexEntry.getKey(), new ORecordId(keyIndexEntry.getValue() + 5,
OClusterPositionFactory.INSTANCE.valueOf(keyIndexEntry.getValue() + 5))));
Assert.assertEquals(keyIndexEntry.getKey(), treeBucket.getKey(keyIndexEntry.getValue()));
}
pointer.free();
}
public void testShrink() throws Exception {
long seed = System.currentTimeMillis();
System.out.println("testShrink seed : " + seed);
TreeSet<Long> keys = new TreeSet<Long>();
Random random = new Random(seed);
while (keys.size() < 2 * OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES / OLongSerializer.LONG_SIZE) {
keys.add(random.nextLong());
}
ODirectMemoryPointer pointer = new ODirectMemoryPointer(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
OSBTreeBonsaiBucket<Long, OIdentifiable> treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, true,
OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE, ODurablePage.TrackMode.FULL);
int index = 0;
for (Long key : keys) {
if (!treeBucket.addEntry(index, new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(OBonsaiBucketPointer.NULL,
OBonsaiBucketPointer.NULL, key, new ORecordId(index, OClusterPositionFactory.INSTANCE.valueOf(index))), true))
break;
index++;
}
int originalSize = treeBucket.size();
treeBucket.shrink(treeBucket.size() / 2);
Assert.assertEquals(treeBucket.size(), index / 2);
index = 0;
final Map<Long, Integer> keyIndexMap = new HashMap<Long, Integer>();
Iterator<Long> keysIterator = keys.iterator();
while (keysIterator.hasNext() && index < treeBucket.size()) {
Long key = keysIterator.next();
keyIndexMap.put(key, index);
index++;
}
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
int bucketIndex = treeBucket.find(keyIndexEntry.getKey());
Assert.assertEquals(bucketIndex, (int) keyIndexEntry.getValue());
}
int keysToAdd = originalSize - treeBucket.size();
int addedKeys = 0;
while (keysIterator.hasNext() && index < originalSize) {
Long key = keysIterator.next();
if (!treeBucket.addEntry(index, new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(OBonsaiBucketPointer.NULL,
OBonsaiBucketPointer.NULL, key, new ORecordId(index, OClusterPositionFactory.INSTANCE.valueOf(index))), true))
break;
keyIndexMap.put(key, index);
index++;
addedKeys++;
}
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable> entry = treeBucket.getEntry(keyIndexEntry.getValue());
Assert.assertEquals(entry, new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(OBonsaiBucketPointer.NULL,
OBonsaiBucketPointer.NULL, keyIndexEntry.getKey(), new ORecordId(keyIndexEntry.getValue(),
OClusterPositionFactory.INSTANCE.valueOf(keyIndexEntry.getValue()))));
}
Assert.assertEquals(treeBucket.size(), originalSize);
Assert.assertEquals(addedKeys, keysToAdd);
pointer.free();
}
public void testRemove() throws Exception {
long seed = System.currentTimeMillis();
System.out.println("testRemove seed : " + seed);
TreeSet<Long> keys = new TreeSet<Long>();
Random random = new Random(seed);
while (keys.size() < 2 * OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES / OLongSerializer.LONG_SIZE) {
keys.add(random.nextLong());
}
ODirectMemoryPointer pointer = new ODirectMemoryPointer(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
OSBTreeBonsaiBucket<Long, OIdentifiable> treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, true,
OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE, ODurablePage.TrackMode.FULL);
int index = 0;
for (Long key : keys) {
if (!treeBucket.addEntry(index, new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(OBonsaiBucketPointer.NULL,
OBonsaiBucketPointer.NULL, key, new ORecordId(index, OClusterPositionFactory.INSTANCE.valueOf(index))), true))
break;
index++;
}
int originalSize = treeBucket.size();
int itemsToDelete = originalSize / 2;
for (int i = 0; i < itemsToDelete; i++) {
treeBucket.remove(treeBucket.size() - 1);
}
Assert.assertEquals(treeBucket.size(), originalSize - itemsToDelete);
final Map<Long, Integer> keyIndexMap = new HashMap<Long, Integer>();
Iterator<Long> keysIterator = keys.iterator();
index = 0;
while (keysIterator.hasNext() && index < treeBucket.size()) {
Long key = keysIterator.next();
keyIndexMap.put(key, index);
index++;
}
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
int bucketIndex = treeBucket.find(keyIndexEntry.getKey());
Assert.assertEquals(bucketIndex, (int) keyIndexEntry.getValue());
}
int keysToAdd = originalSize - treeBucket.size();
int addedKeys = 0;
while (keysIterator.hasNext() && index < originalSize) {
Long key = keysIterator.next();
if (!treeBucket.addEntry(index, new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(OBonsaiBucketPointer.NULL,
OBonsaiBucketPointer.NULL, key, new ORecordId(index, OClusterPositionFactory.INSTANCE.valueOf(index))), true))
break;
keyIndexMap.put(key, index);
index++;
addedKeys++;
}
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable> entry = treeBucket.getEntry(keyIndexEntry.getValue());
Assert.assertEquals(entry, new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(OBonsaiBucketPointer.NULL,
OBonsaiBucketPointer.NULL, keyIndexEntry.getKey(), new ORecordId(keyIndexEntry.getValue(),
OClusterPositionFactory.INSTANCE.valueOf(keyIndexEntry.getValue()))));
}
Assert.assertEquals(treeBucket.size(), originalSize);
Assert.assertEquals(addedKeys, keysToAdd);
pointer.free();
}
public void testSetLeftSibling() throws Exception {
ODirectMemoryPointer pointer = new ODirectMemoryPointer(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
OSBTreeBonsaiBucket<Long, OIdentifiable> treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, true,
OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE, ODurablePage.TrackMode.FULL);
final OBonsaiBucketPointer p = new OBonsaiBucketPointer(123, 8192 * 2);
treeBucket.setLeftSibling(p);
Assert.assertEquals(treeBucket.getLeftSibling(), p);
pointer.free();
}
public void testSetRightSibling() throws Exception {
ODirectMemoryPointer pointer = new ODirectMemoryPointer(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
OSBTreeBonsaiBucket<Long, OIdentifiable> treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, true,
OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE, ODurablePage.TrackMode.FULL);
final OBonsaiBucketPointer p = new OBonsaiBucketPointer(123, 8192 * 2);
treeBucket.setRightSibling(p);
Assert.assertEquals(treeBucket.getRightSibling(), p);
pointer.free();
}
} | 0true
| core_src_test_java_com_orientechnologies_orient_core_index_sbtreebonsai_local_OSBTreeBonsaiLeafBucketTest.java |
1,382 | @XmlRootElement(name = "address")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class AddressWrapper extends BaseWrapper implements APIWrapper<Address>, APIUnwrapper<Address> {
@XmlElement
protected Long id;
@XmlElement
protected String firstName;
@XmlElement
protected String lastName;
@XmlElement
protected String addressLine1;
@XmlElement
protected String addressLine2;
@XmlElement
protected String addressLine3;
@XmlElement
protected String city;
@XmlElement
protected StateWrapper state;
@XmlElement
protected CountryWrapper country;
@XmlElement
protected String postalCode;
@XmlElement
protected PhoneWrapper phonePrimary;
@XmlElement
protected PhoneWrapper phoneSecondary;
@XmlElement
protected PhoneWrapper phoneFax;
@XmlElement
protected String companyName;
@XmlElement
protected Boolean isBusiness;
@XmlElement
protected Boolean isDefault;
@Override
public void wrapDetails(Address model, HttpServletRequest request) {
this.id = model.getId();
this.firstName = model.getFirstName();
this.lastName = model.getLastName();
this.addressLine1 = model.getAddressLine1();
this.addressLine2 = model.getAddressLine2();
this.addressLine3 = model.getAddressLine3();
this.city = model.getCity();
this.postalCode = model.getPostalCode();
this.companyName = model.getCompanyName();
this.isBusiness = model.isBusiness();
this.isDefault = model.isDefault();
if (model.getState() != null) {
StateWrapper stateWrapper = (StateWrapper) context.getBean(StateWrapper.class.getName());
stateWrapper.wrapDetails(model.getState(), request);
this.state = stateWrapper;
}
if (model.getCountry() != null) {
CountryWrapper countryWrapper = (CountryWrapper) context.getBean(CountryWrapper.class.getName());
countryWrapper.wrapDetails(model.getCountry(), request);
this.country = countryWrapper;
}
if (model.getPhonePrimary() != null) {
PhoneWrapper primaryWrapper = (PhoneWrapper) context.getBean(PhoneWrapper.class.getName());
primaryWrapper.wrapDetails(model.getPhonePrimary(), request);
this.phonePrimary = primaryWrapper;
}
if (model.getPhoneSecondary() != null) {
PhoneWrapper secondaryWrapper = (PhoneWrapper) context.getBean(PhoneWrapper.class.getName());
secondaryWrapper.wrapDetails(model.getPhoneSecondary(), request);
this.phoneSecondary = secondaryWrapper;
}
if (model.getPhoneFax() != null) {
PhoneWrapper faxWrapper = (PhoneWrapper) context.getBean(PhoneWrapper.class.getName());
faxWrapper.wrapDetails(model.getPhoneFax(), request);
this.phoneFax = faxWrapper;
}
}
@Override
public void wrapSummary(Address model, HttpServletRequest request) {
wrapDetails(model, request);
}
@Override
public Address unwrap(HttpServletRequest request, ApplicationContext appContext) {
AddressService addressService = (AddressService) appContext.getBean("blAddressService");
Address address = addressService.create();
address.setId(this.id);
address.setFirstName(this.firstName);
address.setLastName(this.lastName);
address.setAddressLine1(this.addressLine1);
address.setAddressLine2(this.addressLine2);
address.setAddressLine3(this.addressLine3);
address.setCity(this.city);
address.setPostalCode(this.postalCode);
address.setCompanyName(this.companyName);
if (this.isBusiness != null) {
address.setBusiness(this.isBusiness);
}
if (this.isDefault != null) {
address.setDefault(this.isDefault);
}
if (this.state != null) {
address.setState(this.state.unwrap(request, appContext));
}
if (this.country != null) {
address.setCountry(this.country.unwrap(request, appContext));
}
if (this.phonePrimary != null) {
address.setPhonePrimary(this.phonePrimary.unwrap(request, appContext));
}
if (this.phoneSecondary != null) {
address.setPhoneSecondary(this.phoneSecondary.unwrap(request, appContext));
}
if (this.phoneFax != null) {
address.setPhoneFax(this.phoneFax.unwrap(request, appContext));
}
return address;
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_AddressWrapper.java |
1,626 | public class SettingsValidatorTests extends ElasticsearchTestCase {
@Test
public void testValidators() throws Exception {
assertThat(Validator.EMPTY.validate("", "anything goes"), nullValue());
assertThat(Validator.TIME.validate("", "10m"), nullValue());
assertThat(Validator.TIME.validate("", "10g"), notNullValue());
assertThat(Validator.TIME.validate("", "bad timing"), notNullValue());
assertThat(Validator.BYTES_SIZE.validate("", "10m"), nullValue());
assertThat(Validator.BYTES_SIZE.validate("", "10g"), nullValue());
assertThat(Validator.BYTES_SIZE.validate("", "bad"), notNullValue());
assertThat(Validator.FLOAT.validate("", "10.2"), nullValue());
assertThat(Validator.FLOAT.validate("", "10.2.3"), notNullValue());
assertThat(Validator.NON_NEGATIVE_FLOAT.validate("", "10.2"), nullValue());
assertThat(Validator.NON_NEGATIVE_FLOAT.validate("", "0.0"), nullValue());
assertThat(Validator.NON_NEGATIVE_FLOAT.validate("", "-1.0"), notNullValue());
assertThat(Validator.NON_NEGATIVE_FLOAT.validate("", "10.2.3"), notNullValue());
assertThat(Validator.DOUBLE.validate("", "10.2"), nullValue());
assertThat(Validator.DOUBLE.validate("", "10.2.3"), notNullValue());
assertThat(Validator.DOUBLE_GTE_2.validate("", "10.2"), nullValue());
assertThat(Validator.DOUBLE_GTE_2.validate("", "2.0"), nullValue());
assertThat(Validator.DOUBLE_GTE_2.validate("", "1.0"), notNullValue());
assertThat(Validator.DOUBLE_GTE_2.validate("", "10.2.3"), notNullValue());
assertThat(Validator.NON_NEGATIVE_DOUBLE.validate("", "10.2"), nullValue());
assertThat(Validator.NON_NEGATIVE_DOUBLE.validate("", "0.0"), nullValue());
assertThat(Validator.NON_NEGATIVE_DOUBLE.validate("", "-1.0"), notNullValue());
assertThat(Validator.NON_NEGATIVE_DOUBLE.validate("", "10.2.3"), notNullValue());
assertThat(Validator.INTEGER.validate("", "10"), nullValue());
assertThat(Validator.INTEGER.validate("", "10.2"), notNullValue());
assertThat(Validator.INTEGER_GTE_2.validate("", "2"), nullValue());
assertThat(Validator.INTEGER_GTE_2.validate("", "1"), notNullValue());
assertThat(Validator.INTEGER_GTE_2.validate("", "0"), notNullValue());
assertThat(Validator.INTEGER_GTE_2.validate("", "10.2.3"), notNullValue());
assertThat(Validator.NON_NEGATIVE_INTEGER.validate("", "2"), nullValue());
assertThat(Validator.NON_NEGATIVE_INTEGER.validate("", "1"), nullValue());
assertThat(Validator.NON_NEGATIVE_INTEGER.validate("", "0"), nullValue());
assertThat(Validator.NON_NEGATIVE_INTEGER.validate("", "-1"), notNullValue());
assertThat(Validator.NON_NEGATIVE_INTEGER.validate("", "10.2"), notNullValue());
assertThat(Validator.POSITIVE_INTEGER.validate("", "2"), nullValue());
assertThat(Validator.POSITIVE_INTEGER.validate("", "1"), nullValue());
assertThat(Validator.POSITIVE_INTEGER.validate("", "0"), notNullValue());
assertThat(Validator.POSITIVE_INTEGER.validate("", "-1"), notNullValue());
assertThat(Validator.POSITIVE_INTEGER.validate("", "10.2"), notNullValue());
}
} | 0true
| src_test_java_org_elasticsearch_cluster_settings_SettingsValidatorTests.java |
123 | @Service("blPageDefaultRuleProcessor")
public class PageDefaultRuleProcessor extends AbstractPageRuleProcessor {
private static final Log LOG = LogFactory.getLog(PageDefaultRuleProcessor.class);
/**
* Returns true if all of the rules associated with the passed in <code>Page</code>
* item match based on the passed in vars.
*
* Also returns true if no rules are present for the passed in item.
*
* @param sc - a structured content item to test
* @param vars - a map of objects used by the rule MVEL expressions
* @return the result of the rule checks
*/
public boolean checkForMatch(PageDTO page, Map<String, Object> vars) {
String ruleExpression = page.getRuleExpression();
if (ruleExpression != null) {
if (LOG.isTraceEnabled()) {
LOG.trace("Processing content rule for page with id " + page.getId() +". Value = " + ruleExpression);
}
boolean result = executeExpression(ruleExpression, vars);
if (! result) {
if (LOG.isDebugEnabled()) {
LOG.debug("Page failed to pass rule and will not be included for Page with id " + page.getId() +". Value = " + ruleExpression);
}
}
return result;
} else {
// If no rule found, then consider this a match.
return true;
}
}
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_service_PageDefaultRuleProcessor.java |
2,682 | public class GatewayModule extends AbstractModule implements SpawnModules {
private final Settings settings;
public GatewayModule(Settings settings) {
this.settings = settings;
}
@Override
public Iterable<? extends Module> spawnModules() {
return ImmutableList.of(Modules.createModule(settings.getAsClass("gateway.type", LocalGatewayModule.class, "org.elasticsearch.gateway.", "GatewayModule"), settings));
}
@Override
protected void configure() {
bind(GatewayService.class).asEagerSingleton();
}
} | 0true
| src_main_java_org_elasticsearch_gateway_GatewayModule.java |
904 | class ShardSuggestResponse extends BroadcastShardOperationResponse {
private final Suggest suggest;
ShardSuggestResponse() {
this.suggest = new Suggest();
}
public ShardSuggestResponse(String index, int shardId, Suggest suggest) {
super(index, shardId);
this.suggest = suggest;
}
public Suggest getSuggest() {
return this.suggest;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
suggest.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
suggest.writeTo(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_suggest_ShardSuggestResponse.java |
1,612 | this.ackTimeoutCallback = threadPool.schedule(ackedUpdateTask.ackTimeout(), ThreadPool.Names.GENERIC, new Runnable() {
@Override
public void run() {
onTimeout();
}
}); | 0true
| src_main_java_org_elasticsearch_cluster_service_InternalClusterService.java |
1,160 | @Beta
public interface ICompletableFuture<V> extends Future<V> {
void andThen(ExecutionCallback<V> callback);
void andThen(ExecutionCallback<V> callback, Executor executor);
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_ICompletableFuture.java |
1,084 | public class UpdateResponse extends ActionResponse {
private String index;
private String id;
private String type;
private long version;
private boolean created;
private GetResult getResult;
public UpdateResponse() {
}
public UpdateResponse(String index, String type, String id, long version, boolean created) {
this.index = index;
this.id = id;
this.type = type;
this.version = version;
this.created = created;
}
/**
* The index the document was indexed into.
*/
public String getIndex() {
return this.index;
}
/**
* The type of the document indexed.
*/
public String getType() {
return this.type;
}
/**
* The id of the document indexed.
*/
public String getId() {
return this.id;
}
/**
* Returns the current version of the doc indexed.
*/
public long getVersion() {
return this.version;
}
public void setGetResult(GetResult getResult) {
this.getResult = getResult;
}
public GetResult getGetResult() {
return this.getResult;
}
/**
* Returns true if document was created due to an UPSERT operation
*/
public boolean isCreated() {
return this.created;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
index = in.readSharedString();
type = in.readSharedString();
id = in.readString();
version = in.readLong();
created = in.readBoolean();
if (in.readBoolean()) {
getResult = GetResult.readGetResult(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeSharedString(index);
out.writeSharedString(type);
out.writeString(id);
out.writeLong(version);
out.writeBoolean(created);
if (getResult == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
getResult.writeTo(out);
}
}
} | 0true
| src_main_java_org_elasticsearch_action_update_UpdateResponse.java |
6,403 | public class TransportService extends AbstractLifecycleComponent<TransportService> {
private final Transport transport;
private final ThreadPool threadPool;
volatile ImmutableMap<String, TransportRequestHandler> serverHandlers = ImmutableMap.of();
final Object serverHandlersMutex = new Object();
final ConcurrentMapLong<RequestHolder> clientHandlers = ConcurrentCollections.newConcurrentMapLongWithAggressiveConcurrency();
final AtomicLong requestIds = new AtomicLong();
final CopyOnWriteArrayList<TransportConnectionListener> connectionListeners = new CopyOnWriteArrayList<TransportConnectionListener>();
// An LRU (don't really care about concurrency here) that holds the latest timed out requests so if they
// do show up, we can print more descriptive information about them
final Map<Long, TimeoutInfoHolder> timeoutInfoHandlers = Collections.synchronizedMap(new LinkedHashMap<Long, TimeoutInfoHolder>(100, .75F, true) {
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > 100;
}
});
private boolean throwConnectException = false;
private final TransportService.Adapter adapter = new Adapter();
public TransportService(Transport transport, ThreadPool threadPool) {
this(EMPTY_SETTINGS, transport, threadPool);
}
@Inject
public TransportService(Settings settings, Transport transport, ThreadPool threadPool) {
super(settings);
this.transport = transport;
this.threadPool = threadPool;
}
@Override
protected void doStart() throws ElasticsearchException {
adapter.rxMetric.clear();
adapter.txMetric.clear();
transport.transportServiceAdapter(adapter);
transport.start();
if (transport.boundAddress() != null && logger.isInfoEnabled()) {
logger.info("{}", transport.boundAddress());
}
}
@Override
protected void doStop() throws ElasticsearchException {
transport.stop();
}
@Override
protected void doClose() throws ElasticsearchException {
transport.close();
}
public boolean addressSupported(Class<? extends TransportAddress> address) {
return transport.addressSupported(address);
}
public TransportInfo info() {
return new TransportInfo(boundAddress());
}
public TransportStats stats() {
return new TransportStats(transport.serverOpen(), adapter.rxMetric.count(), adapter.rxMetric.sum(), adapter.txMetric.count(), adapter.txMetric.sum());
}
public BoundTransportAddress boundAddress() {
return transport.boundAddress();
}
public boolean nodeConnected(DiscoveryNode node) {
return transport.nodeConnected(node);
}
public void connectToNode(DiscoveryNode node) throws ConnectTransportException {
transport.connectToNode(node);
}
public void connectToNodeLight(DiscoveryNode node) throws ConnectTransportException {
transport.connectToNodeLight(node);
}
public void disconnectFromNode(DiscoveryNode node) {
transport.disconnectFromNode(node);
}
public void addConnectionListener(TransportConnectionListener listener) {
connectionListeners.add(listener);
}
public void removeConnectionListener(TransportConnectionListener listener) {
connectionListeners.remove(listener);
}
/**
* Set to <tt>true</tt> to indicate that a {@link ConnectTransportException} should be thrown when
* sending a message (otherwise, it will be passed to the response handler). Defaults to <tt>false</tt>.
* <p/>
* <p>This is useful when logic based on connect failure is needed without having to wrap the handler,
* for example, in case of retries across several nodes.
*/
public void throwConnectException(boolean throwConnectException) {
this.throwConnectException = throwConnectException;
}
public <T extends TransportResponse> TransportFuture<T> submitRequest(DiscoveryNode node, String action, TransportRequest request,
TransportResponseHandler<T> handler) throws TransportException {
return submitRequest(node, action, request, TransportRequestOptions.EMPTY, handler);
}
public <T extends TransportResponse> TransportFuture<T> submitRequest(DiscoveryNode node, String action, TransportRequest request,
TransportRequestOptions options, TransportResponseHandler<T> handler) throws TransportException {
PlainTransportFuture<T> futureHandler = new PlainTransportFuture<T>(handler);
sendRequest(node, action, request, options, futureHandler);
return futureHandler;
}
public <T extends TransportResponse> void sendRequest(final DiscoveryNode node, final String action, final TransportRequest request,
final TransportResponseHandler<T> handler) throws TransportException {
sendRequest(node, action, request, TransportRequestOptions.EMPTY, handler);
}
public <T extends TransportResponse> void sendRequest(final DiscoveryNode node, final String action, final TransportRequest request,
final TransportRequestOptions options, TransportResponseHandler<T> handler) throws TransportException {
if (node == null) {
throw new ElasticsearchIllegalStateException("can't send request to a null node");
}
final long requestId = newRequestId();
TimeoutHandler timeoutHandler = null;
try {
if (options.timeout() != null) {
timeoutHandler = new TimeoutHandler(requestId);
timeoutHandler.future = threadPool.schedule(options.timeout(), ThreadPool.Names.GENERIC, timeoutHandler);
}
clientHandlers.put(requestId, new RequestHolder<T>(handler, node, action, timeoutHandler));
transport.sendRequest(node, requestId, action, request, options);
} catch (final Throwable e) {
// usually happen either because we failed to connect to the node
// or because we failed serializing the message
final RequestHolder holderToNotify = clientHandlers.remove(requestId);
if (timeoutHandler != null) {
timeoutHandler.future.cancel(false);
}
// If holderToNotify == null then handler has already been taken care of.
if (holderToNotify != null) {
// callback that an exception happened, but on a different thread since we don't
// want handlers to worry about stack overflows
final SendRequestTransportException sendRequestException = new SendRequestTransportException(node, action, e);
threadPool.executor(ThreadPool.Names.GENERIC).execute(new Runnable() {
@Override
public void run() {
holderToNotify.handler().handleException(sendRequestException);
}
});
}
if (throwConnectException) {
if (e instanceof ConnectTransportException) {
throw (ConnectTransportException) e;
}
}
}
}
private long newRequestId() {
return requestIds.getAndIncrement();
}
public TransportAddress[] addressesFromString(String address) throws Exception {
return transport.addressesFromString(address);
}
public void registerHandler(String action, TransportRequestHandler handler) {
synchronized (serverHandlersMutex) {
TransportRequestHandler handlerReplaced = serverHandlers.get(action);
serverHandlers = MapBuilder.newMapBuilder(serverHandlers).put(action, handler).immutableMap();
if (handlerReplaced != null) {
logger.warn("Registered two transport handlers for action {}, handlers: {}, {}", action, handler, handlerReplaced);
}
}
}
public void removeHandler(String action) {
synchronized (serverHandlersMutex) {
serverHandlers = MapBuilder.newMapBuilder(serverHandlers).remove(action).immutableMap();
}
}
class Adapter implements TransportServiceAdapter {
final MeanMetric rxMetric = new MeanMetric();
final MeanMetric txMetric = new MeanMetric();
@Override
public void received(long size) {
rxMetric.inc(size);
}
@Override
public void sent(long size) {
txMetric.inc(size);
}
@Override
public TransportRequestHandler handler(String action) {
return serverHandlers.get(action);
}
@Override
public TransportResponseHandler remove(long requestId) {
RequestHolder holder = clientHandlers.remove(requestId);
if (holder == null) {
// lets see if its in the timeout holder
TimeoutInfoHolder timeoutInfoHolder = timeoutInfoHandlers.remove(requestId);
if (timeoutInfoHolder != null) {
long time = System.currentTimeMillis();
logger.warn("Received response for a request that has timed out, sent [{}ms] ago, timed out [{}ms] ago, action [{}], node [{}], id [{}]", time - timeoutInfoHolder.sentTime(), time - timeoutInfoHolder.timeoutTime(), timeoutInfoHolder.action(), timeoutInfoHolder.node(), requestId);
} else {
logger.warn("Transport response handler not found of id [{}]", requestId);
}
return null;
}
holder.cancel();
return holder.handler();
}
@Override
public void raiseNodeConnected(final DiscoveryNode node) {
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
for (TransportConnectionListener connectionListener : connectionListeners) {
connectionListener.onNodeConnected(node);
}
}
});
}
@Override
public void raiseNodeDisconnected(final DiscoveryNode node) {
if (lifecycle.stoppedOrClosed()) {
return;
}
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
try {
for (TransportConnectionListener connectionListener : connectionListeners) {
connectionListener.onNodeDisconnected(node);
}
// node got disconnected, raise disconnection on possible ongoing handlers
for (Map.Entry<Long, RequestHolder> entry : clientHandlers.entrySet()) {
RequestHolder holder = entry.getValue();
if (holder.node().equals(node)) {
final RequestHolder holderToNotify = clientHandlers.remove(entry.getKey());
if (holderToNotify != null) {
// callback that an exception happened, but on a different thread since we don't
// want handlers to worry about stack overflows
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
holderToNotify.handler().handleException(new NodeDisconnectedException(node, holderToNotify.action()));
}
});
}
}
}
} catch (EsRejectedExecutionException ex) {
logger.debug("Rejected execution on NodeDisconnected", ex);
}
}
});
}
}
class TimeoutHandler implements Runnable {
private final long requestId;
private final long sentTime = System.currentTimeMillis();
ScheduledFuture future;
TimeoutHandler(long requestId) {
this.requestId = requestId;
}
public long sentTime() {
return sentTime;
}
@Override
public void run() {
if (future.isCancelled()) {
return;
}
final RequestHolder holder = clientHandlers.remove(requestId);
if (holder != null) {
// add it to the timeout information holder, in case we are going to get a response later
long timeoutTime = System.currentTimeMillis();
timeoutInfoHandlers.put(requestId, new TimeoutInfoHolder(holder.node(), holder.action(), sentTime, timeoutTime));
holder.handler().handleException(new ReceiveTimeoutTransportException(holder.node(), holder.action(), "request_id [" + requestId + "] timed out after [" + (timeoutTime - sentTime) + "ms]"));
}
}
}
static class TimeoutInfoHolder {
private final DiscoveryNode node;
private final String action;
private final long sentTime;
private final long timeoutTime;
TimeoutInfoHolder(DiscoveryNode node, String action, long sentTime, long timeoutTime) {
this.node = node;
this.action = action;
this.sentTime = sentTime;
this.timeoutTime = timeoutTime;
}
public DiscoveryNode node() {
return node;
}
public String action() {
return action;
}
public long sentTime() {
return sentTime;
}
public long timeoutTime() {
return timeoutTime;
}
}
static class RequestHolder<T extends TransportResponse> {
private final TransportResponseHandler<T> handler;
private final DiscoveryNode node;
private final String action;
private final TimeoutHandler timeout;
RequestHolder(TransportResponseHandler<T> handler, DiscoveryNode node, String action, TimeoutHandler timeout) {
this.handler = handler;
this.node = node;
this.action = action;
this.timeout = timeout;
}
public TransportResponseHandler<T> handler() {
return handler;
}
public DiscoveryNode node() {
return this.node;
}
public String action() {
return this.action;
}
public void cancel() {
if (timeout != null) {
timeout.future.cancel(false);
}
}
}
} | 1no label
| src_main_java_org_elasticsearch_transport_TransportService.java |
5 | public class OIterableObject<T> implements Iterable<T>, OResettable, Iterator<T> {
private final T object;
private boolean alreadyRead = false;
public OIterableObject(T o) {
object = o;
}
/**
* Returns an iterator over a set of elements of type T.
*
* @return an Iterator.
*/
public Iterator<T> iterator() {
return this;
}
@Override
public void reset() {
alreadyRead = false;
}
@Override
public boolean hasNext() {
return !alreadyRead;
}
@Override
public T next() {
if (!alreadyRead) {
alreadyRead = true;
return object;
} else
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_collection_OIterableObject.java |
6,089 | public class RestoreService extends AbstractComponent implements ClusterStateListener {
private final ClusterService clusterService;
private final RepositoriesService repositoriesService;
private final TransportService transportService;
private final AllocationService allocationService;
private final MetaDataCreateIndexService createIndexService;
private final CopyOnWriteArrayList<RestoreCompletionListener> listeners = new CopyOnWriteArrayList<RestoreCompletionListener>();
@Inject
public RestoreService(Settings settings, ClusterService clusterService, RepositoriesService repositoriesService, TransportService transportService, AllocationService allocationService, MetaDataCreateIndexService createIndexService) {
super(settings);
this.clusterService = clusterService;
this.repositoriesService = repositoriesService;
this.transportService = transportService;
this.allocationService = allocationService;
this.createIndexService = createIndexService;
transportService.registerHandler(UpdateRestoreStateRequestHandler.ACTION, new UpdateRestoreStateRequestHandler());
clusterService.add(this);
}
/**
* Restores snapshot specified in the restore request.
*
* @param request restore request
* @param listener restore listener
*/
public void restoreSnapshot(final RestoreRequest request, final RestoreSnapshotListener listener) {
try {
// Read snapshot info and metadata from the repository
Repository repository = repositoriesService.repository(request.repository());
final SnapshotId snapshotId = new SnapshotId(request.repository(), request.name());
final Snapshot snapshot = repository.readSnapshot(snapshotId);
ImmutableList<String> filteredIndices = SnapshotUtils.filterIndices(snapshot.indices(), request.indices(), request.indicesOptions());
final MetaData metaData = repository.readSnapshotMetaData(snapshotId, filteredIndices);
// Make sure that we can restore from this snapshot
if (snapshot.state() != SnapshotState.SUCCESS) {
throw new SnapshotRestoreException(snapshotId, "unsupported snapshot state [" + snapshot.state() + "]");
}
if (Version.CURRENT.before(snapshot.version())) {
throw new SnapshotRestoreException(snapshotId, "incompatible snapshot version [" + snapshot.version() + "]");
}
// Find list of indices that we need to restore
final Map<String, String> renamedIndices = newHashMap();
for (String index : filteredIndices) {
String renamedIndex = index;
if (request.renameReplacement() != null && request.renamePattern() != null) {
renamedIndex = index.replaceAll(request.renamePattern(), request.renameReplacement());
}
String previousIndex = renamedIndices.put(renamedIndex, index);
if (previousIndex != null) {
throw new SnapshotRestoreException(snapshotId, "indices [" + index + "] and [" + previousIndex + "] are renamed into the same index [" + renamedIndex + "]");
}
}
// Now we can start the actual restore process by adding shards to be recovered in the cluster state
// and updating cluster metadata (global and index) as needed
clusterService.submitStateUpdateTask(request.cause(), new TimeoutClusterStateUpdateTask() {
RestoreInfo restoreInfo = null;
@Override
public ClusterState execute(ClusterState currentState) {
// Check if another restore process is already running - cannot run two restore processes at the
// same time
RestoreMetaData restoreMetaData = currentState.metaData().custom(RestoreMetaData.TYPE);
if (restoreMetaData != null && !restoreMetaData.entries().isEmpty()) {
throw new ConcurrentSnapshotExecutionException(snapshotId, "Restore process is already running in this cluster");
}
// Updating cluster state
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks());
RoutingTable.Builder rtBuilder = RoutingTable.builder(currentState.routingTable());
if (!metaData.indices().isEmpty()) {
// We have some indices to restore
ImmutableMap.Builder<ShardId, RestoreMetaData.ShardRestoreStatus> shards = ImmutableMap.builder();
for (Map.Entry<String, String> indexEntry : renamedIndices.entrySet()) {
String index = indexEntry.getValue();
// Make sure that index was fully snapshotted - don't restore
if (failed(snapshot, index)) {
throw new SnapshotRestoreException(snapshotId, "index [" + index + "] wasn't fully snapshotted - cannot restore");
}
RestoreSource restoreSource = new RestoreSource(snapshotId, index);
String renamedIndex = indexEntry.getKey();
IndexMetaData snapshotIndexMetaData = metaData.index(index);
// Check that the index is closed or doesn't exist
IndexMetaData currentIndexMetaData = currentState.metaData().index(renamedIndex);
if (currentIndexMetaData == null) {
// Index doesn't exist - create it and start recovery
// Make sure that the index we are about to create has a validate name
createIndexService.validateIndexName(renamedIndex, currentState);
IndexMetaData.Builder indexMdBuilder = IndexMetaData.builder(snapshotIndexMetaData).state(IndexMetaData.State.OPEN).index(renamedIndex);
IndexMetaData updatedIndexMetaData = indexMdBuilder.build();
rtBuilder.addAsNewRestore(updatedIndexMetaData, restoreSource);
mdBuilder.put(updatedIndexMetaData, true);
} else {
// Index exist - checking that it's closed
if (currentIndexMetaData.state() != IndexMetaData.State.CLOSE) {
// TODO: Enable restore for open indices
throw new SnapshotRestoreException(snapshotId, "cannot restore index [" + renamedIndex + "] because it's open");
}
// Make sure that the number of shards is the same. That's the only thing that we cannot change
if (currentIndexMetaData.getNumberOfShards() != snapshotIndexMetaData.getNumberOfShards()) {
throw new SnapshotRestoreException(snapshotId, "cannot restore index [" + renamedIndex + "] with [" + currentIndexMetaData.getNumberOfShards() +
"] shard from snapshot with [" + snapshotIndexMetaData.getNumberOfShards() + "] shards");
}
// Index exists and it's closed - open it in metadata and start recovery
IndexMetaData.Builder indexMdBuilder = IndexMetaData.builder(currentIndexMetaData).state(IndexMetaData.State.OPEN);
IndexMetaData updatedIndexMetaData = indexMdBuilder.index(renamedIndex).build();
rtBuilder.addAsRestore(updatedIndexMetaData, restoreSource);
blocks.removeIndexBlock(index, INDEX_CLOSED_BLOCK);
mdBuilder.put(updatedIndexMetaData, true);
}
for (int shard = 0; shard < snapshotIndexMetaData.getNumberOfShards(); shard++) {
shards.put(new ShardId(renamedIndex, shard), new RestoreMetaData.ShardRestoreStatus(clusterService.state().nodes().localNodeId()));
}
}
RestoreMetaData.Entry restoreEntry = new RestoreMetaData.Entry(snapshotId, RestoreMetaData.State.INIT, ImmutableList.copyOf(renamedIndices.keySet()), shards.build());
mdBuilder.putCustom(RestoreMetaData.TYPE, new RestoreMetaData(restoreEntry));
}
// Restore global state if needed
if (request.includeGlobalState()) {
if (metaData.persistentSettings() != null) {
mdBuilder.persistentSettings(metaData.persistentSettings());
}
if (metaData.templates() != null) {
// TODO: Should all existing templates be deleted first?
for (ObjectCursor<IndexTemplateMetaData> cursor : metaData.templates().values()) {
mdBuilder.put(cursor.value);
}
}
if (metaData.customs() != null) {
for (ObjectObjectCursor<String, MetaData.Custom> cursor : metaData.customs()) {
if (!RepositoriesMetaData.TYPE.equals(cursor.key)) {
// Don't restore repositories while we are working with them
// TODO: Should we restore them at the end?
mdBuilder.putCustom(cursor.key, cursor.value);
}
}
}
}
if (metaData.indices().isEmpty()) {
// We don't have any indices to restore - we are done
restoreInfo = new RestoreInfo(request.name(), ImmutableList.<String>of(), 0, 0);
}
ClusterState updatedState = ClusterState.builder(currentState).metaData(mdBuilder).blocks(blocks).routingTable(rtBuilder).build();
RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder(updatedState).routingTable(rtBuilder).build());
return ClusterState.builder(updatedState).routingResult(routingResult).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.warn("[{}] failed to restore snapshot", t, snapshotId);
listener.onFailure(t);
}
@Override
public TimeValue timeout() {
return request.masterNodeTimeout();
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
listener.onResponse(restoreInfo);
}
});
} catch (Throwable e) {
logger.warn("[{}][{}] failed to restore snapshot", e, request.repository(), request.name());
listener.onFailure(e);
}
}
/**
* This method is used by {@link org.elasticsearch.index.snapshots.IndexShardSnapshotAndRestoreService} to notify
* {@code RestoreService} about shard restore completion.
*
* @param snapshotId snapshot id
* @param shardId shard id
*/
public void indexShardRestoreCompleted(SnapshotId snapshotId, ShardId shardId) {
logger.trace("[{}] successfully restored shard [{}]", snapshotId, shardId);
UpdateIndexShardRestoreStatusRequest request = new UpdateIndexShardRestoreStatusRequest(snapshotId, shardId,
new ShardRestoreStatus(clusterService.state().nodes().localNodeId(), RestoreMetaData.State.SUCCESS));
if (clusterService.state().nodes().localNodeMaster()) {
innerUpdateRestoreState(request);
} else {
transportService.sendRequest(clusterService.state().nodes().masterNode(),
UpdateRestoreStateRequestHandler.ACTION, request, EmptyTransportResponseHandler.INSTANCE_SAME);
}
}
/**
* Updates shard restore record in the cluster state.
*
* @param request update shard status request
*/
private void innerUpdateRestoreState(final UpdateIndexShardRestoreStatusRequest request) {
clusterService.submitStateUpdateTask("update snapshot state", new ProcessedClusterStateUpdateTask() {
private boolean completed = true;
private RestoreInfo restoreInfo = null;
@Override
public ClusterState execute(ClusterState currentState) {
MetaData metaData = currentState.metaData();
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
RestoreMetaData restore = metaData.custom(RestoreMetaData.TYPE);
if (restore != null) {
boolean changed = false;
ArrayList<RestoreMetaData.Entry> entries = newArrayList();
for (RestoreMetaData.Entry entry : restore.entries()) {
if (entry.snapshotId().equals(request.snapshotId())) {
HashMap<ShardId, ShardRestoreStatus> shards = newHashMap(entry.shards());
logger.trace("[{}] Updating shard [{}] with status [{}]", request.snapshotId(), request.shardId(), request.status().state());
shards.put(request.shardId(), request.status());
for (RestoreMetaData.ShardRestoreStatus status : shards.values()) {
if (!status.state().completed()) {
completed = false;
break;
}
}
if (!completed) {
entries.add(new RestoreMetaData.Entry(entry.snapshotId(), RestoreMetaData.State.STARTED, entry.indices(), ImmutableMap.copyOf(shards)));
} else {
logger.info("restore [{}] is done", request.snapshotId());
int failedShards = 0;
for (RestoreMetaData.ShardRestoreStatus status : shards.values()) {
if (status.state() == RestoreMetaData.State.FAILURE) {
failedShards++;
}
}
restoreInfo = new RestoreInfo(entry.snapshotId().getSnapshot(), entry.indices(), shards.size(), shards.size() - failedShards);
}
changed = true;
} else {
entries.add(entry);
}
}
if (changed) {
restore = new RestoreMetaData(entries.toArray(new RestoreMetaData.Entry[entries.size()]));
mdBuilder.putCustom(RestoreMetaData.TYPE, restore);
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
}
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
logger.warn("[{}][{}] failed to update snapshot status to [{}]", t, request.snapshotId(), request.shardId(), request.status());
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
if (restoreInfo != null) {
for (RestoreCompletionListener listener : listeners) {
try {
listener.onRestoreCompletion(request.snapshotId, restoreInfo);
} catch (Throwable e) {
logger.warn("failed to update snapshot status for [{}]", e, listener);
}
}
}
}
});
}
/**
* Checks if any of the deleted indices are still recovering and fails recovery on the shards of these indices
*
* @param event cluster changed event
*/
private void processDeletedIndices(ClusterChangedEvent event) {
MetaData metaData = event.state().metaData();
RestoreMetaData restore = metaData.custom(RestoreMetaData.TYPE);
if (restore == null) {
// Not restoring - nothing to do
return;
}
if (!event.indicesDeleted().isEmpty()) {
// Some indices were deleted, let's make sure all indices that we are restoring still exist
for (RestoreMetaData.Entry entry : restore.entries()) {
List<ShardId> shardsToFail = null;
for (ImmutableMap.Entry<ShardId, ShardRestoreStatus> shard : entry.shards().entrySet()) {
if (!shard.getValue().state().completed()) {
if (!event.state().metaData().hasIndex(shard.getKey().getIndex())) {
if (shardsToFail == null) {
shardsToFail = newArrayList();
}
shardsToFail.add(shard.getKey());
}
}
}
if (shardsToFail != null) {
for (ShardId shardId : shardsToFail) {
logger.trace("[{}] failing running shard restore [{}]", entry.snapshotId(), shardId);
innerUpdateRestoreState(new UpdateIndexShardRestoreStatusRequest(entry.snapshotId(), shardId, new ShardRestoreStatus(null, RestoreMetaData.State.FAILURE, "index was deleted")));
}
}
}
}
}
private boolean failed(Snapshot snapshot, String index) {
for (SnapshotShardFailure failure : snapshot.shardFailures()) {
if (index.equals(failure.index())) {
return true;
}
}
return false;
}
private boolean failed(Snapshot snapshot, String index, int shard) {
for (SnapshotShardFailure failure : snapshot.shardFailures()) {
if (index.equals(failure.index()) && shard == failure.shardId()) {
return true;
}
}
return false;
}
/**
* Adds restore completion listener
* <p/>
* This listener is called for each snapshot that finishes restore operation in the cluster. It's responsibility of
* the listener to decide if it's called for the appropriate snapshot or not.
*
* @param listener restore completion listener
*/
public void addListener(RestoreCompletionListener listener) {
this.listeners.add(listener);
}
/**
* Removes restore completion listener
* <p/>
* This listener is called for each snapshot that finishes restore operation in the cluster.
*
* @param listener restore completion listener
*/
public void removeListener(RestoreCompletionListener listener) {
this.listeners.remove(listener);
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
try {
if (event.localNodeMaster()) {
processDeletedIndices(event);
}
} catch (Throwable t) {
logger.warn("Failed to update restore state ", t);
}
}
/**
* Checks if a repository is currently in use by one of the snapshots
*
* @param clusterState cluster state
* @param repository repository id
* @return true if repository is currently in use by one of the running snapshots
*/
public static boolean isRepositoryInUse(ClusterState clusterState, String repository) {
MetaData metaData = clusterState.metaData();
RestoreMetaData snapshots = metaData.custom(RestoreMetaData.TYPE);
if (snapshots != null) {
for (RestoreMetaData.Entry snapshot : snapshots.entries()) {
if (repository.equals(snapshot.snapshotId().getRepository())) {
return true;
}
}
}
return false;
}
/**
* Restore snapshot request
*/
public static class RestoreRequest {
private String cause;
private String name;
private String repository;
private String[] indices;
private String renamePattern;
private String renameReplacement;
private IndicesOptions indicesOptions = IndicesOptions.strict();
private Settings settings;
private TimeValue masterNodeTimeout;
private boolean includeGlobalState = false;
/**
* Constructs new restore request
*
* @param cause cause for restoring the snapshot
* @param repository repository name
* @param name snapshot name
*/
public RestoreRequest(String cause, String repository, String name) {
this.cause = cause;
this.name = name;
this.repository = repository;
}
/**
* Sets list of indices to restore
*
* @param indices list of indices
* @return this request
*/
public RestoreRequest indices(String[] indices) {
this.indices = indices;
return this;
}
/**
* Sets indices options flags
*
* @param indicesOptions indices options flags
* @return this request
*/
public RestoreRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
/**
* If true global cluster state will be restore as part of the restore operation
*
* @param includeGlobalState restore global state flag
* @return this request
*/
public RestoreRequest includeGlobalState(boolean includeGlobalState) {
this.includeGlobalState = includeGlobalState;
return this;
}
/**
* Sets repository-specific restore settings
*
* @param settings restore settings
* @return this request
*/
public RestoreRequest settings(Settings settings) {
this.settings = settings;
return this;
}
/**
* Sets master node timeout
* <p/>
* This timeout will affect only start of the restore process. Once restore process has started this timeout
* has no affect for the duration of restore.
*
* @param masterNodeTimeout master node timeout
* @return this request
*/
public RestoreRequest masterNodeTimeout(TimeValue masterNodeTimeout) {
this.masterNodeTimeout = masterNodeTimeout;
return this;
}
/**
* Sets index rename pattern
*
* @param renamePattern rename pattern
* @return this request
*/
public RestoreRequest renamePattern(String renamePattern) {
this.renamePattern = renamePattern;
return this;
}
/**
* Sets index rename replacement
*
* @param renameReplacement rename replacement
* @return this request
*/
public RestoreRequest renameReplacement(String renameReplacement) {
this.renameReplacement = renameReplacement;
return this;
}
/**
* Returns restore operation cause
*
* @return restore operation cause
*/
public String cause() {
return cause;
}
/**
* Returns snapshot name
*
* @return snapshot name
*/
public String name() {
return name;
}
/**
* Returns repository name
*
* @return repository name
*/
public String repository() {
return repository;
}
/**
* Return the list of indices to be restored
*
* @return the list of indices
*/
public String[] indices() {
return indices;
}
/**
* Returns indices option flags
*
* @return indices options flags
*/
public IndicesOptions indicesOptions() {
return indicesOptions;
}
/**
* Returns rename pattern
*
* @return rename pattern
*/
public String renamePattern() {
return renamePattern;
}
/**
* Returns replacement pattern
*
* @return replacement pattern
*/
public String renameReplacement() {
return renameReplacement;
}
/**
* Returns repository-specific restore settings
*
* @return restore settings
*/
public Settings settings() {
return settings;
}
/**
* Returns true if global state should be restore during this restore operation
*
* @return restore global state flag
*/
public boolean includeGlobalState() {
return includeGlobalState;
}
/**
* Return master node timeout
*
* @return master node timeout
*/
public TimeValue masterNodeTimeout() {
return masterNodeTimeout;
}
}
/**
* This listener is called as soon as restore operation starts in the cluster.
* <p/>
* To receive notifications about when operation ends in the cluster use {@link RestoreCompletionListener}
*/
public static interface RestoreSnapshotListener {
/**
* Called when restore operations successfully starts in the cluster. Not null value of {@code snapshot} parameter
* means that restore operation didn't involve any shards and therefore has already completed.
*
* @param restoreInfo if restore operation finished, contains information about restore operation, null otherwise
*/
void onResponse(RestoreInfo restoreInfo);
/**
* Called when restore operation failed to start
*
* @param t exception that prevented the restore operation to start
*/
void onFailure(Throwable t);
}
/**
* This listener is called every time a snapshot is restored in the cluster
*/
public static interface RestoreCompletionListener {
/**
* Called for every snapshot that is completed in the cluster
*
* @param snapshotId snapshot id
* @param restoreInfo restore completion information
*/
void onRestoreCompletion(SnapshotId snapshotId, RestoreInfo restoreInfo);
}
/**
* Internal class that is used to send notifications about finished shard restore operations to master node
*/
private static class UpdateIndexShardRestoreStatusRequest extends TransportRequest {
private SnapshotId snapshotId;
private ShardId shardId;
private ShardRestoreStatus status;
private UpdateIndexShardRestoreStatusRequest() {
}
private UpdateIndexShardRestoreStatusRequest(SnapshotId snapshotId, ShardId shardId, ShardRestoreStatus status) {
this.snapshotId = snapshotId;
this.shardId = shardId;
this.status = status;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
snapshotId = SnapshotId.readSnapshotId(in);
shardId = ShardId.readShardId(in);
status = ShardRestoreStatus.readShardRestoreStatus(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
snapshotId.writeTo(out);
shardId.writeTo(out);
status.writeTo(out);
}
public SnapshotId snapshotId() {
return snapshotId;
}
public ShardId shardId() {
return shardId;
}
public ShardRestoreStatus status() {
return status;
}
}
/**
* Internal class that is used to send notifications about finished shard restore operations to master node
*/
private class UpdateRestoreStateRequestHandler extends BaseTransportRequestHandler<UpdateIndexShardRestoreStatusRequest> {
static final String ACTION = "cluster/snapshot/update_restore";
@Override
public UpdateIndexShardRestoreStatusRequest newInstance() {
return new UpdateIndexShardRestoreStatusRequest();
}
@Override
public void messageReceived(UpdateIndexShardRestoreStatusRequest request, final TransportChannel channel) throws Exception {
innerUpdateRestoreState(request);
channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
} | 1no label
| src_main_java_org_elasticsearch_snapshots_RestoreService.java |
244 | public class EditorActionMessages {
static ResourceBundle ResBundle = ResourceBundle
.getBundle(EditorActionMessages.class.getName());
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_EditorActionMessages.java |
374 | public class PutRepositoryRequest extends AcknowledgedRequest<PutRepositoryRequest> {
private String name;
private String type;
private Settings settings = EMPTY_SETTINGS;
PutRepositoryRequest() {
}
/**
* Constructs a new put repository request with the provided name.
*/
public PutRepositoryRequest(String name) {
this.name = name;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (name == null) {
validationException = addValidationError("name is missing", validationException);
}
if (type == null) {
validationException = addValidationError("type is missing", validationException);
}
return validationException;
}
/**
* Sets the name of the repository.
*
* @param name repository name
*/
public PutRepositoryRequest name(String name) {
this.name = name;
return this;
}
/**
* The name of the repository.
*
* @return repository name
*/
public String name() {
return this.name;
}
/**
* The type of the repository
* <p/>
* <ul>
* <li>"fs" - shared filesystem repository</li>
* </ul>
*
* @param type repository type
* @return this request
*/
public PutRepositoryRequest type(String type) {
this.type = type;
return this;
}
/**
* Returns repository type
*
* @return repository type
*/
public String type() {
return this.type;
}
/**
* Sets the repository settings
*
* @param settings repository settings
* @return this request
*/
public PutRepositoryRequest settings(Settings settings) {
this.settings = settings;
return this;
}
/**
* Sets the repository settings
*
* @param settings repository settings
* @return this request
*/
public PutRepositoryRequest settings(Settings.Builder settings) {
this.settings = settings.build();
return this;
}
/**
* Sets the repository settings.
*
* @param source repository settings in json, yaml or properties format
* @return this request
*/
public PutRepositoryRequest settings(String source) {
this.settings = ImmutableSettings.settingsBuilder().loadFromSource(source).build();
return this;
}
/**
* Sets the repository settings.
*
* @param source repository settings
* @return this request
*/
public PutRepositoryRequest settings(Map<String, Object> 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;
}
/**
* Returns repository settings
*
* @return repository settings
*/
public Settings settings() {
return this.settings;
}
/**
* Parses repository definition.
*
* @param repositoryDefinition repository definition
*/
public PutRepositoryRequest source(XContentBuilder repositoryDefinition) {
return source(repositoryDefinition.bytes());
}
/**
* Parses repository definition.
*
* @param repositoryDefinition repository definition
*/
public PutRepositoryRequest source(Map repositoryDefinition) {
Map<String, Object> source = repositoryDefinition;
for (Map.Entry<String, Object> entry : source.entrySet()) {
String name = entry.getKey();
if (name.equals("type")) {
type(entry.getValue().toString());
} else if (name.equals("settings")) {
if (!(entry.getValue() instanceof Map)) {
throw new ElasticsearchIllegalArgumentException("Malformed settings section, should include an inner object");
}
settings((Map<String, Object>) entry.getValue());
}
}
return this;
}
/**
* Parses repository definition.
* JSON, Smile and YAML formats are supported
*
* @param repositoryDefinition repository definition
*/
public PutRepositoryRequest source(String repositoryDefinition) {
try {
return source(XContentFactory.xContent(repositoryDefinition).createParser(repositoryDefinition).mapOrderedAndClose());
} catch (IOException e) {
throw new ElasticsearchIllegalArgumentException("failed to parse repository source [" + repositoryDefinition + "]", e);
}
}
/**
* Parses repository definition.
* JSON, Smile and YAML formats are supported
*
* @param repositoryDefinition repository definition
*/
public PutRepositoryRequest source(byte[] repositoryDefinition) {
return source(repositoryDefinition, 0, repositoryDefinition.length);
}
/**
* Parses repository definition.
* JSON, Smile and YAML formats are supported
*
* @param repositoryDefinition repository definition
*/
public PutRepositoryRequest source(byte[] repositoryDefinition, int offset, int length) {
try {
return source(XContentFactory.xContent(repositoryDefinition, offset, length).createParser(repositoryDefinition, offset, length).mapOrderedAndClose());
} catch (IOException e) {
throw new ElasticsearchIllegalArgumentException("failed to parse repository source", e);
}
}
/**
* Parses repository definition.
* JSON, Smile and YAML formats are supported
*
* @param repositoryDefinition repository definition
*/
public PutRepositoryRequest source(BytesReference repositoryDefinition) {
try {
return source(XContentFactory.xContent(repositoryDefinition).createParser(repositoryDefinition).mapOrderedAndClose());
} catch (IOException e) {
throw new ElasticsearchIllegalArgumentException("failed to parse template source", e);
}
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
name = in.readString();
type = in.readString();
settings = readSettingsFromStream(in);
readTimeout(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(name);
out.writeString(type);
writeSettingsToStream(settings, out);
writeTimeout(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_repositories_put_PutRepositoryRequest.java |
1,917 | public class TempData implements Serializable {
private static final long serialVersionUID = 1L;
private String attr1;
private String attr2;
public TempData() {
}
public TempData(String attr1, String attr2) {
this.attr1 = attr1;
this.attr2 = attr2;
}
public String getAttr1() {
return attr1;
}
public void setAttr1(String attr1) {
this.attr1 = attr1;
}
public String getAttr2() {
return attr2;
}
public void setAttr2(String attr2) {
this.attr2 = attr2;
}
@Override
public String toString() {
return attr1 + " " + attr2;
}
public static class DeleteEntryProcessor extends AbstractEntryProcessor<String, TempData> {
private static final long serialVersionUID = 1L;
public Object process(Map.Entry<String, TempData> entry) {
entry.setValue(null);
return true;
}
}
public static class LoggingEntryProcessor extends AbstractEntryProcessor<String, TempData> {
private static final long serialVersionUID = 1L;
public Object process(Map.Entry<String, TempData> entry) {
return true;
}
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_map_TempData.java |
1,192 | public class MembershipAdapter implements MembershipListener {
@Override
public void memberAdded(final MembershipEvent membershipEvent) {
}
@Override
public void memberRemoved(final MembershipEvent membershipEvent) {
}
@Override
public void memberAttributeChanged(final MemberAttributeEvent memberAttributeEvent) {
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_MembershipAdapter.java |
3,207 | public class ReplicatedMapDataSerializerHook
implements DataSerializerHook {
public static final int F_ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.REPLICATED_MAP_DS_FACTORY, -22);
public static final int VECTOR = 0;
public static final int RECORD = 1;
public static final int REPL_UPDATE_MESSAGE = 2;
public static final int REPL_CLEAR_MESSAGE = 3;
public static final int REPL_MULTI_UPDATE_MESSAGE = 4;
public static final int OP_INIT_CHUNK = 5;
public static final int OP_POST_JOIN = 6;
public static final int OP_CLEAR = 7;
public static final int MAP_STATS = 8;
private static final int LEN = MAP_STATS + 1;
@Override
public int getFactoryId() {
return F_ID;
}
@Override
public DataSerializableFactory createFactory() {
ConstructorFunction<Integer, IdentifiedDataSerializable>[] constructors = new ConstructorFunction[LEN];
constructors[VECTOR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new VectorClock();
}
};
constructors[RECORD] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new ReplicatedRecord();
}
};
constructors[REPL_UPDATE_MESSAGE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new ReplicationMessage();
}
};
constructors[REPL_CLEAR_MESSAGE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new VectorClock();
}
};
constructors[REPL_MULTI_UPDATE_MESSAGE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
@Override
public IdentifiedDataSerializable createNew(Integer arg) {
return new MultiReplicationMessage();
}
};
constructors[OP_INIT_CHUNK] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
@Override
public IdentifiedDataSerializable createNew(Integer arg) {
return new ReplicatedMapInitChunkOperation();
}
};
constructors[OP_POST_JOIN] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
@Override
public IdentifiedDataSerializable createNew(Integer arg) {
return new ReplicatedMapPostJoinOperation();
}
};
constructors[OP_CLEAR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
@Override
public IdentifiedDataSerializable createNew(Integer arg) {
return new ReplicatedMapClearOperation();
}
};
constructors[MAP_STATS] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
@Override
public IdentifiedDataSerializable createNew(Integer arg) {
return new LocalReplicatedMapStatsImpl();
}
};
return new ArrayDataSerializableFactory(constructors);
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_replicatedmap_operation_ReplicatedMapDataSerializerHook.java |
859 | EasyMock.expect(orderServiceMock.findOrderById(EasyMock.isA(Long.class))).andAnswer(new IAnswer<Order>() {
@Override
public Order answer() throws Throwable {
return myOrder.get();
}
}).anyTimes(); | 0true
| core_broadleaf-framework_src_test_java_org_broadleafcommerce_core_offer_service_OfferServiceTest.java |
162 | public class StructuredContentRuleType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, StructuredContentRuleType> TYPES = new LinkedHashMap<String, StructuredContentRuleType>();
public static final StructuredContentRuleType REQUEST = new StructuredContentRuleType("REQUEST", "Request");
public static final StructuredContentRuleType TIME = new StructuredContentRuleType("TIME", "Time");
public static final StructuredContentRuleType PRODUCT = new StructuredContentRuleType("PRODUCT", "Product");
public static final StructuredContentRuleType CUSTOMER = new StructuredContentRuleType("CUSTOMER", "Customer");
/**
* Allows translation from the passed in String to a <code>StructuredContentRuleType</code>
* @param type
* @return The matching rule type
*/
public static StructuredContentRuleType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public StructuredContentRuleType() {
//do nothing
}
/**
* Initialize the type and friendlyType
* @param <code>type</code>
* @param <code>friendlyType</code>
*/
public StructuredContentRuleType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
/**
* Sets the type
* @param type
*/
public void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
}
}
/**
* Gets the type
* @return
*/
public String getType() {
return type;
}
/**
* Gets the name of the type
* @return
*/
public String getFriendlyType() {
return friendlyType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StructuredContentRuleType other = (StructuredContentRuleType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
} | 1no label
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_service_type_StructuredContentRuleType.java |
344 | final EmbeddedGraphDatabase db = new TestEmbeddedGraphDatabase( storeDir, params ) {
@Override
protected FileSystemAbstraction createFileSystemAbstraction()
{
return new AdversarialFileSystemAbstraction( adversary );
}
}; | 0true
| community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_PartialTransactionFailureIT.java |
18 | public static class TransactionCountPruneStrategy extends AbstractPruneStrategy
{
private final int maxTransactionCount;
public TransactionCountPruneStrategy( FileSystemAbstraction fileSystem, int maxTransactionCount )
{
super( fileSystem );
this.maxTransactionCount = maxTransactionCount;
}
@Override
protected Threshold newThreshold()
{
return new Threshold()
{
private Long highest;
@Override
public boolean reached( File file, long version, LogLoader source )
{
// Here we know that the log version exists (checked in AbstractPruneStrategy#prune)
long tx = source.getFirstCommittedTxId( version );
if ( highest == null )
{
highest = source.getLastCommittedTxId();
return false;
}
return highest-tx >= maxTransactionCount;
}
};
}
} | 1no label
| community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.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 |
1,344 | threadPool.generic().execute(new Runnable() {
@Override
public void run() {
innerNodeIndexDeleted(index, nodeId);
}
}); | 0true
| src_main_java_org_elasticsearch_cluster_action_index_NodeIndexDeletedAction.java |
673 | CollectionUtils.filter(filteredUpSales, new Predicate() {
@Override
public boolean evaluate(Object arg) {
return 'Y'!=((Status)((UpSaleProductImpl) arg).getRelatedProduct()).getArchived();
}
}); | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_CategoryImpl.java |
2,418 | public interface LongArray extends BigArray {
/**
* Get an element given its index.
*/
public abstract long get(long index);
/**
* Set a value at the given index and return the previous value.
*/
public abstract long set(long index, long value);
/**
* Increment value at the given index by <code>inc</code> and return the value.
*/
public abstract long increment(long index, long inc);
/**
* Fill slots between <code>fromIndex</code> inclusive to <code>toIndex</code> exclusive with <code>value</code>.
*/
public abstract void fill(long fromIndex, long toIndex, long value);
} | 0true
| src_main_java_org_elasticsearch_common_util_LongArray.java |
23 | public interface Generator<T> { T get(); } | 0true
| src_main_java_jsr166e_CompletableFuture.java |
121 | public interface StateInitializer<S> {
public S initialState();
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_olap_StateInitializer.java |
1,164 | transportServiceClient.submitRequest(bigNode, "benchmark", message, options().withType(TransportRequestOptions.Type.BULK), new BaseTransportResponseHandler<BenchmarkMessageResponse>() {
@Override
public BenchmarkMessageResponse newInstance() {
return new BenchmarkMessageResponse();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(BenchmarkMessageResponse response) {
}
@Override
public void handleException(TransportException exp) {
exp.printStackTrace();
}
}).txGet(); | 0true
| src_test_java_org_elasticsearch_benchmark_transport_BenchmarkNettyLargeMessages.java |
133 | @Test
public class SafeConverterTest extends AbstractConverterTest {
@BeforeClass
public void beforeClass() {
converter = new OSafeBinaryConverter();
}
@Override
public void testPutIntBigEndian() {
super.testPutIntBigEndian();
}
@Override
public void testPutIntLittleEndian() {
super.testPutIntLittleEndian();
}
@Override
public void testPutLongBigEndian() {
super.testPutLongBigEndian();
}
@Override
public void testPutLongLittleEndian() {
super.testPutLongLittleEndian();
}
@Override
public void testPutShortBigEndian() {
super.testPutShortBigEndian();
}
@Override
public void testPutShortLittleEndian() {
super.testPutShortLittleEndian();
}
@Override
public void testPutCharBigEndian() {
super.testPutCharBigEndian();
}
@Override
public void testPutCharLittleEndian() {
super.testPutCharLittleEndian();
}
} | 0true
| commons_src_test_java_com_orientechnologies_common_serialization_SafeConverterTest.java |
3,865 | public class IdsFilterParser implements FilterParser {
public static final String NAME = "ids";
@Inject
public IdsFilterParser() {
}
@Override
public String[] names() {
return new String[]{NAME};
}
@Override
public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
List<BytesRef> ids = new ArrayList<BytesRef>();
Collection<String> types = null;
String filterName = null;
String currentFieldName = null;
XContentParser.Token token;
boolean idsProvided = false;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
if ("values".equals(currentFieldName)) {
idsProvided = true;
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
BytesRef value = parser.bytesOrNull();
if (value == null) {
throw new QueryParsingException(parseContext.index(), "No value specified for term filter");
}
ids.add(value);
}
} else if ("types".equals(currentFieldName) || "type".equals(currentFieldName)) {
types = new ArrayList<String>();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
String value = parser.textOrNull();
if (value == null) {
throw new QueryParsingException(parseContext.index(), "No type specified for term filter");
}
types.add(value);
}
} else {
throw new QueryParsingException(parseContext.index(), "[ids] filter does not support [" + currentFieldName + "]");
}
} else if (token.isValue()) {
if ("type".equals(currentFieldName) || "_type".equals(currentFieldName)) {
types = ImmutableList.of(parser.text());
} else if ("_name".equals(currentFieldName)) {
filterName = parser.text();
} else {
throw new QueryParsingException(parseContext.index(), "[ids] filter does not support [" + currentFieldName + "]");
}
}
}
if (!idsProvided) {
throw new QueryParsingException(parseContext.index(), "[ids] filter requires providing a values element");
}
if (ids.isEmpty()) {
return Queries.MATCH_NO_FILTER;
}
if (types == null || types.isEmpty()) {
types = parseContext.queryTypes();
} else if (types.size() == 1 && Iterables.getFirst(types, null).equals("_all")) {
types = parseContext.mapperService().types();
}
TermsFilter filter = new TermsFilter(UidFieldMapper.NAME, Uid.createTypeUids(types, ids));
if (filterName != null) {
parseContext.addNamedFilter(filterName, filter);
}
return filter;
}
} | 1no label
| src_main_java_org_elasticsearch_index_query_IdsFilterParser.java |
3,746 | public class DefaultSourceMappingTests extends ElasticsearchTestCase {
@Test
public void testNoFormat() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("_source").endObject()
.endObject().endObject().string();
DocumentMapper documentMapper = MapperTestUtils.newParser().parse(mapping);
ParsedDocument doc = documentMapper.parse("type", "1", XContentFactory.jsonBuilder().startObject()
.field("field", "value")
.endObject().bytes());
assertThat(XContentFactory.xContentType(doc.source()), equalTo(XContentType.JSON));
documentMapper = MapperTestUtils.newParser().parse(mapping);
doc = documentMapper.parse("type", "1", XContentFactory.smileBuilder().startObject()
.field("field", "value")
.endObject().bytes());
assertThat(XContentFactory.xContentType(doc.source()), equalTo(XContentType.SMILE));
}
@Test
public void testJsonFormat() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("_source").field("format", "json").endObject()
.endObject().endObject().string();
DocumentMapper documentMapper = MapperTestUtils.newParser().parse(mapping);
ParsedDocument doc = documentMapper.parse("type", "1", XContentFactory.jsonBuilder().startObject()
.field("field", "value")
.endObject().bytes());
assertThat(XContentFactory.xContentType(doc.source()), equalTo(XContentType.JSON));
documentMapper = MapperTestUtils.newParser().parse(mapping);
doc = documentMapper.parse("type", "1", XContentFactory.smileBuilder().startObject()
.field("field", "value")
.endObject().bytes());
assertThat(XContentFactory.xContentType(doc.source()), equalTo(XContentType.JSON));
}
@Test
public void testJsonFormatCompressed() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("_source").field("format", "json").field("compress", true).endObject()
.endObject().endObject().string();
DocumentMapper documentMapper = MapperTestUtils.newParser().parse(mapping);
ParsedDocument doc = documentMapper.parse("type", "1", XContentFactory.jsonBuilder().startObject()
.field("field", "value")
.endObject().bytes());
assertThat(CompressorFactory.isCompressed(doc.source()), equalTo(true));
byte[] uncompressed = CompressorFactory.uncompressIfNeeded(doc.source()).toBytes();
assertThat(XContentFactory.xContentType(uncompressed), equalTo(XContentType.JSON));
documentMapper = MapperTestUtils.newParser().parse(mapping);
doc = documentMapper.parse("type", "1", XContentFactory.smileBuilder().startObject()
.field("field", "value")
.endObject().bytes());
assertThat(CompressorFactory.isCompressed(doc.source()), equalTo(true));
uncompressed = CompressorFactory.uncompressIfNeeded(doc.source()).toBytes();
assertThat(XContentFactory.xContentType(uncompressed), equalTo(XContentType.JSON));
}
@Test
public void testIncludeExclude() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("_source").field("includes", new String[]{"path1*"}).endObject()
.endObject().endObject().string();
DocumentMapper documentMapper = MapperTestUtils.newParser().parse(mapping);
ParsedDocument doc = documentMapper.parse("type", "1", XContentFactory.jsonBuilder().startObject()
.startObject("path1").field("field1", "value1").endObject()
.startObject("path2").field("field2", "value2").endObject()
.endObject().bytes());
IndexableField sourceField = doc.rootDoc().getField("_source");
Map<String, Object> sourceAsMap = XContentFactory.xContent(XContentType.JSON).createParser(new BytesArray(sourceField.binaryValue())).mapAndClose();
assertThat(sourceAsMap.containsKey("path1"), equalTo(true));
assertThat(sourceAsMap.containsKey("path2"), equalTo(false));
}
@Test
public void testDefaultMappingAndNoMapping() throws Exception {
String defaultMapping = XContentFactory.jsonBuilder().startObject().startObject(MapperService.DEFAULT_MAPPING)
.startObject("_source").field("enabled", false).endObject()
.endObject().endObject().string();
DocumentMapper mapper = MapperTestUtils.newParser().parse("my_type", null, defaultMapping);
assertThat(mapper.type(), equalTo("my_type"));
assertThat(mapper.sourceMapper().enabled(), equalTo(false));
try {
mapper = MapperTestUtils.newParser().parse(null, null, defaultMapping);
assertThat(mapper.type(), equalTo("my_type"));
assertThat(mapper.sourceMapper().enabled(), equalTo(false));
fail();
} catch (MapperParsingException e) {
// all is well
}
try {
mapper = MapperTestUtils.newParser().parse(null, "{}", defaultMapping);
assertThat(mapper.type(), equalTo("my_type"));
assertThat(mapper.sourceMapper().enabled(), equalTo(false));
fail();
} catch (MapperParsingException e) {
assertThat(e.getMessage(), equalTo("malformed mapping no root object found"));
// all is well
}
}
@Test
public void testDefaultMappingAndWithMappingOverride() throws Exception {
String defaultMapping = XContentFactory.jsonBuilder().startObject().startObject(MapperService.DEFAULT_MAPPING)
.startObject("_source").field("enabled", false).endObject()
.endObject().endObject().string();
String mapping = XContentFactory.jsonBuilder().startObject().startObject("my_type")
.startObject("_source").field("enabled", true).endObject()
.endObject().endObject().string();
DocumentMapper mapper = MapperTestUtils.newParser().parse("my_type", mapping, defaultMapping);
assertThat(mapper.type(), equalTo("my_type"));
assertThat(mapper.sourceMapper().enabled(), equalTo(true));
}
@Test
public void testDefaultMappingAndNoMappingWithMapperService() throws Exception {
String defaultMapping = XContentFactory.jsonBuilder().startObject().startObject(MapperService.DEFAULT_MAPPING)
.startObject("_source").field("enabled", false).endObject()
.endObject().endObject().string();
MapperService mapperService = MapperTestUtils.newMapperService();
mapperService.merge(MapperService.DEFAULT_MAPPING, new CompressedString(defaultMapping), true);
DocumentMapper mapper = mapperService.documentMapperWithAutoCreate("my_type");
assertThat(mapper.type(), equalTo("my_type"));
assertThat(mapper.sourceMapper().enabled(), equalTo(false));
}
@Test
public void testDefaultMappingAndWithMappingOverrideWithMapperService() throws Exception {
String defaultMapping = XContentFactory.jsonBuilder().startObject().startObject(MapperService.DEFAULT_MAPPING)
.startObject("_source").field("enabled", false).endObject()
.endObject().endObject().string();
MapperService mapperService = MapperTestUtils.newMapperService();
mapperService.merge(MapperService.DEFAULT_MAPPING, new CompressedString(defaultMapping), true);
String mapping = XContentFactory.jsonBuilder().startObject().startObject("my_type")
.startObject("_source").field("enabled", true).endObject()
.endObject().endObject().string();
mapperService.merge("my_type", new CompressedString(mapping), true);
DocumentMapper mapper = mapperService.documentMapper("my_type");
assertThat(mapper.type(), equalTo("my_type"));
assertThat(mapper.sourceMapper().enabled(), equalTo(true));
}
} | 0true
| src_test_java_org_elasticsearch_index_mapper_source_DefaultSourceMappingTests.java |
1,726 | public class Tuple<V1, V2> {
public static <V1, V2> Tuple<V1, V2> tuple(V1 v1, V2 v2) {
return new Tuple<V1, V2>(v1, v2);
}
private final V1 v1;
private final V2 v2;
public Tuple(V1 v1, V2 v2) {
this.v1 = v1;
this.v2 = v2;
}
public V1 v1() {
return v1;
}
public V2 v2() {
return v2;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tuple tuple = (Tuple) o;
if (v1 != null ? !v1.equals(tuple.v1) : tuple.v1 != null) return false;
if (v2 != null ? !v2.equals(tuple.v2) : tuple.v2 != null) return false;
return true;
}
@Override
public int hashCode() {
int result = v1 != null ? v1.hashCode() : 0;
result = 31 * result + (v2 != null ? v2.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple [v1=" + v1 + ", v2=" + v2 + "]";
}
} | 0true
| src_main_java_org_elasticsearch_common_collect_Tuple.java |
802 | public interface CustomerOffer extends Serializable {
public Long getId() ;
public void setId(Long id) ;
public Customer getCustomer() ;
public void setCustomer(Customer customer) ;
public Offer getOffer() ;
public void setOffer(Offer offer) ;
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_CustomerOffer.java |
3,704 | public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Builder builder = uid();
parseField(builder, builder.name, node, parserContext);
return builder;
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_internal_UidFieldMapper.java |
859 | private class AsyncAction extends BaseAsyncAction<DfsSearchResult> {
private final AtomicArray<QueryFetchSearchResult> queryFetchResults;
private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
super(request, listener);
queryFetchResults = new AtomicArray<QueryFetchSearchResult>(firstResults.length());
}
@Override
protected String firstPhaseName() {
return "dfs";
}
@Override
protected void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchRequest request, SearchServiceListener<DfsSearchResult> listener) {
searchService.sendExecuteDfs(node, request, listener);
}
@Override
protected void moveToSecondPhase() {
final AggregatedDfs dfs = searchPhaseController.aggregateDfs(firstResults);
final AtomicInteger counter = new AtomicInteger(firstResults.asList().size());
int localOperations = 0;
for (final AtomicArray.Entry<DfsSearchResult> entry : firstResults.asList()) {
DfsSearchResult dfsResult = entry.value;
DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
localOperations++;
} else {
QuerySearchRequest querySearchRequest = new QuerySearchRequest(request, dfsResult.id(), dfs);
executeSecondPhase(entry.index, dfsResult, counter, node, querySearchRequest);
}
}
if (localOperations > 0) {
if (request.operationThreading() == SearchOperationThreading.SINGLE_THREAD) {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
for (final AtomicArray.Entry<DfsSearchResult> entry : firstResults.asList()) {
DfsSearchResult dfsResult = entry.value;
DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
QuerySearchRequest querySearchRequest = new QuerySearchRequest(request, dfsResult.id(), dfs);
executeSecondPhase(entry.index, dfsResult, counter, node, querySearchRequest);
}
}
}
});
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
for (final AtomicArray.Entry<DfsSearchResult> entry : firstResults.asList()) {
final DfsSearchResult dfsResult = entry.value;
final DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
final QuerySearchRequest querySearchRequest = new QuerySearchRequest(request, dfsResult.id(), dfs);
try {
if (localAsync) {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
executeSecondPhase(entry.index, dfsResult, counter, node, querySearchRequest);
}
});
} else {
executeSecondPhase(entry.index, dfsResult, counter, node, querySearchRequest);
}
} catch (Throwable t) {
onSecondPhaseFailure(t, querySearchRequest, entry.index, dfsResult, counter);
}
}
}
}
}
}
void executeSecondPhase(final int shardIndex, final DfsSearchResult dfsResult, final AtomicInteger counter, DiscoveryNode node, final QuerySearchRequest querySearchRequest) {
searchService.sendExecuteFetch(node, querySearchRequest, new SearchServiceListener<QueryFetchSearchResult>() {
@Override
public void onResult(QueryFetchSearchResult result) {
result.shardTarget(dfsResult.shardTarget());
queryFetchResults.set(shardIndex, result);
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
@Override
public void onFailure(Throwable t) {
onSecondPhaseFailure(t, querySearchRequest, shardIndex, dfsResult, counter);
}
});
}
void onSecondPhaseFailure(Throwable t, QuerySearchRequest querySearchRequest, int shardIndex, DfsSearchResult dfsResult, AtomicInteger counter) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] Failed to execute query phase", t, querySearchRequest.id());
}
this.addShardFailure(shardIndex, dfsResult.shardTarget(), t);
successulOps.decrementAndGet();
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
void finishHim() {
try {
innerFinishHim();
} catch (Throwable e) {
ReduceSearchPhaseException failure = new ReduceSearchPhaseException("query_fetch", "", e, buildShardFailures());
if (logger.isDebugEnabled()) {
logger.debug("failed to reduce search", failure);
}
listener.onFailure(failure);
} finally {
//
}
}
void innerFinishHim() throws Exception {
sortedShardList = searchPhaseController.sortDocs(queryFetchResults);
final InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, queryFetchResults, queryFetchResults);
String scrollId = null;
if (request.scroll() != null) {
scrollId = TransportSearchHelper.buildScrollId(request.searchType(), firstResults, null);
}
listener.onResponse(new SearchResponse(internalResponse, scrollId, expectedSuccessfulOps, successulOps.get(), buildTookInMillis(), buildShardFailures()));
}
} | 0true
| src_main_java_org_elasticsearch_action_search_type_TransportSearchDfsQueryAndFetchAction.java |
1,648 | public class OAutoshardingPlugin extends OServerPluginAbstract implements ODatabaseLifecycleListener {
private boolean enabled = true;
private ServerInstance serverInstance;
private DHTConfiguration dhtConfiguration;
private OServer server;
@Override
public String getName() {
return "autosharding";
}
@Override
public void config(final OServer iServer, OServerParameterConfiguration[] iParams) {
server = iServer;
server.setVariable("OAutoshardingPlugin", this);
String configFile = "/hazelcast.xml";
for (OServerParameterConfiguration param : iParams) {
if (param.name.equalsIgnoreCase("enabled")) {
if (!Boolean.parseBoolean(param.value)) {
enabled = false;
return;
}
} else if (param.name.equalsIgnoreCase("configuration.hazelcast")) {
configFile = OSystemVariableResolver.resolveSystemVariables(param.value);
}
}
dhtConfiguration = new DHTConfiguration(server);
serverInstance = new ServerInstance(server, configFile);
serverInstance.setDHTConfiguration(dhtConfiguration);
}
@Override
public void startup() {
if (!enabled)
return;
serverInstance.init();
super.startup();
Orient.instance().addDbLifecycleListener(this);
}
@Override
public void onCreate(final ODatabase iDatabase) {
onOpen(iDatabase);
}
@Override
public void onOpen(final ODatabase iDatabase) {
if (iDatabase instanceof ODatabaseComplex<?>) {
iDatabase.replaceStorage(new OAutoshardedStorageImpl(serverInstance, (OStorageEmbedded) iDatabase.getStorage(),
dhtConfiguration));
}
}
@Override
public void onClose(ODatabase iDatabase) {
}
public static class DHTConfiguration implements ODHTConfiguration {
private final HashSet<String> undistributableClusters;
private final OServer server;
public DHTConfiguration(final OServer iServer) {
server = iServer;
undistributableClusters = new HashSet<String>();
undistributableClusters.add(OStorage.CLUSTER_DEFAULT_NAME.toLowerCase());
undistributableClusters.add(OMetadataDefault.CLUSTER_INTERNAL_NAME.toLowerCase());
undistributableClusters.add(OMetadataDefault.CLUSTER_INDEX_NAME.toLowerCase());
undistributableClusters.add(OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME.toLowerCase());
undistributableClusters.add(ORole.CLASS_NAME.toLowerCase());
undistributableClusters.add(OUser.CLASS_NAME.toLowerCase());
undistributableClusters.add(OMVRBTreeRIDProvider.PERSISTENT_CLASS_NAME.toLowerCase());
undistributableClusters.add(OSecurityShared.RESTRICTED_CLASSNAME.toLowerCase());
undistributableClusters.add(OSecurityShared.IDENTITY_CLASSNAME.toLowerCase());
undistributableClusters.add(OFunction.CLASS_NAME.toLowerCase());
}
@Override
public Set<String> getDistributedStorageNames() {
return server.getAvailableStorageNames().keySet();
}
@Override
public Set<String> getUndistributableClusters() {
return undistributableClusters;
}
}
} | 0true
| distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_oldsharding_OAutoshardingPlugin.java |
295 | public class NeoStoreXaConnection extends XaConnectionHelpImpl
implements IndexXaConnection // Implements this to enable a temporary workaround, see #createIndex
{
private final NeoStoreXaResource xaResource;
private final NeoStore neoStore;
NeoStoreXaConnection( NeoStore neoStore, XaResourceManager xaRm,
byte branchId[] )
{
super( xaRm );
this.neoStore = neoStore;
this.xaResource = new NeoStoreXaResource(
neoStore.getStorageFileName(), xaRm, branchId );
}
@Override
public XAResource getXaResource()
{
return this.xaResource;
}
@Override
public NeoStoreTransaction getTransaction()
{
try
{
return (NeoStoreTransaction) super.getTransaction();
}
catch ( XAException e )
{
throw new TransactionFailureException( "Unable to create transaction.", e );
}
}
@Override
public NeoStoreTransaction createTransaction()
{
// Is only called once per write transaction so no need
// to cache the transaction here.
try
{
return (NeoStoreTransaction) super.createTransaction();
}
catch ( XAException e )
{
throw new TransactionFailureException( "Unable to create transaction.", e );
}
}
private static class NeoStoreXaResource extends XaResourceHelpImpl
{
private final Object identifier;
NeoStoreXaResource( Object identifier, XaResourceManager xaRm,
byte branchId[] )
{
super( xaRm, branchId );
this.identifier = identifier;
}
@Override
public boolean isSameRM( XAResource xares )
{
if ( xares instanceof NeoStoreXaResource )
{
return identifier
.equals( ((NeoStoreXaResource) xares).identifier );
}
return false;
}
};
// TEST These methods are only used by tests - refactor away if possible
public PropertyStore getPropertyStore()
{
return neoStore.getPropertyStore();
}
public RelationshipTypeTokenStore getRelationshipTypeStore()
{
return neoStore.getRelationshipTypeStore();
}
@Override
public void createIndex( Class<? extends PropertyContainer> entityType, String indexName,
Map<String, String> config )
{
// This gets called in the index creator thread in IndexManagerImpl when "creating"
// an index which uses the graph as its backing. Normally this would add a command to
// a log, put the transaction in a non-read-only state and cause it to commit and
// write these command plus add it to the index store (where index configuration is kept).
// But this is a temporary workaround for supporting in-graph indexes without the
// persistence around their creation or existence. The reason is that there are no
// index life cycle commands for the neo store. When/if graph data source gets merged
// with other index data sources (i.e. they will have one unified log and data source
// to act as the front end) this will be resolved and this workaround can be removed
// (NeoStoreXaConnection implementing IndexXaConnection).
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreXaConnection.java |
1,198 | objectIntMap = build(type, limit, smartSize, availableProcessors, new Recycler.C<ObjectIntOpenHashMap>() {
@Override
public ObjectIntOpenHashMap newInstance(int sizing) {
return new ObjectIntOpenHashMap(size(sizing));
}
@Override
public void clear(ObjectIntOpenHashMap value) {
value.clear();
}
}); | 0true
| src_main_java_org_elasticsearch_cache_recycler_CacheRecycler.java |
753 | public class CopyFileRefactoringParticipant extends CopyParticipant {
private IFile file;
@Override
protected boolean initialize(Object element) {
file = (IFile) element;
return getProcessor() instanceof CopyProcessor &&
getProjectTypeChecker(file.getProject())!=null &&
file.getFileExtension()!=null &&
file.getFileExtension().equals("ceylon");
}
@Override
public String getName() {
return "Copy file participant for Ceylon source";
}
@Override
public RefactoringStatus checkConditions(IProgressMonitor pm,
CheckConditionsContext context) throws OperationCanceledException {
return new RefactoringStatus();
}
public Change createChange(IProgressMonitor pm) throws CoreException {
try {
IFolder dest = (IFolder) getArguments().getDestination();
final String newName = dest.getProjectRelativePath()
.removeFirstSegments(1).toPortableString()
.replace('/', '.');
IFile newFile = dest.getFile(file.getName());
String relFilePath = file.getProjectRelativePath()
.removeFirstSegments(1).toPortableString();
String relPath = file.getProjectRelativePath()
.removeFirstSegments(1).removeLastSegments(1)
.toPortableString();
final String oldName = relPath.replace('/', '.');
final IProject project = file.getProject();
TypeChecker tc = getProjectTypeChecker(project);
if (tc==null) return null;
PhasedUnit phasedUnit = tc.getPhasedUnitFromRelativePath(relFilePath);
if (phasedUnit==null) return null;
final List<ReplaceEdit> edits = new ArrayList<ReplaceEdit>();
final List<Declaration> declarations = phasedUnit.getDeclarations();
final Map<Declaration,String> imports = new HashMap<Declaration,String>();
phasedUnit.getCompilationUnit().visit(new Visitor() {
@Override
public void visit(ImportMemberOrType that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclarationModel());
}
@Override
public void visit(BaseMemberOrTypeExpression that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclaration());
}
@Override
public void visit(BaseType that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclarationModel());
}
@Override
public void visit(ModuleDescriptor that) {
super.visit(that);
visitIt(that.getImportPath());
}
@Override
public void visit(PackageDescriptor that) {
super.visit(that);
visitIt(that.getImportPath());
}
private void visitIt(Tree.ImportPath importPath) {
if (formatPath(importPath.getIdentifiers()).equals(oldName)) {
edits.add(new ReplaceEdit(importPath.getStartIndex(),
oldName.length(), newName));
}
}
private void visitIt(Tree.Identifier id, Declaration dec) {
if (dec!=null && !declarations.contains(dec)) {
String pn = dec.getUnit().getPackage().getNameAsString();
if (pn.equals(oldName) && !pn.isEmpty() &&
!pn.equals(Module.LANGUAGE_MODULE_NAME)) {
imports.put(dec, id.getText());
}
}
}
});
try {
TextFileChange change = new TextFileChange(file.getName(), newFile);
Tree.CompilationUnit cu = phasedUnit.getCompilationUnit();
change.setEdit(new MultiTextEdit());
for (ReplaceEdit edit: edits) {
change.addEdit(edit);
}
if (!imports.isEmpty()) {
List<InsertEdit> list = importEdits(cu,
imports.keySet(), imports.values(),
null, EditorUtil.getDocument(change));
for (TextEdit edit: list) {
change.addEdit(edit);
}
}
Tree.Import toDelete = findImportNode(cu, newName);
if (toDelete!=null) {
change.addEdit(new DeleteEdit(toDelete.getStartIndex(),
toDelete.getStopIndex()-toDelete.getStartIndex()+1));
}
if (change.getEdit().hasChildren()) {
return change;
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_refactor_CopyFileRefactoringParticipant.java |
1,377 | database.getStorage().callInLock(new Callable<Object>() {
@Override
public Object call() throws Exception {
database.getStorage().commit(OTransactionOptimistic.this, null);
callback.run();
return null;
}
}, true); | 1no label
| core_src_main_java_com_orientechnologies_orient_core_tx_OTransactionOptimistic.java |
2,219 | public class BoostScoreFunction extends ScoreFunction {
private final float boost;
public BoostScoreFunction(float boost) {
super(CombineFunction.MULT);
this.boost = boost;
}
public float getBoost() {
return boost;
}
@Override
public void setNextReader(AtomicReaderContext context) {
// nothing to do here...
}
@Override
public double score(int docId, float subQueryScore) {
return boost;
}
@Override
public Explanation explainScore(int docId, Explanation subQueryExpl) {
Explanation exp = new Explanation(boost, "static boost factor");
exp.addDetail(new Explanation(boost, "boostFactor"));
return exp;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
BoostScoreFunction that = (BoostScoreFunction) o;
if (Float.compare(that.boost, boost) != 0)
return false;
return true;
}
@Override
public int hashCode() {
return (boost != +0.0f ? Float.floatToIntBits(boost) : 0);
}
@Override
public String toString() {
return "boost[" + boost + "]";
}
} | 1no label
| src_main_java_org_elasticsearch_common_lucene_search_function_BoostScoreFunction.java |
2,424 | public class SlicedLongListTests extends ElasticsearchTestCase {
@Test
public void testCapacity() {
SlicedLongList list = new SlicedLongList(5);
assertThat(list.length, equalTo(5));
assertThat(list.offset, equalTo(0));
assertThat(list.values.length, equalTo(5));
assertThat(list.size(), equalTo(5));
list = new SlicedLongList(new long[10], 5, 5);
assertThat(list.length, equalTo(5));
assertThat(list.offset, equalTo(5));
assertThat(list.size(), equalTo(5));
assertThat(list.values.length, equalTo(10));
}
@Test
public void testGrow() {
SlicedLongList list = new SlicedLongList(5);
list.length = 1000;
for (int i = 0; i < list.length; i++) {
list.grow(i+1);
list.values[i] = ((long)i);
}
int expected = 0;
for (Long d : list) {
assertThat((long)expected++, equalTo(d));
}
for (int i = 0; i < list.length; i++) {
assertThat((long)i, equalTo(list.get(i)));
}
int count = 0;
for (int i = list.offset; i < list.offset+list.length; i++) {
assertThat((long)count++, equalTo(list.values[i]));
}
}
@Test
public void testSet() {
SlicedLongList list = new SlicedLongList(5);
try {
list.set(0, (long)4);
fail();
} catch (UnsupportedOperationException ex) {
}
try {
list.add((long)4);
fail();
} catch (UnsupportedOperationException ex) {
}
}
@Test
public void testIndexOf() {
SlicedLongList list = new SlicedLongList(5);
list.length = 1000;
for (int i = 0; i < list.length; i++) {
list.grow(i+1);
list.values[i] = ((long)i%100);
}
assertThat(999, equalTo(list.lastIndexOf(99l)));
assertThat(99, equalTo(list.indexOf(99l)));
assertThat(-1, equalTo(list.lastIndexOf(100l)));
assertThat(-1, equalTo(list.indexOf(100l)));
}
public void testIsEmpty() {
SlicedLongList list = new SlicedLongList(5);
assertThat(false, equalTo(list.isEmpty()));
list.length = 0;
assertThat(true, equalTo(list.isEmpty()));
}
@Test
public void testToString() {
SlicedLongList list = new SlicedLongList(5);
assertThat("[0, 0, 0, 0, 0]", equalTo(list.toString()));
for (int i = 0; i < list.length; i++) {
list.grow(i+1);
list.values[i] = ((long)i);
}
assertThat("[0, 1, 2, 3, 4]", equalTo(list.toString()));
}
} | 0true
| src_test_java_org_elasticsearch_common_util_SlicedLongListTests.java |
1,104 | public class SemaphoreConfigReadOnly extends SemaphoreConfig {
public SemaphoreConfigReadOnly(SemaphoreConfig config) {
super(config);
}
public SemaphoreConfig setName(String name) {
throw new UnsupportedOperationException("This config is read-only semaphore: " + getName());
}
public SemaphoreConfig setInitialPermits(int initialPermits) {
throw new UnsupportedOperationException("This config is read-only semaphore: " + getName());
}
public SemaphoreConfig setBackupCount(int backupCount) {
throw new UnsupportedOperationException("This config is read-only semaphore: " + getName());
}
public SemaphoreConfig setAsyncBackupCount(int asyncBackupCount) {
throw new UnsupportedOperationException("This config is read-only semaphore: " + getName());
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_config_SemaphoreConfigReadOnly.java |
670 | public class DeleteWarmerRequestBuilder extends AcknowledgedRequestBuilder<DeleteWarmerRequest, DeleteWarmerResponse, DeleteWarmerRequestBuilder> {
public DeleteWarmerRequestBuilder(IndicesAdminClient indicesClient) {
super((InternalIndicesAdminClient) indicesClient, new DeleteWarmerRequest());
}
public DeleteWarmerRequestBuilder setIndices(String... indices) {
request.indices(indices);
return this;
}
/**
* The name (or wildcard expression) of the index warmer to delete, or null
* to delete all warmers.
*/
public DeleteWarmerRequestBuilder setNames(String... names) {
request.names(names);
return this;
}
/**
* Specifies what type of requested indices to ignore and wildcard indices expressions.
*
* For example indices that don't exist.
*/
public DeleteWarmerRequestBuilder setIndicesOptions(IndicesOptions options) {
request.indicesOptions(options);
return this;
}
@Override
protected void doExecute(ActionListener<DeleteWarmerResponse> listener) {
((IndicesAdminClient) client).deleteWarmer(request, listener);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_warmer_delete_DeleteWarmerRequestBuilder.java |
3,714 | public static class NumericIpTokenizer extends NumericTokenizer {
public NumericIpTokenizer(Reader reader, int precisionStep, char[] buffer) throws IOException {
super(reader, new NumericTokenStream(precisionStep), buffer, null);
}
@Override
protected void setValue(NumericTokenStream tokenStream, String value) {
tokenStream.setLongValue(ipToLong(value));
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_ip_IpFieldMapper.java |
8 | abstract static class Async extends ForkJoinTask<Void>
implements Runnable, AsynchronousCompletionTask {
public final Void getRawResult() { return null; }
public final void setRawResult(Void v) { }
public final void run() { exec(); }
} | 0true
| src_main_java_jsr166e_CompletableFuture.java |
1,663 | public class Strings {
public static final String[] EMPTY_ARRAY = new String[0];
private static final String FOLDER_SEPARATOR = "/";
private static final String WINDOWS_FOLDER_SEPARATOR = "\\";
private static final String TOP_PATH = "src/test";
private static final String CURRENT_PATH = ".";
private static final char EXTENSION_SEPARATOR = '.';
public static void tabify(int tabs, String from, StringBuilder to) throws Exception {
final BufferedReader reader = new BufferedReader(new FastStringReader(from));
try {
String line;
while ((line = reader.readLine()) != null) {
for (int i = 0; i < tabs; i++) {
to.append('\t');
}
to.append(line).append('\n');
}
} finally {
reader.close();
}
}
public static void spaceify(int spaces, String from, StringBuilder to) throws Exception {
final BufferedReader reader = new BufferedReader(new FastStringReader(from));
try {
String line;
while ((line = reader.readLine()) != null) {
for (int i = 0; i < spaces; i++) {
to.append(' ');
}
to.append(line).append('\n');
}
} finally {
reader.close();
}
}
/**
* Splits a backslash escaped string on the separator.
* <p/>
* Current backslash escaping supported:
* <br> \n \t \r \b \f are escaped the same as a Java String
* <br> Other characters following a backslash are produced verbatim (\c => c)
*
* @param s the string to split
* @param separator the separator to split on
* @param decode decode backslash escaping
*/
public static List<String> splitSmart(String s, String separator, boolean decode) {
ArrayList<String> lst = new ArrayList<String>(2);
StringBuilder sb = new StringBuilder();
int pos = 0, end = s.length();
while (pos < end) {
if (s.startsWith(separator, pos)) {
if (sb.length() > 0) {
lst.add(sb.toString());
sb = new StringBuilder();
}
pos += separator.length();
continue;
}
char ch = s.charAt(pos++);
if (ch == '\\') {
if (!decode) sb.append(ch);
if (pos >= end) break; // ERROR, or let it go?
ch = s.charAt(pos++);
if (decode) {
switch (ch) {
case 'n':
ch = '\n';
break;
case 't':
ch = '\t';
break;
case 'r':
ch = '\r';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
}
}
}
sb.append(ch);
}
if (sb.length() > 0) {
lst.add(sb.toString());
}
return lst;
}
public static List<String> splitWS(String s, boolean decode) {
ArrayList<String> lst = new ArrayList<String>(2);
StringBuilder sb = new StringBuilder();
int pos = 0, end = s.length();
while (pos < end) {
char ch = s.charAt(pos++);
if (Character.isWhitespace(ch)) {
if (sb.length() > 0) {
lst.add(sb.toString());
sb = new StringBuilder();
}
continue;
}
if (ch == '\\') {
if (!decode) sb.append(ch);
if (pos >= end) break; // ERROR, or let it go?
ch = s.charAt(pos++);
if (decode) {
switch (ch) {
case 'n':
ch = '\n';
break;
case 't':
ch = '\t';
break;
case 'r':
ch = '\r';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
}
}
}
sb.append(ch);
}
if (sb.length() > 0) {
lst.add(sb.toString());
}
return lst;
}
//---------------------------------------------------------------------
// General convenience methods for working with Strings
//---------------------------------------------------------------------
/**
* Check that the given CharSequence is neither <code>null</code> nor of length 0.
* Note: Will return <code>true</code> for a CharSequence that purely consists of whitespace.
* <p><pre>
* StringUtils.hasLength(null) = false
* StringUtils.hasLength("") = false
* StringUtils.hasLength(" ") = true
* StringUtils.hasLength("Hello") = true
* </pre>
*
* @param str the CharSequence to check (may be <code>null</code>)
* @return <code>true</code> if the CharSequence is not null and has length
* @see #hasText(String)
*/
public static boolean hasLength(CharSequence str) {
return (str != null && str.length() > 0);
}
/**
* Check that the given String is neither <code>null</code> nor of length 0.
* Note: Will return <code>true</code> for a String that purely consists of whitespace.
*
* @param str the String to check (may be <code>null</code>)
* @return <code>true</code> if the String is not null and has length
* @see #hasLength(CharSequence)
*/
public static boolean hasLength(String str) {
return hasLength((CharSequence) str);
}
/**
* Check whether the given CharSequence has actual text.
* More specifically, returns <code>true</code> if the string not <code>null</code>,
* its length is greater than 0, and it contains at least one non-whitespace character.
* <p><pre>
* StringUtils.hasText(null) = false
* StringUtils.hasText("") = false
* StringUtils.hasText(" ") = false
* StringUtils.hasText("12345") = true
* StringUtils.hasText(" 12345 ") = true
* </pre>
*
* @param str the CharSequence to check (may be <code>null</code>)
* @return <code>true</code> if the CharSequence is not <code>null</code>,
* its length is greater than 0, and it does not contain whitespace only
* @see java.lang.Character#isWhitespace
*/
public static boolean hasText(CharSequence str) {
if (!hasLength(str)) {
return false;
}
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
/**
* Check whether the given String has actual text.
* More specifically, returns <code>true</code> if the string not <code>null</code>,
* its length is greater than 0, and it contains at least one non-whitespace character.
*
* @param str the String to check (may be <code>null</code>)
* @return <code>true</code> if the String is not <code>null</code>, its length is
* greater than 0, and it does not contain whitespace only
* @see #hasText(CharSequence)
*/
public static boolean hasText(String str) {
return hasText((CharSequence) str);
}
/**
* Check whether the given CharSequence contains any whitespace characters.
*
* @param str the CharSequence to check (may be <code>null</code>)
* @return <code>true</code> if the CharSequence is not empty and
* contains at least 1 whitespace character
* @see java.lang.Character#isWhitespace
*/
public static boolean containsWhitespace(CharSequence str) {
if (!hasLength(str)) {
return false;
}
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
/**
* Check whether the given String contains any whitespace characters.
*
* @param str the String to check (may be <code>null</code>)
* @return <code>true</code> if the String is not empty and
* contains at least 1 whitespace character
* @see #containsWhitespace(CharSequence)
*/
public static boolean containsWhitespace(String str) {
return containsWhitespace((CharSequence) str);
}
/**
* Trim leading and trailing whitespace from the given String.
*
* @param str the String to check
* @return the trimmed String
* @see java.lang.Character#isWhitespace
*/
public static String trimWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
sb.deleteCharAt(0);
}
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
/**
* Trim <i>all</i> whitespace from the given String:
* leading, trailing, and inbetween characters.
*
* @param str the String to check
* @return the trimmed String
* @see java.lang.Character#isWhitespace
*/
public static String trimAllWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
StringBuilder sb = new StringBuilder(str);
int index = 0;
while (sb.length() > index) {
if (Character.isWhitespace(sb.charAt(index))) {
sb.deleteCharAt(index);
} else {
index++;
}
}
return sb.toString();
}
/**
* Trim leading whitespace from the given String.
*
* @param str the String to check
* @return the trimmed String
* @see java.lang.Character#isWhitespace
*/
public static String trimLeadingWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
sb.deleteCharAt(0);
}
return sb.toString();
}
/**
* Trim trailing whitespace from the given String.
*
* @param str the String to check
* @return the trimmed String
* @see java.lang.Character#isWhitespace
*/
public static String trimTrailingWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
/**
* Trim all occurences of the supplied leading character from the given String.
*
* @param str the String to check
* @param leadingCharacter the leading character to be trimmed
* @return the trimmed String
*/
public static String trimLeadingCharacter(String str, char leadingCharacter) {
if (!hasLength(str)) {
return str;
}
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {
sb.deleteCharAt(0);
}
return sb.toString();
}
/**
* Trim all occurences of the supplied trailing character from the given String.
*
* @param str the String to check
* @param trailingCharacter the trailing character to be trimmed
* @return the trimmed String
*/
public static String trimTrailingCharacter(String str, char trailingCharacter) {
if (!hasLength(str)) {
return str;
}
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
/**
* Test if the given String starts with the specified prefix,
* ignoring upper/lower case.
*
* @param str the String to check
* @param prefix the prefix to look for
* @see java.lang.String#startsWith
*/
public static boolean startsWithIgnoreCase(String str, String prefix) {
if (str == null || prefix == null) {
return false;
}
if (str.startsWith(prefix)) {
return true;
}
if (str.length() < prefix.length()) {
return false;
}
String lcStr = str.substring(0, prefix.length()).toLowerCase(Locale.ROOT);
String lcPrefix = prefix.toLowerCase(Locale.ROOT);
return lcStr.equals(lcPrefix);
}
/**
* Test if the given String ends with the specified suffix,
* ignoring upper/lower case.
*
* @param str the String to check
* @param suffix the suffix to look for
* @see java.lang.String#endsWith
*/
public static boolean endsWithIgnoreCase(String str, String suffix) {
if (str == null || suffix == null) {
return false;
}
if (str.endsWith(suffix)) {
return true;
}
if (str.length() < suffix.length()) {
return false;
}
String lcStr = str.substring(str.length() - suffix.length()).toLowerCase(Locale.ROOT);
String lcSuffix = suffix.toLowerCase(Locale.ROOT);
return lcStr.equals(lcSuffix);
}
/**
* Test whether the given string matches the given substring
* at the given index.
*
* @param str the original string (or StringBuilder)
* @param index the index in the original string to start matching against
* @param substring the substring to match at the given index
*/
public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {
for (int j = 0; j < substring.length(); j++) {
int i = index + j;
if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {
return false;
}
}
return true;
}
/**
* Count the occurrences of the substring in string s.
*
* @param str string to search in. Return 0 if this is null.
* @param sub string to search for. Return 0 if this is null.
*/
public static int countOccurrencesOf(String str, String sub) {
if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {
return 0;
}
int count = 0;
int pos = 0;
int idx;
while ((idx = str.indexOf(sub, pos)) != -1) {
++count;
pos = idx + sub.length();
}
return count;
}
/**
* Replace all occurences of a substring within a string with
* another string.
*
* @param inString String to examine
* @param oldPattern String to replace
* @param newPattern String to insert
* @return a String with the replacements
*/
public static String replace(String inString, String oldPattern, String newPattern) {
if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {
return inString;
}
StringBuilder sb = new StringBuilder();
int pos = 0; // our position in the old string
int index = inString.indexOf(oldPattern);
// the index of an occurrence we've found, or -1
int patLen = oldPattern.length();
while (index >= 0) {
sb.append(inString.substring(pos, index));
sb.append(newPattern);
pos = index + patLen;
index = inString.indexOf(oldPattern, pos);
}
sb.append(inString.substring(pos));
// remember to append any characters to the right of a match
return sb.toString();
}
/**
* Delete all occurrences of the given substring.
*
* @param inString the original String
* @param pattern the pattern to delete all occurrences of
* @return the resulting String
*/
public static String delete(String inString, String pattern) {
return replace(inString, pattern, "");
}
/**
* Delete any character in a given String.
*
* @param inString the original String
* @param charsToDelete a set of characters to delete.
* E.g. "az\n" will delete 'a's, 'z's and new lines.
* @return the resulting String
*/
public static String deleteAny(String inString, String charsToDelete) {
if (!hasLength(inString) || !hasLength(charsToDelete)) {
return inString;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inString.length(); i++) {
char c = inString.charAt(i);
if (charsToDelete.indexOf(c) == -1) {
sb.append(c);
}
}
return sb.toString();
}
//---------------------------------------------------------------------
// Convenience methods for working with formatted Strings
//---------------------------------------------------------------------
/**
* Quote the given String with single quotes.
*
* @param str the input String (e.g. "myString")
* @return the quoted String (e.g. "'myString'"),
* or <code>null<code> if the input was <code>null</code>
*/
public static String quote(String str) {
return (str != null ? "'" + str + "'" : null);
}
/**
* Turn the given Object into a String with single quotes
* if it is a String; keeping the Object as-is else.
*
* @param obj the input Object (e.g. "myString")
* @return the quoted String (e.g. "'myString'"),
* or the input object as-is if not a String
*/
public static Object quoteIfString(Object obj) {
return (obj instanceof String ? quote((String) obj) : obj);
}
/**
* Unqualify a string qualified by a '.' dot character. For example,
* "this.name.is.qualified", returns "qualified".
*
* @param qualifiedName the qualified name
*/
public static String unqualify(String qualifiedName) {
return unqualify(qualifiedName, '.');
}
/**
* Unqualify a string qualified by a separator character. For example,
* "this:name:is:qualified" returns "qualified" if using a ':' separator.
*
* @param qualifiedName the qualified name
* @param separator the separator
*/
public static String unqualify(String qualifiedName, char separator) {
return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);
}
/**
* Capitalize a <code>String</code>, changing the first letter to
* upper case as per {@link Character#toUpperCase(char)}.
* No other letters are changed.
*
* @param str the String to capitalize, may be <code>null</code>
* @return the capitalized String, <code>null</code> if null
*/
public static String capitalize(String str) {
return changeFirstCharacterCase(str, true);
}
/**
* Uncapitalize a <code>String</code>, changing the first letter to
* lower case as per {@link Character#toLowerCase(char)}.
* No other letters are changed.
*
* @param str the String to uncapitalize, may be <code>null</code>
* @return the uncapitalized String, <code>null</code> if null
*/
public static String uncapitalize(String str) {
return changeFirstCharacterCase(str, false);
}
private static String changeFirstCharacterCase(String str, boolean capitalize) {
if (str == null || str.length() == 0) {
return str;
}
StringBuilder sb = new StringBuilder(str.length());
if (capitalize) {
sb.append(Character.toUpperCase(str.charAt(0)));
} else {
sb.append(Character.toLowerCase(str.charAt(0)));
}
sb.append(str.substring(1));
return sb.toString();
}
public static final ImmutableSet<Character> INVALID_FILENAME_CHARS = ImmutableSet.of('\\', '/', '*', '?', '"', '<', '>', '|', ' ', ',');
public static boolean validFileName(String fileName) {
for (int i = 0; i < fileName.length(); i++) {
char c = fileName.charAt(i);
if (INVALID_FILENAME_CHARS.contains(c)) {
return false;
}
}
return true;
}
public static boolean validFileNameExcludingAstrix(String fileName) {
for (int i = 0; i < fileName.length(); i++) {
char c = fileName.charAt(i);
if (c != '*' && INVALID_FILENAME_CHARS.contains(c)) {
return false;
}
}
return true;
}
/**
* Extract the filename from the given path,
* e.g. "mypath/myfile.txt" -> "myfile.txt".
*
* @param path the file path (may be <code>null</code>)
* @return the extracted filename, or <code>null</code> if none
*/
public static String getFilename(String path) {
if (path == null) {
return null;
}
int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);
}
/**
* Extract the filename extension from the given path,
* e.g. "mypath/myfile.txt" -> "txt".
*
* @param path the file path (may be <code>null</code>)
* @return the extracted filename extension, or <code>null</code> if none
*/
public static String getFilenameExtension(String path) {
if (path == null) {
return null;
}
int sepIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
return (sepIndex != -1 ? path.substring(sepIndex + 1) : null);
}
/**
* Strip the filename extension from the given path,
* e.g. "mypath/myfile.txt" -> "mypath/myfile".
*
* @param path the file path (may be <code>null</code>)
* @return the path with stripped filename extension,
* or <code>null</code> if none
*/
public static String stripFilenameExtension(String path) {
if (path == null) {
return null;
}
int sepIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
return (sepIndex != -1 ? path.substring(0, sepIndex) : path);
}
/**
* Apply the given relative path to the given path,
* assuming standard Java folder separation (i.e. "/" separators);
*
* @param path the path to start from (usually a full file path)
* @param relativePath the relative path to apply
* (relative to the full file path above)
* @return the full file path that results from applying the relative path
*/
public static String applyRelativePath(String path, String relativePath) {
int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
if (separatorIndex != -1) {
String newPath = path.substring(0, separatorIndex);
if (!relativePath.startsWith(FOLDER_SEPARATOR)) {
newPath += FOLDER_SEPARATOR;
}
return newPath + relativePath;
} else {
return relativePath;
}
}
/**
* Normalize the path by suppressing sequences like "path/.." and
* inner simple dots.
* <p>The result is convenient for path comparison. For other uses,
* notice that Windows separators ("\") are replaced by simple slashes.
*
* @param path the original path
* @return the normalized path
*/
public static String cleanPath(String path) {
if (path == null) {
return null;
}
String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);
// Strip prefix from path to analyze, to not treat it as part of the
// first path element. This is necessary to correctly parse paths like
// "file:core/../core/io/Resource.class", where the ".." should just
// strip the first "core" directory while keeping the "file:" prefix.
int prefixIndex = pathToUse.indexOf(":");
String prefix = "";
if (prefixIndex != -1) {
prefix = pathToUse.substring(0, prefixIndex + 1);
pathToUse = pathToUse.substring(prefixIndex + 1);
}
if (pathToUse.startsWith(FOLDER_SEPARATOR)) {
prefix = prefix + FOLDER_SEPARATOR;
pathToUse = pathToUse.substring(1);
}
String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);
List<String> pathElements = new LinkedList<String>();
int tops = 0;
for (int i = pathArray.length - 1; i >= 0; i--) {
String element = pathArray[i];
if (CURRENT_PATH.equals(element)) {
// Points to current directory - drop it.
} else if (TOP_PATH.equals(element)) {
// Registering top path found.
tops++;
} else {
if (tops > 0) {
// Merging path element with element corresponding to top path.
tops--;
} else {
// Normal path element found.
pathElements.add(0, element);
}
}
}
// Remaining top paths need to be retained.
for (int i = 0; i < tops; i++) {
pathElements.add(0, TOP_PATH);
}
return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);
}
/**
* Compare two paths after normalization of them.
*
* @param path1 first path for comparison
* @param path2 second path for comparison
* @return whether the two paths are equivalent after normalization
*/
public static boolean pathEquals(String path1, String path2) {
return cleanPath(path1).equals(cleanPath(path2));
}
/**
* Parse the given <code>localeString</code> into a {@link Locale}.
* <p>This is the inverse operation of {@link Locale#toString Locale's toString}.
*
* @param localeString the locale string, following <code>Locale's</code>
* <code>toString()</code> format ("en", "en_UK", etc);
* also accepts spaces as separators, as an alternative to underscores
* @return a corresponding <code>Locale</code> instance
*/
public static Locale parseLocaleString(String localeString) {
String[] parts = tokenizeToStringArray(localeString, "_ ", false, false);
String language = (parts.length != 0 ? parts[0] : "");
String country = (parts.length > 1 ? parts[1] : "");
String variant = "";
if (parts.length >= 2) {
// There is definitely a variant, and it is everything after the country
// code sans the separator between the country code and the variant.
int endIndexOfCountryCode = localeString.indexOf(country) + country.length();
// Strip off any leading '_' and whitespace, what's left is the variant.
variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));
if (variant.startsWith("_")) {
variant = trimLeadingCharacter(variant, '_');
}
}
return (language.length() > 0 ? new Locale(language, country, variant) : null);
}
/**
* Determine the RFC 3066 compliant language tag,
* as used for the HTTP "Accept-Language" header.
*
* @param locale the Locale to transform to a language tag
* @return the RFC 3066 compliant language tag as String
*/
public static String toLanguageTag(Locale locale) {
return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : "");
}
//---------------------------------------------------------------------
// Convenience methods for working with String arrays
//---------------------------------------------------------------------
/**
* Append the given String to the given String array, returning a new array
* consisting of the input array contents plus the given String.
*
* @param array the array to append to (can be <code>null</code>)
* @param str the String to append
* @return the new array (never <code>null</code>)
*/
public static String[] addStringToArray(String[] array, String str) {
if (isEmpty(array)) {
return new String[]{str};
}
String[] newArr = new String[array.length + 1];
System.arraycopy(array, 0, newArr, 0, array.length);
newArr[array.length] = str;
return newArr;
}
/**
* Concatenate the given String arrays into one,
* with overlapping array elements included twice.
* <p>The order of elements in the original arrays is preserved.
*
* @param array1 the first array (can be <code>null</code>)
* @param array2 the second array (can be <code>null</code>)
* @return the new array (<code>null</code> if both given arrays were <code>null</code>)
*/
public static String[] concatenateStringArrays(String[] array1, String[] array2) {
if (isEmpty(array1)) {
return array2;
}
if (isEmpty(array2)) {
return array1;
}
String[] newArr = new String[array1.length + array2.length];
System.arraycopy(array1, 0, newArr, 0, array1.length);
System.arraycopy(array2, 0, newArr, array1.length, array2.length);
return newArr;
}
/**
* Merge the given String arrays into one, with overlapping
* array elements only included once.
* <p>The order of elements in the original arrays is preserved
* (with the exception of overlapping elements, which are only
* included on their first occurence).
*
* @param array1 the first array (can be <code>null</code>)
* @param array2 the second array (can be <code>null</code>)
* @return the new array (<code>null</code> if both given arrays were <code>null</code>)
*/
public static String[] mergeStringArrays(String[] array1, String[] array2) {
if (isEmpty(array1)) {
return array2;
}
if (isEmpty(array2)) {
return array1;
}
List<String> result = new ArrayList<String>();
result.addAll(Arrays.asList(array1));
for (String str : array2) {
if (!result.contains(str)) {
result.add(str);
}
}
return toStringArray(result);
}
/**
* Turn given source String array into sorted array.
*
* @param array the source array
* @return the sorted array (never <code>null</code>)
*/
public static String[] sortStringArray(String[] array) {
if (isEmpty(array)) {
return new String[0];
}
Arrays.sort(array);
return array;
}
/**
* Copy the given Collection into a String array.
* The Collection must contain String elements only.
*
* @param collection the Collection to copy
* @return the String array (<code>null</code> if the passed-in
* Collection was <code>null</code>)
*/
public static String[] toStringArray(Collection<String> collection) {
if (collection == null) {
return null;
}
return collection.toArray(new String[collection.size()]);
}
/**
* Copy the given Enumeration into a String array.
* The Enumeration must contain String elements only.
*
* @param enumeration the Enumeration to copy
* @return the String array (<code>null</code> if the passed-in
* Enumeration was <code>null</code>)
*/
public static String[] toStringArray(Enumeration<String> enumeration) {
if (enumeration == null) {
return null;
}
List<String> list = Collections.list(enumeration);
return list.toArray(new String[list.size()]);
}
/**
* Trim the elements of the given String array,
* calling <code>String.trim()</code> on each of them.
*
* @param array the original String array
* @return the resulting array (of the same size) with trimmed elements
*/
public static String[] trimArrayElements(String[] array) {
if (isEmpty(array)) {
return new String[0];
}
String[] result = new String[array.length];
for (int i = 0; i < array.length; i++) {
String element = array[i];
result[i] = (element != null ? element.trim() : null);
}
return result;
}
/**
* Remove duplicate Strings from the given array.
* Also sorts the array, as it uses a TreeSet.
*
* @param array the String array
* @return an array without duplicates, in natural sort order
*/
public static String[] removeDuplicateStrings(String[] array) {
if (isEmpty(array)) {
return array;
}
Set<String> set = new TreeSet<String>();
set.addAll(Arrays.asList(array));
return toStringArray(set);
}
public static Set<String> splitStringByCommaToSet(final String s) {
return splitStringToSet(s, ',');
}
public static String[] splitStringByCommaToArray(final String s) {
return splitStringToArray(s, ',');
}
public static Set<String> splitStringToSet(final String s, final char c) {
final char[] chars = s.toCharArray();
int count = 1;
for (final char x : chars) {
if (x == c) {
count++;
}
}
// TODO (MvG): No push: hppc or jcf?
final Set<String> result = new HashSet<String>(count);
final int len = chars.length;
int start = 0; // starting index in chars of the current substring.
int pos = 0; // current index in chars.
for (; pos < len; pos++) {
if (chars[pos] == c) {
int size = pos - start;
if (size > 0) { // only add non empty strings
result.add(new String(chars, start, size));
}
start = pos + 1;
}
}
int size = pos - start;
if (size > 0) {
result.add(new String(chars, start, size));
}
return result;
}
public static String[] splitStringToArray(final CharSequence s, final char c) {
if (s == null || s.length() == 0) {
return Strings.EMPTY_ARRAY;
}
int count = 1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
count++;
}
}
final String[] result = new String[count];
final StringBuilder builder = new StringBuilder();
int res = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
if (builder.length() > 0) {
result[res++] = builder.toString();
builder.setLength(0);
}
} else {
builder.append(s.charAt(i));
}
}
if (builder.length() > 0) {
result[res++] = builder.toString();
}
if (res != count) {
// we have empty strings, copy over to a new array
String[] result1 = new String[res];
System.arraycopy(result, 0, result1, 0, res);
return result1;
}
return result;
}
/**
* Split a String at the first occurrence of the delimiter.
* Does not include the delimiter in the result.
*
* @param toSplit the string to split
* @param delimiter to split the string up with
* @return a two element array with index 0 being before the delimiter, and
* index 1 being after the delimiter (neither element includes the delimiter);
* or <code>null</code> if the delimiter wasn't found in the given input String
*/
public static String[] split(String toSplit, String delimiter) {
if (!hasLength(toSplit) || !hasLength(delimiter)) {
return null;
}
int offset = toSplit.indexOf(delimiter);
if (offset < 0) {
return null;
}
String beforeDelimiter = toSplit.substring(0, offset);
String afterDelimiter = toSplit.substring(offset + delimiter.length());
return new String[]{beforeDelimiter, afterDelimiter};
}
/**
* Take an array Strings and split each element based on the given delimiter.
* A <code>Properties</code> instance is then generated, with the left of the
* delimiter providing the key, and the right of the delimiter providing the value.
* <p>Will trim both the key and value before adding them to the
* <code>Properties</code> instance.
*
* @param array the array to process
* @param delimiter to split each element using (typically the equals symbol)
* @return a <code>Properties</code> instance representing the array contents,
* or <code>null</code> if the array to process was null or empty
*/
public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {
return splitArrayElementsIntoProperties(array, delimiter, null);
}
/**
* Take an array Strings and split each element based on the given delimiter.
* A <code>Properties</code> instance is then generated, with the left of the
* delimiter providing the key, and the right of the delimiter providing the value.
* <p>Will trim both the key and value before adding them to the
* <code>Properties</code> instance.
*
* @param array the array to process
* @param delimiter to split each element using (typically the equals symbol)
* @param charsToDelete one or more characters to remove from each element
* prior to attempting the split operation (typically the quotation mark
* symbol), or <code>null</code> if no removal should occur
* @return a <code>Properties</code> instance representing the array contents,
* or <code>null</code> if the array to process was <code>null</code> or empty
*/
public static Properties splitArrayElementsIntoProperties(
String[] array, String delimiter, String charsToDelete) {
if (isEmpty(array)) {
return null;
}
Properties result = new Properties();
for (String element : array) {
if (charsToDelete != null) {
element = deleteAny(element, charsToDelete);
}
String[] splittedElement = split(element, delimiter);
if (splittedElement == null) {
continue;
}
result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());
}
return result;
}
/**
* Tokenize the given String into a String array via a StringTokenizer.
* Trims tokens and omits empty tokens.
* <p>The given delimiters string is supposed to consist of any number of
* delimiter characters. Each of those characters can be used to separate
* tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using <code>delimitedListToStringArray</code>
*
* @param str the String to tokenize
* @param delimiters the delimiter characters, assembled as String
* (each of those characters is individually considered as delimiter).
* @return an array of the tokens
* @see java.util.StringTokenizer
* @see java.lang.String#trim()
* @see #delimitedListToStringArray
*/
public static String[] tokenizeToStringArray(String str, String delimiters) {
return tokenizeToStringArray(str, delimiters, true, true);
}
/**
* Tokenize the given String into a String array via a StringTokenizer.
* <p>The given delimiters string is supposed to consist of any number of
* delimiter characters. Each of those characters can be used to separate
* tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using <code>delimitedListToStringArray</code>
*
* @param str the String to tokenize
* @param delimiters the delimiter characters, assembled as String
* (each of those characters is individually considered as delimiter)
* @param trimTokens trim the tokens via String's <code>trim</code>
* @param ignoreEmptyTokens omit empty tokens from the result array
* (only applies to tokens that are empty after trimming; StringTokenizer
* will not consider subsequent delimiters as token in the first place).
* @return an array of the tokens (<code>null</code> if the input String
* was <code>null</code>)
* @see java.util.StringTokenizer
* @see java.lang.String#trim()
* @see #delimitedListToStringArray
*/
public static String[] tokenizeToStringArray(
String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {
if (str == null) {
return null;
}
StringTokenizer st = new StringTokenizer(str, delimiters);
List<String> tokens = new ArrayList<String>();
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (trimTokens) {
token = token.trim();
}
if (!ignoreEmptyTokens || token.length() > 0) {
tokens.add(token);
}
}
return toStringArray(tokens);
}
/**
* Take a String which is a delimited list and convert it to a String array.
* <p>A single delimiter can consists of more than one character: It will still
* be considered as single delimiter string, rather than as bunch of potential
* delimiter characters - in contrast to <code>tokenizeToStringArray</code>.
*
* @param str the input String
* @param delimiter the delimiter between elements (this is a single delimiter,
* rather than a bunch individual delimiter characters)
* @return an array of the tokens in the list
* @see #tokenizeToStringArray
*/
public static String[] delimitedListToStringArray(String str, String delimiter) {
return delimitedListToStringArray(str, delimiter, null);
}
/**
* Take a String which is a delimited list and convert it to a String array.
* <p>A single delimiter can consists of more than one character: It will still
* be considered as single delimiter string, rather than as bunch of potential
* delimiter characters - in contrast to <code>tokenizeToStringArray</code>.
*
* @param str the input String
* @param delimiter the delimiter between elements (this is a single delimiter,
* rather than a bunch individual delimiter characters)
* @param charsToDelete a set of characters to delete. Useful for deleting unwanted
* line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String.
* @return an array of the tokens in the list
* @see #tokenizeToStringArray
*/
public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {
if (str == null) {
return new String[0];
}
if (delimiter == null) {
return new String[]{str};
}
List<String> result = new ArrayList<String>();
if ("".equals(delimiter)) {
for (int i = 0; i < str.length(); i++) {
result.add(deleteAny(str.substring(i, i + 1), charsToDelete));
}
} else {
int pos = 0;
int delPos;
while ((delPos = str.indexOf(delimiter, pos)) != -1) {
result.add(deleteAny(str.substring(pos, delPos), charsToDelete));
pos = delPos + delimiter.length();
}
if (str.length() > 0 && pos <= str.length()) {
// Add rest of String, but not in case of empty input.
result.add(deleteAny(str.substring(pos), charsToDelete));
}
}
return toStringArray(result);
}
/**
* Convert a CSV list into an array of Strings.
*
* @param str the input String
* @return an array of Strings, or the empty array in case of empty input
*/
public static String[] commaDelimitedListToStringArray(String str) {
return delimitedListToStringArray(str, ",");
}
/**
* Convenience method to convert a CSV string list to a set.
* Note that this will suppress duplicates.
*
* @param str the input String
* @return a Set of String entries in the list
*/
public static Set<String> commaDelimitedListToSet(String str) {
Set<String> set = new TreeSet<String>();
String[] tokens = commaDelimitedListToStringArray(str);
set.addAll(Arrays.asList(tokens));
return set;
}
/**
* Convenience method to return a Collection as a delimited (e.g. CSV)
* String. E.g. useful for <code>toString()</code> implementations.
*
* @param coll the Collection to display
* @param delim the delimiter to use (probably a ",")
* @param prefix the String to start each element with
* @param suffix the String to end each element with
* @return the delimited String
*/
public static String collectionToDelimitedString(Iterable<?> coll, String delim, String prefix, String suffix) {
return collectionToDelimitedString(coll, delim, prefix, suffix, new StringBuilder());
}
public static String collectionToDelimitedString(Iterable<?> coll, String delim, String prefix, String suffix, StringBuilder sb) {
if (Iterables.isEmpty(coll)) {
return "";
}
Iterator<?> it = coll.iterator();
while (it.hasNext()) {
sb.append(prefix).append(it.next()).append(suffix);
if (it.hasNext()) {
sb.append(delim);
}
}
return sb.toString();
}
/**
* Convenience method to return a Collection as a delimited (e.g. CSV)
* String. E.g. useful for <code>toString()</code> implementations.
*
* @param coll the Collection to display
* @param delim the delimiter to use (probably a ",")
* @return the delimited String
*/
public static String collectionToDelimitedString(Iterable<?> coll, String delim) {
return collectionToDelimitedString(coll, delim, "", "");
}
/**
* Convenience method to return a Collection as a CSV String.
* E.g. useful for <code>toString()</code> implementations.
*
* @param coll the Collection to display
* @return the delimited String
*/
public static String collectionToCommaDelimitedString(Iterable<?> coll) {
return collectionToDelimitedString(coll, ",");
}
/**
* Convenience method to return a String array as a delimited (e.g. CSV)
* String. E.g. useful for <code>toString()</code> implementations.
*
* @param arr the array to display
* @param delim the delimiter to use (probably a ",")
* @return the delimited String
*/
public static String arrayToDelimitedString(Object[] arr, String delim) {
return arrayToDelimitedString(arr, delim, new StringBuilder());
}
public static String arrayToDelimitedString(Object[] arr, String delim, StringBuilder sb) {
if (isEmpty(arr)) {
return "";
}
for (int i = 0; i < arr.length; i++) {
if (i > 0) {
sb.append(delim);
}
sb.append(arr[i]);
}
return sb.toString();
}
/**
* Convenience method to return a String array as a CSV String.
* E.g. useful for <code>toString()</code> implementations.
*
* @param arr the array to display
* @return the delimited String
*/
public static String arrayToCommaDelimitedString(Object[] arr) {
return arrayToDelimitedString(arr, ",");
}
/**
* Format the double value with a single decimal points, trimming trailing '.0'.
*/
public static String format1Decimals(double value, String suffix) {
String p = String.valueOf(value);
int ix = p.indexOf('.') + 1;
int ex = p.indexOf('E');
char fraction = p.charAt(ix);
if (fraction == '0') {
if (ex != -1) {
return p.substring(0, ix - 1) + p.substring(ex) + suffix;
} else {
return p.substring(0, ix - 1) + suffix;
}
} else {
if (ex != -1) {
return p.substring(0, ix) + fraction + p.substring(ex) + suffix;
} else {
return p.substring(0, ix) + fraction + suffix;
}
}
}
public static String toCamelCase(String value) {
return toCamelCase(value, null);
}
public static String toCamelCase(String value, StringBuilder sb) {
boolean changed = false;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '_') {
if (!changed) {
if (sb != null) {
sb.setLength(0);
} else {
sb = new StringBuilder();
}
// copy it over here
for (int j = 0; j < i; j++) {
sb.append(value.charAt(j));
}
changed = true;
}
sb.append(Character.toUpperCase(value.charAt(++i)));
} else {
if (changed) {
sb.append(c);
}
}
}
if (!changed) {
return value;
}
return sb.toString();
}
public static String toUnderscoreCase(String value) {
return toUnderscoreCase(value, null);
}
public static String toUnderscoreCase(String value, StringBuilder sb) {
boolean changed = false;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (Character.isUpperCase(c)) {
if (!changed) {
if (sb != null) {
sb.setLength(0);
} else {
sb = new StringBuilder();
}
// copy it over here
for (int j = 0; j < i; j++) {
sb.append(value.charAt(j));
}
changed = true;
if (i == 0) {
sb.append(Character.toLowerCase(c));
} else {
sb.append('_');
sb.append(Character.toLowerCase(c));
}
} else {
sb.append('_');
sb.append(Character.toLowerCase(c));
}
} else {
if (changed) {
sb.append(c);
}
}
}
if (!changed) {
return value;
}
return sb.toString();
}
/**
* Determine whether the given array is empty:
* i.e. <code>null</code> or of zero length.
*
* @param array the array to check
*/
private static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
private Strings() {
}
public static byte[] toUTF8Bytes(CharSequence charSequence) {
return toUTF8Bytes(charSequence, new BytesRef());
}
public static byte[] toUTF8Bytes(CharSequence charSequence, BytesRef spare) {
UnicodeUtil.UTF16toUTF8(charSequence, 0, charSequence.length(), spare);
final byte[] bytes = new byte[spare.length];
System.arraycopy(spare.bytes, spare.offset, bytes, 0, bytes.length);
return bytes;
}
private static class SecureRandomHolder {
// class loading is atomic - this is a lazy & safe singleton
private static final SecureRandom INSTANCE = new SecureRandom();
}
/**
* Returns a Base64 encoded version of a Version 4.0 compatible UUID
* as defined here: http://www.ietf.org/rfc/rfc4122.txt
*/
public static String randomBase64UUID() {
return randomBase64UUID(SecureRandomHolder.INSTANCE);
}
/**
* Returns a Base64 encoded version of a Version 4.0 compatible UUID
* randomly initialized by the given {@link Random} instance
* as defined here: http://www.ietf.org/rfc/rfc4122.txt
*/
public static String randomBase64UUID(Random random) {
final byte[] randomBytes = new byte[16];
random.nextBytes(randomBytes);
/* Set the version to version 4 (see http://www.ietf.org/rfc/rfc4122.txt)
* The randomly or pseudo-randomly generated version.
* The version number is in the most significant 4 bits of the time
* stamp (bits 4 through 7 of the time_hi_and_version field).*/
randomBytes[6] &= 0x0f; /* clear the 4 most significant bits for the version */
randomBytes[6] |= 0x40; /* set the version to 0100 / 0x40 */
/* Set the variant:
* The high field of th clock sequence multiplexed with the variant.
* We set only the MSB of the variant*/
randomBytes[8] &= 0x3f; /* clear the 2 most significant bits */
randomBytes[8] |= 0x80; /* set the variant (MSB is set)*/
try {
byte[] encoded = Base64.encodeBytesToBytes(randomBytes, 0, randomBytes.length, Base64.URL_SAFE);
// we know the bytes are 16, and not a multi of 3, so remove the 2 padding chars that are added
assert encoded[encoded.length - 1] == '=';
assert encoded[encoded.length - 2] == '=';
// we always have padding of two at the end, encode it differently
return new String(encoded, 0, encoded.length - 2, Base64.PREFERRED_ENCODING);
} catch (IOException e) {
throw new ElasticsearchIllegalStateException("should not be thrown");
}
}
/**
* Return substring(beginIndex, endIndex) that is impervious to string length.
*/
public static String substring(String s, int beginIndex, int endIndex) {
if (s == null) {
return s;
}
int realEndIndex = s.length() > 0 ? s.length() - 1 : 0;
if (endIndex > realEndIndex) {
return s.substring(beginIndex);
} else {
return s.substring(beginIndex, endIndex);
}
}
/**
* If an array only consists of zero or one element, which is "*" or "_all" return an empty array
* which is usually used as everything
*/
public static boolean isAllOrWildcard(String[] data) {
return CollectionUtils.isEmpty(data) ||
data.length == 1 && ("_all".equals(data[0]) || "*".equals(data[0]));
}
} | 0true
| src_main_java_org_elasticsearch_common_Strings.java |
1,542 | @SuppressWarnings({ "rawtypes", "unchecked" })
public class OObjectSerializerContext implements OObjectSerializer<Object, Object> {
final private Map<Class<?>, OObjectSerializer> customSerializers = new LinkedHashMap<Class<?>, OObjectSerializer>();
public void bind(final OObjectSerializer serializer) {
final Type[] actualTypes = OReflectionHelper.getGenericTypes(serializer.getClass());
if (actualTypes[0] instanceof Class<?>) {
customSerializers.put((Class<?>) actualTypes[0], serializer);
OObjectEntityClassHandler.getInstance().deregisterEntityClass((Class<?>) actualTypes[0]);
} else if (actualTypes[0] instanceof ParameterizedType) {
customSerializers.put((Class<?>) ((ParameterizedType) actualTypes[0]).getRawType(), serializer);
OObjectEntityClassHandler.getInstance().deregisterEntityClass((Class<?>) ((ParameterizedType) actualTypes[0]).getRawType());
}
}
public void unbind(final OObjectSerializer serializer) {
final Type genericType = serializer.getClass().getGenericInterfaces()[0];
if (genericType != null && genericType instanceof ParameterizedType) {
final ParameterizedType pt = (ParameterizedType) genericType;
if (pt.getActualTypeArguments() != null && pt.getActualTypeArguments().length > 1) {
final Type[] actualTypes = pt.getActualTypeArguments();
if (actualTypes[0] instanceof Class<?>) {
customSerializers.remove((Class<?>) actualTypes[0]);
} else if (actualTypes[0] instanceof ParameterizedType) {
customSerializers.remove((Class<?>) ((ParameterizedType) actualTypes[0]).getRawType());
}
}
}
}
public boolean isClassBinded(Class<?> iClass) {
return customSerializers.get(iClass) != null;
}
public Object serializeFieldValue(final Class<?> iClass, Object iFieldValue) {
for (Class<?> type : customSerializers.keySet()) {
if (type.isInstance(iFieldValue) || (iFieldValue == null && type == Void.class)) {
iFieldValue = customSerializers.get(type).serializeFieldValue(iClass, iFieldValue);
break;
}
}
return iFieldValue;
}
public Object unserializeFieldValue(final Class<?> iClass, final Object iFieldValue) {
if (iClass != null)
for (Class<?> type : customSerializers.keySet()) {
if (type.isAssignableFrom(iClass) || type == Void.class) {
return customSerializers.get(type).unserializeFieldValue(iClass, iFieldValue);
}
}
return iFieldValue;
}
} | 0true
| object_src_main_java_com_orientechnologies_orient_object_serialization_OObjectSerializerContext.java |
91 | public interface ObjectToLong<A> { long apply(A a); } | 0true
| src_main_java_jsr166e_ConcurrentHashMapV8.java |
374 | public class ODatabaseBinary extends ODatabaseRecordTx {
public ODatabaseBinary(String iURL) {
super(iURL, ORecordBytes.RECORD_TYPE);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_record_ODatabaseBinary.java |
2,826 | public final class CJKWidthFilterFactory extends AbstractTokenFilterFactory {
@Inject
public CJKWidthFilterFactory(Index index, Settings indexSettings, String name, Settings settings) {
super(index, indexSettings, name, settings);
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new CJKWidthFilter(tokenStream);
}
} | 0true
| src_main_java_org_elasticsearch_index_analysis_CJKWidthFilterFactory.java |
745 | public interface CheckoutService {
public CheckoutResponse performCheckout(Order order) throws CheckoutException;
public CheckoutResponse performCheckout(Order order, Map<PaymentInfo, Referenced> payments) throws CheckoutException;
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_checkout_service_CheckoutService.java |
987 | public static class Name {
public static final String OrderItems = "OrderImpl_Order_Items_Tab";
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_DiscreteOrderItemImpl.java |
1,076 | public class OSQLScriptEngineFactory implements ScriptEngineFactory {
private static final List<String> NAMES = new ArrayList<String>();
private static final List<String> EXTENSIONS = new ArrayList<String>();
static {
NAMES.add(OSQLScriptEngine.NAME);
EXTENSIONS.add(OSQLScriptEngine.NAME);
}
@Override
public String getEngineName() {
return OSQLScriptEngine.NAME;
}
@Override
public String getEngineVersion() {
return OConstants.ORIENT_VERSION;
}
@Override
public List<String> getExtensions() {
return EXTENSIONS;
}
@Override
public List<String> getMimeTypes() {
return null;
}
@Override
public List<String> getNames() {
return NAMES;
}
@Override
public String getLanguageName() {
return OSQLScriptEngine.NAME;
}
@Override
public String getLanguageVersion() {
return OConstants.ORIENT_VERSION;
}
@Override
public Object getParameter(String key) {
return null;
}
@Override
public String getMethodCallSyntax(String obj, String m, String... args) {
return null;
}
@Override
public String getOutputStatement(String toDisplay) {
return null;
}
@Override
public String getProgram(String... statements) {
final StringBuilder buffer = new StringBuilder();
for (String s : statements)
buffer.append(s).append(";\n");
return buffer.toString();
}
@Override
public ScriptEngine getScriptEngine() {
return new OSQLScriptEngine(this);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_sql_OSQLScriptEngineFactory.java |
1,147 | public class ParentChildIndexGenerator {
private final static Random RANDOM = new Random();
private final Client client;
private final int numParents;
private final int numChildrenPerParent;
private final int queryValueRatio;
public ParentChildIndexGenerator(Client client, int numParents, int numChildrenPerParent, int queryValueRatio) {
this.client = client;
this.numParents = numParents;
this.numChildrenPerParent = numChildrenPerParent;
this.queryValueRatio = queryValueRatio;
}
public void index() {
// Memory intensive...
ObjectOpenHashSet<String> usedParentIds = ObjectOpenHashSet.newInstanceWithCapacity(numParents, 0.5f);
ObjectArrayList<ParentDocument> parents = ObjectArrayList.newInstanceWithCapacity(numParents);
for (int i = 0; i < numParents; i++) {
String parentId;
do {
parentId = RandomStrings.randomAsciiOfLength(RANDOM, 10);
} while (!usedParentIds.add(parentId));
String[] queryValues = new String[numChildrenPerParent];
for (int j = 0; j < numChildrenPerParent; j++) {
queryValues[j] = getQueryValue();
}
parents.add(new ParentDocument(parentId, queryValues));
}
int indexCounter = 0;
int childIdCounter = 0;
while (!parents.isEmpty()) {
BulkRequestBuilder request = client.prepareBulk();
for (int i = 0; !parents.isEmpty() && i < 100; i++) {
int index = RANDOM.nextInt(parents.size());
ParentDocument parentDocument = parents.get(index);
if (parentDocument.indexCounter == -1) {
request.add(Requests.indexRequest("test").type("parent")
.id(parentDocument.parentId)
.source("field1", getQueryValue()));
} else {
request.add(Requests.indexRequest("test").type("child")
.parent(parentDocument.parentId)
.id(String.valueOf(++childIdCounter))
.source("field2", parentDocument.queryValues[parentDocument.indexCounter]));
}
if (++parentDocument.indexCounter == parentDocument.queryValues.length) {
parents.remove(index);
}
}
BulkResponse response = request.execute().actionGet();
if (response.hasFailures()) {
System.err.println("--> failures...");
}
indexCounter += response.getItems().length;
if (indexCounter % 100000 == 0) {
System.out.println("--> Indexed " + indexCounter + " documents");
}
}
}
public String getQueryValue() {
return "value" + RANDOM.nextInt(numChildrenPerParent / queryValueRatio);
}
class ParentDocument {
final String parentId;
final String[] queryValues;
int indexCounter;
ParentDocument(String parentId, String[] queryValues) {
this.parentId = parentId;
this.queryValues = queryValues;
this.indexCounter = -1;
}
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_search_child_ParentChildIndexGenerator.java |
105 | static final class ValueIterator<K,V> extends BaseIterator<K,V>
implements Iterator<V>, Enumeration<V> {
ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
ConcurrentHashMapV8<K,V> map) {
super(tab, index, size, limit, map);
}
public final V next() {
Node<K,V> p;
if ((p = next) == null)
throw new NoSuchElementException();
V v = p.val;
lastReturned = p;
advance();
return v;
}
public final V nextElement() { return next(); }
} | 0true
| src_main_java_jsr166e_ConcurrentHashMapV8.java |
681 | constructors[LIST_GET] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new ListGetOperation();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java |
473 | private class CleanupThread extends Thread {
private boolean stop = false;
public CleanupThread() {
this.setDaemon(true);
this.setName("ExpirationStoreCache-" + getId());
}
@Override
public void run() {
while (true) {
if (stop) return;
try {
penaltyCountdown.await();
} catch (InterruptedException e) {
if (stop) return;
else throw new RuntimeException("Cleanup thread got interrupted",e);
}
//Do clean up work by invalidating all entries for expired keys
HashMap<StaticBuffer,Long> expiredKeysCopy = new HashMap<StaticBuffer,Long>(expiredKeys.size());
for (Map.Entry<StaticBuffer,Long> expKey : expiredKeys.entrySet()) {
if (isBeyondExpirationTime(expKey.getValue()))
expiredKeys.remove(expKey.getKey(), expKey.getValue());
else if (getAge(expKey.getValue())>= invalidationGracePeriodMS)
expiredKeysCopy.put(expKey.getKey(),expKey.getValue());
}
for (KeySliceQuery ksq : cache.asMap().keySet()) {
if (expiredKeysCopy.containsKey(ksq.getKey())) cache.invalidate(ksq);
}
penaltyCountdown = new CountDownLatch(PENALTY_THRESHOLD);
for (Map.Entry<StaticBuffer,Long> expKey : expiredKeysCopy.entrySet()) {
expiredKeys.remove(expKey.getKey(),expKey.getValue());
}
}
}
void stopThread() {
stop = true;
this.interrupt();
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_cache_ExpirationKCVSCache.java |
302 | public abstract class OAbstractStorageClusterConfiguration implements OStorageClusterConfiguration {
public int id;
public String name;
public String location;
protected int dataSegmentId;
public OAbstractStorageClusterConfiguration(final String name, final int id, final int iDataSegmentId) {
this.name = name;
this.id = id;
this.dataSegmentId = iDataSegmentId;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public void setId(final int iId) {
id = iId;
}
public int getDataSegmentId() {
return dataSegmentId;
}
public String getLocation() {
return location;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_config_OAbstractStorageClusterConfiguration.java |
1,013 | execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response result) {
try {
channel.sendResponse(result);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response for get", e1);
}
}
}); | 0true
| src_main_java_org_elasticsearch_action_support_single_custom_TransportSingleCustomOperationAction.java |
831 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class AtomicReferenceInstanceSharingTest extends HazelcastTestSupport {
private static HazelcastInstance[] instances;
private static HazelcastInstance local;
private static HazelcastInstance remote;
@BeforeClass
public static void setUp() {
instances = new TestHazelcastInstanceFactory(2).newInstances();
warmUpPartitions(instances);
local = instances[0];
remote = instances[1];
}
@Test
public void invocationToLocalMember() throws ExecutionException, InterruptedException {
String localKey = generateKeyOwnedBy(local);
IAtomicReference<DummyObject> ref = local.getAtomicReference(localKey);
DummyObject inserted = new DummyObject();
ref.set(inserted);
DummyObject get1 = ref.get();
DummyObject get2 = ref.get();
assertNotNull(get1);
assertNotNull(get2);
assertNotSame(get1, get2);
assertNotSame(get1, inserted);
assertNotSame(get2, inserted);
}
public static class DummyObject implements Serializable {
}
@Test
public void invocationToRemoteMember() throws ExecutionException, InterruptedException {
String localKey = generateKeyOwnedBy(remote);
IAtomicReference<DummyObject> ref = local.getAtomicReference(localKey);
DummyObject inserted = new DummyObject();
ref.set(inserted);
DummyObject get1 = ref.get();
DummyObject get2 = ref.get();
assertNotNull(get1);
assertNotNull(get2);
assertNotSame(get1, get2);
assertNotSame(get1, inserted);
assertNotSame(get2, inserted);
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_concurrent_atomicreference_AtomicReferenceInstanceSharingTest.java |
1,177 | clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(clientHandler);
}
}); | 0true
| src_test_java_org_elasticsearch_benchmark_transport_netty_NettyEchoBenchmark.java |
1,377 | private static class CassandraMapIterable implements Iterable<Entry> {
private final SortedMap<ByteBuffer, Column> columnValues;
public CassandraMapIterable(final SortedMap<ByteBuffer, Column> columnValues) {
Preconditions.checkNotNull(columnValues);
this.columnValues = columnValues;
}
@Override
public Iterator<Entry> iterator() {
return new CassandraMapIterator(columnValues.entrySet().iterator());
}
} | 1no label
| titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_formats_cassandra_TitanCassandraHadoopGraph.java |
3,081 | static class Delete implements Operation {
private final String type;
private final String id;
private final Term uid;
private long version = Versions.MATCH_ANY;
private VersionType versionType = VersionType.INTERNAL;
private Origin origin = Origin.PRIMARY;
private boolean found;
private long startTime;
private long endTime;
public Delete(String type, String id, Term uid) {
this.type = type;
this.id = id;
this.uid = uid;
}
@Override
public Type opType() {
return Type.DELETE;
}
public Delete origin(Origin origin) {
this.origin = origin;
return this;
}
@Override
public Origin origin() {
return this.origin;
}
public String type() {
return this.type;
}
public String id() {
return this.id;
}
public Term uid() {
return this.uid;
}
public Delete version(long version) {
this.version = version;
return this;
}
/**
* before delete execution this is the version to be deleted. After this is the version of the "delete" transaction record.
*/
public long version() {
return this.version;
}
public Delete versionType(VersionType versionType) {
this.versionType = versionType;
return this;
}
public VersionType versionType() {
return this.versionType;
}
public boolean found() {
return this.found;
}
public Delete found(boolean found) {
this.found = found;
return this;
}
public Delete startTime(long startTime) {
this.startTime = startTime;
return this;
}
/**
* Returns operation start time in nanoseconds.
*/
public long startTime() {
return this.startTime;
}
public Delete endTime(long endTime) {
this.endTime = endTime;
return this;
}
/**
* Returns operation end time in nanoseconds.
*/
public long endTime() {
return this.endTime;
}
} | 0true
| src_main_java_org_elasticsearch_index_engine_Engine.java |
2,315 | static class DayTimeZoneRoundingFloor extends TimeZoneRounding {
final static byte ID = 3;
private DateTimeUnit unit;
private DateTimeZone preTz;
private DateTimeZone postTz;
DayTimeZoneRoundingFloor() { // for serialization
}
DayTimeZoneRoundingFloor(DateTimeUnit unit, DateTimeZone preTz, DateTimeZone postTz) {
this.unit = unit;
this.preTz = preTz;
this.postTz = postTz;
}
@Override
public byte id() {
return ID;
}
@Override
public long roundKey(long utcMillis) {
long time = utcMillis + preTz.getOffset(utcMillis);
return unit.field().roundFloor(time);
}
@Override
public long valueForKey(long time) {
// after rounding, since its day level (and above), its actually UTC!
// now apply post Tz
time = time + postTz.getOffset(time);
return time;
}
@Override
public long nextRoundingValue(long value) {
return unit.field().getDurationField().getUnitMillis() + value;
}
@Override
public void readFrom(StreamInput in) throws IOException {
unit = DateTimeUnit.resolve(in.readByte());
preTz = DateTimeZone.forID(in.readSharedString());
postTz = DateTimeZone.forID(in.readSharedString());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeByte(unit.id());
out.writeSharedString(preTz.getID());
out.writeSharedString(postTz.getID());
}
} | 0true
| src_main_java_org_elasticsearch_common_rounding_TimeZoneRounding.java |
325 | public interface ReadConfiguration {
public static final ReadConfiguration EMPTY = new ReadConfiguration() {
@Override
public<O> O get(String key, Class<O> datatype) {
return null;
}
@Override
public Iterable<String> getKeys(String prefix) {
return ImmutableList.of();
}
@Override
public void close() {
//Nothing
}
};
public<O> O get(String key, Class<O> datatype);
public Iterable<String> getKeys(String prefix);
public void close();
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_ReadConfiguration.java |
243 | weightComparator) {
private final Set<BytesRef> seen = new HashSet<BytesRef>();
@Override
protected boolean acceptResult(IntsRef input, Pair<Long,BytesRef> output) {
// Dedup: when the input analyzes to a graph we
// can get duplicate surface forms:
if (seen.contains(output.output2)) {
return false;
}
seen.add(output.output2);
if (!exactFirst) {
return true;
} else {
// In exactFirst mode, don't accept any paths
// matching the surface form since that will
// create duplicate results:
if (sameSurfaceForm(utf8Key, output.output2)) {
// We found exact match, which means we should
// have already found it in the first search:
assert results.size() == 1;
return false;
} else {
return true;
}
}
}
}; | 0true
| src_main_java_org_apache_lucene_search_suggest_analyzing_XAnalyzingSuggester.java |
3,485 | public static class ParseListenerAdapter implements ParseListener {
@Override
public boolean beforeFieldAdded(FieldMapper fieldMapper, Field fieldable, Object parseContext) {
return true;
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_DocumentMapper.java |
531 | @Deprecated
public class GatewaySnapshotAction extends IndicesAction<GatewaySnapshotRequest, GatewaySnapshotResponse, GatewaySnapshotRequestBuilder> {
public static final GatewaySnapshotAction INSTANCE = new GatewaySnapshotAction();
public static final String NAME = "indices/gateway/snapshot";
private GatewaySnapshotAction() {
super(NAME);
}
@Override
public GatewaySnapshotResponse newResponse() {
return new GatewaySnapshotResponse();
}
@Override
public GatewaySnapshotRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new GatewaySnapshotRequestBuilder(client);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_gateway_snapshot_GatewaySnapshotAction.java |
258 | final class FormatBlockAction extends Action {
private final CeylonEditor editor;
FormatBlockAction(CeylonEditor editor) {
super(null);
this.editor = editor;
}
@Override
public void run() {
IDocument document = editor.getCeylonSourceViewer().getDocument();
final ITextSelection ts = getSelection(editor);
CeylonParseController pc = editor.getParseController();
Tree.CompilationUnit rootNode = pc.getRootNode();
if (rootNode==null) return;
class FindBodyVisitor extends Visitor {
Node result;
private void handle(Node that) {
if (ts.getOffset()>=that.getStartIndex() &&
ts.getOffset()+ts.getLength()<=that.getStopIndex()+1) {
result = that;
}
}
@Override
public void visit(Tree.Body that) {
handle(that);
super.visit(that);
}
@Override
public void visit(Tree.NamedArgumentList that) {
handle(that);
super.visit(that);
}
@Override
public void visit(Tree.ImportMemberOrTypeList that) {
handle(that);
super.visit(that);
}
}
FindBodyVisitor fbv = new FindBodyVisitor();
fbv.visit(rootNode);
StringBuilder builder = new StringBuilder();
Node bodyNode = fbv.result;
if (bodyNode instanceof Tree.Body) {
Tree.Body body = (Tree.Body) bodyNode;
String bodyIndent = getIndent(findDeclarationWithBody(rootNode, body), document);
String indent = bodyIndent + getDefaultIndent();
String delim = getDefaultLineDelimiter(document);
if (!body.getStatements().isEmpty()) {
builder.append(delim);
for (Tree.Statement st: body.getStatements()) {
builder.append(indent)
.append(Nodes.toString(st, pc.getTokens()))
.append(delim);
}
builder.append(bodyIndent);
}
}
else if (bodyNode instanceof Tree.NamedArgumentList) {
Tree.NamedArgumentList body = (Tree.NamedArgumentList) bodyNode;
String bodyIndent = getIndent(body, document);
String indent = bodyIndent + getDefaultIndent();
String delim = getDefaultLineDelimiter(document);
if (!body.getNamedArguments().isEmpty()) {
for (Tree.NamedArgument st: body.getNamedArguments()) {
builder.append(indent)
.append(Nodes.toString(st, pc.getTokens()))
.append(delim);
}
}
if (body.getSequencedArgument()!=null) {
builder.append(indent)
.append(Nodes.toString(body.getSequencedArgument(),
pc.getTokens()))
.append(delim);
}
if (builder.length()!=0) {
builder.insert(0, delim);
builder.append(bodyIndent);
}
}
else if (bodyNode instanceof Tree.ImportMemberOrTypeList) {
Tree.ImportMemberOrTypeList body = (Tree.ImportMemberOrTypeList) bodyNode;
String bodyIndent = getIndent(body, document);
String indent = bodyIndent + getDefaultIndent();
String delim = getDefaultLineDelimiter(document);
if (!body.getImportMemberOrTypes().isEmpty()) {
for (Tree.ImportMemberOrType st: body.getImportMemberOrTypes()) {
builder.append(indent)
.append(Nodes.toString(st, pc.getTokens()))
.append(",")
.append(delim);
}
}
if (body.getImportWildcard()!=null) {
builder.append(indent)
.append(Nodes.toString(body.getImportWildcard(),
pc.getTokens()))
.append(delim);
}
if (builder.toString().endsWith(","+delim)) {
builder.setLength(builder.length()-1-delim.length());
builder.append(delim);
}
if (builder.length()!=0) {
builder.insert(0, delim);
builder.append(bodyIndent);
}
}
else {
return;
}
String text = builder.toString();
int start = bodyNode.getStartIndex()+1;
int len = bodyNode.getStopIndex()-bodyNode.getStartIndex()-1;
try {
if (!document.get(start, len).equals(text)) {
DocumentChange change =
new DocumentChange("Format Block", document);
change.setEdit(new ReplaceEdit(start, len, text));
change.perform(new NullProgressMonitor());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_FormatBlockAction.java |
130 | final ClientListener clientListener = new ClientListener() {
@Override
public void clientConnected(Client client) {
totalAdd.incrementAndGet();
latchAdd.countDown();
}
@Override
public void clientDisconnected(Client client) {
latchRemove.countDown();
}
}; | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_ClientServiceTest.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 |
1,445 | public class OCommandGremlinExecutor extends OCommandExecutorAbstract {
private ODatabaseDocumentTx db;
@SuppressWarnings("unchecked")
@Override
public <RET extends OCommandExecutor> RET parse(OCommandRequest iRequest) {
parserText = ((OCommandRequestText) iRequest).getText();
db = OGremlinHelper.getGraphDatabase(ODatabaseRecordThreadLocal.INSTANCE.get());
return (RET) this;
}
@Override
public Object execute(final Map<Object, Object> iArgs) {
parameters = iArgs;
final List<Object> result = new ArrayList<Object>();
final Object scriptResult = OGremlinHelper.execute(db, parserText, parameters, new HashMap<Object, Object>(), result, null,
null);
return scriptResult != null ? scriptResult : result;
}
@Override
public boolean isIdempotent() {
return false;
}
@Override
protected void throwSyntaxErrorException(String iText) {
throw new OCommandScriptException("Error on parsing of the script: " + iText);
}
} | 0true
| graphdb_src_main_java_com_orientechnologies_orient_graph_gremlin_OCommandGremlinExecutor.java |
224 | public class BerkeleyKeyValueTest extends KeyValueStoreTest {
@Override
public OrderedKeyValueStoreManager openStorageManager() throws BackendException {
return new BerkeleyJEStoreManager(BerkeleyStorageSetup.getBerkeleyJEConfiguration());
}
} | 0true
| titan-berkeleyje_src_test_java_com_thinkaurelius_titan_diskstorage_berkeleyje_BerkeleyKeyValueTest.java |
3,187 | public interface IndexFieldData<FD extends AtomicFieldData> extends IndexComponent {
public static class CommonSettings {
/**
* Should single value cross documents case be optimized to remove ords. Note, this optimization
* might not be supported by all Field Data implementations, but the ones that do, should consult
* this method to check if it should be done or not.
*/
public static boolean removeOrdsOnSingleValue(FieldDataType fieldDataType) {
return !"always".equals(fieldDataType.getSettings().get("ordinals"));
}
}
/**
* The field name.
*/
FieldMapper.Names getFieldNames();
/**
* Are the values ordered? (in ascending manner).
*/
boolean valuesOrdered();
/**
* Loads the atomic field data for the reader, possibly cached.
*/
FD load(AtomicReaderContext context);
/**
* Loads directly the atomic field data for the reader, ignoring any caching involved.
*/
FD loadDirect(AtomicReaderContext context) throws Exception;
/**
* Comparator used for sorting.
*/
XFieldComparatorSource comparatorSource(@Nullable Object missingValue, SortMode sortMode);
/**
* Clears any resources associated with this field data.
*/
void clear();
void clear(IndexReader reader);
// we need this extended source we we have custom comparators to reuse our field data
// in this case, we need to reduce type that will be used when search results are reduced
// on another node (we don't have the custom source them...)
public abstract class XFieldComparatorSource extends FieldComparatorSource {
/** UTF-8 term containing a single code point: {@link Character#MAX_CODE_POINT} which will compare greater than all other index terms
* since {@link Character#MAX_CODE_POINT} is a noncharacter and thus shouldn't appear in an index term. */
public static final BytesRef MAX_TERM;
static {
MAX_TERM = new BytesRef();
final char[] chars = Character.toChars(Character.MAX_CODE_POINT);
UnicodeUtil.UTF16toUTF8(chars, 0, chars.length, MAX_TERM);
}
/** Whether missing values should be sorted first. */
protected final boolean sortMissingFirst(Object missingValue) {
return "_first".equals(missingValue);
}
/** Whether missing values should be sorted last, this is the default. */
protected final boolean sortMissingLast(Object missingValue) {
return missingValue == null || "_last".equals(missingValue);
}
/** Return the missing object value according to the reduced type of the comparator. */
protected final Object missingObject(Object missingValue, boolean reversed) {
if (sortMissingFirst(missingValue) || sortMissingLast(missingValue)) {
final boolean min = sortMissingFirst(missingValue) ^ reversed;
switch (reducedType()) {
case INT:
return min ? Integer.MIN_VALUE : Integer.MAX_VALUE;
case LONG:
return min ? Long.MIN_VALUE : Long.MAX_VALUE;
case FLOAT:
return min ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
case DOUBLE:
return min ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
case STRING:
case STRING_VAL:
return min ? null : MAX_TERM;
default:
throw new UnsupportedOperationException("Unsupported reduced type: " + reducedType());
}
} else {
switch (reducedType()) {
case INT:
if (missingValue instanceof Number) {
return ((Number) missingValue).intValue();
} else {
return Integer.parseInt(missingValue.toString());
}
case LONG:
if (missingValue instanceof Number) {
return ((Number) missingValue).longValue();
} else {
return Long.parseLong(missingValue.toString());
}
case FLOAT:
if (missingValue instanceof Number) {
return ((Number) missingValue).floatValue();
} else {
return Float.parseFloat(missingValue.toString());
}
case DOUBLE:
if (missingValue instanceof Number) {
return ((Number) missingValue).doubleValue();
} else {
return Double.parseDouble(missingValue.toString());
}
case STRING:
case STRING_VAL:
if (missingValue instanceof BytesRef) {
return (BytesRef) missingValue;
} else if (missingValue instanceof byte[]) {
return new BytesRef((byte[]) missingValue);
} else {
return new BytesRef(missingValue.toString());
}
default:
throw new UnsupportedOperationException("Unsupported reduced type: " + reducedType());
}
}
}
public abstract SortField.Type reducedType();
}
interface Builder {
IndexFieldData build(Index index, @IndexSettings Settings indexSettings, FieldMapper<?> mapper, IndexFieldDataCache cache,
CircuitBreakerService breakerService);
}
public interface WithOrdinals<FD extends AtomicFieldData.WithOrdinals> extends IndexFieldData<FD> {
/**
* Loads the atomic field data for the reader, possibly cached.
*/
FD load(AtomicReaderContext context);
/**
* Loads directly the atomic field data for the reader, ignoring any caching involved.
*/
FD loadDirect(AtomicReaderContext context) throws Exception;
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_IndexFieldData.java |
232 | public abstract class AbstractCassandraStoreTest extends KeyColumnValueStoreTest {
private static final Logger log =
LoggerFactory.getLogger(AbstractCassandraStoreTest.class);
private static final String TEST_CF_NAME = "testcf";
private static final String DEFAULT_COMPRESSOR_PACKAGE = "org.apache.cassandra.io.compress";
public abstract ModifiableConfiguration getBaseStorageConfiguration();
public abstract AbstractCassandraStoreManager openStorageManager(Configuration c) throws BackendException;
@Test
@Category({ UnorderedKeyStoreTests.class })
public void testUnorderedConfiguration() {
if (!manager.getFeatures().hasUnorderedScan()) {
log.warn(
"Can't test key-unordered features on incompatible store. "
+ "This warning could indicate reduced test coverage and "
+ "a broken JUnit configuration. Skipping test {}.",
name.getMethodName());
return;
}
StoreFeatures features = manager.getFeatures();
assertFalse(features.isKeyOrdered());
assertFalse(features.hasLocalKeyPartition());
}
@Test
@Category({ OrderedKeyStoreTests.class })
public void testOrderedConfiguration() {
if (!manager.getFeatures().hasOrderedScan()) {
log.warn(
"Can't test key-ordered features on incompatible store. "
+ "This warning could indicate reduced test coverage and "
+ "a broken JUnit configuration. Skipping test {}.",
name.getMethodName());
return;
}
StoreFeatures features = manager.getFeatures();
assertTrue(features.isKeyOrdered());
}
@Test
public void testDefaultCFCompressor() throws BackendException {
final String cf = TEST_CF_NAME + "_snappy";
AbstractCassandraStoreManager mgr = openStorageManager();
mgr.openDatabase(cf);
Map<String, String> defaultCfCompressionOps =
new ImmutableMap.Builder<String, String>()
.put("sstable_compression", DEFAULT_COMPRESSOR_PACKAGE + "." + AbstractCassandraStoreManager.CF_COMPRESSION_TYPE.getDefaultValue())
.put("chunk_length_kb", "64")
.build();
assertEquals(defaultCfCompressionOps, mgr.getCompressionOptions(cf));
}
@Test
public void testCustomCFCompressor() throws BackendException {
final String cname = "DeflateCompressor";
final int ckb = 128;
final String cf = TEST_CF_NAME + "_gzip";
ModifiableConfiguration config = getBaseStorageConfiguration();
config.set(AbstractCassandraStoreManager.CF_COMPRESSION_TYPE,cname);
config.set(AbstractCassandraStoreManager.CF_COMPRESSION_BLOCK_SIZE,ckb);
AbstractCassandraStoreManager mgr = openStorageManager(config);
// N.B.: clearStorage() truncates CFs but does not delete them
mgr.openDatabase(cf);
final Map<String, String> expected = ImmutableMap
.<String, String> builder()
.put("sstable_compression",
DEFAULT_COMPRESSOR_PACKAGE + "." + cname)
.put("chunk_length_kb", String.valueOf(ckb)).build();
assertEquals(expected, mgr.getCompressionOptions(cf));
}
@Test
public void testDisableCFCompressor() throws BackendException {
final String cf = TEST_CF_NAME + "_nocompress";
ModifiableConfiguration config = getBaseStorageConfiguration();
config.set(AbstractCassandraStoreManager.CF_COMPRESSION,false);
AbstractCassandraStoreManager mgr = openStorageManager(config);
// N.B.: clearStorage() truncates CFs but does not delete them
mgr.openDatabase(cf);
assertEquals(Collections.emptyMap(), mgr.getCompressionOptions(cf));
}
@Test
public void testTTLSupported() throws Exception {
StoreFeatures features = manager.getFeatures();
assertTrue(features.hasCellTTL());
}
@Override
public AbstractCassandraStoreManager openStorageManager() throws BackendException {
return openStorageManager(getBaseStorageConfiguration());
}
} | 0true
| titan-cassandra_src_test_java_com_thinkaurelius_titan_diskstorage_cassandra_AbstractCassandraStoreTest.java |
1,094 | public abstract class OSQLFunctionConfigurableAbstract extends OSQLFunctionAbstract {
protected Object[] configuredParameters;
protected OSQLFunctionConfigurableAbstract(final String iName, final int iMinParams, final int iMaxParams) {
super(iName, iMinParams, iMaxParams);
}
@Override
public void config(final Object[] iConfiguredParameters) {
configuredParameters = iConfiguredParameters;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_functions_OSQLFunctionConfigurableAbstract.java |
834 | @SuppressWarnings("deprecation")
public class CreateOfferUtility {
private OfferDao offerDao;
private OfferCodeDao offerCodeDao;
private OfferService offerService;
public CreateOfferUtility(OfferDao offerDao, OfferCodeDao offerCodeDao, OfferService offerService) {
this.offerDao = offerDao;
this.offerCodeDao = offerCodeDao;
this.offerService = offerService;
}
public OfferCode createOfferCode(String offerName, OfferType offerType, OfferDiscountType discountType, double value, String customerRule, String orderRule, boolean stackable, boolean combinable, int priority) {
return createOfferCode("NONAME", offerName, offerType, discountType, value, customerRule, orderRule, stackable, combinable, priority);
}
public OfferCode createOfferCode(String offerCodeName, String offerName, OfferType offerType, OfferDiscountType discountType, double value, String customerRule, String orderRule, boolean stackable, boolean combinable, int priority) {
OfferCode offerCode = offerCodeDao.create();
Offer offer = createOffer(offerName, offerType, discountType, value, customerRule, orderRule, stackable, combinable, priority);
offerCode.setOffer(offer);
offerCode.setOfferCode(offerCodeName);
offerCode = offerService.saveOfferCode(offerCode);
return offerCode;
}
public Offer createOffer(String offerName, OfferType offerType, OfferDiscountType discountType, double value, String customerRule, String orderRule, boolean stackable, boolean combinable, int priority) {
Offer offer = offerDao.create();
offer.setName(offerName);
offer.setStartDate(SystemTime.asDate());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
offer.setStartDate(calendar.getTime());
calendar.add(Calendar.DATE, 2);
offer.setEndDate(calendar.getTime());
offer.setType(offerType);
offer.setDiscountType(discountType);
offer.setValue(BigDecimal.valueOf(value));
offer.setDeliveryType(OfferDeliveryType.CODE);
offer.setStackable(stackable);
offer.setAppliesToOrderRules(orderRule);
offer.setAppliesToCustomerRules(customerRule);
offer.setCombinableWithOtherOffers(combinable);
offer.setPriority(priority);
offer = offerService.save(offer);
offer.setMaxUses(50);
return offer;
}
public Offer updateOfferCodeMaxCustomerUses(OfferCode code, Long maxUses) {
code.getOffer().setMaxUsesPerCustomer(maxUses);
return offerService.save(code.getOffer());
}
} | 1no label
| integration_src_test_java_org_broadleafcommerce_core_offer_service_CreateOfferUtility.java |
5,976 | return new LookupFactory() {
@Override
public Lookup getLookup(FieldMapper<?> mapper, CompletionSuggestionContext suggestionContext) {
AnalyzingSuggestHolder analyzingSuggestHolder = lookupMap.get(mapper.names().indexName());
if (analyzingSuggestHolder == null) {
return null;
}
int flags = analyzingSuggestHolder.preserveSep ? XAnalyzingSuggester.PRESERVE_SEP : 0;
XAnalyzingSuggester suggester;
if (suggestionContext.isFuzzy()) {
suggester = new XFuzzySuggester(mapper.indexAnalyzer(), mapper.searchAnalyzer(), flags,
analyzingSuggestHolder.maxSurfaceFormsPerAnalyzedForm, analyzingSuggestHolder.maxGraphExpansions,
suggestionContext.getFuzzyEditDistance(), suggestionContext.isFuzzyTranspositions(),
suggestionContext.getFuzzyPrefixLength(), suggestionContext.getFuzzyMinLength(), suggestionContext.isFuzzyUnicodeAware(),
analyzingSuggestHolder.fst, analyzingSuggestHolder.hasPayloads,
analyzingSuggestHolder.maxAnalyzedPathsForOneInput, analyzingSuggestHolder.sepLabel, analyzingSuggestHolder.payloadSep, analyzingSuggestHolder.endByte,
analyzingSuggestHolder.holeCharacter);
} else {
suggester = new XAnalyzingSuggester(mapper.indexAnalyzer(), mapper.searchAnalyzer(), flags,
analyzingSuggestHolder.maxSurfaceFormsPerAnalyzedForm, analyzingSuggestHolder.maxGraphExpansions,
analyzingSuggestHolder.preservePositionIncrements, analyzingSuggestHolder.fst, analyzingSuggestHolder.hasPayloads,
analyzingSuggestHolder.maxAnalyzedPathsForOneInput, analyzingSuggestHolder.sepLabel, analyzingSuggestHolder.payloadSep, analyzingSuggestHolder.endByte,
analyzingSuggestHolder.holeCharacter);
}
return suggester;
}
@Override
public CompletionStats stats(String... fields) {
long sizeInBytes = 0;
ObjectLongOpenHashMap<String> completionFields = null;
if (fields != null && fields.length > 0) {
completionFields = new ObjectLongOpenHashMap<String>(fields.length);
}
for (Map.Entry<String, AnalyzingSuggestHolder> entry : lookupMap.entrySet()) {
sizeInBytes += entry.getValue().fst.sizeInBytes();
if (fields == null || fields.length == 0) {
continue;
}
for (String field : fields) {
// support for getting fields by regex as in fielddata
if (Regex.simpleMatch(field, entry.getKey())) {
long fstSize = entry.getValue().fst.sizeInBytes();
completionFields.addTo(field, fstSize);
}
}
}
return new CompletionStats(sizeInBytes, completionFields);
}
@Override
AnalyzingSuggestHolder getAnalyzingSuggestHolder(FieldMapper<?> mapper) {
return lookupMap.get(mapper.names().indexName());
}
@Override
public long ramBytesUsed() {
return ramBytesUsed;
}
}; | 1no label
| src_main_java_org_elasticsearch_search_suggest_completion_AnalyzingCompletionLookupProvider.java |
1,266 | addOperation(operations, new Runnable() {
public void run() {
IQueue q = hazelcast.getQueue("myQ");
q.offer(new byte[100]);
}
}, 10); | 0true
| hazelcast_src_main_java_com_hazelcast_examples_AllTest.java |
686 | public interface CategoryXref extends Serializable {
public Long getDisplayOrder();
public void setDisplayOrder(final Long displayOrder);
public Category getCategory();
public void setCategory(final Category category);
public Category getSubCategory();
public void setSubCategory(final Category subCategory);
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_CategoryXref.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.