Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
2,497 | enum Token {
START_OBJECT {
@Override
public boolean isValue() {
return false;
}
},
END_OBJECT {
@Override
public boolean isValue() {
return false;
}
},
START_ARRAY {
@Override
public boolean isValue() {
return false;
}
},
END_ARRAY {
@Override
public boolean isValue() {
return false;
}
},
FIELD_NAME {
@Override
public boolean isValue() {
return false;
}
},
VALUE_STRING {
@Override
public boolean isValue() {
return true;
}
},
VALUE_NUMBER {
@Override
public boolean isValue() {
return true;
}
},
VALUE_BOOLEAN {
@Override
public boolean isValue() {
return true;
}
},
// usually a binary value
VALUE_EMBEDDED_OBJECT {
@Override
public boolean isValue() {
return true;
}
},
VALUE_NULL {
@Override
public boolean isValue() {
return false;
}
};
public abstract boolean isValue();
} | 0true
| src_main_java_org_elasticsearch_common_xcontent_XContentParser.java |
587 | class ShardRefreshRequest extends BroadcastShardOperationRequest {
private boolean force = true;
ShardRefreshRequest() {
}
public ShardRefreshRequest(String index, int shardId, RefreshRequest request) {
super(index, shardId, request);
force = request.force();
}
public boolean force() {
return force;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
force = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(force);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_refresh_ShardRefreshRequest.java |
304 | public class CommonConfigTest extends WritableConfigurationTest {
@Override
public WriteConfiguration getConfig() {
return new CommonsConfiguration(new BaseConfiguration());
}
@Test
public void testDateParsing() {
BaseConfiguration base = new BaseConfiguration();
CommonsConfiguration config = new CommonsConfiguration(base);
for (TimeUnit unit : TimeUnit.values()) {
base.setProperty("test","100 " + unit.toString());
Duration d = config.get("test",Duration.class);
assertEquals(unit,d.getNativeUnit());
assertEquals(100,d.getLength(unit));
}
Map<TimeUnit,String> mapping = ImmutableMap.of(TimeUnit.MICROSECONDS,"us", TimeUnit.DAYS,"d");
for (Map.Entry<TimeUnit,String> entry : mapping.entrySet()) {
base.setProperty("test","100 " + entry.getValue());
Duration d = config.get("test",Duration.class);
assertEquals(entry.getKey(),d.getNativeUnit());
assertEquals(100,d.getLength(entry.getKey()));
}
}
} | 0true
| titan-test_src_test_java_com_thinkaurelius_titan_diskstorage_configuration_CommonConfigTest.java |
3,432 | public static class Index {
private long startTime = 0;
private long time = 0;
private long version = -1;
private int numberOfFiles = 0;
private long totalSize = 0;
private int numberOfReusedFiles = 0;
private long reusedTotalSize = 0;
private AtomicLong currentFilesSize = new AtomicLong();
public long startTime() {
return this.startTime;
}
public void startTime(long startTime) {
this.startTime = startTime;
}
public long time() {
return this.time;
}
public void time(long time) {
this.time = time;
}
public long version() {
return this.version;
}
public void files(int numberOfFiles, long totalSize, int numberOfReusedFiles, long reusedTotalSize) {
this.numberOfFiles = numberOfFiles;
this.totalSize = totalSize;
this.numberOfReusedFiles = numberOfReusedFiles;
this.reusedTotalSize = reusedTotalSize;
}
public int numberOfFiles() {
return numberOfFiles;
}
public int numberOfRecoveredFiles() {
return numberOfFiles - numberOfReusedFiles;
}
public long totalSize() {
return this.totalSize;
}
public int numberOfReusedFiles() {
return numberOfReusedFiles;
}
public long reusedTotalSize() {
return this.reusedTotalSize;
}
public long recoveredTotalSize() {
return totalSize - reusedTotalSize;
}
public void updateVersion(long version) {
this.version = version;
}
public long currentFilesSize() {
return this.currentFilesSize.get();
}
public void addCurrentFilesSize(long updatedSize) {
this.currentFilesSize.addAndGet(updatedSize);
}
} | 0true
| src_main_java_org_elasticsearch_index_gateway_RecoveryStatus.java |
3,123 | Arrays.sort(segmentsArr, new Comparator<Segment>() {
@Override
public int compare(Segment o1, Segment o2) {
return (int) (o1.getGeneration() - o2.getGeneration());
}
}); | 1no label
| src_main_java_org_elasticsearch_index_engine_internal_InternalEngine.java |
2,620 | private class LeaveRequestRequestHandler extends BaseTransportRequestHandler<LeaveRequest> {
static final String ACTION = "discovery/zen/leave";
@Override
public LeaveRequest newInstance() {
return new LeaveRequest();
}
@Override
public void messageReceived(LeaveRequest request, TransportChannel channel) throws Exception {
listener.onLeave(request.node);
channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
@Override
public String executor() {
return ThreadPool.Names.GENERIC;
}
} | 0true
| src_main_java_org_elasticsearch_discovery_zen_membership_MembershipAction.java |
4,246 | static class Delete implements Operation {
private Term uid;
private long version;
public Delete() {
}
public Delete(Engine.Delete delete) {
this(delete.uid());
this.version = delete.version();
}
public Delete(Term uid) {
this.uid = uid;
}
@Override
public Type opType() {
return Type.DELETE;
}
@Override
public long estimateSize() {
return ((uid.field().length() + uid.text().length()) * 2) + 20;
}
public Term uid() {
return this.uid;
}
public long version() {
return this.version;
}
@Override
public Source readSource(StreamInput in) throws IOException {
throw new ElasticsearchIllegalStateException("trying to read doc source from delete operation");
}
@Override
public void readFrom(StreamInput in) throws IOException {
int version = in.readVInt(); // version
uid = new Term(in.readString(), in.readString());
if (version >= 1) {
this.version = in.readLong();
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(1); // version
out.writeString(uid.field());
out.writeString(uid.text());
out.writeLong(version);
}
} | 1no label
| src_main_java_org_elasticsearch_index_translog_Translog.java |
884 | threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
executePhase(shardIndex, node, target.v2());
}
}); | 0true
| src_main_java_org_elasticsearch_action_search_type_TransportSearchScrollQueryAndFetchAction.java |
614 | public class MergeClustersOperation extends AbstractClusterOperation {
private Address newTargetAddress;
public MergeClustersOperation() {
}
public MergeClustersOperation(Address newTargetAddress) {
this.newTargetAddress = newTargetAddress;
}
@Override
public void run() {
final Address caller = getCallerAddress();
final NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine();
final Node node = nodeEngine.getNode();
final Address masterAddress = node.getMasterAddress();
final ILogger logger = node.loggingService.getLogger(this.getClass().getName());
boolean local = caller == null;
if (!local && !caller.equals(masterAddress)) {
logger.warning("Merge instruction sent from non-master endpoint: " + caller);
return;
}
logger.warning(node.getThisAddress() + " is merging to " + newTargetAddress
+ ", because: instructed by master " + masterAddress);
node.getClusterService().merge(newTargetAddress);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
newTargetAddress = new Address();
newTargetAddress.readData(in);
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
newTargetAddress.writeData(out);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_cluster_MergeClustersOperation.java |
844 | public class AlterRequest extends AbstractAlterRequest {
public AlterRequest() {
}
public AlterRequest(String name, Data function) {
super(name, function);
}
@Override
protected Operation prepareOperation() {
return new AlterOperation(name, function);
}
@Override
public int getClassId() {
return AtomicReferencePortableHook.ALTER;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_AlterRequest.java |
426 | private final class ClientTrackableJob<V>
implements TrackableJob<V> {
private final String jobId;
private final Address jobOwner;
private final AbstractCompletableFuture<V> completableFuture;
private ClientTrackableJob(String jobId, Address jobOwner,
AbstractCompletableFuture<V> completableFuture) {
this.jobId = jobId;
this.jobOwner = jobOwner;
this.completableFuture = completableFuture;
}
@Override
public JobTracker getJobTracker() {
return ClientMapReduceProxy.this;
}
@Override
public String getName() {
return ClientMapReduceProxy.this.getName();
}
@Override
public String getJobId() {
return jobId;
}
@Override
public ICompletableFuture<V> getCompletableFuture() {
return completableFuture;
}
@Override
public JobProcessInformation getJobProcessInformation() {
try {
return invoke(new ClientJobProcessInformationRequest(getName(), jobId), jobId);
} catch (Exception ignore) {
}
return null;
}
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientMapReduceProxy.java |
2,629 | ping(new PingListener() {
@Override
public void onPing(PingResponse[] pings) {
response.set(pings);
latch.countDown();
}
}, timeout); | 0true
| src_main_java_org_elasticsearch_discovery_zen_ping_ZenPingService.java |
1,420 | public final class HazelcastAccessor {
private HazelcastAccessor(){}
static final ILogger logger = Logger.getLogger(HazelcastAccessor.class);
/**
* Tries to extract <code>HazelcastInstance</code> from <code>Session</code>.
*
* @param session
* @return Currently used <code>HazelcastInstance</code> or null if an error occurs.
*/
public static HazelcastInstance getHazelcastInstance(final Session session) {
return getHazelcastInstance(session.getSessionFactory());
}
/**
* Tries to extract <code>HazelcastInstance</code> from <code>SessionFactory</code>.
*
* @param sessionFactory
* @return Currently used <code>HazelcastInstance</code> or null if an error occurs.
*/
public static HazelcastInstance getHazelcastInstance(final SessionFactory sessionFactory) {
if (!(sessionFactory instanceof SessionFactoryImplementor)) {
logger.warning("SessionFactory is expected to be instance of SessionFactoryImplementor.");
return null;
}
return getHazelcastInstance((SessionFactoryImplementor) sessionFactory);
}
/**
* Tries to extract <code>HazelcastInstance</code> from <code>SessionFactoryImplementor</code>.
*
* @param sessionFactory
* @return currently used <code>HazelcastInstance</code> or null if an error occurs.
*/
public static HazelcastInstance getHazelcastInstance(final SessionFactoryImplementor sessionFactory) {
final Settings settings = sessionFactory.getSettings();
final RegionFactory rf = settings.getRegionFactory();
if (rf == null) {
logger.severe("Hibernate 2nd level cache has not been enabled!");
return null;
}
if (rf instanceof AbstractHazelcastCacheRegionFactory) {
return ((AbstractHazelcastCacheRegionFactory) rf).getHazelcastInstance();
} else {
logger.warning("Current 2nd level cache implementation is not HazelcastCacheRegionFactory!");
}
return null;
}
} | 0true
| hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_instance_HazelcastAccessor.java |
176 | {
@Override
public long nextSequenceId()
{
return 1;
}
@Override
public long nextRandomLong()
{
return 14; // soo random
}
}; | 0true
| community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_XidImplTest.java |
49 | public interface DoubleByDoubleToDouble { double apply(double a, double b); } | 0true
| src_main_java_jsr166e_ConcurrentHashMapV8.java |
493 | new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
String message = "Internal executor rejected task: " + r + ", because client is shutting down...";
LOGGER.finest(message);
throw new RejectedExecutionException(message);
}
}); | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientExecutionServiceImpl.java |
74 | public interface VertexLabel extends TitanVertex, TitanSchemaType {
/**
* Whether vertices with this label are partitioned.
*
* @return
*/
public boolean isPartitioned();
/**
* Whether vertices with this label are static, that is, immutable beyond the transaction
* in which they were created.
*
* @return
*/
public boolean isStatic();
//TTL
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_VertexLabel.java |
1,484 | public class Hibernate4CacheEntrySerializerHook
implements SerializerHook {
private static final String SKIP_INIT_MSG = "Hibernate4 not available, skipping serializer initialization";
private final Class<?> cacheEntryClass;
public Hibernate4CacheEntrySerializerHook() {
Class<?> cacheEntryClass = null;
if (UnsafeHelper.UNSAFE_AVAILABLE) {
try {
cacheEntryClass = Class.forName("org.hibernate.cache.spi.entry.CacheEntry");
} catch (Exception e) {
Logger.getLogger(Hibernate4CacheEntrySerializerHook.class).finest(SKIP_INIT_MSG);
}
}
this.cacheEntryClass = cacheEntryClass;
}
@Override
public Class getSerializationType() {
return cacheEntryClass;
}
@Override
public Serializer createSerializer() {
if (cacheEntryClass != null) {
return new Hibernate4CacheEntrySerializer();
}
return null;
}
@Override
public boolean isOverwritable() {
return true;
}
} | 1no label
| hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_serialization_Hibernate4CacheEntrySerializerHook.java |
1,316 | @Deprecated
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
public class SearchInterceptImpl implements SearchIntercept {
@Id
@GeneratedValue(generator = "SearchInterceptId")
@GenericGenerator(
name="SearchInterceptId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="SearchInterceptImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.search.domain.SearchInterceptImpl")
}
)
@Column(name = "SEARCH_INTERCEPT_ID")
protected Long id;
@Column(name = "TERM")
@Index(name="SEARCHINTERCEPT_TERM_INDEX", columnNames={"TERM"})
private String term;
@Column(name = "REDIRECT")
private String redirect;
/* (non-Javadoc)
* @see org.broadleafcommerce.core.search.domain.SearchIntercept#getTerm()
*/
@Override
public String getTerm() {
return term;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.search.domain.SearchIntercept#setTerm(java.lang.String)
*/
@Override
public void setTerm(String term) {
this.term = term;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.search.domain.SearchIntercept#getRedirect()
*/
@Override
public String getRedirect() {
return redirect;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.search.domain.SearchIntercept#setRedirect(java.lang.String)
*/
@Override
public void setRedirect(String redirect) {
this.redirect = redirect;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_domain_SearchInterceptImpl.java |
1,111 | public class OrderServiceException extends RuntimeException {
private static final long serialVersionUID = 1L;
public OrderServiceException() {
super();
}
public OrderServiceException(String message, Throwable cause) {
super(message, cause);
}
public OrderServiceException(String message) {
super(message);
}
public OrderServiceException(Throwable cause) {
super(cause);
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_exception_OrderServiceException.java |
728 | loadEntriesMinor(key, inclusive, new RangeResultListener<K, V>() {
@Override
public boolean addResult(Map.Entry<K, V> entry) {
result.add(entry.getValue());
if (maxValuesToFetch > -1 && result.size() >= maxValuesToFetch)
return false;
return true;
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_sbtree_local_OSBTree.java |
699 | constructors[LIST_INDEX_OF] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListIndexOfRequest();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java |
2,710 | assertThat(awaitBusy(new Predicate<Object>() {
@Override
public boolean apply(Object input) {
logger.info("--> running cluster_health (wait for the shards to startup)");
ClusterHealthResponse clusterHealth = activeClient.admin().cluster().health(clusterHealthRequest().waitForYellowStatus().waitForNodes("2").waitForActiveShards(4)).actionGet();
logger.info("--> done cluster_health, status " + clusterHealth.getStatus());
return (!clusterHealth.isTimedOut()) && clusterHealth.getStatus() == ClusterHealthStatus.YELLOW;
}
}, 30, TimeUnit.SECONDS), equalTo(true)); | 0true
| src_test_java_org_elasticsearch_gateway_local_QuorumLocalGatewayTests.java |
2,830 | private class SyncReplicaVersionTask implements Runnable {
@Override
public void run() {
if (node.isActive() && migrationActive.get()) {
final Address thisAddress = node.getThisAddress();
for (final InternalPartitionImpl partition : partitions) {
if (thisAddress.equals(partition.getOwnerOrNull())) {
for (int index = 1; index < InternalPartition.MAX_REPLICA_COUNT; index++) {
if (partition.getReplicaAddress(index) != null) {
SyncReplicaVersion op = new SyncReplicaVersion(index, null);
op.setService(InternalPartitionServiceImpl.this);
op.setNodeEngine(nodeEngine);
op.setResponseHandler(ResponseHandlerFactory
.createErrorLoggingResponseHandler(node.getLogger(SyncReplicaVersion.class)));
op.setPartitionId(partition.getPartitionId());
nodeEngine.getOperationService().executeOperation(op);
}
}
}
}
}
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_partition_impl_InternalPartitionServiceImpl.java |
297 | class SelectEnclosingAction extends Action {
private CeylonEditor editor;
public SelectEnclosingAction() {
this(null);
}
public SelectEnclosingAction(CeylonEditor editor) {
super("Select Enclosing");
setActionDefinitionId(SELECT_ENCLOSING);
setEditor(editor);
}
private void setEditor(ITextEditor editor) {
if (editor instanceof CeylonEditor) {
this.editor = (CeylonEditor) editor;
}
else {
this.editor = null;
}
setEnabled(this.editor!=null);
}
private static class EnclosingVisitor extends Visitor implements NaturalVisitor {
private Node result;
private int startOffset;
private int endOffset;
private EnclosingVisitor(int startOffset, int endOffset) {
this.startOffset = startOffset;
this.endOffset = endOffset;
}
private boolean expandsSelection(Node that) {
Integer nodeStart = that.getStartIndex();
Integer nodeStop = that.getStopIndex();
if (nodeStart!=null && nodeStop!=null) {
return nodeStart<startOffset && nodeStop+1>=endOffset ||
nodeStart<=startOffset && nodeStop+1>endOffset;
}
else {
return false;
}
}
@Override
public void visit(CompilationUnit that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(Body that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(ArgumentList that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(ParameterList that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(ControlClause that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(ConditionList that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(Condition that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(Type that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(Identifier that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(Term that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(ImportMemberOrTypeList that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(ImportMemberOrType that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(SpecifierOrInitializerExpression that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(Expression that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
@Override
public void visit(StatementOrArgument that) {
if (expandsSelection(that)) {
result = that;
}
super.visit(that);
}
}
@Override
public void run() {
IRegion selection = editor.getSelection();
int startOffset = selection.getOffset();
int endOffset = startOffset + selection.getLength();
CompilationUnit rootNode = editor.getParseController().getRootNode();
if (rootNode!=null) {
EnclosingVisitor ev = new EnclosingVisitor(startOffset, endOffset);
ev.visit(rootNode);
Node result = ev.result;
if (result!=null) {
editor.selectAndReveal(result.getStartIndex(),
result.getStopIndex()-result.getStartIndex()+1);
}
}
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_SelectEnclosingAction.java |
744 | public class ListRemoveRequest extends CollectionRequest {
int index;
public ListRemoveRequest() {
}
public ListRemoveRequest(String name, int index) {
super(name);
this.index = index;
}
@Override
protected Operation prepareOperation() {
return new ListRemoveOperation(name, index);
}
@Override
public int getClassId() {
return CollectionPortableHook.LIST_REMOVE;
}
public void write(PortableWriter writer) throws IOException {
super.write(writer);
writer.writeInt("i", index);
}
public void read(PortableReader reader) throws IOException {
super.read(reader);
index = reader.readInt("i");
}
@Override
public String getRequiredAction() {
return ActionConstants.ACTION_REMOVE;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_client_ListRemoveRequest.java |
65 | public interface FieldGroup extends Serializable {
public Long getId();
public void setId(Long id);
public String getName();
public void setName(String name);
public Boolean getInitCollapsedFlag();
public void setInitCollapsedFlag(Boolean initCollapsedFlag);
public List<FieldDefinition> getFieldDefinitions();
public void setFieldDefinitions(List<FieldDefinition> fieldDefinitions);
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_field_domain_FieldGroup.java |
1,033 | public abstract class AbstractTermVectorTests extends ElasticsearchIntegrationTest {
protected static class TestFieldSetting {
final public String name;
final public boolean storedOffset;
final public boolean storedPayloads;
final public boolean storedPositions;
public TestFieldSetting(String name, boolean storedOffset, boolean storedPayloads, boolean storedPositions) {
this.name = name;
this.storedOffset = storedOffset;
this.storedPayloads = storedPayloads;
this.storedPositions = storedPositions;
}
public void addToMappings(XContentBuilder mappingsBuilder) throws IOException {
mappingsBuilder.startObject(name);
mappingsBuilder.field("type", "string");
String tv_settings;
if (storedPositions && storedOffset && storedPayloads) {
tv_settings = "with_positions_offsets_payloads";
} else if (storedPositions && storedOffset) {
tv_settings = "with_positions_offsets";
} else if (storedPayloads) {
tv_settings = "with_positions_payloads";
} else if (storedPositions) {
tv_settings = "with_positions";
} else if (storedOffset) {
tv_settings = "with_offsets";
} else {
tv_settings = "yes";
}
mappingsBuilder.field("term_vector", tv_settings);
if (storedPayloads) {
mappingsBuilder.field("analyzer", "tv_test");
}
mappingsBuilder.endObject();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("name: ").append(name).append(" tv_with:");
if (storedPayloads) {
sb.append("payloads,");
}
if (storedOffset) {
sb.append("offsets,");
}
if (storedPositions) {
sb.append("positions,");
}
return sb.toString();
}
}
protected static class TestDoc {
final public String id;
final public TestFieldSetting[] fieldSettings;
final public String[] fieldContent;
public String index = "test";
public String type = "type1";
public TestDoc(String id, TestFieldSetting[] fieldSettings, String[] fieldContent) {
this.id = id;
assertEquals(fieldSettings.length, fieldContent.length);
this.fieldSettings = fieldSettings;
this.fieldContent = fieldContent;
}
public TestDoc index(String index) {
this.index = index;
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("index:").append(index).append(" type:").append(type).append(" id:").append(id);
for (int i = 0; i < fieldSettings.length; i++) {
TestFieldSetting f = fieldSettings[i];
sb.append("\n").append("Field: ").append(f).append("\n content:").append(fieldContent[i]);
}
sb.append("\n");
return sb.toString();
}
}
protected static class TestConfig {
final public TestDoc doc;
final public String[] selectedFields;
final public boolean requestPositions;
final public boolean requestOffsets;
final public boolean requestPayloads;
public Class expectedException = null;
public TestConfig(TestDoc doc, String[] selectedFields, boolean requestPositions, boolean requestOffsets, boolean requestPayloads) {
this.doc = doc;
this.selectedFields = selectedFields;
this.requestPositions = requestPositions;
this.requestOffsets = requestOffsets;
this.requestPayloads = requestPayloads;
}
public TestConfig expectedException(Class exceptionClass) {
this.expectedException = exceptionClass;
return this;
}
@Override
public String toString() {
String requested = "";
if (requestOffsets) {
requested += "offsets,";
}
if (requestPositions) {
requested += "position,";
}
if (requestPayloads) {
requested += "payload,";
}
Locale aLocale = new Locale("en", "US");
return String.format(aLocale, "(doc: %s\n requested: %s, fields: %s)", doc, requested,
selectedFields == null ? "NULL" : Join.join(",", selectedFields));
}
}
protected void createIndexBasedOnFieldSettings(TestFieldSetting[] fieldSettings, int number_of_shards) throws IOException {
wipeIndices("test");
XContentBuilder mappingBuilder = jsonBuilder();
mappingBuilder.startObject().startObject("type1").startObject("properties");
for (TestFieldSetting field : fieldSettings) {
field.addToMappings(mappingBuilder);
}
ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder()
.put("index.analysis.analyzer.tv_test.tokenizer", "standard")
.putArray("index.analysis.analyzer.tv_test.filter", "type_as_payload", "lowercase");
if (number_of_shards > 0) {
settings.put("number_of_shards", number_of_shards);
}
mappingBuilder.endObject().endObject().endObject();
prepareCreate("test").addMapping("type1", mappingBuilder).setSettings(settings).get();
ensureYellow();
}
/**
* Generate test documentsThe returned documents are already indexed.
*/
protected TestDoc[] generateTestDocs(int numberOfDocs, TestFieldSetting[] fieldSettings) {
String[] fieldContentOptions = new String[]{"Generating a random permutation of a sequence (such as when shuffling cards).",
"Selecting a random sample of a population (important in statistical sampling).",
"Allocating experimental units via random assignment to a treatment or control condition.",
"Generating random numbers: see Random number generation.",
"Transforming a data stream (such as when using a scrambler in telecommunications)."};
String[] contentArray = new String[fieldSettings.length];
Map<String, Object> docSource = new HashMap<String, Object>();
TestDoc[] testDocs = new TestDoc[numberOfDocs];
for (int docId = 0; docId < numberOfDocs; docId++) {
docSource.clear();
for (int i = 0; i < contentArray.length; i++) {
contentArray[i] = fieldContentOptions[randomInt(fieldContentOptions.length - 1)];
docSource.put(fieldSettings[i].name, contentArray[i]);
}
TestDoc doc = new TestDoc(Integer.toString(docId), fieldSettings, contentArray.clone());
index(doc.index, doc.type, doc.id, docSource);
testDocs[docId] = doc;
}
refresh();
return testDocs;
}
protected TestConfig[] generateTestConfigs(int numberOfTests, TestDoc[] testDocs, TestFieldSetting[] fieldSettings) {
ArrayList<TestConfig> configs = new ArrayList<TestConfig>();
for (int i = 0; i < numberOfTests; i++) {
ArrayList<String> selectedFields = null;
if (randomBoolean()) {
// used field selection
selectedFields = new ArrayList<String>();
if (randomBoolean()) {
selectedFields.add("Doesnt_exist"); // this will be ignored.
}
for (TestFieldSetting field : fieldSettings)
if (randomBoolean()) {
selectedFields.add(field.name);
}
if (selectedFields.size() == 0) {
selectedFields = null; // 0 length set is not supported.
}
}
TestConfig config = new TestConfig(testDocs[randomInt(testDocs.length - 1)], selectedFields == null ? null
: selectedFields.toArray(new String[]{}), randomBoolean(), randomBoolean(), randomBoolean());
configs.add(config);
}
// always adds a test that fails
configs.add(new TestConfig(new TestDoc("doesnt_exist", new TestFieldSetting[]{}, new String[]{}).index("doesn't_exist"),
new String[]{"doesnt_exist"}, true, true, true).expectedException(IndexMissingException.class));
refresh();
return configs.toArray(new TestConfig[]{});
}
protected TestFieldSetting[] getFieldSettings() {
return new TestFieldSetting[]{new TestFieldSetting("field_with_positions", false, false, true),
new TestFieldSetting("field_with_offsets", true, false, false),
new TestFieldSetting("field_with_only_tv", false, false, false),
new TestFieldSetting("field_with_positions_offsets", false, false, true),
new TestFieldSetting("field_with_positions_payloads", false, true, true)
};
}
protected DirectoryReader indexDocsWithLucene(TestDoc[] testDocs) throws IOException {
Map<String, Analyzer> mapping = new HashMap<String, Analyzer>();
for (TestFieldSetting field : testDocs[0].fieldSettings) {
if (field.storedPayloads) {
mapping.put(field.name, new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new StandardTokenizer(Version.CURRENT.luceneVersion, reader);
TokenFilter filter = new LowerCaseFilter(Version.CURRENT.luceneVersion, tokenizer);
filter = new TypeAsPayloadTokenFilter(filter);
return new TokenStreamComponents(tokenizer, filter);
}
});
}
}
PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(new StandardAnalyzer(Version.CURRENT.luceneVersion, CharArraySet.EMPTY_SET), mapping);
Directory dir = new RAMDirectory();
IndexWriterConfig conf = new IndexWriterConfig(Version.CURRENT.luceneVersion, wrapper);
conf.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
IndexWriter writer = new IndexWriter(dir, conf);
for (TestDoc doc : testDocs) {
Document d = new Document();
d.add(new Field("id", doc.id, StringField.TYPE_STORED));
for (int i = 0; i < doc.fieldContent.length; i++) {
FieldType type = new FieldType(TextField.TYPE_STORED);
TestFieldSetting fieldSetting = doc.fieldSettings[i];
type.setStoreTermVectorOffsets(fieldSetting.storedOffset);
type.setStoreTermVectorPayloads(fieldSetting.storedPayloads);
type.setStoreTermVectorPositions(fieldSetting.storedPositions || fieldSetting.storedPayloads || fieldSetting.storedOffset);
type.setStoreTermVectors(true);
type.freeze();
d.add(new Field(fieldSetting.name, doc.fieldContent[i], type));
}
writer.updateDocument(new Term("id", doc.id), d);
writer.commit();
}
writer.close();
return DirectoryReader.open(dir);
}
protected void validateResponse(TermVectorResponse esResponse, Fields luceneFields, TestConfig testConfig) throws IOException {
TestDoc testDoc = testConfig.doc;
HashSet<String> selectedFields = testConfig.selectedFields == null ? null : new HashSet<String>(
Arrays.asList(testConfig.selectedFields));
Fields esTermVectorFields = esResponse.getFields();
for (TestFieldSetting field : testDoc.fieldSettings) {
Terms esTerms = esTermVectorFields.terms(field.name);
if (selectedFields != null && !selectedFields.contains(field.name)) {
assertNull(esTerms);
continue;
}
assertNotNull(esTerms);
Terms luceneTerms = luceneFields.terms(field.name);
TermsEnum esTermEnum = esTerms.iterator(null);
TermsEnum luceneTermEnum = luceneTerms.iterator(null);
while (esTermEnum.next() != null) {
assertNotNull(luceneTermEnum.next());
assertThat(esTermEnum.totalTermFreq(), equalTo(luceneTermEnum.totalTermFreq()));
DocsAndPositionsEnum esDocsPosEnum = esTermEnum.docsAndPositions(null, null, 0);
DocsAndPositionsEnum luceneDocsPosEnum = luceneTermEnum.docsAndPositions(null, null, 0);
if (luceneDocsPosEnum == null) {
// test we expect that...
assertFalse(field.storedOffset);
assertFalse(field.storedPayloads);
assertFalse(field.storedPositions);
continue;
}
String currentTerm = esTermEnum.term().utf8ToString();
assertThat("Token mismatch for field: " + field.name, currentTerm, equalTo(luceneTermEnum.term().utf8ToString()));
esDocsPosEnum.nextDoc();
luceneDocsPosEnum.nextDoc();
int freq = esDocsPosEnum.freq();
assertThat(freq, equalTo(luceneDocsPosEnum.freq()));
for (int i = 0; i < freq; i++) {
String failDesc = " (field:" + field.name + " term:" + currentTerm + ")";
int lucenePos = luceneDocsPosEnum.nextPosition();
int esPos = esDocsPosEnum.nextPosition();
if (field.storedPositions && testConfig.requestPositions) {
assertThat("Position test failed" + failDesc, lucenePos, equalTo(esPos));
} else {
assertThat("Missing position test failed" + failDesc, esPos, equalTo(-1));
}
if (field.storedOffset && testConfig.requestOffsets) {
assertThat("Offset test failed" + failDesc, luceneDocsPosEnum.startOffset(), equalTo(esDocsPosEnum.startOffset()));
assertThat("Offset test failed" + failDesc, luceneDocsPosEnum.endOffset(), equalTo(esDocsPosEnum.endOffset()));
} else {
assertThat("Missing offset test failed" + failDesc, esDocsPosEnum.startOffset(), equalTo(-1));
assertThat("Missing offset test failed" + failDesc, esDocsPosEnum.endOffset(), equalTo(-1));
}
if (field.storedPayloads && testConfig.requestPayloads) {
assertThat("Payload test failed" + failDesc, luceneDocsPosEnum.getPayload(), equalTo(esDocsPosEnum.getPayload()));
} else {
assertThat("Missing payload test failed" + failDesc, esDocsPosEnum.getPayload(), equalTo(null));
}
}
}
assertNull("Es returned terms are done but lucene isn't", luceneTermEnum.next());
}
}
protected TermVectorRequestBuilder getRequestForConfig(TestConfig config) {
return client().prepareTermVector(config.doc.index, config.doc.type, config.doc.id).setPayloads(config.requestPayloads)
.setOffsets(config.requestOffsets).setPositions(config.requestPositions).setFieldStatistics(true).setTermStatistics(true)
.setSelectedFields(config.selectedFields);
}
protected Fields getTermVectorsFromLucene(DirectoryReader directoryReader, TestDoc doc) throws IOException {
IndexSearcher searcher = new IndexSearcher(directoryReader);
TopDocs search = searcher.search(new TermQuery(new Term("id", doc.id)), 1);
ScoreDoc[] scoreDocs = search.scoreDocs;
assertEquals(1, scoreDocs.length);
return directoryReader.getTermVectors(scoreDocs[0].doc);
}
} | 0true
| src_test_java_org_elasticsearch_action_termvector_AbstractTermVectorTests.java |
326 | public class NodesInfoRequestBuilder extends NodesOperationRequestBuilder<NodesInfoRequest, NodesInfoResponse, NodesInfoRequestBuilder> {
public NodesInfoRequestBuilder(ClusterAdminClient clusterClient) {
super((InternalClusterAdminClient) clusterClient, new NodesInfoRequest());
}
/**
* Clears all info flags.
*/
public NodesInfoRequestBuilder clear() {
request.clear();
return this;
}
/**
* Sets to reutrn all the data.
*/
public NodesInfoRequestBuilder all() {
request.all();
return this;
}
/**
* Should the node settings be returned.
*/
public NodesInfoRequestBuilder setSettings(boolean settings) {
request.settings(settings);
return this;
}
/**
* Should the node OS info be returned.
*/
public NodesInfoRequestBuilder setOs(boolean os) {
request.os(os);
return this;
}
/**
* Should the node OS process be returned.
*/
public NodesInfoRequestBuilder setProcess(boolean process) {
request.process(process);
return this;
}
/**
* Should the node JVM info be returned.
*/
public NodesInfoRequestBuilder setJvm(boolean jvm) {
request.jvm(jvm);
return this;
}
/**
* Should the node thread pool info be returned.
*/
public NodesInfoRequestBuilder setThreadPool(boolean threadPool) {
request.threadPool(threadPool);
return this;
}
/**
* Should the node Network info be returned.
*/
public NodesInfoRequestBuilder setNetwork(boolean network) {
request.network(network);
return this;
}
/**
* Should the node Transport info be returned.
*/
public NodesInfoRequestBuilder setTransport(boolean transport) {
request.transport(transport);
return this;
}
/**
* Should the node HTTP info be returned.
*/
public NodesInfoRequestBuilder setHttp(boolean http) {
request.http(http);
return this;
}
public NodesInfoRequestBuilder setPlugin(boolean plugin) {
request().plugin(plugin);
return this;
}
@Override
protected void doExecute(ActionListener<NodesInfoResponse> listener) {
((ClusterAdminClient) client).nodesInfo(request, listener);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_node_info_NodesInfoRequestBuilder.java |
477 | public final class RandomGenerator {
private final static char[] CHARSET = new char[] { 'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9' };
private RandomGenerator() {
/**
* Intentionally blank to force static usage
*/
}
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public static String generateRandomId(String prng, int len) throws NoSuchAlgorithmException {
return generateRandomId(SecureRandom.getInstance(prng), len);
}
public static String generateRandomId(SecureRandom sr, int len) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len + 1; i++) {
int index = sr.nextInt(CHARSET.length);
char c = CHARSET[index];
sb.append(c);
if ((i % 4) == 0 && i != 0 && i < len) {
sb.append('-');
}
}
return sb.toString();
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_security_RandomGenerator.java |
306 | public abstract class ConfigElement {
public static final char SEPARATOR = '.';
public static final char[] ILLEGAL_CHARS = new char[]{SEPARATOR,' ','\t','#','@','<','>','?','/',';','"','\'',':','+','(',')','*','^','`','~','$','%','|','\\','{','[',']','}'};
private final ConfigNamespace namespace;
private final String name;
private final String description;
public ConfigElement(ConfigNamespace namespace, String name, String description) {
Preconditions.checkArgument(StringUtils.isNotBlank(name),"Name cannot be empty: %s",name);
Preconditions.checkArgument(!StringUtils.containsAny(name, ILLEGAL_CHARS),"Name contains illegal character: %s (%s)",name,ILLEGAL_CHARS);
Preconditions.checkArgument(namespace!=null || this instanceof ConfigNamespace,"Need to specify namespace for ConfigOption");
Preconditions.checkArgument(StringUtils.isNotBlank(description));
this.namespace = namespace;
this.name = name;
this.description = description;
if (namespace!=null) namespace.registerChild(this);
}
public ConfigNamespace getNamespace() {
Preconditions.checkArgument(namespace !=null,"Cannot get namespace of root");
return namespace;
}
public boolean isRoot() {
return namespace ==null;
}
public ConfigNamespace getRoot() {
if (isRoot()) return (ConfigNamespace)this;
else return getNamespace().getRoot();
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public abstract boolean isOption();
public boolean isNamespace() {
return !isOption();
}
@Override
public String toString() {
return (namespace !=null? namespace.toString()+SEPARATOR:"") + name;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(name).append(namespace).toHashCode();
}
@Override
public boolean equals(Object oth) {
if (this==oth) return true;
else if (oth==null || !getClass().isInstance(oth)) return false;
ConfigElement c = (ConfigElement)oth;
return name.equals(c.name) && namespace ==c.namespace;
}
public static String[] getComponents(final String path) {
return StringUtils.split(path,SEPARATOR);
}
public static String toStringSingle(ConfigElement element) {
return toStringSingle(element,"");
}
private static String toStringSingle(ConfigElement element, String indent) {
String result = element.getName();
if (element.isNamespace()) {
result = "+ " + result;
if (((ConfigNamespace)element).isUmbrella())
result += " [*]";
} else {
result = "- " + result;
ConfigOption option = (ConfigOption)element;
result+= " [";
switch (option.getType()) {
case FIXED: result+="f"; break;
case GLOBAL_OFFLINE: result+="g!"; break;
case GLOBAL: result+="g"; break;
case MASKABLE: result+="m"; break;
case LOCAL: result+="l"; break;
}
result+=","+option.getDatatype().getSimpleName();
result+=","+option.getDefaultValue();
result+="]";
}
result = indent + result + "\n" + indent;
String desc = element.getDescription();
result+="\t"+'"'+desc.substring(0, Math.min(desc.length(), 50))+'"';
return result;
}
public static String toString(ConfigElement element) {
//return toStringRecursive(element,"");
return toStringSingle(element, "");
}
// private static String toStringRecursive(ConfigElement element, String indent) {
// String result = toStringSingle(element, indent) + "\n";
// if (element.isNamespace()) {
// ConfigNamespace ns = (ConfigNamespace)element;
// indent += "\t";
// for (ConfigElement child : ns.getChildren()) {
// result += toStringRecursive(child,indent);
// }
// }
// return result;
// }
public static String getPath(ConfigElement element, String... umbrellaElements) {
Preconditions.checkNotNull(element);
if (umbrellaElements==null) umbrellaElements = new String[0];
String path = element.getName();
int umbrellaPos = umbrellaElements.length-1;
while (!element.isRoot() && !element.getNamespace().isRoot()) {
ConfigNamespace parent = element.getNamespace();
if (parent.isUmbrella()) {
Preconditions.checkArgument(umbrellaPos>=0,"Missing umbrella element path for element: %s",element);
String umbrellaName = umbrellaElements[umbrellaPos];
Preconditions.checkArgument(!StringUtils.containsAny(umbrellaName,ILLEGAL_CHARS),"Invalid umbrella name provided: %s. Contains illegal chars",umbrellaName);
path = umbrellaName + SEPARATOR + path;
umbrellaPos--;
}
path = parent.getName() + SEPARATOR + path;
element = parent;
}
//Don't make this check so that we can still access more general config items
Preconditions.checkArgument(umbrellaPos<0,"Found unused umbrella element: %s",umbrellaPos<0?null:umbrellaElements[umbrellaPos]);
return path;
}
public static PathIdentifier parse(ConfigNamespace root, String path) {
Preconditions.checkNotNull(root);
if (StringUtils.isBlank(path)) return new PathIdentifier(root,new String[]{},false);
String[] components = getComponents(path);
Preconditions.checkArgument(components.length>0,"Empty path provided: %s",path);
List<String> umbrellaElements = Lists.newArrayList();
ConfigNamespace parent = root;
ConfigElement last = root;
boolean lastIsUmbrella = false;
for (int i=0;i<components.length;i++) {
if (parent.isUmbrella() && !lastIsUmbrella) {
umbrellaElements.add(components[i]);
lastIsUmbrella = true;
} else {
last = parent.getChild(components[i]);
Preconditions.checkArgument(last!=null,"Unknown configuration element in namespace [%s]: %s",parent.toString(),components[i]);
if (i+1<components.length) {
Preconditions.checkArgument(last instanceof ConfigNamespace,"Expected namespace at position [%s] of [%s] but got: %s",i,path,last);
parent = (ConfigNamespace)last;
}
lastIsUmbrella = false;
}
}
return new PathIdentifier(last,umbrellaElements.toArray(new String[umbrellaElements.size()]), lastIsUmbrella);
}
public static class PathIdentifier {
public final ConfigElement element;
public final String[] umbrellaElements;
public final boolean lastIsUmbrella;
private PathIdentifier(ConfigElement element, String[] umbrellaElements, boolean lastIsUmbrella) {
this.lastIsUmbrella = lastIsUmbrella;
Preconditions.checkNotNull(element);
Preconditions.checkNotNull(umbrellaElements);
this.element = element;
this.umbrellaElements = umbrellaElements;
}
public boolean hasUmbrellaElements() {
return umbrellaElements.length>0;
}
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_ConfigElement.java |
737 | public class OSBTreeException extends OException {
public OSBTreeException() {
}
public OSBTreeException(String message) {
super(message);
}
public OSBTreeException(Throwable cause) {
super(cause);
}
public OSBTreeException(String message, Throwable cause) {
super(message, cause);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_sbtree_local_OSBTreeException.java |
1,096 | public class BundleOrderItemRequest {
protected String name;
protected Category category;
protected int quantity;
protected Order order;
protected List<DiscreteOrderItemRequest> discreteOrderItems = new ArrayList<DiscreteOrderItemRequest>();
protected List<BundleOrderItemFeePrice> bundleOrderItemFeePrices = new ArrayList<BundleOrderItemFeePrice>();
protected Money salePriceOverride;
protected Money retailPriceOverride;
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public List<DiscreteOrderItemRequest> getDiscreteOrderItems() {
return discreteOrderItems;
}
public void setDiscreteOrderItems(List<DiscreteOrderItemRequest> discreteOrderItems) {
this.discreteOrderItems = discreteOrderItems;
}
public List<BundleOrderItemFeePrice> getBundleOrderItemFeePrices() {
return bundleOrderItemFeePrices;
}
public void setBundleOrderItemFeePrices(
List<BundleOrderItemFeePrice> bundleOrderItemFeePrices) {
this.bundleOrderItemFeePrices = bundleOrderItemFeePrices;
}
public Money getSalePriceOverride() {
return salePriceOverride;
}
public void setSalePriceOverride(Money salePriceOverride) {
this.salePriceOverride = salePriceOverride;
}
public Money getRetailPriceOverride() {
return retailPriceOverride;
}
public void setRetailPriceOverride(Money retailPriceOverride) {
this.retailPriceOverride = retailPriceOverride;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BundleOrderItemRequest other = (BundleOrderItemRequest) obj;
if (category == null) {
if (other.category != null)
return false;
} else if (!category.equals(other.category))
return false;
if (discreteOrderItems == null) {
if (other.discreteOrderItems != null)
return false;
} else if (!discreteOrderItems.equals(other.discreteOrderItems))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (quantity != other.quantity)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((category == null) ? 0 : category.hashCode());
result = prime * result + ((discreteOrderItems == null) ? 0 : discreteOrderItems.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + quantity;
return result;
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_call_BundleOrderItemRequest.java |
1,560 | public interface ActivityStateManager {
/**
* Register a RollbackHandler instance and some arbitrary state items with the
* StateManager. In the event of a rollbackAllState() call, the StateManager will
* execute all registered RollbackHandler instances. Note, Broadleaf does not try to wrap
* the RollbackHandler execution in a database transaction. Therefore, if the RollbackHandler
* implementation requires a database transaction (i.e. it's updating the database), then
* the implementer must supply it. The easiest way to achieve this is to register the RollbackHandler
* as a Spring bean and either use <aop> declaration in the app context xml, or use @Transactional
* annotations in the implementation itself. Then, inject the RollbackHandler into your activity and
* call registerState when appropriate.
*
* @param rollbackHandler A RollbackHandler instance that should be executed by the StateManager
* @param stateItems Configuration items for the RollbackHandler (can be null)
*/
public void registerState(RollbackHandler rollbackHandler, Map<String, Object> stateItems);
/**
* Register a RollbackHandler instance and some arbitrary state items with the
* StateManager. In the event of a rollbackAllState() call, the StateManager will
* execute all registered RollbackHandler instances. Note, Broadleaf does not try to wrap
* the RollbackHandler execution in a database transaction. Therefore, if the RollbackHandler
* implementation requires a database transaction (i.e. it's updating the database), then
* the implementer must supply it. The easiest way to achieve this is to register the RollbackHandler
* as a Spring bean and either use <aop> declaration in the app context xml, or use @Transactional
* annotations in the implementation itself. Then, inject the RollbackHandler into your activity and
* call registerState when appropriate.
*
* @param activity the current activity associated with the RollbackHandler (can be null)
* @param processContext the current ProcessContext associated with the activity (can be null)
* @param rollbackHandler A RollbackHandler instance that should be executed by the StateManager
* @param stateItems Configuration items for the RollbackHandler (can be null)
*/
public void registerState(Activity<? extends ProcessContext> activity, ProcessContext processContext, RollbackHandler rollbackHandler, Map<String, Object> stateItems);
/**
* Register a RollbackHandler instance and some arbitrary state items with the
* StateManager. Can be used in conjunction with rollbackRegionState() to limit the scope of a rollback.
* Note, Broadleaf does not try to wrap the RollbackHandler execution in a database transaction. Therefore,
* if the RollbackHandler implementation requires a database transaction (i.e. it's updating the database), then
* the implementer must supply it. The easiest way to achieve this is to register the RollbackHandler
* as a Spring bean and either use <aop> declaration in the app context xml, or use @Transactional
* annotations in the implementation itself. Then, inject the RollbackHandler into your activity and
* call registerState when appropriate.
*
* @param activity the current activity associated with the RollbackHandler (can be null)
* @param processContext the current ProcessContext associated with the activity (can be null)
* @param region Label this rollback handler with a particular name.
* @param rollbackHandler A RollbackHandler instance that should be executed by the StateManager
* @param stateItems Configuration items for the RollbackHandler (can be null)
*/
public void registerState(Activity<? extends ProcessContext> activity, ProcessContext processContext, String region, RollbackHandler rollbackHandler, Map<String, Object> stateItems);
/**
* Cause the StateManager to call all registered RollbackHandlers
*
* @throws RollbackFailureException if the rollback fails for some reason
*/
public void rollbackAllState() throws RollbackFailureException;
/**
* Cause the StateManager to call all registered RollbackHandlers in the specified region.
*
* @throws RollbackFailureException if the rollback fails for some reason
*/
public void rollbackRegionState(String region) throws RollbackFailureException;
/**
* Remove all previously registered RollbackHandlers for the current workflow
*/
public void clearAllState();
/**
* Remove all previously registered Rollbackhandlers for the current workflow labelled with the specified region
*
* @param region The region to which the scope of removal is limited
*/
public void clearRegionState(String region);
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_workflow_state_ActivityStateManager.java |
2,105 | public class BytesStreamsTests extends ElasticsearchTestCase {
@Test
public void testSimpleStreams() throws Exception {
assumeTrue(Constants.JRE_IS_64BIT);
BytesStreamOutput out = new BytesStreamOutput();
out.writeBoolean(false);
out.writeByte((byte) 1);
out.writeShort((short) -1);
out.writeInt(-1);
out.writeVInt(2);
out.writeLong(-3);
out.writeVLong(4);
out.writeFloat(1.1f);
out.writeDouble(2.2);
int[] intArray = {1, 2, 3};
out.writeGenericValue(intArray);
long[] longArray = {1, 2, 3};
out.writeGenericValue(longArray);
float[] floatArray = {1.1f, 2.2f, 3.3f};
out.writeGenericValue(floatArray);
double[] doubleArray = {1.1, 2.2, 3.3};
out.writeGenericValue(doubleArray);
out.writeString("hello");
out.writeString("goodbye");
BytesStreamInput in = new BytesStreamInput(out.bytes().toBytes(), false);
assertThat(in.readBoolean(), equalTo(false));
assertThat(in.readByte(), equalTo((byte) 1));
assertThat(in.readShort(), equalTo((short) -1));
assertThat(in.readInt(), equalTo(-1));
assertThat(in.readVInt(), equalTo(2));
assertThat(in.readLong(), equalTo((long) -3));
assertThat(in.readVLong(), equalTo((long) 4));
assertThat((double) in.readFloat(), closeTo(1.1, 0.0001));
assertThat(in.readDouble(), closeTo(2.2, 0.0001));
assertThat(in.readGenericValue(), equalTo((Object)intArray));
assertThat(in.readGenericValue(), equalTo((Object)longArray));
assertThat(in.readGenericValue(), equalTo((Object)floatArray));
assertThat(in.readGenericValue(), equalTo((Object)doubleArray));
assertThat(in.readString(), equalTo("hello"));
assertThat(in.readString(), equalTo("goodbye"));
}
@Test
public void testGrowLogic() throws Exception {
assumeTrue(Constants.JRE_IS_64BIT);
BytesStreamOutput out = new BytesStreamOutput();
out.writeBytes(new byte[BytesStreamOutput.DEFAULT_SIZE - 5]);
assertThat(out.bufferSize(), equalTo(2048)); // remains the default
out.writeBytes(new byte[1 * 1024]);
assertThat(out.bufferSize(), equalTo(4608));
out.writeBytes(new byte[32 * 1024]);
assertThat(out.bufferSize(), equalTo(40320));
out.writeBytes(new byte[32 * 1024]);
assertThat(out.bufferSize(), equalTo(90720));
}
} | 0true
| src_test_java_org_elasticsearch_common_io_streams_BytesStreamsTests.java |
1,571 | @ManagedDescription("ReplicatedMap")
public class ReplicatedMapMBean extends HazelcastMBean<ReplicatedMapProxy> {
private final AtomicLong totalAddedEntryCount = new AtomicLong();
private final AtomicLong totalRemovedEntryCount = new AtomicLong();
private final AtomicLong totalUpdatedEntryCount = new AtomicLong();
private final String listenerId;
protected ReplicatedMapMBean(ReplicatedMapProxy managedObject, ManagementService service) {
super(managedObject, service);
objectName = service.createObjectName("ReplicatedMap", managedObject.getName());
//todo: using the event system to register number of adds/remove is an very expensive price to pay.
EntryListener entryListener = new EntryListener() {
@Override
public void entryAdded(EntryEvent event) {
totalAddedEntryCount.incrementAndGet();
}
@Override
public void entryRemoved(EntryEvent event) {
totalRemovedEntryCount.incrementAndGet();
}
@Override
public void entryUpdated(EntryEvent event) {
totalUpdatedEntryCount.incrementAndGet();
}
@Override
public void entryEvicted(EntryEvent event) {
}
};
listenerId = managedObject.addEntryListener(entryListener, false);
}
@Override
public void preDeregister() throws Exception {
super.preDeregister();
try {
managedObject.removeEntryListener(listenerId);
} catch (Exception ignored) {
}
}
@ManagedAnnotation("localOwnedEntryCount")
@ManagedDescription("number of entries owned on this member")
public long getLocalOwnedEntryCount(){
return managedObject.getReplicatedMapStats().getOwnedEntryCount();
}
@ManagedAnnotation("localCreationTime")
@ManagedDescription("the creation time of this map on this member.")
public long getLocalCreationTime(){
return managedObject.getReplicatedMapStats().getCreationTime();
}
@ManagedAnnotation("localLastAccessTime")
@ManagedDescription("the last access (read) time of the locally owned entries.")
public long getLocalLastAccessTime(){
return managedObject.getReplicatedMapStats().getLastAccessTime();
}
@ManagedAnnotation("localLastUpdateTime")
@ManagedDescription("the last update time of the locally owned entries.")
public long getLocalLastUpdateTime(){
return managedObject.getReplicatedMapStats().getLastUpdateTime();
}
@ManagedAnnotation("localHits")
@ManagedDescription("the number of hits (reads) of the locally owned entries.")
public long getLocalHits(){
return managedObject.getReplicatedMapStats().getHits();
}
@ManagedAnnotation("localPutOperationCount")
@ManagedDescription("the number of put operations on this member")
public long getLocalPutOperationCount(){
return managedObject.getReplicatedMapStats().getPutOperationCount();
}
@ManagedAnnotation("localGetOperationCount")
@ManagedDescription("number of get operations on this member")
public long getLocalGetOperationCount(){
return managedObject.getReplicatedMapStats().getGetOperationCount();
}
@ManagedAnnotation("localRemoveOperationCount")
@ManagedDescription("number of remove operations on this member")
public long getLocalRemoveOperationCount(){
return managedObject.getReplicatedMapStats().getRemoveOperationCount();
}
@ManagedAnnotation("localTotalPutLatency")
@ManagedDescription("the total latency of put operations. To get the average latency, divide to number of puts")
public long getLocalTotalPutLatency(){
return managedObject.getReplicatedMapStats().getTotalPutLatency();
}
@ManagedAnnotation("localTotalGetLatency")
@ManagedDescription("the total latency of get operations. To get the average latency, divide to number of gets")
public long getLocalTotalGetLatency(){
return managedObject.getReplicatedMapStats().getTotalGetLatency();
}
@ManagedAnnotation("localTotalRemoveLatency")
@ManagedDescription("the total latency of remove operations. To get the average latency, divide to number of gets")
public long getLocalTotalRemoveLatency(){
return managedObject.getReplicatedMapStats().getTotalRemoveLatency();
}
@ManagedAnnotation("localMaxPutLatency")
@ManagedDescription("the maximum latency of put operations. To get the average latency, divide to number of puts")
public long getLocalMaxPutLatency(){
return managedObject.getReplicatedMapStats().getMaxPutLatency();
}
@ManagedAnnotation("localMaxGetLatency")
@ManagedDescription("the maximum latency of get operations. To get the average latency, divide to number of gets")
public long getLocalMaxGetLatency(){
return managedObject.getReplicatedMapStats().getMaxGetLatency();
}
@ManagedAnnotation("localMaxRemoveLatency")
@ManagedDescription("the maximum latency of remove operations. To get the average latency, divide to number of gets")
public long getMaxRemoveLatency(){
return managedObject.getReplicatedMapStats().getMaxRemoveLatency();
}
@ManagedAnnotation("localEventOperationCount")
@ManagedDescription("number of events received on this member")
public long getLocalEventOperationCount(){
return managedObject.getReplicatedMapStats().getEventOperationCount();
}
@ManagedAnnotation("localReplicationEventCount")
@ManagedDescription("number of replication events received on this member")
public long getLocalReplicationEventCount(){
return managedObject.getReplicatedMapStats().getReplicationEventCount();
}
@ManagedAnnotation("localOtherOperationCount")
@ManagedDescription("the total number of other operations on this member")
public long getLocalOtherOperationCount(){
return managedObject.getReplicatedMapStats().getOtherOperationCount();
}
@ManagedAnnotation("localTotal")
@ManagedDescription("the total number of operations on this member")
public long localTotal(){
return managedObject.getReplicatedMapStats().total();
}
@ManagedAnnotation("name")
@ManagedDescription("name of the map")
public String getName(){
return managedObject.getName();
}
@ManagedAnnotation("size")
@ManagedDescription("size of the map")
public int getSize(){
return managedObject.size();
}
@ManagedAnnotation("config")
@ManagedDescription("MapConfig")
public String getConfig(){
return service.instance.getConfig().findMapConfig(managedObject.getName()).toString();
}
@ManagedAnnotation("totalAddedEntryCount")
public long getTotalAddedEntryCount(){
return totalAddedEntryCount.get();
}
@ManagedAnnotation("totalRemovedEntryCount")
public long getTotalRemovedEntryCount() {
return totalRemovedEntryCount.get();
}
@ManagedAnnotation("totalUpdatedEntryCount")
public long getTotalUpdatedEntryCount() {
return totalUpdatedEntryCount.get();
}
@ManagedAnnotation(value = "clear", operation = true)
@ManagedDescription("Clear Map")
public void clear(){
managedObject.clear();
}
@ManagedAnnotation(value = "values", operation = true)
public String values(){
Collection coll = managedObject.values();
StringBuilder buf = new StringBuilder();
if (coll.size() == 0){
buf.append("Empty");
}
else {
buf.append("[");
for (Object obj: coll){
buf.append(obj);
buf.append(", ");
}
buf.replace(buf.length()-1, buf.length(), "]");
}
return buf.toString();
}
@ManagedAnnotation(value = "entrySet", operation = true)
public String entrySet(){
Set<Map.Entry> entrySet = managedObject.entrySet();
StringBuilder buf = new StringBuilder();
if (entrySet.size() == 0){
buf.append("Empty");
}
else {
buf.append("[");
for (Map.Entry entry: entrySet){
buf.append("{key:");
buf.append(entry.getKey());
buf.append(", value:");
buf.append(entry.getValue());
buf.append("}, ");
}
buf.replace(buf.length()-1, buf.length(), "]");
}
return buf.toString();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_jmx_ReplicatedMapMBean.java |
1,759 | public static class PlaneFixedSourceDistance implements FixedSourceDistance {
private final double sourceLatitude;
private final double sourceLongitude;
private final double distancePerDegree;
public PlaneFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
this.sourceLatitude = sourceLatitude;
this.sourceLongitude = sourceLongitude;
this.distancePerDegree = unit.getDistancePerDegree();
}
@Override
public double calculate(double targetLatitude, double targetLongitude) {
double px = targetLongitude - sourceLongitude;
double py = targetLatitude - sourceLatitude;
return Math.sqrt(px * px + py * py) * distancePerDegree;
}
} | 0true
| src_main_java_org_elasticsearch_common_geo_GeoDistance.java |
787 | @Repository("blOfferCodeDao")
public class OfferCodeDaoImpl implements OfferCodeDao {
@PersistenceContext(unitName="blPU")
protected EntityManager em;
@Resource(name="blEntityConfiguration")
protected EntityConfiguration entityConfiguration;
public OfferCode create() {
return ((OfferCode) entityConfiguration.createEntityInstance(OfferCode.class.getName()));
}
public void delete(OfferCode offerCode) {
if (!em.contains(offerCode)) {
offerCode = readOfferCodeById(offerCode.getId());
}
em.remove(offerCode);
}
public OfferCode save(OfferCode offerCode) {
return em.merge(offerCode);
}
public OfferCode readOfferCodeById(Long offerCodeId) {
return (OfferCode) em.find(OfferCodeImpl.class, offerCodeId);
}
@SuppressWarnings("unchecked")
public OfferCode readOfferCodeByCode(String code) {
OfferCode offerCode = null;
Query query = em.createNamedQuery("BC_READ_OFFER_CODE_BY_CODE");
query.setParameter("code", code);
query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");
List<OfferCode> result = query.getResultList();
if (result.size() > 0) {
offerCode = result.get(0);
}
return offerCode;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_dao_OfferCodeDaoImpl.java |
431 | public interface Retriever {
/**
* Returns the {@link IndexRetriever} for a given index.
* @param index
* @return
*/
public IndexRetriever get(String index);
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_KeyInformation.java |
2,430 | public class AtomicArray<E> {
private static final AtomicArray EMPTY = new AtomicArray(0);
@SuppressWarnings("unchecked")
public static <E> E empty() {
return (E) EMPTY;
}
private final AtomicReferenceArray<E> array;
private volatile List<Entry<E>> nonNullList;
public AtomicArray(int size) {
array = new AtomicReferenceArray<E>(size);
}
/**
* The size of the expected results, including potential null values.
*/
public int length() {
return array.length();
}
/**
* Sets the element at position {@code i} to the given value.
*
* @param i the index
* @param value the new value
*/
public void set(int i, E value) {
array.set(i, value);
if (nonNullList != null) { // read first, lighter, and most times it will be null...
nonNullList = null;
}
}
/**
* Gets the current value at position {@code i}.
*
* @param i the index
* @return the current value
*/
public E get(int i) {
return array.get(i);
}
/**
* Returns the it as a non null list, with an Entry wrapping each value allowing to
* retain its index.
*/
public List<Entry<E>> asList() {
if (nonNullList == null) {
if (array == null || array.length() == 0) {
nonNullList = ImmutableList.of();
} else {
List<Entry<E>> list = new ArrayList<Entry<E>>(array.length());
for (int i = 0; i < array.length(); i++) {
E e = array.get(i);
if (e != null) {
list.add(new Entry<E>(i, e));
}
}
nonNullList = list;
}
}
return nonNullList;
}
/**
* Copies the content of the underlying atomic array to a normal one.
*/
public E[] toArray(E[] a) {
if (a.length != array.length()) {
throw new ElasticsearchGenerationException("AtomicArrays can only be copied to arrays of the same size");
}
for (int i = 0; i < array.length(); i++) {
a[i] = array.get(i);
}
return a;
}
/**
* An entry within the array.
*/
public static class Entry<E> {
/**
* The original index of the value within the array.
*/
public final int index;
/**
* The value.
*/
public final E value;
public Entry(int index, E value) {
this.index = index;
this.value = value;
}
}
} | 0true
| src_main_java_org_elasticsearch_common_util_concurrent_AtomicArray.java |
4,276 | public class SimpleFsTranslogFile implements FsTranslogFile {
private final long id;
private final ShardId shardId;
private final RafReference raf;
private final AtomicInteger operationCounter = new AtomicInteger();
private final AtomicLong lastPosition = new AtomicLong(0);
private final AtomicLong lastWrittenPosition = new AtomicLong(0);
private volatile long lastSyncPosition = 0;
public SimpleFsTranslogFile(ShardId shardId, long id, RafReference raf) throws IOException {
this.shardId = shardId;
this.id = id;
this.raf = raf;
raf.raf().setLength(0);
}
public long id() {
return this.id;
}
public int estimatedNumberOfOperations() {
return operationCounter.get();
}
public long translogSizeInBytes() {
return lastWrittenPosition.get();
}
public Translog.Location add(byte[] data, int from, int size) throws IOException {
long position = lastPosition.getAndAdd(size);
raf.channel().write(ByteBuffer.wrap(data, from, size), position);
lastWrittenPosition.getAndAdd(size);
operationCounter.incrementAndGet();
return new Translog.Location(id, position, size);
}
public byte[] read(Translog.Location location) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(location.size);
raf.channel().read(buffer, location.translogLocation);
return buffer.array();
}
public void close(boolean delete) {
sync();
raf.decreaseRefCount(delete);
}
/**
* Returns a snapshot on this file, <tt>null</tt> if it failed to snapshot.
*/
public FsChannelSnapshot snapshot() throws TranslogException {
try {
if (!raf.increaseRefCount()) {
return null;
}
return new FsChannelSnapshot(this.id, raf, lastWrittenPosition.get(), operationCounter.get());
} catch (Exception e) {
throw new TranslogException(shardId, "Failed to snapshot", e);
}
}
@Override
public boolean syncNeeded() {
return lastWrittenPosition.get() != lastSyncPosition;
}
public void sync() {
try {
// check if we really need to sync here...
long last = lastWrittenPosition.get();
if (last == lastSyncPosition) {
return;
}
lastSyncPosition = last;
raf.channel().force(false);
} catch (Exception e) {
// ignore
}
}
@Override
public void reuse(FsTranslogFile other) {
// nothing to do there
}
@Override
public void updateBufferSize(int bufferSize) throws TranslogException {
// nothing to do here...
}
} | 1no label
| src_main_java_org_elasticsearch_index_translog_fs_SimpleFsTranslogFile.java |
2,139 | public class LuceneTest {
/*
* simple test that ensures that we bumb the version on Upgrade
*/
@Test
public void testVersion() {
ESLogger logger = ESLoggerFactory.getLogger(LuceneTest.class.getName());
Version[] values = Version.values();
assertThat(Version.LUCENE_CURRENT, equalTo(values[values.length-1]));
assertThat("Latest Lucene Version is not set after upgrade", Lucene.VERSION, equalTo(values[values.length-2]));
assertThat(Lucene.parseVersion(null, Lucene.VERSION, null), equalTo(Lucene.VERSION));
for (int i = 0; i < values.length-1; i++) {
// this should fail if the lucene version is not mapped as a string in Lucene.java
assertThat(Lucene.parseVersion(values[i].name().replaceFirst("^LUCENE_(\\d)(\\d)$", "$1.$2"), Version.LUCENE_CURRENT, logger), equalTo(values[i]));
}
}
} | 0true
| src_test_java_org_elasticsearch_common_lucene_LuceneTest.java |
1,584 | enum EXECUTION_MODE {
RESPONSE, NO_RESPONSE
}; | 0true
| server_src_main_java_com_orientechnologies_orient_server_distributed_ODistributedRequest.java |
3,289 | private static final class RegexFilter extends FilteredTermsEnum {
private final Matcher matcher;
private final CharsRef spare = new CharsRef();
public RegexFilter(TermsEnum delegate, Matcher matcher) {
super(delegate, false);
this.matcher = matcher;
}
public static TermsEnum filter(TermsEnum iterator, Terms terms, AtomicReader reader, Settings regex) {
String pattern = regex.get("pattern");
if (pattern == null) {
return iterator;
}
Pattern p = Pattern.compile(pattern);
return new RegexFilter(iterator, p.matcher(""));
}
@Override
protected AcceptStatus accept(BytesRef arg0) throws IOException {
UnicodeUtil.UTF8toUTF16(arg0, spare);
matcher.reset(spare);
if (matcher.matches()) {
return AcceptStatus.YES;
}
return AcceptStatus.NO;
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_AbstractBytesIndexFieldData.java |
343 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ClientMapTryLockConcurrentTests {
static HazelcastInstance client;
static HazelcastInstance server;
@BeforeClass
public static void init() {
server = Hazelcast.newHazelcastInstance();
client = HazelcastClient.newHazelcastClient();
}
@AfterClass
public static void destroy() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void concurrent_MapTryLockTest() throws InterruptedException {
concurrent_MapTryLock(false);
}
@Test
public void concurrent_MapTryLockTimeOutTest() throws InterruptedException {
concurrent_MapTryLock(true);
}
private void concurrent_MapTryLock(boolean withTimeOut) throws InterruptedException {
final int maxThreads = 8;
final IMap<String, Integer> map = client.getMap(randomString());
final String upKey = "upKey";
final String downKey = "downKey";
map.put(upKey, 0);
map.put(downKey, 0);
Thread threads[] = new Thread[maxThreads];
for ( int i=0; i< threads.length; i++ ) {
Thread t;
if(withTimeOut){
t = new MapTryLockTimeOutThread(map, upKey, downKey);
}else{
t = new MapTryLockThread(map, upKey, downKey);
}
t.start();
threads[i] = t;
}
assertJoinable(threads);
int upTotal = map.get(upKey);
int downTotal = map.get(downKey);
assertTrue("concurrent access to locked code caused wrong total", upTotal + downTotal == 0);
}
static class MapTryLockThread extends TestHelper {
public MapTryLockThread(IMap map, String upKey, String downKey){
super(map, upKey, downKey);
}
public void doRun() throws Exception{
if(map.tryLock(upKey)){
try{
if(map.tryLock(downKey)){
try {
work();
}finally {
map.unlock(downKey);
}
}
}finally {
map.unlock(upKey);
}
}
}
}
static class MapTryLockTimeOutThread extends TestHelper {
public MapTryLockTimeOutThread(IMap map, String upKey, String downKey){
super(map, upKey, downKey);
}
public void doRun() throws Exception{
if(map.tryLock(upKey, 1, TimeUnit.MILLISECONDS)){
try{
if(map.tryLock(downKey, 1, TimeUnit.MILLISECONDS )){
try {
work();
}finally {
map.unlock(downKey);
}
}
}finally {
map.unlock(upKey);
}
}
}
}
static abstract class TestHelper extends Thread {
protected static final int ITERATIONS = 1000*10;
protected final Random random = new Random();
protected final IMap<String, Integer> map;
protected final String upKey;
protected final String downKey;
public TestHelper(IMap map, String upKey, String downKey){
this.map = map;
this.upKey = upKey;
this.downKey = downKey;
}
public void run() {
try{
for ( int i=0; i < ITERATIONS; i++ ) {
doRun();
}
}catch(Exception e){
throw new RuntimeException("Test Thread crashed with ", e);
}
}
abstract void doRun()throws Exception;
public void work(){
int upTotal = map.get(upKey);
int downTotal = map.get(downKey);
int dif = random.nextInt(1000);
upTotal += dif;
downTotal -= dif;
map.put(upKey, upTotal);
map.put(downKey, downTotal);
}
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTryLockConcurrentTests.java |
333 | public class InsertChildrenOf extends BaseHandler {
public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) {
if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) {
return null;
}
Node node1 = nodeList1.get(0);
Node node2 = nodeList2.get(0);
NodeList list2 = node2.getChildNodes();
for (int j = 0; j < list2.getLength(); j++) {
node1.appendChild(node1.getOwnerDocument().importNode(list2.item(j).cloneNode(true), true));
}
Node[] response = new Node[nodeList2.size()];
for (int j = 0; j < response.length; j++) {
response[j] = nodeList2.get(j);
}
return response;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_InsertChildrenOf.java |
721 | public class CollectionTransactionRollbackOperation extends CollectionOperation {
String transactionId;
public CollectionTransactionRollbackOperation() {
}
public CollectionTransactionRollbackOperation(String name, String transactionId) {
super(name);
this.transactionId = transactionId;
}
@Override
public int getId() {
return CollectionDataSerializerHook.TX_ROLLBACK;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
getOrCreateContainer().rollbackTransaction(transactionId);
}
@Override
public void afterRun() throws Exception {
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeUTF(transactionId);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
transactionId = in.readUTF();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionTransactionRollbackOperation.java |
1,496 | public class ODictionaryWrapper extends ODictionary<Object> {
private ODatabaseObject database;
public ODictionaryWrapper(final ODatabaseObject iDatabase,OIndex<OIdentifiable> index) {
super(index);
this.database = iDatabase;
}
@SuppressWarnings("unchecked")
public <RET extends Object> RET get(final String iKey, final String iFetchPlan) {
final ORecordInternal<?> record = super.get(iKey);
return (RET) database.getUserObjectByRecord(record, iFetchPlan);
}
public void put(final String iKey, final Object iValue) {
final ODocument record = (ODocument) database.getRecordByUserObject(iValue, false);
super.put(iKey, record);
}
} | 0true
| object_src_main_java_com_orientechnologies_orient_object_dictionary_ODictionaryWrapper.java |
641 | public class CollectionAddBackupOperation extends CollectionOperation implements BackupOperation {
private long itemId;
private Data value;
public CollectionAddBackupOperation() {
}
public CollectionAddBackupOperation(String name, long itemId, Data value) {
super(name);
this.itemId = itemId;
this.value = value;
}
@Override
public int getId() {
return CollectionDataSerializerHook.COLLECTION_ADD_BACKUP;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
getOrCreateContainer().addBackup(itemId, value);
}
@Override
public void afterRun() throws Exception {
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeLong(itemId);
value.writeData(out);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
itemId = in.readLong();
value = new Data();
value.readData(in);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionAddBackupOperation.java |
1,732 | public interface LifecycleComponent<T> extends CloseableComponent {
Lifecycle.State lifecycleState();
void addLifecycleListener(LifecycleListener listener);
void removeLifecycleListener(LifecycleListener listener);
T start() throws ElasticsearchException;
T stop() throws ElasticsearchException;
} | 0true
| src_main_java_org_elasticsearch_common_component_LifecycleComponent.java |
389 | public static class Builder {
private boolean supportsDocumentTTL = false;
private Mapping defaultStringMapping = Mapping.TEXT;
private Set<Mapping> supportedMappings = Sets.newHashSet();
public Builder supportsDocumentTTL() {
supportsDocumentTTL=true;
return this;
}
public Builder setDefaultStringMapping(Mapping map) {
defaultStringMapping = map;
return this;
}
public Builder supportedStringMappings(Mapping... maps) {
supportedMappings.addAll(Arrays.asList(maps));
return this;
}
public IndexFeatures build() {
return new IndexFeatures(supportsDocumentTTL, defaultStringMapping,
ImmutableSet.copyOf(supportedMappings));
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexFeatures.java |
391 | public class SupportLogger extends Logger {
private static final String FQCN = SupportLevel.class.getName();
protected String moduleName;
public SupportLogger(String moduleName, String name) {
super(name);
this.moduleName = moduleName;
}
/**
* Generate a SUPPORT level log message
*
* @param message the log message
*/
public void support(Object message) {
if (repository.isDisabled(SupportLevel.SUPPORT_INT))
return;
if (SupportLevel.SUPPORT.isGreaterOrEqual(this.getEffectiveLevel())) {
forcedLog(FQCN, SupportLevel.SUPPORT, moduleName + " - " + message, null);
}
}
/**
* Generate a SUPPORT level log message with an accompanying Throwable
*
* @param message the log message
* @param t the exception to accompany the log message - will result in a stack track in the log
*/
public void support(Object message, Throwable t) {
if (repository.isDisabled(SupportLevel.SUPPORT_INT))
return;
if (SupportLevel.SUPPORT.isGreaterOrEqual(this.getEffectiveLevel())) {
forcedLog(FQCN, SupportLevel.SUPPORT, moduleName + " - " + message, t);
}
}
/**
* Generate a specialized SUPPORT level log message that includes a LifeCycleEvent
* in the message.
*
* @param lifeCycleEvent The module life cycle type for this log message
* @param message the log message
*/
public void lifecycle(LifeCycleEvent lifeCycleEvent, Object message) {
if (repository.isDisabled(SupportLevel.SUPPORT_INT))
return;
if (SupportLevel.SUPPORT.isGreaterOrEqual(this.getEffectiveLevel())) {
forcedLog(FQCN, SupportLevel.SUPPORT, moduleName + " - " + lifeCycleEvent.toString() + (!StringUtils.isEmpty(message.toString())?" - " + message:""), null);
}
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_logging_SupportLogger.java |
1,825 | @Retention(RUNTIME)
@Target(TYPE)
public @interface ImplementedBy {
/**
* The implementation type.
*/
Class<?> value();
} | 0true
| src_main_java_org_elasticsearch_common_inject_ImplementedBy.java |
609 | public class BroadleafResourceHttpRequestBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
String[] names = factory.getBeanNamesForType(ResourceHttpRequestHandler.class);
for (String name : names) {
BeanDefinition bd = factory.getBeanDefinition(name);
bd.setBeanClassName(BroadleafGWTModuleURLMappingResourceHttpRequestHandler.class.getName());
}
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_web_BroadleafResourceHttpRequestBeanFactoryPostProcessor.java |
1,927 | public class MapAddEntryListenerSqlRequest extends AbstractMapAddEntryListenerRequest {
private String predicate;
transient private Predicate cachedPredicate;
public MapAddEntryListenerSqlRequest() {
super();
}
public MapAddEntryListenerSqlRequest(String name, boolean includeValue) {
super(name, includeValue);
}
public MapAddEntryListenerSqlRequest(String name, Data key, boolean includeValue) {
super(name, key, includeValue);
}
public MapAddEntryListenerSqlRequest(String name, Data key, boolean includeValue, String predicate) {
super(name, key, includeValue);
this.predicate = predicate;
}
protected Predicate getPredicate() {
if (cachedPredicate == null && predicate != null) {
cachedPredicate = new SqlPredicate(predicate);
}
return cachedPredicate;
}
public int getClassId() {
return MapPortableHook.ADD_ENTRY_LISTENER_SQL;
}
public void write(PortableWriter writer) throws IOException {
final boolean hasKey = key != null;
writer.writeBoolean("key", hasKey);
if (predicate == null) {
writer.writeBoolean("pre", false);
if (hasKey) {
final ObjectDataOutput out = writer.getRawDataOutput();
key.writeData(out);
}
} else {
writer.writeBoolean("pre", true);
writer.writeUTF("p", predicate);
final ObjectDataOutput out = writer.getRawDataOutput();
if (hasKey) {
key.writeData(out);
}
}
}
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("name");
includeValue = reader.readBoolean("i");
boolean hasKey = reader.readBoolean("key");
if (reader.readBoolean("pre")) {
predicate = reader.readUTF("p");
final ObjectDataInput in = reader.getRawDataInput();
if (hasKey) {
key = new Data();
key.readData(in);
}
} else if (hasKey) {
final ObjectDataInput in = reader.getRawDataInput();
key = new Data();
key.readData(in);
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_client_MapAddEntryListenerSqlRequest.java |
232 | private static final class HierarchyPresenterControlCreator
implements IInformationControlCreator {
private CeylonEditor editor;
private HierarchyPresenterControlCreator(CeylonEditor editor) {
this.editor = editor;
}
@Override
public IInformationControl createInformationControl(Shell parent) {
return new HierarchyPopup(editor, parent, getPopupStyle());
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonSourceViewerConfiguration.java |
1,718 | runnable = new Runnable() { public void run() { map.putAll(mapWithNullValue); } }; | 0true
| hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java |
273 | public enum PoolExhaustedAction {
BLOCK(GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK),
FAIL(GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL),
GROW(GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW);
private final byte b;
PoolExhaustedAction(byte b) {
this.b = b;
}
public byte getByte() {
return b;
}
} | 0true
| titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_thrift_CassandraThriftStoreManager.java |
286 | static class NeoStoreCommand extends Command
{
private final NeoStoreRecord record;
private final NeoStore neoStore;
NeoStoreCommand( NeoStore neoStore, NeoStoreRecord record )
{
super( record.getId(), Mode.fromRecordState( record ) );
this.neoStore = neoStore;
this.record = record;
}
@Override
public void execute()
{
neoStore.setGraphNextProp( record.getNextProp() );
}
@Override
public void accept( CommandRecordVisitor visitor )
{
visitor.visitNeoStore( record );
}
@Override
public String toString()
{
return record.toString();
}
@Override
void removeFromCache( CacheAccessBackDoor cacheAccess )
{
// no-op
}
@Override
public void writeToFile( LogBuffer buffer ) throws IOException
{
buffer.put( NEOSTORE_COMMAND ).putLong( record.getNextProp() );
}
public static Command readFromFile( NeoStore neoStore,
ReadableByteChannel byteChannel, ByteBuffer buffer )
throws IOException
{
if ( !readAndFlip( byteChannel, buffer, 8 ) )
{
return null;
}
long nextProp = buffer.getLong();
NeoStoreRecord record = new NeoStoreRecord();
record.setNextProp( nextProp );
return new NeoStoreCommand( neoStore, record );
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_Command.java |
157 | class MockConnection implements Connection {
volatile boolean live = true;
final int port;
MockConnection(int port) {
this.port = port;
}
BlockingQueue<SocketWritable> q = new LinkedBlockingQueue<SocketWritable>();
public boolean write(SocketWritable packet) {
return q.offer(packet);
}
@Override
public Address getEndPoint() {
return null;
}
@Override
public boolean live() {
return live;
}
@Override
public long lastReadTime() {
return 0;
}
@Override
public long lastWriteTime() {
return 0;
}
@Override
public void close() {
live = false;
}
@Override
public boolean isClient() {
return true;
}
@Override
public ConnectionType getType() {
return ConnectionType.BINARY_CLIENT;
}
@Override
public InetAddress getInetAddress() {
return null;
}
@Override
public InetSocketAddress getRemoteSocketAddress() {
return null;
}
@Override
public int getPort() {
return port;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MockConnection)) return false;
MockConnection that = (MockConnection) o;
if (port != that.port) return false;
return true;
}
@Override
public int hashCode() {
return port;
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_client_MockSimpleClient.java |
195 | public class SocketOptions {
// socket options
private boolean tcpNoDelay;
private boolean keepAlive = true;
private boolean reuseAddress = true;
private int lingerSeconds = 3;
private int bufferSize = -1;
// in kb
public boolean isTcpNoDelay() {
return tcpNoDelay;
}
public SocketOptions setTcpNoDelay(boolean tcpNoDelay) {
this.tcpNoDelay = tcpNoDelay;
return this;
}
public boolean isKeepAlive() {
return keepAlive;
}
public SocketOptions setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
return this;
}
public boolean isReuseAddress() {
return reuseAddress;
}
public SocketOptions setReuseAddress(boolean reuseAddress) {
this.reuseAddress = reuseAddress;
return this;
}
public int getLingerSeconds() {
return lingerSeconds;
}
public SocketOptions setLingerSeconds(int lingerSeconds) {
this.lingerSeconds = lingerSeconds;
return this;
}
public int getBufferSize() {
return bufferSize;
}
public SocketOptions setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
return this;
}
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_config_SocketOptions.java |
5,835 | public class SourceScoreOrderFragmentsBuilder extends ScoreOrderFragmentsBuilder {
private final FieldMapper<?> mapper;
private final SearchContext searchContext;
public SourceScoreOrderFragmentsBuilder(FieldMapper<?> mapper, SearchContext searchContext,
String[] preTags, String[] postTags, BoundaryScanner boundaryScanner) {
super(preTags, postTags, boundaryScanner);
this.mapper = mapper;
this.searchContext = searchContext;
}
@Override
protected Field[] getFields(IndexReader reader, int docId, String fieldName) throws IOException {
// we know its low level reader, and matching docId, since that's how we call the highlighter with
SearchLookup lookup = searchContext.lookup();
lookup.setNextReader((AtomicReaderContext) reader.getContext());
lookup.setNextDocId(docId);
List<Object> values = lookup.source().extractRawValues(mapper.names().sourcePath());
Field[] fields = new Field[values.size()];
for (int i = 0; i < values.size(); i++) {
fields[i] = new Field(mapper.names().indexName(), values.get(i).toString(), TextField.TYPE_NOT_STORED);
}
return fields;
}
protected String makeFragment( StringBuilder buffer, int[] index, Field[] values, WeightedFragInfo fragInfo,
String[] preTags, String[] postTags, Encoder encoder ){
return super.makeFragment(buffer, index, values, FragmentBuilderHelper.fixWeightedFragInfo(mapper, values, fragInfo), preTags, postTags, encoder);
}
} | 1no label
| src_main_java_org_elasticsearch_search_highlight_vectorhighlight_SourceScoreOrderFragmentsBuilder.java |
309 | new Processor() {
@Override
public void visit(Tree.Annotation that) {
super.visit(that);
terminateWithSemicolon(that);
}
@Override
public void visit(Tree.StaticType that) {
super.visit(that);
terminateWithSemicolon(that);
}
@Override
public void visit(Tree.Expression that) {
super.visit(that);
terminateWithSemicolon(that);
}
boolean terminatedInLine(Node node) {
return node!=null &&
node.getStartIndex()<=endOfCodeInLine;
}
@Override
public void visit(Tree.IfClause that) {
super.visit(that);
if (missingBlock(that.getBlock()) &&
terminatedInLine(that.getConditionList())) {
terminateWithParenAndBaces(that,
that.getConditionList());
}
}
@Override
public void visit(Tree.ElseClause that) {
super.visit(that);
if (missingBlock(that.getBlock())) {
terminateWithBaces(that);
}
}
@Override
public void visit(Tree.ForClause that) {
super.visit(that);
if (missingBlock(that.getBlock()) &&
terminatedInLine(that.getForIterator())) {
terminateWithParenAndBaces(that,
that.getForIterator());
}
}
@Override
public void visit(Tree.WhileClause that) {
super.visit(that);
if (missingBlock(that.getBlock()) &&
terminatedInLine(that.getConditionList())) {
terminateWithParenAndBaces(that,
that.getConditionList());
}
}
@Override
public void visit(Tree.CaseClause that) {
super.visit(that);
if (missingBlock(that.getBlock()) &&
terminatedInLine(that.getCaseItem())) {
terminateWithParenAndBaces(that, that.getCaseItem());
}
}
@Override
public void visit(Tree.TryClause that) {
super.visit(that);
if (missingBlock(that.getBlock())) {
terminateWithBaces(that);
}
}
@Override
public void visit(Tree.CatchClause that) {
super.visit(that);
if (missingBlock(that.getBlock()) &&
terminatedInLine(that.getCatchVariable())) {
terminateWithParenAndBaces(that,
that.getCatchVariable());
}
}
@Override
public void visit(Tree.FinallyClause that) {
super.visit(that);
if (missingBlock(that.getBlock())) {
terminateWithBaces(that);
}
}
@Override
public void visit(Tree.StatementOrArgument that) {
if (that instanceof Tree.ExecutableStatement &&
!(that instanceof Tree.ControlStatement) ||
that instanceof Tree.AttributeDeclaration ||
that instanceof Tree.ImportModule ||
that instanceof Tree.TypeAliasDeclaration ||
that instanceof Tree.SpecifiedArgument) {
terminateWithSemicolon(that);
}
if (that instanceof Tree.MethodDeclaration) {
MethodDeclaration md = (Tree.MethodDeclaration) that;
if (md.getSpecifierExpression()==null) {
List<ParameterList> pl = md.getParameterLists();
if (md.getIdentifier()!=null && terminatedInLine(md.getIdentifier())) {
terminateWithParenAndBaces(that, pl.isEmpty() ? null : pl.get(pl.size()-1));
}
}
else {
terminateWithSemicolon(that);
}
}
if (that instanceof Tree.ClassDeclaration) {
ClassDeclaration cd = (Tree.ClassDeclaration) that;
if (cd.getClassSpecifier()==null) {
terminateWithParenAndBaces(that, cd.getParameterList());
}
else {
terminateWithSemicolon(that);
}
}
if (that instanceof Tree.InterfaceDeclaration) {
Tree.InterfaceDeclaration id = (Tree.InterfaceDeclaration) that;
if (id.getTypeSpecifier()==null) {
terminateWithBaces(that);
}
else {
terminateWithSemicolon(that);
}
}
super.visit(that);
}
private void terminateWithParenAndBaces(Node that, Node subnode) {
try {
if (that.getStartIndex()<=endOfCodeInLine &&
that.getStopIndex()>=endOfCodeInLine) {
if (subnode==null ||
subnode.getStartIndex()>endOfCodeInLine) {
if (!change.getEdit().hasChildren()) {
change.addEdit(new InsertEdit(endOfCodeInLine+1, "() {}"));
}
}
else {
Token et = that.getEndToken();
Token set = subnode.getEndToken();
if (set==null ||
set.getType()!=CeylonLexer.RPAREN ||
subnode.getStopIndex()>endOfCodeInLine) {
if (!change.getEdit().hasChildren()) {
change.addEdit(new InsertEdit(endOfCodeInLine+1, ") {}"));
}
}
else if (et==null ||
et.getType()!=CeylonLexer.RBRACE ||
that.getStopIndex()>endOfCodeInLine) {
if (!change.getEdit().hasChildren()) {
change.addEdit(new InsertEdit(endOfCodeInLine+1, " {}"));
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private void terminateWithBaces(Node that) {
try {
if (that.getStartIndex()<=endOfCodeInLine &&
that.getStopIndex()>=endOfCodeInLine) {
Token et = that.getEndToken();
if (et==null ||
et.getType()!=CeylonLexer.SEMICOLON &&
et.getType()!=CeylonLexer.RBRACE ||
that.getStopIndex()>endOfCodeInLine) {
if (!change.getEdit().hasChildren()) {
change.addEdit(new InsertEdit(endOfCodeInLine+1, " {}"));
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private void terminateWithSemicolon(Node that) {
try {
if (that.getStartIndex()<=endOfCodeInLine &&
that.getStopIndex()>=endOfCodeInLine) {
Token et = that.getEndToken();
if (et==null ||
et.getType()!=CeylonLexer.SEMICOLON ||
that.getStopIndex()>endOfCodeInLine) {
if (!change.getEdit().hasChildren()) {
change.addEdit(new InsertEdit(endOfCodeInLine+1, ";"));
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
protected boolean missingBlock(Block block) {
return block==null || block.getMainToken()==null ||
block.getMainToken()
.getText().startsWith("<missing");
}
}.visit(rootNode); | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_TerminateStatementAction.java |
1,032 | public class ConfigLoader {
private ConfigLoader() {
}
public static Config load(final String path) throws IOException {
final URL url = locateConfig(path);
if (url == null) {
return null;
}
return new UrlXmlConfig(url);
}
public static URL locateConfig(final String path) {
URL url = asFile(path);
if (url == null) {
url = asURL(path);
}
if (url == null) {
url = asResource(path);
}
return url;
}
private static URL asFile(final String path) {
File file = new File(path);
if (file.exists()) {
try {
return file.toURI().toURL();
} catch (MalformedURLException ignored) {
}
}
return null;
}
private static URL asURL(final String path) {
try {
return new URL(path);
} catch (MalformedURLException ignored) {
}
return null;
}
private static URL asResource(final String path) {
URL url = null;
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (contextClassLoader != null) {
url = contextClassLoader.getResource(path);
}
if (url == null) {
url = ConfigLoader.class.getClassLoader().getResource(path);
}
if (url == null) {
url = ClassLoader.getSystemClassLoader().getResource(path);
}
return url;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_config_ConfigLoader.java |
272 | public class LogTruncationTest
{
InMemoryLogBuffer inMemoryBuffer = new InMemoryLogBuffer();
@Test
public void testSerializationInFaceOfLogTruncation() throws Exception
{
// TODO: add support for other commands and permutations as well...
assertHandlesLogTruncation( new Command.NodeCommand( null,
new NodeRecord( 12l, 13l, 13l ),
new NodeRecord( 0,0,0 ) ) );
assertHandlesLogTruncation( new Command.LabelTokenCommand( null, new LabelTokenRecord( 1 )) );
assertHandlesLogTruncation( new Command.NeoStoreCommand( null, new NeoStoreRecord() ) );
// assertHandlesLogTruncation( new Command.PropertyCommand( null,
// new PropertyRecord( 1, true, new NodeRecord(1, 12, 12, true) ),
// new PropertyRecord( 1, true, new NodeRecord(1, 12, 12, true) ) ) );
}
private void assertHandlesLogTruncation( XaCommand cmd ) throws IOException
{
inMemoryBuffer.reset();
cmd.writeToFile( inMemoryBuffer );
int bytesSuccessfullyWritten = inMemoryBuffer.bytesWritten();
assertEquals( cmd, Command.readCommand( null, null, inMemoryBuffer, ByteBuffer.allocate( 100 ) ));
bytesSuccessfullyWritten--;
while(bytesSuccessfullyWritten --> 0)
{
inMemoryBuffer.reset();
cmd.writeToFile( inMemoryBuffer );
inMemoryBuffer.truncateTo( bytesSuccessfullyWritten );
Command deserialized = Command.readCommand( null, null, inMemoryBuffer, ByteBuffer.allocate( 100 ) );
assertNull( "Deserialization did not detect log truncation! Record: " + cmd +
", deserialized: " + deserialized, deserialized );
}
}
public class InMemoryLogBuffer implements LogBuffer, ReadableByteChannel
{
private byte[] bytes = new byte[1000];
private int writeIndex;
private int readIndex;
private ByteBuffer bufferForConversions = ByteBuffer.wrap( new byte[100] );
public InMemoryLogBuffer()
{
}
public void reset()
{
writeIndex = readIndex = 0;
}
public void truncateTo( int bytes )
{
writeIndex = bytes;
}
public int bytesWritten()
{
return writeIndex;
}
private void ensureArrayCapacityPlus( int plus )
{
while ( writeIndex+plus > bytes.length )
{
byte[] tmp = bytes;
bytes = new byte[bytes.length*2];
System.arraycopy( tmp, 0, bytes, 0, tmp.length );
}
}
private LogBuffer flipAndPut()
{
ensureArrayCapacityPlus( bufferForConversions.limit() );
System.arraycopy( bufferForConversions.flip().array(), 0, bytes, writeIndex,
bufferForConversions.limit() );
writeIndex += bufferForConversions.limit();
return this;
}
public LogBuffer put( byte b ) throws IOException
{
ensureArrayCapacityPlus( 1 );
bytes[writeIndex++] = b;
return this;
}
public LogBuffer putShort( short s ) throws IOException
{
((ByteBuffer) bufferForConversions.clear()).putShort( s );
return flipAndPut();
}
public LogBuffer putInt( int i ) throws IOException
{
((ByteBuffer) bufferForConversions.clear()).putInt( i );
return flipAndPut();
}
public LogBuffer putLong( long l ) throws IOException
{
((ByteBuffer) bufferForConversions.clear()).putLong( l );
return flipAndPut();
}
public LogBuffer putFloat( float f ) throws IOException
{
((ByteBuffer) bufferForConversions.clear()).putFloat( f );
return flipAndPut();
}
public LogBuffer putDouble( double d ) throws IOException
{
((ByteBuffer) bufferForConversions.clear()).putDouble( d );
return flipAndPut();
}
public LogBuffer put( byte[] bytes ) throws IOException
{
ensureArrayCapacityPlus( bytes.length );
System.arraycopy( bytes, 0, this.bytes, writeIndex, bytes.length );
writeIndex += bytes.length;
return this;
}
public LogBuffer put( char[] chars ) throws IOException
{
ensureConversionBufferCapacity( chars.length*2 );
bufferForConversions.clear();
for ( char ch : chars )
{
bufferForConversions.putChar( ch );
}
return flipAndPut();
}
private void ensureConversionBufferCapacity( int length )
{
if ( bufferForConversions.capacity() < length )
{
bufferForConversions = ByteBuffer.wrap( new byte[length*2] );
}
}
@Override
public void writeOut() throws IOException
{
}
public void force() throws IOException
{
}
public long getFileChannelPosition() throws IOException
{
return this.readIndex;
}
public StoreChannel getFileChannel()
{
throw new UnsupportedOperationException();
}
public boolean isOpen()
{
return true;
}
public void close() throws IOException
{
}
public int read( ByteBuffer dst ) throws IOException
{
if ( readIndex >= writeIndex )
{
return -1;
}
int actualLengthToRead = Math.min( dst.limit(), writeIndex-readIndex );
try
{
dst.put( bytes, readIndex, actualLengthToRead );
return actualLengthToRead;
}
finally
{
readIndex += actualLengthToRead;
}
}
}
} | 0true
| community_kernel_src_test_java_org_neo4j_kernel_impl_nioneo_xa_LogTruncationTest.java |
3,025 | public class DiskDocValuesFormatProvider extends AbstractDocValuesFormatProvider {
private final DocValuesFormat docValuesFormat;
@Inject
public DiskDocValuesFormatProvider(@Assisted String name, @Assisted Settings docValuesFormatSettings) {
super(name);
this.docValuesFormat = new DiskDocValuesFormat();
}
@Override
public DocValuesFormat get() {
return docValuesFormat;
}
} | 0true
| src_main_java_org_elasticsearch_index_codec_docvaluesformat_DiskDocValuesFormatProvider.java |
127 | public interface PropertyKeyMaker extends RelationTypeMaker {
/**
* Configures the {@link com.thinkaurelius.titan.core.Cardinality} of this property key.
*
* @param cardinality
* @return this PropertyKeyMaker
*/
public PropertyKeyMaker cardinality(Cardinality cardinality);
/**
* Configures the data type for this property key.
* <p/>
* Property instances for this key will only accept values that are instances of this class.
* Every property key must have its data type configured. Setting the data type to Object.class allows
* any type of value but comes at the expense of longer serialization because class information
* is stored with the value.
* <p/>
* It is strongly advised to pick an appropriate data type class so Titan can enforce it throughout the database.
*
* @param clazz Data type to be configured.
* @return this PropertyKeyMaker
* @see com.thinkaurelius.titan.core.PropertyKey#getDataType()
*/
public PropertyKeyMaker dataType(Class<?> clazz);
@Override
public PropertyKeyMaker signature(RelationType... types);
/**
* Defines the {@link com.thinkaurelius.titan.core.PropertyKey} specified by this PropertyKeyMaker and returns the resulting key.
*
* @return the created {@link PropertyKey}
*/
@Override
public PropertyKey make();
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_schema_PropertyKeyMaker.java |
1,617 | public class OMapReduceCommandTask extends OSQLCommandTask {
private static final long serialVersionUID = 1L;
public OMapReduceCommandTask() {
}
public OMapReduceCommandTask(final String iCommand) {
super(iCommand);
}
@Override
public RESULT_STRATEGY getResultStrategy() {
return RESULT_STRATEGY.MERGE;
}
public QUORUM_TYPE getQuorumType() {
return QUORUM_TYPE.NONE;
}
@Override
public String getName() {
return "map_reduce_command";
}
} | 0true
| server_src_main_java_com_orientechnologies_orient_server_distributed_task_OMapReduceCommandTask.java |
2,983 | public class FilterCacheModule extends AbstractModule {
public static final class FilterCacheSettings {
public static final String FILTER_CACHE_TYPE = "index.cache.filter.type";
}
private final Settings settings;
public FilterCacheModule(Settings settings) {
this.settings = settings;
}
@Override
protected void configure() {
bind(FilterCache.class)
.to(settings.getAsClass(FilterCacheSettings.FILTER_CACHE_TYPE, WeightedFilterCache.class, "org.elasticsearch.index.cache.filter.", "FilterCache"))
.in(Scopes.SINGLETON);
}
} | 0true
| src_main_java_org_elasticsearch_index_cache_filter_FilterCacheModule.java |
165 | public class RemoveDistributedObjectListenerRequest extends BaseClientRemoveListenerRequest {
public static final String CLEAR_LISTENERS_COMMAND = "clear-all-listeners";
public RemoveDistributedObjectListenerRequest() {
}
public RemoveDistributedObjectListenerRequest(String registrationId) {
super(null, registrationId);
}
@Override
public Object call() throws Exception {
//Please see above JavaDoc
if (CLEAR_LISTENERS_COMMAND.equals(name)) {
endpoint.clearAllListeners();
return true;
}
return clientEngine.getProxyService().removeProxyListener(registrationId);
}
@Override
public String getServiceName() {
return null;
}
@Override
public int getFactoryId() {
return ClientPortableHook.ID;
}
@Override
public int getClassId() {
return ClientPortableHook.REMOVE_LISTENER;
}
@Override
public Permission getRequiredPermission() {
return null;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_client_RemoveDistributedObjectListenerRequest.java |
931 | public final class LockStoreProxy implements LockStore {
private final LockStoreContainer container;
private final ObjectNamespace namespace;
public LockStoreProxy(LockStoreContainer container, ObjectNamespace namespace) {
this.container = container;
this.namespace = namespace;
}
@Override
public boolean lock(Data key, String caller, long threadId, long ttl) {
LockStore lockStore = getLockStore();
return lockStore.lock(key, caller, threadId, ttl);
}
@Override
public boolean txnLock(Data key, String caller, long threadId, long ttl) {
LockStore lockStore = getLockStore();
return lockStore.txnLock(key, caller, threadId, ttl);
}
@Override
public boolean extendLeaseTime(Data key, String caller, long threadId, long ttl) {
LockStore lockStore = getLockStore();
return lockStore.extendLeaseTime(key, caller, threadId, ttl);
}
@Override
public boolean unlock(Data key, String caller, long threadId) {
LockStore lockStore = getLockStore();
return lockStore.unlock(key, caller, threadId);
}
@Override
public boolean isLocked(Data key) {
LockStore lockStore = getLockStore();
return lockStore.isLocked(key);
}
@Override
public boolean isLockedBy(Data key, String caller, long threadId) {
LockStore lockStore = getLockStore();
return lockStore.isLockedBy(key, caller, threadId);
}
@Override
public int getLockCount(Data key) {
LockStore lockStore = getLockStore();
return lockStore.getLockCount(key);
}
@Override
public long getRemainingLeaseTime(Data key) {
LockStore lockStore = getLockStore();
return lockStore.getRemainingLeaseTime(key);
}
@Override
public boolean canAcquireLock(Data key, String caller, long threadId) {
LockStore lockStore = getLockStore();
return lockStore.canAcquireLock(key, caller, threadId);
}
@Override
public Set<Data> getLockedKeys() {
LockStore lockStore = getLockStore();
return lockStore.getLockedKeys();
}
@Override
public boolean forceUnlock(Data key) {
LockStore lockStore = getLockStore();
return lockStore.forceUnlock(key);
}
@Override
public String getOwnerInfo(Data dataKey) {
LockStore lockStore = getLockStore();
return lockStore.getOwnerInfo(dataKey);
}
private LockStore getLockStore() {
return container.getLockStore(namespace);
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockStoreProxy.java |
2,772 | public abstract class AbstractIndexComponent implements IndexComponent {
protected final ESLogger logger;
protected final Index index;
protected final Settings indexSettings;
protected final Settings componentSettings;
/**
* Constructs a new index component, with the index name and its settings.
*
* @param index The index name
* @param indexSettings The index settings
*/
protected AbstractIndexComponent(Index index, @IndexSettings Settings indexSettings) {
this.index = index;
this.indexSettings = indexSettings;
this.componentSettings = indexSettings.getComponentSettings(getClass());
this.logger = Loggers.getLogger(getClass(), indexSettings, index);
}
/**
* Constructs a new index component, with the index name and its settings, as well as settings prefix.
*
* @param index The index name
* @param indexSettings The index settings
* @param prefixSettings A settings prefix (like "com.mycompany") to simplify extracting the component settings
*/
protected AbstractIndexComponent(Index index, @IndexSettings Settings indexSettings, String prefixSettings) {
this.index = index;
this.indexSettings = indexSettings;
this.componentSettings = indexSettings.getComponentSettings(prefixSettings, getClass());
this.logger = Loggers.getLogger(getClass(), indexSettings, index);
}
@Override
public Index index() {
return this.index;
}
public String nodeName() {
return indexSettings.get("name", "");
}
} | 0true
| src_main_java_org_elasticsearch_index_AbstractIndexComponent.java |
760 | public class CompositeActivity extends BaseActivity<CheckoutContext> {
private SequenceProcessor workflow;
/* (non-Javadoc)
* @see org.broadleafcommerce.core.workflow.Activity#execute(org.broadleafcommerce.core.workflow.ProcessContext)
*/
@Override
public CheckoutContext execute(CheckoutContext context) throws Exception {
ProcessContext subContext = workflow.doActivities(context.getSeedData());
if (subContext.isStopped()) {
context.stopProcess();
}
return context;
}
public SequenceProcessor getWorkflow() {
return workflow;
}
public void setWorkflow(SequenceProcessor workflow) {
this.workflow = workflow;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_checkout_service_workflow_CompositeActivity.java |
414 | @Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface AdminPresentationCollection {
/**
* <p>Optional - field name will be used if not specified</p>
*
* <p>The friendly name to present to a user for this field in a GUI. If supporting i18N,
* the friendly name may be a key to retrieve a localized friendly name using
* the GWT support for i18N.</p>
*
* @return the friendly name
*/
String friendlyName() default "";
/**
* <p>Optional - only required if you wish to apply security to this field</p>
*
* <p>If a security level is specified, it is registered with the SecurityManager.
* The SecurityManager checks the permission of the current user to
* determine if this field should be disabled based on the specified level.</p>
*
* @return the security level
*/
String securityLevel() default "";
/**
* <p>Optional - fields are not excluded by default</p>
*
* <p>Specify if this field should be excluded from inclusion in the
* admin presentation layer</p>
*
* @return whether or not the field should be excluded
*/
boolean excluded() default false;
/**
* <p>Optional - only required if you want to make the field immutable</p>
*
* <p>Explicityly specify whether or not this field is mutable.</p>
*
* @return whether or not this field is read only
*/
boolean readOnly() default false;
/**
* <p>Optional - only required if you want to make the field ignore caching</p>
*
* <p>Explicitly specify whether or not this field will use server-side
* caching during inspection</p>
*
* @return whether or not this field uses caching
*/
boolean useServerSideInspectionCache() default true;
/**
* <p>Optional - only required if you want to lookup an item
* for this association, rather than creating a new instance of the
* target item. Note - if the type is changed to LOOKUP, this has
* the side effect of causing the only the association to be deleted
* during a remove, leaving the target lookup entity intact.</p>
*
* <p>Define whether or not added items for this
* collection are acquired via search or construction.</p>
*
* @return the item is acquired via lookup or construction
*/
AddMethodType addType() default AddMethodType.PERSIST;
/**
* <p>Optional - only required in the absence of a "mappedBy" property
* on the JPA annotation</p>
*
* <p>For the target entity of this collection, specify the field
* name that refers back to the parent entity.</p>
*
* <p>For collection definitions that use the "mappedBy" property
* of the @OneToMany and @ManyToMany annotations, this value
* can be safely ignored as the system will be able to infer
* the proper value from this.</p>
*
* @return the parent entity referring field name
*/
String manyToField() default "";
/**
* <p>Optional - only required if you want to specify ordering for this field</p>
*
* <p>The order in which this field will appear in a GUI relative to other collections from the same class</p>
*
* @return the display order
*/
int order() default 99999;
/**
* Optional - only required if you want the field to appear under a different tab
*
* Specify a GUI tab for this field
*
* @return the tab for this field
*/
String tab() default "General";
/**
* Optional - only required if you want to order the appearance of the tabs in the UI
*
* Specify an order for this tab. Tabs will be sorted int he resulting form in
* ascending order based on this parameter.
*
* The default tab will render with an order of 100.
*
* @return the order for this tab
*/
int tabOrder() default 100;
/**
* <p>Optional - only required if you need to specially handle crud operations for this
* specific collection on the server</p>
*
* <p>Custom string values that will be passed to the server during CRUB operations on this
* collection. These criteria values can be detected in a custom persistence handler
* (@CustomPersistenceHandler) in order to engage special handling through custom server
* side code for this collection.</p>
*
* @return the custom string array to pass to the server during CRUD operations
*/
String[] customCriteria() default {};
/**
* <p>Optional - only required if a special operation type is required for a CRUD operation. This
* setting is not normally changed and is an advanced setting</p>
*
* <p>The operation type for a CRUD operation</p>
*
* @return the operation type
*/
AdminPresentationOperationTypes operationTypes() default @AdminPresentationOperationTypes(addType = OperationType.BASIC, fetchType = OperationType.BASIC, inspectType = OperationType.BASIC, removeType = OperationType.BASIC, updateType = OperationType.BASIC);
/**
* <p>Optional - propertyName , only required if you want hide the field based on this property's value</p>
*
* <p>If the property is defined and found to be set to false, in the AppConfiguraionService, then this field will be excluded in the
* admin presentation layer</p>
*
* @return name of the property
*/
String showIfProperty() default "";
/**
* Optional - If you have FieldType set to SupportedFieldType.MONEY, *
* then you can specify a money currency property field.
*
*
* @return the currency property field
*/
String currencyCodeField() default "";
} | 0true
| common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentationCollection.java |
2,771 | public class NettyHttpServerTransportModule extends AbstractModule {
@Override
protected void configure() {
bind(HttpServerTransport.class).to(NettyHttpServerTransport.class).asEagerSingleton();
}
} | 0true
| src_main_java_org_elasticsearch_http_netty_NettyHttpServerTransportModule.java |
197 | public class OCLibraryFactory {
public static final OCLibraryFactory INSTANCE = new OCLibraryFactory();
private static final CLibrary C_LIBRARY;
static {
if (Platform.isAIX())
C_LIBRARY = new AIXCLibrary();
else
C_LIBRARY = new GeneralCLibrary();
}
public CLibrary library() {
return C_LIBRARY;
}
} | 0true
| nativeos_src_main_java_com_orientechnologies_nio_OCLibraryFactory.java |
779 | getAction.execute(getRequest, new ActionListener<GetResponse>() {
@Override
public void onResponse(GetResponse getResponse) {
if (!getResponse.isExists()) {
listener.onFailure(new DocumentMissingException(null, request.type(), request.id()));
return;
}
final BoolQueryBuilder boolBuilder = boolQuery();
try {
final DocumentMapper docMapper = indicesService.indexServiceSafe(concreteIndex).mapperService().documentMapper(request.type());
if (docMapper == null) {
throw new ElasticsearchException("No DocumentMapper found for type [" + request.type() + "]");
}
final Set<String> fields = newHashSet();
if (request.fields() != null) {
for (String field : request.fields()) {
FieldMappers fieldMappers = docMapper.mappers().smartName(field);
if (fieldMappers != null) {
fields.add(fieldMappers.mapper().names().indexName());
} else {
fields.add(field);
}
}
}
if (!fields.isEmpty()) {
// if fields are not empty, see if we got them in the response
for (Iterator<String> it = fields.iterator(); it.hasNext(); ) {
String field = it.next();
GetField getField = getResponse.getField(field);
if (getField != null) {
for (Object value : getField.getValues()) {
addMoreLikeThis(request, boolBuilder, getField.getName(), value.toString(), true);
}
it.remove();
}
}
if (!fields.isEmpty()) {
// if we don't get all the fields in the get response, see if we can parse the source
parseSource(getResponse, boolBuilder, docMapper, fields, request);
}
} else {
// we did not ask for any fields, try and get it from the source
parseSource(getResponse, boolBuilder, docMapper, fields, request);
}
if (!boolBuilder.hasClauses()) {
// no field added, fail
listener.onFailure(new ElasticsearchException("No fields found to fetch the 'likeText' from"));
return;
}
// exclude myself
Term uidTerm = docMapper.uidMapper().term(request.type(), request.id());
boolBuilder.mustNot(termQuery(uidTerm.field(), uidTerm.text()));
boolBuilder.adjustPureNegative(false);
} catch (Throwable e) {
listener.onFailure(e);
return;
}
String[] searchIndices = request.searchIndices();
if (searchIndices == null) {
searchIndices = new String[]{request.index()};
}
String[] searchTypes = request.searchTypes();
if (searchTypes == null) {
searchTypes = new String[]{request.type()};
}
int size = request.searchSize() != 0 ? request.searchSize() : 10;
int from = request.searchFrom() != 0 ? request.searchFrom() : 0;
SearchRequest searchRequest = searchRequest(searchIndices)
.types(searchTypes)
.searchType(request.searchType())
.scroll(request.searchScroll())
.extraSource(searchSource()
.query(boolBuilder)
.from(from)
.size(size)
)
.listenerThreaded(request.listenerThreaded());
if (request.searchSource() != null) {
searchRequest.source(request.searchSource(), request.searchSourceUnsafe());
}
searchAction.execute(searchRequest, new ActionListener<SearchResponse>() {
@Override
public void onResponse(SearchResponse response) {
listener.onResponse(response);
}
@Override
public void onFailure(Throwable e) {
listener.onFailure(e);
}
});
}
@Override
public void onFailure(Throwable e) {
listener.onFailure(e);
}
}); | 1no label
| src_main_java_org_elasticsearch_action_mlt_TransportMoreLikeThisAction.java |
930 | public class BroadcastShardOperationFailedException extends IndexShardException implements ElasticsearchWrapperException {
public BroadcastShardOperationFailedException(ShardId shardId, String msg) {
super(shardId, msg, null);
}
public BroadcastShardOperationFailedException(ShardId shardId, Throwable cause) {
super(shardId, "", cause);
}
public BroadcastShardOperationFailedException(ShardId shardId, String msg, Throwable cause) {
super(shardId, msg, cause);
}
} | 0true
| src_main_java_org_elasticsearch_action_support_broadcast_BroadcastShardOperationFailedException.java |
82 | LESS_THAN_EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp<=0:false;
}
@Override
public String toString() {
return "<=";
}
@Override
public TitanPredicate negate() {
return GREATER_THAN;
}
}, | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java |
1,367 | public class ClusterBlock implements Serializable, Streamable, ToXContent {
private int id;
private String description;
private ClusterBlockLevel[] levels;
private boolean retryable;
private boolean disableStatePersistence = false;
private RestStatus status;
ClusterBlock() {
}
public ClusterBlock(int id, String description, boolean retryable, boolean disableStatePersistence, RestStatus status, ClusterBlockLevel... levels) {
this.id = id;
this.description = description;
this.retryable = retryable;
this.disableStatePersistence = disableStatePersistence;
this.status = status;
this.levels = levels;
}
public int id() {
return this.id;
}
public String description() {
return this.description;
}
public RestStatus status() {
return this.status;
}
public ClusterBlockLevel[] levels() {
return this.levels;
}
public boolean contains(ClusterBlockLevel level) {
for (ClusterBlockLevel testLevel : levels) {
if (testLevel == level) {
return true;
}
}
return false;
}
/**
* Should operations get into retry state if this block is present.
*/
public boolean retryable() {
return this.retryable;
}
/**
* Should global state persistence be disabled when this block is present. Note,
* only relevant for global blocks.
*/
public boolean disableStatePersistence() {
return this.disableStatePersistence;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Integer.toString(id));
builder.field("description", description);
builder.field("retryable", retryable);
if (disableStatePersistence) {
builder.field("disable_state_persistence", disableStatePersistence);
}
builder.startArray("levels");
for (ClusterBlockLevel level : levels) {
builder.value(level.name().toLowerCase(Locale.ROOT));
}
builder.endArray();
builder.endObject();
return builder;
}
public static ClusterBlock readClusterBlock(StreamInput in) throws IOException {
ClusterBlock block = new ClusterBlock();
block.readFrom(in);
return block;
}
@Override
public void readFrom(StreamInput in) throws IOException {
id = in.readVInt();
description = in.readString();
levels = new ClusterBlockLevel[in.readVInt()];
for (int i = 0; i < levels.length; i++) {
levels[i] = ClusterBlockLevel.fromId(in.readVInt());
}
retryable = in.readBoolean();
disableStatePersistence = in.readBoolean();
status = RestStatus.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(id);
out.writeString(description);
out.writeVInt(levels.length);
for (ClusterBlockLevel level : levels) {
out.writeVInt(level.id());
}
out.writeBoolean(retryable);
out.writeBoolean(disableStatePersistence);
RestStatus.writeTo(out, status);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(id).append(",").append(description).append(", blocks ");
for (ClusterBlockLevel level : levels) {
sb.append(level.name()).append(",");
}
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClusterBlock that = (ClusterBlock) o;
if (id != that.id) return false;
return true;
}
@Override
public int hashCode() {
return id;
}
} | 1no label
| src_main_java_org_elasticsearch_cluster_block_ClusterBlock.java |
938 | Thread t = new Thread(new Runnable() {
public void run() {
final ILock lock = instance1.getLock(name);
lock.lock();
latch.countDown();
}
}); | 0true
| hazelcast_src_test_java_com_hazelcast_concurrent_lock_LockTest.java |
1,668 | interface BlobNameFilter {
/**
* Return <tt>false</tt> if the blob should be filtered.
*/
boolean accept(String blobName);
} | 0true
| src_main_java_org_elasticsearch_common_blobstore_BlobContainer.java |
614 | indexEngine.getValuesMinor(iRangeTo, isInclusive, MultiValuesTransformer.INSTANCE, new OIndexEngine.ValuesResultListener() {
@Override
public boolean addResult(OIdentifiable identifiable) {
return resultListener.addResult(identifiable);
}
}); | 1no label
| core_src_main_java_com_orientechnologies_orient_core_index_OIndexMultiValues.java |
998 | protected class PrimaryOperationRequest implements Streamable {
public int shardId;
public Request request;
public PrimaryOperationRequest() {
}
public PrimaryOperationRequest(int shardId, Request request) {
this.shardId = shardId;
this.request = request;
}
@Override
public void readFrom(StreamInput in) throws IOException {
shardId = in.readVInt();
request = newRequestInstance();
request.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(shardId);
request.writeTo(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_support_replication_TransportShardReplicationOperationAction.java |
688 | private static final class BucketPath {
private final BucketPath parent;
private final int hashMapOffset;
private final int itemIndex;
private final int nodeIndex;
private final int nodeGlobalDepth;
private final int nodeLocalDepth;
private BucketPath(BucketPath parent, int hashMapOffset, int itemIndex, int nodeIndex, int nodeLocalDepth, int nodeGlobalDepth) {
this.parent = parent;
this.hashMapOffset = hashMapOffset;
this.itemIndex = itemIndex;
this.nodeIndex = nodeIndex;
this.nodeGlobalDepth = nodeGlobalDepth;
this.nodeLocalDepth = nodeLocalDepth;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_OLocalHashTable.java |
112 | public interface LogProcessorFramework {
/**
* Returns a processor builder for the transaction log with the given log identifier.
* Only one processor may be registered per transaction log.
*
* @param logIdentifier Name that identifies the transaction log to be processed,
* i.e. the one used in {@link com.thinkaurelius.titan.core.TransactionBuilder#setLogIdentifier(String)}
* @return
*/
public LogProcessorBuilder addLogProcessor(String logIdentifier);
/**
* Removes the log processor for the given identifier and closes the associated log.
*
* @param logIdentifier
* @return
*/
public boolean removeLogProcessor(String logIdentifier);
/**
* Closes all log processors, their associated logs, and the backing graph instance
*
* @throws TitanException
*/
public void shutdown() throws TitanException;
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_log_LogProcessorFramework.java |
428 | BackendOperation.execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
index.mutate(mutations, keyInformations, indexTx);
return true;
}
@Override
public String toString() {
return "IndexMutation";
}
}, maxWriteTime); | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexTransaction.java |
1,049 | @SuppressWarnings("unchecked")
public class OCommandExecutorSQLResultsetDelegate extends OCommandExecutorSQLDelegate implements Iterable<OIdentifiable> {
public Iterator<OIdentifiable> iterator() {
return ((OCommandExecutorSQLResultsetAbstract) delegate).iterator();
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLResultsetDelegate.java |
345 | public class PartialTransactionFailureIT
{
@Rule
public TargetDirectory.TestDirectory dir =
TargetDirectory.testDirForTest( PartialTransactionFailureIT.class );
@Test
public void concurrentlyCommittingTransactionsMustNotRotateOutLoggedCommandsOfFailingTransaction()
throws Exception
{
final ClassGuardedAdversary adversary = new ClassGuardedAdversary(
new CountingAdversary( 1, false ),
"org.neo4j.kernel.impl.nioneo.xa.Command$RelationshipCommand" );
adversary.disable();
Map<String, String> params = stringMap(
"logical_log_rotation_threshold", "1",
"use_memory_mapped_buffers", "false");
String storeDir = dir.directory().getAbsolutePath();
final EmbeddedGraphDatabase db = new TestEmbeddedGraphDatabase( storeDir, params ) {
@Override
protected FileSystemAbstraction createFileSystemAbstraction()
{
return new AdversarialFileSystemAbstraction( adversary );
}
};
Node a, b, c, d;
Transaction tx = db.beginTx();
try
{
a = db.createNode();
b = db.createNode();
c = db.createNode();
d = db.createNode();
tx.success();
}
finally
{
tx.finish();
}
adversary.enable();
CountDownLatch latch = new CountDownLatch( 1 );
Thread t1 = new Thread( createRelationship( db, a, b, latch ) );
Thread t2 = new Thread( createRelationship( db, c, d, latch ) );
t1.start();
t2.start();
// Wait for both threads to get going
t1.join( 10 );
t2.join( 10 );
latch.countDown();
// Wait for the transactions to finish
t1.join( 25000 );
t2.join( 25000 );
db.shutdown();
// We should observe the store in a consistent state
EmbeddedGraphDatabase db2 = new TestEmbeddedGraphDatabase( storeDir, stringMap() );
tx = db2.beginTx();
try
{
Node x = db2.getNodeById( a.getId() );
Node y = db2.getNodeById( b.getId() );
Node z = db2.getNodeById( c.getId() );
Node w = db2.getNodeById( d.getId() );
Iterator<Relationship> itrRelX = x.getRelationships().iterator();
Iterator<Relationship> itrRelY = y.getRelationships().iterator();
Iterator<Relationship> itrRelZ = z.getRelationships().iterator();
Iterator<Relationship> itrRelW = w.getRelationships().iterator();
if ( itrRelX.hasNext() != itrRelY.hasNext() )
{
fail( "Node x and y have inconsistent relationship counts" );
}
else if ( itrRelX.hasNext() )
{
Relationship rel = itrRelX.next();
assertEquals( rel, itrRelY.next() );
assertFalse( itrRelX.hasNext() );
assertFalse( itrRelY.hasNext() );
}
if ( itrRelZ.hasNext() != itrRelW.hasNext() )
{
fail( "Node z and w have inconsistent relationship counts" );
}
else if ( itrRelZ.hasNext() )
{
Relationship rel = itrRelZ.next();
assertEquals( rel, itrRelW.next() );
assertFalse( itrRelZ.hasNext() );
assertFalse( itrRelW.hasNext() );
}
}
finally
{
try
{
tx.finish();
}
finally
{
db2.shutdown();
}
}
}
private Runnable createRelationship(
final EmbeddedGraphDatabase db,
final Node x,
final Node y,
final CountDownLatch latch )
{
return new Runnable()
{
@Override
public void run()
{
Transaction tx = db.beginTx();
try
{
x.createRelationshipTo( y, DynamicRelationshipType.withName( "r" ) );
tx.success();
latch.await();
tx.finish();
}
catch ( Exception ignore )
{
// We don't care about our transactions failing, as long as we
// can recover our database to a consistent state.
}
}
};
}
private static class TestEmbeddedGraphDatabase extends EmbeddedGraphDatabase
{
public TestEmbeddedGraphDatabase( String storeDir, Map<String, String> params )
{
super( storeDir,
params,
dependencies() );
}
private static Dependencies dependencies()
{
GraphDatabaseFactoryState state = new GraphDatabaseFactoryState();
state.addKernelExtensions( Arrays.asList(
new InMemoryIndexProviderFactory(),
new InMemoryLabelScanStoreExtension() ) );
state.setCacheProviders( Arrays.<CacheProvider>asList( new SoftCacheProvider() ) );
state.setTransactionInterceptorProviders( Iterables.<TransactionInterceptorProvider>empty() );
return state.databaseDependencies();
}
}
} | 0true
| community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_PartialTransactionFailureIT.java |
1,104 | public class OrderItemRequestDTO {
private Long skuId;
private Long categoryId;
private Long productId;
private Long orderItemId;
private Integer quantity;
private Money overrideSalePrice;
private Money overrideRetailPrice;
private Map<String,String> itemAttributes = new HashMap<String,String>();
public OrderItemRequestDTO() {}
public OrderItemRequestDTO(Long productId, Integer quantity) {
setProductId(productId);
setQuantity(quantity);
}
public OrderItemRequestDTO(Long productId, Long skuId, Integer quantity) {
setProductId(productId);
setSkuId(skuId);
setQuantity(quantity);
}
public OrderItemRequestDTO(Long productId, Long skuId, Long categoryId, Integer quantity) {
setProductId(productId);
setSkuId(skuId);
setCategoryId(categoryId);
setQuantity(quantity);
}
public Long getSkuId() {
return skuId;
}
public OrderItemRequestDTO setSkuId(Long skuId) {
this.skuId = skuId;
return this;
}
public Long getCategoryId() {
return categoryId;
}
public OrderItemRequestDTO setCategoryId(Long categoryId) {
this.categoryId = categoryId;
return this;
}
public Long getProductId() {
return productId;
}
public OrderItemRequestDTO setProductId(Long productId) {
this.productId = productId;
return this;
}
public Integer getQuantity() {
return quantity;
}
public OrderItemRequestDTO setQuantity(Integer quantity) {
this.quantity = quantity;
return this;
}
public Map<String, String> getItemAttributes() {
return itemAttributes;
}
public OrderItemRequestDTO setItemAttributes(Map<String, String> itemAttributes) {
this.itemAttributes = itemAttributes;
return this;
}
public Long getOrderItemId() {
return orderItemId;
}
public OrderItemRequestDTO setOrderItemId(Long orderItemId) {
this.orderItemId = orderItemId;
return this;
}
public Money getOverrideSalePrice() {
return overrideSalePrice;
}
public void setOverrideSalePrice(Money overrideSalePrice) {
this.overrideSalePrice = overrideSalePrice;
}
public Money getOverrideRetailPrice() {
return overrideRetailPrice;
}
public void setOverrideRetailPrice(Money overrideRetailPrice) {
this.overrideRetailPrice = overrideRetailPrice;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_call_OrderItemRequestDTO.java |
163 | @SuppressWarnings("unchecked")
public class OSynchEventAdapter<RESOURCE_TYPE, RESPONSE_TYPE> {
protected final LinkedHashMap<RESOURCE_TYPE, Object[]> queue = new LinkedHashMap<RESOURCE_TYPE, Object[]>();
public OSynchEventAdapter() {
}
public void registerCallbackCurrentThread(final RESOURCE_TYPE iResource) {
queue.put(iResource, new Object[] { iResource, null });
}
/**
* Wait forever until the requested resource is unlocked.
*/
public RESPONSE_TYPE waitForResource(final RESOURCE_TYPE iResource) {
return getValue(iResource, 0);
}
/**
* Wait until the requested resource is unlocked. Put the current thread in sleep until timeout or is waked up by an unlock.
*/
public synchronized RESPONSE_TYPE getValue(final RESOURCE_TYPE iResource, final long iTimeout) {
if (OLogManager.instance().isDebugEnabled())
OLogManager.instance().debug(
this,
"Thread [" + Thread.currentThread().getId() + "] is waiting for the resource " + iResource
+ (iTimeout <= 0 ? " forever" : " until " + iTimeout + "ms"));
synchronized (iResource) {
try {
iResource.wait(iTimeout);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new OLockException("Thread interrupted while waiting for resource '" + iResource + "'");
}
}
Object[] value = queue.remove(iResource);
return (RESPONSE_TYPE) (value != null ? value[1] : null);
}
public void setValue(final RESOURCE_TYPE iResource, final Object iValue) {
final Object[] waiter = queue.get(iResource);
if (waiter == null)
return;
synchronized (waiter[0]) {
waiter[1] = iValue;
waiter[0].notifyAll();
}
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_synch_OSynchEventAdapter.java |
703 | public interface ODiskCache {
long openFile(String fileName) throws IOException;
void openFile(long fileId) throws IOException;
OCacheEntry load(long fileId, long pageIndex, boolean checkPinnedPages) throws IOException;
void pinPage(OCacheEntry cacheEntry) throws IOException;
void loadPinnedPage(OCacheEntry cacheEntry) throws IOException;
OCacheEntry allocateNewPage(long fileId) throws IOException;
void release(OCacheEntry cacheEntry);
long getFilledUpTo(long fileId) throws IOException;
void flushFile(long fileId) throws IOException;
void closeFile(long fileId) throws IOException;
void closeFile(long fileId, boolean flush) throws IOException;
void deleteFile(long fileId) throws IOException;
void renameFile(long fileId, String oldFileName, String newFileName) throws IOException;
void truncateFile(long fileId) throws IOException;
boolean wasSoftlyClosed(long fileId) throws IOException;
void setSoftlyClosed(long fileId, boolean softlyClosed) throws IOException;
void setSoftlyClosed(boolean softlyClosed) throws IOException;
void flushBuffer() throws IOException;
void clear() throws IOException;
void close() throws IOException;
void delete() throws IOException;
OPageDataVerificationError[] checkStoredPages(OCommandOutputListener commandOutputListener);
Set<ODirtyPage> logDirtyPagesTable() throws IOException;
void forceSyncStoredChanges() throws IOException;
boolean isOpen(long fileId);
boolean exists(String name);
String fileNameById(long fileId);
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_cache_ODiskCache.java |
2,154 | public class TxnLockAndGetOperation extends LockAwareOperation {
private VersionedValue response;
private String ownerUuid;
public TxnLockAndGetOperation() {
}
public TxnLockAndGetOperation(String name, Data dataKey, long timeout, long ttl, String ownerUuid) {
super(name, dataKey, ttl);
this.ownerUuid = ownerUuid;
setWaitTimeout(timeout);
}
@Override
public void run() throws Exception {
if (!recordStore.txnLock(getKey(), ownerUuid, getThreadId(), ttl)) {
throw new TransactionException("Transaction couldn't obtain lock.");
}
Record record = recordStore.getRecord(dataKey);
Data value = record == null ? null : mapService.toData(record.getValue());
response = new VersionedValue(value, record == null ? 0 : record.getVersion());
}
public boolean shouldWait() {
return !recordStore.canAcquireLock(dataKey, ownerUuid, getThreadId());
}
@Override
public void onWaitExpire() {
final ResponseHandler responseHandler = getResponseHandler();
responseHandler.sendResponse(null);
}
@Override
public Object getResponse() {
return response;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeUTF(ownerUuid);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
ownerUuid = in.readUTF();
}
@Override
public String toString() {
return "TxnLockAndGetOperation{" +
"timeout=" + getWaitTimeout() +
", thread=" + getThreadId() +
'}';
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_map_tx_TxnLockAndGetOperation.java |
38 | public class SimpleCommand extends AbstractTextCommand {
ByteBuffer response;
public SimpleCommand(TextCommandType type) {
super(type);
}
public boolean readFrom(ByteBuffer cb) {
return true;
}
public void setResponse(byte[] value) {
this.response = ByteBuffer.wrap(value);
}
public boolean writeTo(ByteBuffer bb) {
while (bb.hasRemaining() && response.hasRemaining()) {
bb.put(response.get());
}
return !response.hasRemaining();
}
@Override
public String toString() {
return "SimpleCommand [" + type + "]{"
+ '}'
+ super.toString();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_ascii_memcache_SimpleCommand.java |
1,120 | public class ScriptsConstantScoreBenchmark extends BasicScriptBenchmark {
public static void main(String[] args) throws Exception {
int minTerms = 49;
int maxTerms = 50;
int maxIter = 1000;
int warmerIter = 1000;
init(maxTerms);
List<Results> allResults = new ArrayList<BasicScriptBenchmark.Results>();
Settings settings = settingsBuilder().put("plugin.types", NativeScriptExamplesPlugin.class.getName()).build();
String clusterName = ScriptsConstantScoreBenchmark.class.getSimpleName();
Node node1 = nodeBuilder().clusterName(clusterName).settings(settingsBuilder().put(settings).put("name", "node1")).node();
Client client = node1.client();
client.admin().cluster().prepareHealth("test").setWaitForGreenStatus().setTimeout("10s").execute().actionGet();
indexData(10000, client, true);
client.admin().cluster().prepareHealth("test").setWaitForGreenStatus().setTimeout("10s").execute().actionGet();
Results results = new Results();
results.init(maxTerms - minTerms, "native const script score (log(2) 10X)",
"Results for native const script score with score = log(2) 10X:", "black", "-.");
// init script searches
List<Entry<String, RequestInfo>> searchRequests = initScriptMatchAllSearchRequests(
NativeConstantForLoopScoreScript.NATIVE_CONSTANT_FOR_LOOP_SCRIPT_SCORE, true);
// run actual benchmark
runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter);
allResults.add(results);
// init native script searches
results = new Results();
results.init(maxTerms - minTerms, "mvel const (log(2) 10X)", "Results for mvel const score = log(2) 10X:", "red", "-.");
searchRequests = initScriptMatchAllSearchRequests("score = 0; for (int i=0; i<10;i++) {score = score + log(2);} return score",
false);
// run actual benchmark
runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter);
allResults.add(results);
results = new Results();
results.init(maxTerms - minTerms, "native const script score (2)", "Results for native const script score with score = 2:",
"black", ":");
// init native script searches
searchRequests = initScriptMatchAllSearchRequests(NativeConstantScoreScript.NATIVE_CONSTANT_SCRIPT_SCORE, true);
// run actual benchmark
runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter);
allResults.add(results);
results = new Results();
results.init(maxTerms - minTerms, "mvel const (2)", "Results for mvel const score = 2:", "red", "--");
// init native script searches
searchRequests = initScriptMatchAllSearchRequests("2", false);
// run actual benchmark
runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter);
allResults.add(results);
printOctaveScript(allResults, args);
client.close();
node1.close();
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_scripts_score_ScriptsConstantScoreBenchmark.java |
1,495 | public class NonResourceWebContentInterceptor extends WebContentInterceptor {
protected static final int TEN_YEARS_SECONDS = 60 * 60 * 24 * 365 * 10;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws ServletException {
if (BroadleafResourceHttpRequestHandler.class.isAssignableFrom(handler.getClass())) {
// Bundle resources are cached for ten years
BroadleafResourceHttpRequestHandler h = (BroadleafResourceHttpRequestHandler) handler;
if (h.isBundleRequest(request)) {
applyCacheSeconds(response, TEN_YEARS_SECONDS);
}
return true;
} else if (ResourceHttpRequestHandler.class.isAssignableFrom(handler.getClass())) {
// Non-bundle resources will not specify cache parameters - we will rely on the server responding
// with a 304 if the resource hasn't been modified.
return true;
} else {
// Non-resources (meaning requests that go to controllers) will apply the configured caching parameters.
return super.preHandle(request, response, handler);
}
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_interceptor_NonResourceWebContentInterceptor.java |
344 | public class ElasticSearchConfigTest {
private static final String INDEX_NAME = "escfg";
@Test
public void testTransportClient() throws BackendException, InterruptedException {
ElasticsearchRunner esr = new ElasticsearchRunner();
esr.start();
ModifiableConfiguration config = GraphDatabaseConfiguration.buildConfiguration();
config.set(INTERFACE, ElasticSearchSetup.TRANSPORT_CLIENT, INDEX_NAME);
Configuration indexConfig = config.restrictTo(INDEX_NAME);
IndexProvider idx = new ElasticSearchIndex(indexConfig);
simpleWriteAndQuery(idx);
idx.close();
config = GraphDatabaseConfiguration.buildConfiguration();
config.set(INTERFACE, ElasticSearchSetup.TRANSPORT_CLIENT, INDEX_NAME);
config.set(INDEX_HOSTS, new String[]{ "10.11.12.13" }, INDEX_NAME);
indexConfig = config.restrictTo(INDEX_NAME);
Throwable failure = null;
try {
idx = new ElasticSearchIndex(indexConfig);
} catch (Throwable t) {
failure = t;
}
// idx.close();
Assert.assertNotNull("ES client failed to throw exception on connection failure", failure);
esr.stop();
}
@Test
public void testLocalNodeUsingExt() throws BackendException, InterruptedException {
String baseDir = Joiner.on("/").join("target", "es", "jvmlocal_ext");
assertFalse(new File(baseDir + File.separator + "data").exists());
CommonsConfiguration cc = new CommonsConfiguration(new BaseConfiguration());
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.node.data", "true");
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.node.client", "false");
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.node.local", "true");
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.path.data", baseDir + File.separator + "data");
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.path.work", baseDir + File.separator + "work");
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.path.logs", baseDir + File.separator + "logs");
ModifiableConfiguration config =
new ModifiableConfiguration(GraphDatabaseConfiguration.ROOT_NS,
cc, BasicConfiguration.Restriction.NONE);
config.set(INTERFACE, ElasticSearchSetup.NODE, INDEX_NAME);
Configuration indexConfig = config.restrictTo(INDEX_NAME);
IndexProvider idx = new ElasticSearchIndex(indexConfig);
simpleWriteAndQuery(idx);
idx.close();
assertTrue(new File(baseDir + File.separator + "data").exists());
}
@Test
public void testLocalNodeUsingExtAndIndexDirectory() throws BackendException, InterruptedException {
String baseDir = Joiner.on("/").join("target", "es", "jvmlocal_ext2");
assertFalse(new File(baseDir + File.separator + "data").exists());
CommonsConfiguration cc = new CommonsConfiguration(new BaseConfiguration());
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.node.data", "true");
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.node.client", "false");
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.node.local", "true");
ModifiableConfiguration config =
new ModifiableConfiguration(GraphDatabaseConfiguration.ROOT_NS,
cc, BasicConfiguration.Restriction.NONE);
config.set(INTERFACE, ElasticSearchSetup.NODE, INDEX_NAME);
config.set(INDEX_DIRECTORY, baseDir, INDEX_NAME);
Configuration indexConfig = config.restrictTo(INDEX_NAME);
IndexProvider idx = new ElasticSearchIndex(indexConfig);
simpleWriteAndQuery(idx);
idx.close();
assertTrue(new File(baseDir + File.separator + "data").exists());
}
@Test
public void testLocalNodeUsingYaml() throws BackendException, InterruptedException {
String baseDir = Joiner.on("/").join("target", "es", "jvmlocal_yml");
assertFalse(new File(baseDir + File.separator + "data").exists());
ModifiableConfiguration config = GraphDatabaseConfiguration.buildConfiguration();
config.set(INTERFACE, ElasticSearchSetup.NODE, INDEX_NAME);
config.set(INDEX_CONF_FILE,
Joiner.on(File.separator).join("target", "test-classes", "es_jvmlocal.yml"), INDEX_NAME);
Configuration indexConfig = config.restrictTo(INDEX_NAME);
IndexProvider idx = new ElasticSearchIndex(indexConfig);
simpleWriteAndQuery(idx);
idx.close();
assertTrue(new File(baseDir + File.separator + "data").exists());
}
@Test
public void testNetworkNodeUsingExt() throws BackendException, InterruptedException {
ElasticsearchRunner esr = new ElasticsearchRunner();
esr.start();
CommonsConfiguration cc = new CommonsConfiguration(new BaseConfiguration());
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.node.data", "false");
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.node.client", "true");
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.discovery.zen.ping.multicast.enabled", "false");
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.discovery.zen.ping.unicast.hosts", "localhost,127.0.0.1:9300");
ModifiableConfiguration config =
new ModifiableConfiguration(GraphDatabaseConfiguration.ROOT_NS,
cc, BasicConfiguration.Restriction.NONE);
config.set(INTERFACE, ElasticSearchSetup.NODE, INDEX_NAME);
Configuration indexConfig = config.restrictTo(INDEX_NAME);
IndexProvider idx = new ElasticSearchIndex(indexConfig);
simpleWriteAndQuery(idx);
idx.close();
cc.set("index." + INDEX_NAME + ".elasticsearch.ext.discovery.zen.ping.unicast.hosts", "10.11.12.13");
config = new ModifiableConfiguration(GraphDatabaseConfiguration.ROOT_NS,
cc, BasicConfiguration.Restriction.NONE);
config.set(INTERFACE, ElasticSearchSetup.NODE, INDEX_NAME);
config.set(HEALTH_REQUEST_TIMEOUT, "5s", INDEX_NAME);
indexConfig = config.restrictTo(INDEX_NAME);
Throwable failure = null;
try {
idx = new ElasticSearchIndex(indexConfig);
} catch (Throwable t) {
failure = t;
}
// idx.close();
Assert.assertNotNull("ES client failed to throw exception on connection failure", failure);
esr.stop();
}
@Test
public void testNetworkNodeUsingYaml() throws BackendException, InterruptedException {
ElasticsearchRunner esr = new ElasticsearchRunner();
esr.start();
ModifiableConfiguration config = GraphDatabaseConfiguration.buildConfiguration();
config.set(INTERFACE, ElasticSearchSetup.NODE, INDEX_NAME);
config.set(INDEX_CONF_FILE,
Joiner.on(File.separator).join("target", "test-classes", "es_cfg_nodeclient.yml"), INDEX_NAME);
Configuration indexConfig = config.restrictTo(INDEX_NAME);
IndexProvider idx = new ElasticSearchIndex(indexConfig);
simpleWriteAndQuery(idx);
idx.close();
config = GraphDatabaseConfiguration.buildConfiguration();
config.set(INTERFACE, ElasticSearchSetup.NODE, INDEX_NAME);
config.set(HEALTH_REQUEST_TIMEOUT, "5s", INDEX_NAME);
config.set(INDEX_CONF_FILE,
Joiner.on(File.separator).join("target", "test-classes", "es_cfg_bogus_nodeclient.yml"), INDEX_NAME);
indexConfig = config.restrictTo(INDEX_NAME);
Throwable failure = null;
try {
idx = new ElasticSearchIndex(indexConfig);
} catch (Throwable t) {
failure = t;
}
//idx.close();
Assert.assertNotNull("ES client failed to throw exception on connection failure", failure);
esr.stop();
}
private void simpleWriteAndQuery(IndexProvider idx) throws BackendException, InterruptedException {
final Duration maxWrite = new StandardDuration(2000L, TimeUnit.MILLISECONDS);
final String storeName = "jvmlocal_test_store";
final KeyInformation.IndexRetriever indexRetriever = IndexProviderTest.getIndexRetriever(IndexProviderTest.getMapping(idx.getFeatures()));
BaseTransactionConfig txConfig = StandardBaseTransactionConfig.of(Timestamps.MILLI);
IndexTransaction itx = new IndexTransaction(idx, indexRetriever, txConfig, maxWrite);
assertEquals(0, itx.query(new IndexQuery(storeName, PredicateCondition.of(IndexProviderTest.NAME, Text.PREFIX, "ali"))).size());
itx.add(storeName, "doc", IndexProviderTest.NAME, "alice", false);
itx.commit();
Thread.sleep(1500L); // Slightly longer than default 1s index.refresh_interval
itx = new IndexTransaction(idx, indexRetriever, txConfig, maxWrite);
assertEquals(0, itx.query(new IndexQuery(storeName, PredicateCondition.of(IndexProviderTest.NAME, Text.PREFIX, "zed"))).size());
assertEquals(1, itx.query(new IndexQuery(storeName, PredicateCondition.of(IndexProviderTest.NAME, Text.PREFIX, "ali"))).size());
itx.rollback();
}
} | 0true
| titan-es_src_test_java_com_thinkaurelius_titan_diskstorage_es_ElasticSearchConfigTest.java |
42 | @Persistent
public final class PartitionTimestamps implements Cloneable {
private long startTimestamp;
private long endTimestamp;
public PartitionTimestamps() {
//
}
public PartitionTimestamps(long startTimestamp, long endTimestamp) {
this.startTimestamp = startTimestamp;
this.endTimestamp = endTimestamp;
}
public long getStartTimestamp() {
return startTimestamp;
}
public void setStartTimestamp(long startTimestamp) {
this.startTimestamp = startTimestamp;
}
public long getEndTimestamp() {
return endTimestamp;
}
public void setEndTimestamp(long endTimestamp) {
this.endTimestamp = endTimestamp;
}
@Override
public PartitionTimestamps clone() {
try {
return (PartitionTimestamps) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e); // should never happen
}
}
public void merge(long aStartTimestamp, long aEndTimestamp) {
startTimestamp = Math.min(startTimestamp, aStartTimestamp);
endTimestamp = Math.max(endTimestamp, aEndTimestamp);
}
public void merge(PartitionTimestamps timeStamp) {
merge(timeStamp.startTimestamp, timeStamp.endTimestamp);
}
@Override
public String toString() {
return "[" + startTimestamp + ", " + endTimestamp + "]";
}
} | 0true
| timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_disk_internal_PartitionTimestamps.java |
344 | fOpenAndLinkWithEditorHelper= new OpenAndLinkWithEditorHelper(fViewer) {
@Override
protected void activate(ISelection selection) {
try {
final Object selectedElement= SelectionUtil.getSingleElement(selection);
if (EditorUtility.isOpenInEditor(selectedElement) != null)
EditorUtility.openInEditor(selectedElement, true);
} catch (PartInitException ex) {
// ignore if no editor input can be found
}
}
@Override
protected void linkToEditor(ISelection selection) {
PackageExplorerPart.this.linkToEditor(selection);
}
@Override
protected void open(ISelection selection, boolean activate) {
fActionSet.handleOpen(selection, activate);
}
}; | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_PackageExplorerPart.java |
812 | @Entity
@Table(name = "BLC_OFFER")
@Inheritance(strategy=InheritanceType.JOINED)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "OfferImpl_baseOffer")
@SQLDelete(sql="UPDATE BLC_OFFER SET ARCHIVED = 'Y' WHERE OFFER_ID = ?")
public class OfferImpl implements Offer, Status, AdminMainEntity {
public static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator= "OfferId")
@GenericGenerator(
name="OfferId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="OfferImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.offer.domain.OfferImpl")
}
)
@Column(name = "OFFER_ID")
@AdminPresentation(friendlyName = "OfferImpl_Offer_Id", visibility = VisibilityEnum.HIDDEN_ALL)
protected Long id;
@OneToMany(mappedBy = "offer", targetEntity = OfferCodeImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
@BatchSize(size = 50)
@AdminPresentationCollection(addType = AddMethodType.PERSIST,
friendlyName = "offerCodeTitle",
order = 1,
tab = Presentation.Tab.Name.Codes,
tabOrder = Presentation.Tab.Order.Codes)
protected List<OfferCode> offerCodes = new ArrayList<OfferCode>(100);
@Column(name = "OFFER_NAME", nullable=false)
@Index(name="OFFER_NAME_INDEX", columnNames={"OFFER_NAME"})
@AdminPresentation(friendlyName = "OfferImpl_Offer_Name", order = 1000,
group = Presentation.Group.Name.Description, groupOrder = Presentation.Group.Order.Description,
prominent = true, gridOrder = 1)
protected String name;
@Column(name = "OFFER_DESCRIPTION")
@AdminPresentation(friendlyName = "OfferImpl_Offer_Description", order = 2000,
group = Presentation.Group.Name.Description, groupOrder = Presentation.Group.Order.Description,
prominent = true, gridOrder = 2,
largeEntry = true)
protected String description;
@Column(name = "MARKETING_MESSASGE")
@Index(name = "OFFER_MARKETING_MESSAGE_INDEX", columnNames = { "MARKETING_MESSASGE" })
@AdminPresentation(friendlyName = "OfferImpl_marketingMessage", order = 6000,
group = Presentation.Group.Name.Description, groupOrder = Presentation.Group.Order.Description,
translatable = true)
protected String marketingMessage;
@Column(name = "OFFER_TYPE", nullable=false)
@Index(name="OFFER_TYPE_INDEX", columnNames={"OFFER_TYPE"})
@AdminPresentation(friendlyName = "OfferImpl_Offer_Type", order = 3000,
group = Presentation.Group.Name.Description, groupOrder = Presentation.Group.Order.Description,
prominent = true, gridOrder = 3,
fieldType=SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration="org.broadleafcommerce.core.offer.service.type.OfferType")
protected String type;
@Column(name = "OFFER_DISCOUNT_TYPE")
@Index(name="OFFER_DISCOUNT_INDEX", columnNames={"OFFER_DISCOUNT_TYPE"})
@AdminPresentation(friendlyName = "OfferImpl_Offer_Discount_Type", order = 1000,
group = Presentation.Group.Name.Amount, groupOrder = Presentation.Group.Order.Amount,
requiredOverride = RequiredOverride.REQUIRED,
fieldType=SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration="org.broadleafcommerce.core.offer.service.type.OfferDiscountType")
protected String discountType;
@Column(name = "OFFER_VALUE", nullable=false, precision=19, scale=5)
@AdminPresentation(friendlyName = "OfferImpl_Offer_Value", order = 2000,
group = Presentation.Group.Name.Amount, groupOrder = Presentation.Group.Order.Amount,
prominent = true, gridOrder = 4)
protected BigDecimal value;
@Column(name = "OFFER_PRIORITY")
@AdminPresentation(friendlyName = "OfferImpl_Offer_Priority", order = 7,
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
protected Integer priority;
@Column(name = "START_DATE")
@AdminPresentation(friendlyName = "OfferImpl_Offer_Start_Date", order = 1,
group = Presentation.Group.Name.ActivityRange, groupOrder = Presentation.Group.Order.ActivityRange)
protected Date startDate;
@Column(name = "END_DATE")
@AdminPresentation(friendlyName = "OfferImpl_Offer_End_Date", order = 2,
group = Presentation.Group.Name.ActivityRange, groupOrder = Presentation.Group.Order.ActivityRange)
protected Date endDate;
@Column(name = "STACKABLE")
protected Boolean stackable = true;
@Column(name = "TARGET_SYSTEM")
@AdminPresentation(friendlyName = "OfferImpl_Offer_Target_System",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
protected String targetSystem;
@Column(name = "APPLY_TO_SALE_PRICE")
@AdminPresentation(friendlyName = "OfferImpl_Apply_To_Sale_Price",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
protected Boolean applyToSalePrice = false;
@Column(name = "APPLIES_TO_RULES", length = Integer.MAX_VALUE - 1)
@AdminPresentation(excluded = true)
@Lob
@Type(type = "org.hibernate.type.StringClobType")
@Deprecated
protected String appliesToOrderRules;
@Column(name = "APPLIES_WHEN_RULES", length = Integer.MAX_VALUE - 1)
@AdminPresentation(excluded = true)
@Lob
@Type(type = "org.hibernate.type.StringClobType")
@Deprecated
protected String appliesToCustomerRules;
@Column(name = "APPLY_OFFER_TO_MARKED_ITEMS")
@AdminPresentation(excluded = true)
@Deprecated
protected boolean applyDiscountToMarkedItems;
/**
* No offers can be applied on top of this offer;
* If false, stackable has to be false also
*/
@Column(name = "COMBINABLE_WITH_OTHER_OFFERS")
@AdminPresentation(friendlyName = "OfferImpl_Offer_Combinable",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
protected Boolean combinableWithOtherOffers = true;
@Column(name = "OFFER_DELIVERY_TYPE")
@AdminPresentation(excluded = true)
protected String deliveryType;
@Column(name = "AUTOMATICALLY_ADDED")
@AdminPresentation(friendlyName = "OfferImpl_Offer_Automatically_Added", order = 5000,
group = Presentation.Group.Name.Description, groupOrder = Presentation.Group.Order.Description,
fieldType = SupportedFieldType.BOOLEAN)
protected Boolean automaticallyAdded = false;
@Column(name = "MAX_USES")
@AdminPresentation(friendlyName = "OfferImpl_Offer_Max_Uses_Per_Order", order = 7,
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
protected Integer maxUsesPerOrder;
@Column(name = "MAX_USES_PER_CUSTOMER")
@AdminPresentation(friendlyName = "OfferImpl_Max_Uses_Per_Customer", order = 8,
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
protected Long maxUsesPerCustomer;
@Column(name = "USES")
@AdminPresentation(friendlyName = "OfferImpl_Offer_Current_Uses",
visibility = VisibilityEnum.HIDDEN_ALL)
@Deprecated
protected int uses;
@Column(name = "OFFER_ITEM_QUALIFIER_RULE")
@AdminPresentation(friendlyName = "OfferImpl_Item_Qualifier_Rule",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced,
fieldType = SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration = "org.broadleafcommerce.core.offer.service.type.OfferItemRestrictionRuleType")
protected String offerItemQualifierRuleType;
@Column(name = "OFFER_ITEM_TARGET_RULE")
@AdminPresentation(friendlyName = "OfferImpl_Item_Target_Rule",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced,
fieldType = SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration = "org.broadleafcommerce.core.offer.service.type.OfferItemRestrictionRuleType")
protected String offerItemTargetRuleType;
@OneToMany(fetch = FetchType.LAZY, targetEntity = OfferItemCriteriaImpl.class, cascade={CascadeType.ALL})
@JoinTable(name = "BLC_QUAL_CRIT_OFFER_XREF", joinColumns = @JoinColumn(name = "OFFER_ID"),
inverseJoinColumns = @JoinColumn(name = "OFFER_ITEM_CRITERIA_ID"))
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@AdminPresentation(friendlyName = "OfferImpl_Qualifying_Item_Rule",
group = Presentation.Group.Name.Qualifiers, groupOrder = Presentation.Group.Order.Qualifiers,
fieldType = SupportedFieldType.RULE_WITH_QUANTITY, ruleIdentifier = RuleIdentifier.ORDERITEM)
protected Set<OfferItemCriteria> qualifyingItemCriteria = new HashSet<OfferItemCriteria>();
@OneToMany(fetch = FetchType.LAZY, targetEntity = OfferItemCriteriaImpl.class, cascade={CascadeType.ALL})
@JoinTable(name = "BLC_TAR_CRIT_OFFER_XREF", joinColumns = @JoinColumn(name = "OFFER_ID"),
inverseJoinColumns = @JoinColumn(name = "OFFER_ITEM_CRITERIA_ID"))
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@AdminPresentation(friendlyName = "OfferImpl_Target_Item_Rule",
group = Presentation.Group.Name.ItemTarget, groupOrder = Presentation.Group.Order.ItemTarget,
fieldType = SupportedFieldType.RULE_WITH_QUANTITY,
ruleIdentifier = RuleIdentifier.ORDERITEM,
validationConfigurations = {@ValidationConfiguration(validationImplementation="blTargetItemRulesValidator")})
protected Set<OfferItemCriteria> targetItemCriteria = new HashSet<OfferItemCriteria>();
@Column(name = "TOTALITARIAN_OFFER")
@AdminPresentation(friendlyName = "OfferImpl_Totalitarian_Offer",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced,
visibility = VisibilityEnum.HIDDEN_ALL)
protected Boolean totalitarianOffer = false;
@ManyToMany(targetEntity = OfferRuleImpl.class, cascade = {CascadeType.ALL})
@JoinTable(name = "BLC_OFFER_RULE_MAP",
inverseJoinColumns = @JoinColumn(name = "OFFER_RULE_ID", referencedColumnName = "OFFER_RULE_ID"))
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@MapKeyColumn(name = "MAP_KEY", nullable = false)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@AdminPresentationMapFields(
mapDisplayFields = {
@AdminPresentationMapField(
fieldName = RuleIdentifier.CUSTOMER_FIELD_KEY,
fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE,
group = Presentation.Group.Name.Qualifiers, groupOrder = Presentation.Group.Order.Qualifiers,
ruleIdentifier = RuleIdentifier.CUSTOMER, friendlyName = "OfferImpl_Customer_Rule")
),
@AdminPresentationMapField(
fieldName = RuleIdentifier.TIME_FIELD_KEY,
fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE,
group = Presentation.Group.Name.ActivityRange, groupOrder = Presentation.Group.Order.ActivityRange,
ruleIdentifier = RuleIdentifier.TIME, friendlyName = "OfferImpl_Time_Rule")
),
@AdminPresentationMapField(
fieldName = RuleIdentifier.ORDER_FIELD_KEY,
fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE,
group = Presentation.Group.Name.Qualifiers, groupOrder = Presentation.Group.Order.Qualifiers,
ruleIdentifier = RuleIdentifier.ORDER, friendlyName = "OfferImpl_Order_Rule")
),
@AdminPresentationMapField(
fieldName = RuleIdentifier.FULFILLMENT_GROUP_FIELD_KEY,
fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE,
group = Presentation.Group.Name.Qualifiers, groupOrder = Presentation.Group.Order.Qualifiers,
ruleIdentifier = RuleIdentifier.FULFILLMENTGROUP, friendlyName = "OfferImpl_FG_Rule")
)
}
)
Map<String, OfferRule> offerMatchRules = new HashMap<String, OfferRule>();
@Column(name = "USE_NEW_FORMAT")
@AdminPresentation(friendlyName = "OfferImpl_Treat_As_New_Format",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced,
visibility = VisibilityEnum.HIDDEN_ALL)
protected Boolean treatAsNewFormat = false;
@Column(name = "QUALIFYING_ITEM_MIN_TOTAL", precision=19, scale=5)
@AdminPresentation(friendlyName="OfferImpl_Qualifying_Item_Subtotal",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
protected BigDecimal qualifyingItemSubTotal;
@Embedded
protected ArchiveStatus archiveStatus = new ArchiveStatus();
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public OfferType getType() {
return OfferType.getInstance(type);
}
@Override
public void setType(OfferType type) {
this.type = type.getType();
}
@Override
public OfferDiscountType getDiscountType() {
return OfferDiscountType.getInstance(discountType);
}
@Override
public void setDiscountType(OfferDiscountType discountType) {
this.discountType = discountType.getType();
}
@Override
public OfferItemRestrictionRuleType getOfferItemQualifierRuleType() {
OfferItemRestrictionRuleType returnType = OfferItemRestrictionRuleType.getInstance(offerItemQualifierRuleType);
if (returnType == null) {
return OfferItemRestrictionRuleType.NONE;
} else {
return returnType;
}
}
@Override
public void setOfferItemQualifierRuleType(OfferItemRestrictionRuleType restrictionRuleType) {
this.offerItemQualifierRuleType = restrictionRuleType.getType();
}
@Override
public OfferItemRestrictionRuleType getOfferItemTargetRuleType() {
OfferItemRestrictionRuleType returnType = OfferItemRestrictionRuleType.getInstance(offerItemTargetRuleType);
if (returnType == null) {
return OfferItemRestrictionRuleType.NONE;
} else {
return returnType;
}
}
@Override
public void setOfferItemTargetRuleType(OfferItemRestrictionRuleType restrictionRuleType) {
this.offerItemTargetRuleType = restrictionRuleType.getType();
}
@Override
public BigDecimal getValue() {
return value;
}
@Override
public void setValue(BigDecimal value) {
this.value = value;
}
@Override
public int getPriority() {
return priority == null ? 0 : priority;
}
@Override
public void setPriority(int priority) {
this.priority = priority;
}
@Override
public Date getStartDate() {
if ('Y'==getArchived()) {
return null;
}
return startDate;
}
@Override
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
@Override
public Date getEndDate() {
return endDate;
}
@Override
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
/**
* Returns true if this offer can be stacked on top of another offer. Stackable is evaluated
* against offers with the same offer type.
*
* @return true if stackable, otherwise false
*/
@Override
public boolean isStackable() {
return stackable == null ? false : stackable;
}
/**
* Sets the stackable value for this offer.
*
* @param stackable
*/
@Override
public void setStackable(boolean stackable) {
this.stackable = stackable;
}
@Deprecated
@JsonIgnore
public boolean getStackable(){
return stackable;
}
@Override
public String getTargetSystem() {
return targetSystem;
}
@Override
public void setTargetSystem(String targetSystem) {
this.targetSystem = targetSystem;
}
@Override
public boolean getApplyDiscountToSalePrice() {
return applyToSalePrice == null ? false : applyToSalePrice;
}
@Override
public void setApplyDiscountToSalePrice(boolean applyToSalePrice) {
this.applyToSalePrice=applyToSalePrice;
}
@Override
@Deprecated
public String getAppliesToOrderRules() {
return appliesToOrderRules;
}
@Override
@Deprecated
public void setAppliesToOrderRules(String appliesToOrderRules) {
this.appliesToOrderRules = appliesToOrderRules;
}
@Override
@Deprecated
public String getAppliesToCustomerRules() {
return appliesToCustomerRules;
}
@Override
@Deprecated
public void setAppliesToCustomerRules(String appliesToCustomerRules) {
this.appliesToCustomerRules = appliesToCustomerRules;
}
@Override
@Deprecated
public boolean isApplyDiscountToMarkedItems() {
return applyDiscountToMarkedItems;
}
@Deprecated
@JsonIgnore
public boolean getApplyDiscountToMarkedItems() {
return applyDiscountToMarkedItems;
}
@Override
@Deprecated
public void setApplyDiscountToMarkedItems(boolean applyDiscountToMarkedItems) {
this.applyDiscountToMarkedItems = applyDiscountToMarkedItems;
}
/**
* Returns true if this offer can be combined with other offers in the order.
*
* @return true if combinableWithOtherOffers, otherwise false
*/
@Override
public boolean isCombinableWithOtherOffers() {
return combinableWithOtherOffers == null ? false : combinableWithOtherOffers;
}
/**
* Sets the combinableWithOtherOffers value for this offer.
*
* @param combinableWithOtherOffers
*/
@Override
public void setCombinableWithOtherOffers(boolean combinableWithOtherOffers) {
this.combinableWithOtherOffers = combinableWithOtherOffers;
}
@Deprecated
@JsonIgnore
public boolean getCombinableWithOtherOffers() {
return combinableWithOtherOffers;
}
@Override
public boolean isAutomaticallyAdded() {
if (automaticallyAdded == null) {
if (deliveryType != null) {
OfferDeliveryType offerDeliveryType = OfferDeliveryType.getInstance(deliveryType);
return OfferDeliveryType.AUTOMATIC.equals(offerDeliveryType);
}
return false;
}
return automaticallyAdded;
}
@Override
public void setAutomaticallyAdded(boolean automaticallyAdded) {
this.automaticallyAdded = automaticallyAdded;
}
@Override
@Deprecated
@JsonIgnore
public OfferDeliveryType getDeliveryType() {
if (deliveryType == null) {
if (isAutomaticallyAdded()) {
return OfferDeliveryType.AUTOMATIC;
} else {
return OfferDeliveryType.MANUAL;
}
}
return OfferDeliveryType.getInstance(deliveryType);
}
@Override
public void setDeliveryType(OfferDeliveryType deliveryType) {
this.deliveryType = deliveryType.getType();
}
@Override
public Long getMaxUsesPerCustomer() {
return maxUsesPerCustomer == null ? 0 : maxUsesPerCustomer;
}
@Override
public void setMaxUsesPerCustomer(Long maxUsesPerCustomer) {
this.maxUsesPerCustomer = maxUsesPerCustomer;
}
@Override
public boolean isUnlimitedUsePerCustomer() {
return getMaxUsesPerCustomer() == 0;
}
@Override
public boolean isLimitedUsePerCustomer() {
return getMaxUsesPerCustomer() > 0;
}
@Override
public int getMaxUsesPerOrder() {
return maxUsesPerOrder == null ? 0 : maxUsesPerOrder;
}
@Override
public void setMaxUsesPerOrder(int maxUsesPerOrder) {
this.maxUsesPerOrder = maxUsesPerOrder;
}
@Override
public boolean isUnlimitedUsePerOrder() {
return getMaxUsesPerOrder() == 0;
}
@Override
public boolean isLimitedUsePerOrder() {
return getMaxUsesPerOrder() > 0;
}
@Override
@Deprecated
public int getMaxUses() {
return getMaxUsesPerOrder();
}
@Override
public void setMaxUses(int maxUses) {
setMaxUsesPerOrder(maxUses);
}
@Override
@Deprecated
public int getUses() {
return uses;
}
@Override
public String getMarketingMessage() {
return DynamicTranslationProvider.getValue(this, "marketingMessage", marketingMessage);
}
@Override
public void setMarketingMessage(String marketingMessage) {
this.marketingMessage = marketingMessage;
}
@Override
@Deprecated
public void setUses(int uses) {
this.uses = uses;
}
@Override
public Set<OfferItemCriteria> getQualifyingItemCriteria() {
return qualifyingItemCriteria;
}
@Override
public void setQualifyingItemCriteria(Set<OfferItemCriteria> qualifyingItemCriteria) {
this.qualifyingItemCriteria = qualifyingItemCriteria;
}
@Override
public Set<OfferItemCriteria> getTargetItemCriteria() {
return targetItemCriteria;
}
@Override
public void setTargetItemCriteria(Set<OfferItemCriteria> targetItemCriteria) {
this.targetItemCriteria = targetItemCriteria;
}
@Override
public Boolean isTotalitarianOffer() {
if (totalitarianOffer == null) {
return false;
} else {
return totalitarianOffer.booleanValue();
}
}
@Override
public void setTotalitarianOffer(Boolean totalitarianOffer) {
if (totalitarianOffer == null) {
this.totalitarianOffer = false;
} else {
this.totalitarianOffer = totalitarianOffer;
}
}
@Override
public Map<String, OfferRule> getOfferMatchRules() {
if (offerMatchRules == null) {
offerMatchRules = new HashMap<String, OfferRule>();
}
return offerMatchRules;
}
@Override
public void setOfferMatchRules(Map<String, OfferRule> offerMatchRules) {
this.offerMatchRules = offerMatchRules;
}
@Override
public Boolean getTreatAsNewFormat() {
return treatAsNewFormat;
}
@Override
public void setTreatAsNewFormat(Boolean treatAsNewFormat) {
this.treatAsNewFormat = treatAsNewFormat;
}
@Override
public Character getArchived() {
if (archiveStatus == null) {
archiveStatus = new ArchiveStatus();
}
return archiveStatus.getArchived();
}
@Override
public void setArchived(Character archived) {
if (archiveStatus == null) {
archiveStatus = new ArchiveStatus();
}
archiveStatus.setArchived(archived);
}
@Override
public boolean isActive() {
return DateUtil.isActive(startDate, endDate, true) && 'Y'!=getArchived();
}
@Override
public Money getQualifyingItemSubTotal() {
return qualifyingItemSubTotal == null ? null : BroadleafCurrencyUtils.getMoney(qualifyingItemSubTotal, null);
}
@Override
public void setQualifyingItemSubTotal(Money qualifyingItemSubTotal) {
this.qualifyingItemSubTotal = Money.toAmount(qualifyingItemSubTotal);
}
@Override
public List<OfferCode> getOfferCodes() {
return offerCodes;
}
@Override
public void setOfferCodes(List<OfferCode> offerCodes) {
this.offerCodes = offerCodes;
}
@Override
public String getMainEntityName() {
return getName();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(name)
.append(startDate)
.append(type)
.append(value)
.build();
}
@Override
public boolean equals(Object o) {
if (o instanceof OfferImpl) {
OfferImpl that = (OfferImpl) o;
return new EqualsBuilder()
.append(this.id, that.id)
.append(this.name, that.name)
.append(this.startDate, that.startDate)
.append(this.type, that.type)
.append(this.value, that.value)
.build();
}
return false;
}
public static class Presentation {
public static class Tab {
public static class Name {
public static final String Codes = "OfferImpl_Codes_Tab";
public static final String Advanced = "OfferImpl_Advanced_Tab";
}
public static class Order {
public static final int Codes = 1000;
public static final int Advanced = 2000;
}
}
public static class Group {
public static class Name {
public static final String Description = "OfferImpl_Description";
public static final String Amount = "OfferImpl_Amount";
public static final String ActivityRange = "OfferImpl_Activity_Range";
public static final String Qualifiers = "OfferImpl_Qualifiers";
public static final String ItemTarget = "OfferImpl_Item_Target";
public static final String Advanced = "OfferImpl_Advanced";
}
public static class Order {
public static final int Description = 1000;
public static final int Amount = 2000;
public static final int ActivityRange = 3000;
public static final int Qualifiers = 4000;
public static final int ItemTarget = 5000;
public static final int Advanced = 1000;
}
}
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OfferImpl.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.