Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
4,234 |
public final class RamDirectoryService extends AbstractIndexShardComponent implements DirectoryService {
@Inject
public RamDirectoryService(ShardId shardId, @IndexSettings Settings indexSettings) {
super(shardId, indexSettings);
}
@Override
public long throttleTimeInNanos() {
return 0;
}
@Override
public Directory[] build() {
return new Directory[]{new CustomRAMDirectory()};
}
@Override
public void renameFile(Directory dir, String from, String to) throws IOException {
CustomRAMDirectory leaf = DirectoryUtils.getLeaf(dir, CustomRAMDirectory.class);
assert leaf != null;
leaf.renameTo(from, to);
}
@Override
public void fullDelete(Directory dir) {
}
static class CustomRAMDirectory extends RAMDirectory {
public synchronized void renameTo(String from, String to) throws IOException {
RAMFile fromFile = fileMap.get(from);
if (fromFile == null)
throw new FileNotFoundException(from);
RAMFile toFile = fileMap.get(to);
if (toFile != null) {
sizeInBytes.addAndGet(-fileLength(from));
fileMap.remove(from);
}
fileMap.put(to, fromFile);
}
@Override
public String toString() {
return "ram";
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_store_ram_RamDirectoryService.java
|
1,180 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_PAYMENT_LOG")
public class PaymentLogImpl implements PaymentLog {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "PaymentLogId")
@GenericGenerator(
name="PaymentLogId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="PaymentLogImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.payment.domain.PaymentLogImpl")
}
)
@Column(name = "PAYMENT_LOG_ID")
protected Long id;
@Column(name = "USER_NAME", nullable=false)
@Index(name="PAYMENTLOG_USER_INDEX", columnNames={"USER_NAME"})
@AdminPresentation(friendlyName = "PaymentLogImpl_User_Name", order = 1, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected String userName;
@Column(name = "TRANSACTION_TIMESTAMP", nullable=false)
@Temporal(TemporalType.TIMESTAMP)
@AdminPresentation(friendlyName = "PaymentLogImpl_Transaction_Time", order = 3, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected Date transactionTimestamp;
@Column(name = "ORDER_PAYMENT_ID")
@Index(name="PAYMENTLOG_ORDERPAYMENT_INDEX", columnNames={"ORDER_PAYMENT_ID"})
@AdminPresentation(excluded = true, readOnly = true)
protected Long paymentInfoId;
@ManyToOne(targetEntity = CustomerImpl.class)
@JoinColumn(name = "CUSTOMER_ID")
@Index(name="PAYMENTLOG_CUSTOMER_INDEX", columnNames={"CUSTOMER_ID"})
protected Customer customer;
@Column(name = "PAYMENT_INFO_REFERENCE_NUMBER")
@Index(name="PAYMENTLOG_REFERENCE_INDEX", columnNames={"PAYMENT_INFO_REFERENCE_NUMBER"})
@AdminPresentation(friendlyName = "PaymentLogImpl_Payment_Ref_Number", order = 4, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected String paymentInfoReferenceNumber;
@Column(name = "TRANSACTION_TYPE", nullable=false)
@Index(name="PAYMENTLOG_TRANTYPE_INDEX", columnNames={"TRANSACTION_TYPE"})
@AdminPresentation(friendlyName = "PaymentLogImpl_Transaction_Type", order = 5, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected String transactionType;
@Column(name = "TRANSACTION_SUCCESS")
@AdminPresentation(friendlyName = "PaymentLogImpl_Transaction_Successfule", order = 6, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected Boolean transactionSuccess = false;
@Column(name = "EXCEPTION_MESSAGE")
@AdminPresentation(friendlyName = "PaymentLogImpl_Exception_Message", order = 7, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected String exceptionMessage;
@Column(name = "LOG_TYPE", nullable=false)
@Index(name="PAYMENTLOG_LOGTYPE_INDEX", columnNames={"LOG_TYPE"})
@AdminPresentation(friendlyName = "PaymentLogImpl_Type", order = 8, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected String logType;
@Column(name = "AMOUNT_PAID", precision=19, scale=5)
@AdminPresentation(friendlyName = "PaymentLogImpl_Amount", order = 2, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected BigDecimal amountPaid;
@ManyToOne(targetEntity = BroadleafCurrencyImpl.class)
@JoinColumn(name = "CURRENCY_CODE")
@AdminPresentation(friendlyName = "PaymentLogImpl_currency", order = 2, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected BroadleafCurrency currency;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getUserName() {
return userName;
}
@Override
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public Date getTransactionTimestamp() {
return transactionTimestamp;
}
@Override
public void setTransactionTimestamp(Date transactionTimestamp) {
this.transactionTimestamp = transactionTimestamp;
}
@Override
public Long getPaymentInfoId() {
return paymentInfoId;
}
@Override
public void setPaymentInfoId(Long paymentInfoId) {
this.paymentInfoId = paymentInfoId;
}
@Override
public Customer getCustomer() {
return customer;
}
@Override
public void setCustomer(Customer customer) {
this.customer = customer;
}
@Override
public String getPaymentInfoReferenceNumber() {
return paymentInfoReferenceNumber;
}
@Override
public void setPaymentInfoReferenceNumber(String paymentInfoReferenceNumber) {
this.paymentInfoReferenceNumber = paymentInfoReferenceNumber;
}
@Override
public TransactionType getTransactionType() {
return TransactionType.getInstance(transactionType);
}
@Override
public void setTransactionType(TransactionType transactionType) {
this.transactionType = transactionType.getType();
}
@Override
public PaymentLogEventType getLogType() {
return PaymentLogEventType.getInstance(logType);
}
@Override
public void setLogType(PaymentLogEventType logType) {
this.logType = logType.getType();
}
@Override
public Boolean getTransactionSuccess() {
if (transactionSuccess == null) {
return Boolean.FALSE;
} else {
return transactionSuccess;
}
}
@Override
public void setTransactionSuccess(Boolean transactionSuccess) {
this.transactionSuccess = transactionSuccess;
}
@Override
public String getExceptionMessage() {
return exceptionMessage;
}
@Override
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
@Override
public Money getAmountPaid() {
return BroadleafCurrencyUtils.getMoney(amountPaid, currency);
}
@Override
public void setAmountPaid(Money amountPaid) {
this.amountPaid = Money.toAmount(amountPaid);
}
@Override
public BroadleafCurrency getCurrency() {
return currency;
}
@Override
public void setCurrency(BroadleafCurrency currency) {
this.currency = currency;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((customer == null) ? 0 : customer.hashCode());
result = prime * result + ((paymentInfoId == null) ? 0 : paymentInfoId.hashCode());
result = prime * result + ((paymentInfoReferenceNumber == null) ? 0 : paymentInfoReferenceNumber.hashCode());
result = prime * result + ((transactionTimestamp == null) ? 0 : transactionTimestamp.hashCode());
result = prime * result + ((userName == null) ? 0 : userName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PaymentLogImpl other = (PaymentLogImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (customer == null) {
if (other.customer != null) {
return false;
}
} else if (!customer.equals(other.customer)) {
return false;
}
if (paymentInfoId == null) {
if (other.paymentInfoId != null) {
return false;
}
} else if (!paymentInfoId.equals(other.paymentInfoId)) {
return false;
}
if (paymentInfoReferenceNumber == null) {
if (other.paymentInfoReferenceNumber != null) {
return false;
}
} else if (!paymentInfoReferenceNumber.equals(other.paymentInfoReferenceNumber)) {
return false;
}
if (transactionTimestamp == null) {
if (other.transactionTimestamp != null) {
return false;
}
} else if (!transactionTimestamp.equals(other.transactionTimestamp)) {
return false;
}
if (userName == null) {
if (other.userName != null) {
return false;
}
} else if (!userName.equals(other.userName)) {
return false;
}
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_domain_PaymentLogImpl.java
|
23 |
public class EndCommand extends NoOpCommand {
public EndCommand() {
super(END);
}
@Override
public String toString() {
return "EndCommand{}";
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_ascii_memcache_EndCommand.java
|
5,226 |
public class InternalHistogram<B extends InternalHistogram.Bucket> extends InternalAggregation implements Histogram {
final static Type TYPE = new Type("histogram", "histo");
final static Factory FACTORY = new Factory();
private final static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public InternalHistogram readResult(StreamInput in) throws IOException {
InternalHistogram histogram = new InternalHistogram();
histogram.readFrom(in);
return histogram;
}
};
public static void registerStream() {
AggregationStreams.registerStream(STREAM, TYPE.stream());
}
public static class Bucket implements Histogram.Bucket {
long key;
long docCount;
InternalAggregations aggregations;
public Bucket(long key, long docCount, InternalAggregations aggregations) {
this.key = key;
this.docCount = docCount;
this.aggregations = aggregations;
}
@Override
public String getKey() {
return String.valueOf(key);
}
@Override
public Text getKeyAsText() {
return new StringText(getKey());
}
@Override
public Number getKeyAsNumber() {
return key;
}
@Override
public long getDocCount() {
return docCount;
}
@Override
public Aggregations getAggregations() {
return aggregations;
}
<B extends Bucket> B reduce(List<B> buckets, CacheRecycler cacheRecycler) {
if (buckets.size() == 1) {
// we only need to reduce the sub aggregations
Bucket bucket = buckets.get(0);
bucket.aggregations.reduce(cacheRecycler);
return (B) bucket;
}
List<InternalAggregations> aggregations = new ArrayList<InternalAggregations>(buckets.size());
Bucket reduced = null;
for (Bucket bucket : buckets) {
if (reduced == null) {
reduced = bucket;
} else {
reduced.docCount += bucket.docCount;
}
aggregations.add((InternalAggregations) bucket.getAggregations());
}
reduced.aggregations = InternalAggregations.reduce(aggregations, cacheRecycler);
return (B) reduced;
}
}
static class EmptyBucketInfo {
final Rounding rounding;
final InternalAggregations subAggregations;
EmptyBucketInfo(Rounding rounding, InternalAggregations subAggregations) {
this.rounding = rounding;
this.subAggregations = subAggregations;
}
public static EmptyBucketInfo readFrom(StreamInput in) throws IOException {
return new EmptyBucketInfo(Rounding.Streams.read(in), InternalAggregations.readAggregations(in));
}
public static void writeTo(EmptyBucketInfo info, StreamOutput out) throws IOException {
Rounding.Streams.write(info.rounding, out);
info.subAggregations.writeTo(out);
}
}
static class Factory<B extends InternalHistogram.Bucket> {
protected Factory() {
}
public String type() {
return TYPE.name();
}
public InternalHistogram<B> create(String name, List<B> buckets, InternalOrder order, long minDocCount,
EmptyBucketInfo emptyBucketInfo, ValueFormatter formatter, boolean keyed) {
return new InternalHistogram<B>(name, buckets, order, minDocCount, emptyBucketInfo, formatter, keyed);
}
public B createBucket(long key, long docCount, InternalAggregations aggregations, ValueFormatter formatter) {
return (B) new Bucket(key, docCount, aggregations);
}
}
private List<B> buckets;
private LongObjectOpenHashMap<B> bucketsMap;
private InternalOrder order;
private ValueFormatter formatter;
private boolean keyed;
private long minDocCount;
private EmptyBucketInfo emptyBucketInfo;
InternalHistogram() {} // for serialization
InternalHistogram(String name, List<B> buckets, InternalOrder order, long minDocCount, EmptyBucketInfo emptyBucketInfo, ValueFormatter formatter, boolean keyed) {
super(name);
this.buckets = buckets;
this.order = order;
assert (minDocCount == 0) == (emptyBucketInfo != null);
this.minDocCount = minDocCount;
this.emptyBucketInfo = emptyBucketInfo;
this.formatter = formatter;
this.keyed = keyed;
}
@Override
public Type type() {
return TYPE;
}
@Override
public Collection<B> getBuckets() {
return buckets;
}
@Override
public B getBucketByKey(String key) {
return getBucketByKey(Long.valueOf(key));
}
@Override
public B getBucketByKey(Number key) {
if (bucketsMap == null) {
bucketsMap = new LongObjectOpenHashMap<B>(buckets.size());
for (B bucket : buckets) {
bucketsMap.put(bucket.key, bucket);
}
}
return bucketsMap.get(key.longValue());
}
@Override
public InternalAggregation reduce(ReduceContext reduceContext) {
List<InternalAggregation> aggregations = reduceContext.aggregations();
if (aggregations.size() == 1) {
InternalHistogram<B> histo = (InternalHistogram<B>) aggregations.get(0);
if (minDocCount == 1) {
for (B bucket : histo.buckets) {
bucket.aggregations.reduce(reduceContext.cacheRecycler());
}
return histo;
}
CollectionUtil.introSort(histo.buckets, order.asc ? InternalOrder.KEY_ASC.comparator() : InternalOrder.KEY_DESC.comparator());
List<B> list = order.asc ? histo.buckets : Lists.reverse(histo.buckets);
B prevBucket = null;
ListIterator<B> iter = list.listIterator();
if (minDocCount == 0) {
// we need to fill the gaps with empty buckets
while (iter.hasNext()) {
// look ahead on the next bucket without advancing the iter
// so we'll be able to insert elements at the right position
B nextBucket = list.get(iter.nextIndex());
nextBucket.aggregations.reduce(reduceContext.cacheRecycler());
if (prevBucket != null) {
long key = emptyBucketInfo.rounding.nextRoundingValue(prevBucket.key);
while (key != nextBucket.key) {
iter.add(createBucket(key, 0, emptyBucketInfo.subAggregations, formatter));
key = emptyBucketInfo.rounding.nextRoundingValue(key);
}
}
prevBucket = iter.next();
}
} else {
while (iter.hasNext()) {
InternalHistogram.Bucket bucket = iter.next();
if (bucket.getDocCount() < minDocCount) {
iter.remove();
} else {
bucket.aggregations.reduce(reduceContext.cacheRecycler());
}
}
}
if (order != InternalOrder.KEY_ASC && order != InternalOrder.KEY_DESC) {
CollectionUtil.introSort(histo.buckets, order.comparator());
}
return histo;
}
InternalHistogram reduced = (InternalHistogram) aggregations.get(0);
Recycler.V<LongObjectOpenHashMap<List<Histogram.Bucket>>> bucketsByKey = reduceContext.cacheRecycler().longObjectMap(-1);
for (InternalAggregation aggregation : aggregations) {
InternalHistogram<B> histogram = (InternalHistogram) aggregation;
for (B bucket : histogram.buckets) {
List<Histogram.Bucket> bucketList = bucketsByKey.v().get(bucket.key);
if (bucketList == null) {
bucketList = new ArrayList<Histogram.Bucket>(aggregations.size());
bucketsByKey.v().put(bucket.key, bucketList);
}
bucketList.add(bucket);
}
}
List<B> reducedBuckets = new ArrayList<B>(bucketsByKey.v().size());
Object[] buckets = bucketsByKey.v().values;
boolean[] allocated = bucketsByKey.v().allocated;
for (int i = 0; i < allocated.length; i++) {
if (allocated[i]) {
B bucket = ((List<B>) buckets[i]).get(0).reduce(((List<B>) buckets[i]), reduceContext.cacheRecycler());
if (bucket.getDocCount() >= minDocCount) {
reducedBuckets.add(bucket);
}
}
}
bucketsByKey.release();
// adding empty buckets in needed
if (minDocCount == 0) {
CollectionUtil.introSort(reducedBuckets, order.asc ? InternalOrder.KEY_ASC.comparator() : InternalOrder.KEY_DESC.comparator());
List<B> list = order.asc ? reducedBuckets : Lists.reverse(reducedBuckets);
B prevBucket = null;
ListIterator<B> iter = list.listIterator();
while (iter.hasNext()) {
B nextBucket = list.get(iter.nextIndex());
if (prevBucket != null) {
long key = emptyBucketInfo.rounding.nextRoundingValue(prevBucket.key);
while (key != nextBucket.key) {
iter.add(createBucket(key, 0, emptyBucketInfo.subAggregations, formatter));
key = emptyBucketInfo.rounding.nextRoundingValue(key);
}
}
prevBucket = iter.next();
}
if (order != InternalOrder.KEY_ASC && order != InternalOrder.KEY_DESC) {
CollectionUtil.introSort(reducedBuckets, order.comparator());
}
} else {
CollectionUtil.introSort(reducedBuckets, order.comparator());
}
reduced.buckets = reducedBuckets;
return reduced;
}
protected B createBucket(long key, long docCount, InternalAggregations aggregations, ValueFormatter formatter) {
return (B) new InternalHistogram.Bucket(key, docCount, aggregations);
}
@Override
public void readFrom(StreamInput in) throws IOException {
name = in.readString();
order = InternalOrder.Streams.readOrder(in);
minDocCount = in.readVLong();
if (minDocCount == 0) {
emptyBucketInfo = EmptyBucketInfo.readFrom(in);
}
formatter = ValueFormatterStreams.readOptional(in);
keyed = in.readBoolean();
int size = in.readVInt();
List<B> buckets = new ArrayList<B>(size);
for (int i = 0; i < size; i++) {
buckets.add(createBucket(in.readLong(), in.readVLong(), InternalAggregations.readAggregations(in), formatter));
}
this.buckets = buckets;
this.bucketsMap = null;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
InternalOrder.Streams.writeOrder(order, out);
out.writeVLong(minDocCount);
if (minDocCount == 0) {
EmptyBucketInfo.writeTo(emptyBucketInfo, out);
}
ValueFormatterStreams.writeOptional(formatter, out);
out.writeBoolean(keyed);
out.writeVInt(buckets.size());
for (B bucket : buckets) {
out.writeLong(bucket.key);
out.writeVLong(bucket.docCount);
bucket.aggregations.writeTo(out);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
if (keyed) {
builder.startObject(CommonFields.BUCKETS);
} else {
builder.startArray(CommonFields.BUCKETS);
}
for (B bucket : buckets) {
if (formatter != null) {
Text keyTxt = new StringText(formatter.format(bucket.key));
if (keyed) {
builder.startObject(keyTxt.string());
} else {
builder.startObject();
}
builder.field(CommonFields.KEY_AS_STRING, keyTxt);
} else {
if (keyed) {
builder.startObject(String.valueOf(bucket.getKeyAsNumber()));
} else {
builder.startObject();
}
}
builder.field(CommonFields.KEY, bucket.key);
builder.field(CommonFields.DOC_COUNT, bucket.docCount);
bucket.aggregations.toXContentInternal(builder, params);
builder.endObject();
}
if (keyed) {
builder.endObject();
} else {
builder.endArray();
}
return builder.endObject();
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_bucket_histogram_InternalHistogram.java
|
9 |
public class BufferFullException extends Exception {
private static final long serialVersionUID = 2028815233703151762L;
/**
* Default constructor.
*/
public BufferFullException() {
super();
}
/**
* Overloaded constructor with single message argument.
* @param msg - Message to display buffer full exception.
*/
public BufferFullException(String msg) {
super(msg);
}
}
| 0true
|
mctcore_src_main_java_gov_nasa_arc_mct_api_feed_BufferFullException.java
|
259 |
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ExecutionDelayTest extends HazelcastTestSupport {
private static final int NODES = 3;
private final List<HazelcastInstance> hzs = new ArrayList<HazelcastInstance>(NODES);
static final AtomicInteger counter = new AtomicInteger();
@Before
public void init() {
counter.set(0);
for (int i = 0; i < NODES; i++) {
hzs.add(Hazelcast.newHazelcastInstance());
}
}
@After
public void destroy() throws InterruptedException {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testExecutorOneNodeFailsUnexpectedly() throws InterruptedException, ExecutionException {
final int executions = 20;
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
try {
ex.schedule(new Runnable() {
@Override
public void run() {
hzs.get(1).getLifecycleService().terminate();
}
}, 1000, TimeUnit.MILLISECONDS);
Task task = new Task();
runClient(task, executions);
assertTrueEventually(new AssertTask() {
@Override
public void run() {
assertEquals(executions, counter.get());
}
});
} finally {
ex.shutdown();
}
}
@Test
public void testExecutorOneNodeShutdown() throws InterruptedException, ExecutionException {
final int executions = 20;
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
try {
ex.schedule(new Runnable() {
@Override
public void run() {
hzs.get(1).shutdown();
}
}, 1000, TimeUnit.MILLISECONDS);
Task task = new Task();
runClient(task, executions);
assertTrueEventually(new AssertTask() {
@Override
public void run() {
assertEquals(executions, counter.get());
}
});
} finally {
ex.shutdown();
}
}
private void runClient(Task task, int executions) throws InterruptedException, ExecutionException {
final ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().setRedoOperation(true);
HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
IExecutorService executor = client.getExecutorService("executor");
for (int i = 0; i < executions; i++) {
Future future = executor.submitToKeyOwner(task, i);
future.get();
Thread.sleep(100);
}
}
private static class Task implements Serializable, Callable {
@Override
public Object call() throws Exception {
counter.incrementAndGet();
return null;
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_ExecutionDelayTest.java
|
142 |
private static class FileCountPruneStrategy extends AbstractPruneStrategy
{
private final int maxNonEmptyLogCount;
public FileCountPruneStrategy( FileSystemAbstraction fileSystem, int maxNonEmptyLogCount )
{
super( fileSystem );
this.maxNonEmptyLogCount = maxNonEmptyLogCount;
}
@Override
protected Threshold newThreshold()
{
return new Threshold()
{
int nonEmptyLogCount = 0;
@Override
public boolean reached( File file, long version, LogLoader source )
{
return ++nonEmptyLogCount >= maxNonEmptyLogCount;
}
};
}
@Override
public String toString()
{
return getClass().getSimpleName() + "[max:" + maxNonEmptyLogCount + "]";
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
|
2,925 |
public class PreBuiltTokenFilterFactoryFactory implements TokenFilterFactoryFactory {
private final TokenFilterFactory tokenFilterFactory;
public PreBuiltTokenFilterFactoryFactory(TokenFilterFactory tokenFilterFactory) {
this.tokenFilterFactory = tokenFilterFactory;
}
@Override
public TokenFilterFactory create(String name, Settings settings) {
Version indexVersion = settings.getAsVersion(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT);
if (!Version.CURRENT.equals(indexVersion)) {
return PreBuiltTokenFilters.valueOf(name.toUpperCase(Locale.ROOT)).getTokenFilterFactory(indexVersion);
}
return tokenFilterFactory;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_analysis_PreBuiltTokenFilterFactoryFactory.java
|
1,599 |
public class Console {
private static final String HISTORY_FILE = ".gremlin_titan_hadoop_history";
private static final String STANDARD_INPUT_PROMPT = "gremlin> ";
private static final String STANDARD_RESULT_PROMPT = "==>";
/*static {
try {
System.setProperty("log4j.configuration", "./resources" + File.separatorChar + "log4j.properties");
} catch (Exception e) {
}
}*/
public Console(final IO io, final String inputPrompt, final String resultPrompt) {
io.out.println();
io.out.println(" \\,,,/");
io.out.println(" (o o)");
io.out.println("-----oOOo-(_)-oOOo-----");
final Groovysh groovy = new Groovysh();
groovy.setResultHook(new NullResultHookClosure(groovy));
for (final String imps : Imports.getImports()) {
groovy.execute("import " + imps);
}
for (final String evs : Imports.getEvaluates()) {
groovy.execute(evs);
}
groovy.setResultHook(new ResultHookClosure(groovy, io, resultPrompt));
groovy.setHistory(new History());
final InteractiveShellRunner runner = new InteractiveShellRunner(groovy, new PromptClosure(groovy, inputPrompt));
runner.setErrorHandler(new ErrorHookClosure(runner, io));
try {
runner.setHistory(new History(new File(System.getProperty("user.home") + "/" + HISTORY_FILE)));
} catch (IOException e) {
io.err.println("Unable to create history file: " + HISTORY_FILE);
}
Gremlin.load();
HadoopGremlin.load();
try {
runner.run();
} catch (Error e) {
//System.err.println(e.getMessage());
}
System.exit(0);
}
public Console() {
this(new IO(System.in, System.out, System.err), STANDARD_INPUT_PROMPT, STANDARD_RESULT_PROMPT);
}
public static void main(final String[] args) {
new Console();
}
}
| 1no label
|
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_tinkerpop_gremlin_Console.java
|
484 |
public interface ExploitProtectionService {
/**
* Detect and remove possible XSS threats from the passed in string. This
* includes {@code <script>} tags, and the like.
*
* @param string The possibly dirty string
* @return The cleansed version of the string
* @throws ServiceException
*/
public String cleanString(String string) throws ServiceException;
/**
* Detect and remove possible XSS threats from the passed in string. This
* includes {@code <script>} tags, and the like. If an html, validation, or
* security problem is detected, an exception is thrown. This method also emits
* well formed xml, which is important if using Thymeleaf to display the results.
*
* @param string The possibly dirty string
* @return The cleansed version of the string
* @throws ServiceException, CleanStringException
*/
public String cleanStringWithResults(String string) throws ServiceException;
public String getAntiSamyPolicyFileLocation();
public void setAntiSamyPolicyFileLocation(String antiSamyPolicyFileLocation);
/**
* Detect possible XSRF attacks by comparing the csrf token included
* in the request against the true token for this user from the session. If they are
* different, then the exception is thrown.
*
* @param passedToken The csrf token that was passed in the request
* @throws ServiceException
*/
public void compareToken(String passedToken) throws ServiceException;
public String getCSRFToken() throws ServiceException;
public String getCsrfTokenParameter();
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_security_service_ExploitProtectionService.java
|
582 |
public class PaymentException extends BroadleafException {
private static final long serialVersionUID = 1L;
protected PaymentResponse paymentResponse;
public PaymentException() {
super();
}
public PaymentException(String message, Throwable cause) {
super(message, cause);
}
public PaymentException(String message) {
super(message);
}
public PaymentException(Throwable cause) {
super(cause);
}
public PaymentResponse getPaymentResponse() {
return paymentResponse;
}
public void setPaymentResponse(PaymentResponse paymentResponse) {
this.paymentResponse = paymentResponse;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_vendor_service_exception_PaymentException.java
|
1,478 |
return OSQLEngine.foreachRecord(new OCallable<Object, OIdentifiable>() {
@Override
public Object call(final OIdentifiable iArgument) {
return move(graph, iArgument, labels);
}
}, iCurrentResult, iContext);
| 1no label
|
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_functions_OSQLFunctionMove.java
|
124 |
client.getLifecycleService().addLifecycleListener(new LifecycleListener() {
@Override
public void stateChanged(LifecycleEvent event) {
connectedLatch.countDown();
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_ClientReconnectTest.java
|
1,489 |
public interface ShardRouting extends Streamable, Serializable, ToXContent {
/**
* The shard id.
*/
ShardId shardId();
/**
* The index name.
*/
String index();
/**
* The index name.
*/
String getIndex();
/**
* The shard id.
*/
int id();
/**
* The shard id.
*/
int getId();
/**
* The routing version associated with the shard.
*/
long version();
/**
* The shard state.
*/
ShardRoutingState state();
/**
* The shard is unassigned (not allocated to any node).
*/
boolean unassigned();
/**
* The shard is initializing (usually recovering either from peer shard
* or from gateway).
*/
boolean initializing();
/**
* The shard is in started mode.
*/
boolean started();
/**
* Returns <code>true</code> iff the this shard is currently relocating to
* another node. Otherwise <code>false</code>
*
* @see ShardRoutingState#RELOCATING
*/
boolean relocating();
/**
* Returns <code>true</code> iff the this shard is currently
* {@link ShardRoutingState#STARTED started} or
* {@link ShardRoutingState#RELOCATING relocating} to another node.
* Otherwise <code>false</code>
*/
boolean active();
/**
* Returns <code>true</code> iff this shard is assigned to a node ie. not
* {@link ShardRoutingState#UNASSIGNED unassigned}. Otherwise <code>false</code>
*/
boolean assignedToNode();
/**
* The current node id the shard is allocated on.
*/
String currentNodeId();
/**
* The relocating node id the shard is either relocating to or relocating from.
*/
String relocatingNodeId();
/**
* Snapshot id and repository where this shard is being restored from
*/
RestoreSource restoreSource();
/**
* Returns <code>true</code> iff this shard is a primary.
*/
boolean primary();
/**
* A short description of the shard.
*/
String shortSummary();
/**
* A shard iterator with just this shard in it.
*/
ShardIterator shardsIt();
/**
* Does not write index name and shard id
*/
void writeToThin(StreamOutput out) throws IOException;
void readFromThin(StreamInput in) throws ClassNotFoundException, IOException;
}
| 0true
|
src_main_java_org_elasticsearch_cluster_routing_ShardRouting.java
|
601 |
public interface OIndexFactory {
/**
* @return List of supported indexes of this factory
*/
Set<String> getTypes();
/**
*
*
*
*
*
* @param database
* @param indexType
* index type
* @param algorithm
* @param valueContainerAlgorithm
* @return OIndexInternal
* @throws OConfigurationException
* if index creation failed
*/
OIndexInternal<?> createIndex(ODatabaseRecord database, String indexType, String algorithm, String valueContainerAlgorithm)
throws OConfigurationException;
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_index_OIndexFactory.java
|
425 |
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.UPDATE);
Assert.assertEquals(event.getOldValue(), "value2");
Assert.assertEquals(event.getKey().intValue(), 1);
Assert.assertEquals(event.getValue(), "value4");
changed.value = true;
}
});
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java
|
294 |
new Thread() {
public void run() {
if (!l.tryLock()) {
latch.countDown();
}
}
}.start();
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_lock_ClientLockTest.java
|
5,292 |
public static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public DoubleTerms readResult(StreamInput in) throws IOException {
DoubleTerms buckets = new DoubleTerms();
buckets.readFrom(in);
return buckets;
}
};
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_bucket_terms_DoubleTerms.java
|
389 |
public interface ORecordElement {
/**
* Available record statuses.
*/
public enum STATUS {
NOT_LOADED, LOADED, MARSHALLING, UNMARSHALLING
}
/**
* Returns the current status of the record.
*
* @return Current status as value between the defined values in the enum {@link STATUS}
*/
public STATUS getInternalStatus();
/**
* Changes the current internal status.
*
* @param iStatus
* status between the values defined in the enum {@link STATUS}
*/
public void setInternalStatus(STATUS iStatus);
/**
* Marks the instance as dirty. The dirty status could be propagated up if the implementation supports ownership concept.
*
* @return The object it self. Useful to call methods in chain.
*/
public <RET> RET setDirty();
/**
* Internal only.
*/
public void onBeforeIdentityChanged(ORID iRID);
/**
* Internal only.
*/
public void onAfterIdentityChanged(ORecord<?> iRecord);
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_record_ORecordElement.java
|
6,315 |
public class ThreadPool extends AbstractComponent {
public static class Names {
public static final String SAME = "same";
public static final String GENERIC = "generic";
public static final String GET = "get";
public static final String INDEX = "index";
public static final String BULK = "bulk";
public static final String SEARCH = "search";
public static final String SUGGEST = "suggest";
public static final String PERCOLATE = "percolate";
public static final String MANAGEMENT = "management";
public static final String FLUSH = "flush";
public static final String MERGE = "merge";
public static final String REFRESH = "refresh";
public static final String WARMER = "warmer";
public static final String SNAPSHOT = "snapshot";
public static final String OPTIMIZE = "optimize";
}
public static final String THREADPOOL_GROUP = "threadpool.";
private volatile ImmutableMap<String, ExecutorHolder> executors;
private final ImmutableMap<String, Settings> defaultExecutorTypeSettings;
private final Queue<ExecutorHolder> retiredExecutors = new ConcurrentLinkedQueue<ExecutorHolder>();
private final ScheduledThreadPoolExecutor scheduler;
private final EstimatedTimeThread estimatedTimeThread;
public ThreadPool() {
this(ImmutableSettings.Builder.EMPTY_SETTINGS, null);
}
@Inject
public ThreadPool(Settings settings, @Nullable NodeSettingsService nodeSettingsService) {
super(settings);
Map<String, Settings> groupSettings = settings.getGroups(THREADPOOL_GROUP);
int availableProcessors = EsExecutors.boundedNumberOfProcessors(settings);
int halfProcMaxAt5 = Math.min(((availableProcessors + 1) / 2), 5);
int halfProcMaxAt10 = Math.min(((availableProcessors + 1) / 2), 10);
defaultExecutorTypeSettings = ImmutableMap.<String, Settings>builder()
.put(Names.GENERIC, settingsBuilder().put("type", "cached").put("keep_alive", "30s").build())
.put(Names.INDEX, settingsBuilder().put("type", "fixed").put("size", availableProcessors).put("queue_size", 200).build())
.put(Names.BULK, settingsBuilder().put("type", "fixed").put("size", availableProcessors).put("queue_size", 50).build())
.put(Names.GET, settingsBuilder().put("type", "fixed").put("size", availableProcessors).put("queue_size", 1000).build())
.put(Names.SEARCH, settingsBuilder().put("type", "fixed").put("size", availableProcessors * 3).put("queue_size", 1000).build())
.put(Names.SUGGEST, settingsBuilder().put("type", "fixed").put("size", availableProcessors).put("queue_size", 1000).build())
.put(Names.PERCOLATE, settingsBuilder().put("type", "fixed").put("size", availableProcessors).put("queue_size", 1000).build())
.put(Names.MANAGEMENT, settingsBuilder().put("type", "scaling").put("keep_alive", "5m").put("size", 5).build())
.put(Names.FLUSH, settingsBuilder().put("type", "scaling").put("keep_alive", "5m").put("size", halfProcMaxAt5).build())
.put(Names.MERGE, settingsBuilder().put("type", "scaling").put("keep_alive", "5m").put("size", halfProcMaxAt5).build())
.put(Names.REFRESH, settingsBuilder().put("type", "scaling").put("keep_alive", "5m").put("size", halfProcMaxAt10).build())
.put(Names.WARMER, settingsBuilder().put("type", "scaling").put("keep_alive", "5m").put("size", halfProcMaxAt5).build())
.put(Names.SNAPSHOT, settingsBuilder().put("type", "scaling").put("keep_alive", "5m").put("size", halfProcMaxAt5).build())
.put(Names.OPTIMIZE, settingsBuilder().put("type", "fixed").put("size", 1).build())
.build();
Map<String, ExecutorHolder> executors = Maps.newHashMap();
for (Map.Entry<String, Settings> executor : defaultExecutorTypeSettings.entrySet()) {
executors.put(executor.getKey(), build(executor.getKey(), groupSettings.get(executor.getKey()), executor.getValue()));
}
executors.put(Names.SAME, new ExecutorHolder(MoreExecutors.sameThreadExecutor(), new Info(Names.SAME, "same")));
if (!executors.get(Names.GENERIC).info.getType().equals("cached")) {
throw new ElasticsearchIllegalArgumentException("generic thread pool must be of type cached");
}
this.executors = ImmutableMap.copyOf(executors);
this.scheduler = new ScheduledThreadPoolExecutor(1, EsExecutors.daemonThreadFactory(settings, "scheduler"), new EsAbortPolicy());
this.scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
this.scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
if (nodeSettingsService != null) {
nodeSettingsService.addListener(new ApplySettings());
}
TimeValue estimatedTimeInterval = componentSettings.getAsTime("estimated_time_interval", TimeValue.timeValueMillis(200));
this.estimatedTimeThread = new EstimatedTimeThread(EsExecutors.threadName(settings, "[timer]"), estimatedTimeInterval.millis());
this.estimatedTimeThread.start();
}
public long estimatedTimeInMillis() {
return estimatedTimeThread.estimatedTimeInMillis();
}
public ThreadPoolInfo info() {
List<Info> infos = new ArrayList<Info>();
for (ExecutorHolder holder : executors.values()) {
String name = holder.info.getName();
// no need to have info on "same" thread pool
if ("same".equals(name)) {
continue;
}
infos.add(holder.info);
}
return new ThreadPoolInfo(infos);
}
public Info info(String name) {
ExecutorHolder holder = executors.get(name);
if (holder == null) {
return null;
}
return holder.info;
}
public ThreadPoolStats stats() {
List<ThreadPoolStats.Stats> stats = new ArrayList<ThreadPoolStats.Stats>();
for (ExecutorHolder holder : executors.values()) {
String name = holder.info.getName();
// no need to have info on "same" thread pool
if ("same".equals(name)) {
continue;
}
int threads = -1;
int queue = -1;
int active = -1;
long rejected = -1;
int largest = -1;
long completed = -1;
if (holder.executor instanceof ThreadPoolExecutor) {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) holder.executor;
threads = threadPoolExecutor.getPoolSize();
queue = threadPoolExecutor.getQueue().size();
active = threadPoolExecutor.getActiveCount();
largest = threadPoolExecutor.getLargestPoolSize();
completed = threadPoolExecutor.getCompletedTaskCount();
RejectedExecutionHandler rejectedExecutionHandler = threadPoolExecutor.getRejectedExecutionHandler();
if (rejectedExecutionHandler instanceof XRejectedExecutionHandler) {
rejected = ((XRejectedExecutionHandler) rejectedExecutionHandler).rejected();
}
}
stats.add(new ThreadPoolStats.Stats(name, threads, queue, active, rejected, largest, completed));
}
return new ThreadPoolStats(stats);
}
public Executor generic() {
return executor(Names.GENERIC);
}
public Executor executor(String name) {
Executor executor = executors.get(name).executor;
if (executor == null) {
throw new ElasticsearchIllegalArgumentException("No executor found for [" + name + "]");
}
return executor;
}
public ScheduledExecutorService scheduler() {
return this.scheduler;
}
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, TimeValue interval) {
return scheduler.scheduleWithFixedDelay(new LoggingRunnable(command), interval.millis(), interval.millis(), TimeUnit.MILLISECONDS);
}
public ScheduledFuture<?> schedule(TimeValue delay, String name, Runnable command) {
if (!Names.SAME.equals(name)) {
command = new ThreadedRunnable(command, executor(name));
}
return scheduler.schedule(command, delay.millis(), TimeUnit.MILLISECONDS);
}
public void shutdown() {
estimatedTimeThread.running = false;
estimatedTimeThread.interrupt();
scheduler.shutdown();
for (ExecutorHolder executor : executors.values()) {
if (executor.executor instanceof ThreadPoolExecutor) {
((ThreadPoolExecutor) executor.executor).shutdown();
}
}
}
public void shutdownNow() {
estimatedTimeThread.running = false;
estimatedTimeThread.interrupt();
scheduler.shutdownNow();
for (ExecutorHolder executor : executors.values()) {
if (executor.executor instanceof ThreadPoolExecutor) {
((ThreadPoolExecutor) executor.executor).shutdownNow();
}
}
while (!retiredExecutors.isEmpty()) {
((ThreadPoolExecutor) retiredExecutors.remove().executor).shutdownNow();
}
}
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
boolean result = scheduler.awaitTermination(timeout, unit);
for (ExecutorHolder executor : executors.values()) {
if (executor.executor instanceof ThreadPoolExecutor) {
result &= ((ThreadPoolExecutor) executor.executor).awaitTermination(timeout, unit);
}
}
while (!retiredExecutors.isEmpty()) {
result &= ((ThreadPoolExecutor) retiredExecutors.remove().executor).awaitTermination(timeout, unit);
}
return result;
}
private ExecutorHolder build(String name, @Nullable Settings settings, Settings defaultSettings) {
return rebuild(name, null, settings, defaultSettings);
}
private ExecutorHolder rebuild(String name, ExecutorHolder previousExecutorHolder, @Nullable Settings settings, Settings defaultSettings) {
if (Names.SAME.equals(name)) {
// Don't allow to change the "same" thread executor
return previousExecutorHolder;
}
if (settings == null) {
settings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
Info previousInfo = previousExecutorHolder != null ? previousExecutorHolder.info : null;
String type = settings.get("type", previousInfo != null ? previousInfo.getType() : defaultSettings.get("type"));
ThreadFactory threadFactory = EsExecutors.daemonThreadFactory(this.settings, name);
if ("same".equals(type)) {
if (previousExecutorHolder != null) {
logger.debug("updating thread_pool [{}], type [{}]", name, type);
} else {
logger.debug("creating thread_pool [{}], type [{}]", name, type);
}
return new ExecutorHolder(MoreExecutors.sameThreadExecutor(), new Info(name, type));
} else if ("cached".equals(type)) {
TimeValue defaultKeepAlive = defaultSettings.getAsTime("keep_alive", timeValueMinutes(5));
if (previousExecutorHolder != null) {
if ("cached".equals(previousInfo.getType())) {
TimeValue updatedKeepAlive = settings.getAsTime("keep_alive", previousInfo.getKeepAlive());
if (!previousInfo.getKeepAlive().equals(updatedKeepAlive)) {
logger.debug("updating thread_pool [{}], type [{}], keep_alive [{}]", name, type, updatedKeepAlive);
((EsThreadPoolExecutor) previousExecutorHolder.executor).setKeepAliveTime(updatedKeepAlive.millis(), TimeUnit.MILLISECONDS);
return new ExecutorHolder(previousExecutorHolder.executor, new Info(name, type, -1, -1, updatedKeepAlive, null));
}
return previousExecutorHolder;
}
if (previousInfo.getKeepAlive() != null) {
defaultKeepAlive = previousInfo.getKeepAlive();
}
}
TimeValue keepAlive = settings.getAsTime("keep_alive", defaultKeepAlive);
if (previousExecutorHolder != null) {
logger.debug("updating thread_pool [{}], type [{}], keep_alive [{}]", name, type, keepAlive);
} else {
logger.debug("creating thread_pool [{}], type [{}], keep_alive [{}]", name, type, keepAlive);
}
Executor executor = EsExecutors.newCached(keepAlive.millis(), TimeUnit.MILLISECONDS, threadFactory);
return new ExecutorHolder(executor, new Info(name, type, -1, -1, keepAlive, null));
} else if ("fixed".equals(type)) {
int defaultSize = defaultSettings.getAsInt("size", EsExecutors.boundedNumberOfProcessors(settings));
SizeValue defaultQueueSize = defaultSettings.getAsSize("queue", defaultSettings.getAsSize("queue_size", null));
if (previousExecutorHolder != null) {
if ("fixed".equals(previousInfo.getType())) {
SizeValue updatedQueueSize = settings.getAsSize("capacity", settings.getAsSize("queue", settings.getAsSize("queue_size", previousInfo.getQueueSize())));
if (Objects.equal(previousInfo.getQueueSize(), updatedQueueSize)) {
int updatedSize = settings.getAsInt("size", previousInfo.getMax());
if (previousInfo.getMax() != updatedSize) {
logger.debug("updating thread_pool [{}], type [{}], size [{}], queue_size [{}]", name, type, updatedSize, updatedQueueSize);
((EsThreadPoolExecutor) previousExecutorHolder.executor).setCorePoolSize(updatedSize);
((EsThreadPoolExecutor) previousExecutorHolder.executor).setMaximumPoolSize(updatedSize);
return new ExecutorHolder(previousExecutorHolder.executor, new Info(name, type, updatedSize, updatedSize, null, updatedQueueSize));
}
return previousExecutorHolder;
}
}
if (previousInfo.getMax() >= 0) {
defaultSize = previousInfo.getMax();
}
defaultQueueSize = previousInfo.getQueueSize();
}
int size = settings.getAsInt("size", defaultSize);
SizeValue queueSize = settings.getAsSize("capacity", settings.getAsSize("queue", settings.getAsSize("queue_size", defaultQueueSize)));
logger.debug("creating thread_pool [{}], type [{}], size [{}], queue_size [{}]", name, type, size, queueSize);
Executor executor = EsExecutors.newFixed(size, queueSize == null ? -1 : (int) queueSize.singles(), threadFactory);
return new ExecutorHolder(executor, new Info(name, type, size, size, null, queueSize));
} else if ("scaling".equals(type)) {
TimeValue defaultKeepAlive = defaultSettings.getAsTime("keep_alive", timeValueMinutes(5));
int defaultMin = defaultSettings.getAsInt("min", 1);
int defaultSize = defaultSettings.getAsInt("size", EsExecutors.boundedNumberOfProcessors(settings));
if (previousExecutorHolder != null) {
if ("scaling".equals(previousInfo.getType())) {
TimeValue updatedKeepAlive = settings.getAsTime("keep_alive", previousInfo.getKeepAlive());
int updatedMin = settings.getAsInt("min", previousInfo.getMin());
int updatedSize = settings.getAsInt("max", settings.getAsInt("size", previousInfo.getMax()));
if (!previousInfo.getKeepAlive().equals(updatedKeepAlive) || previousInfo.getMin() != updatedMin || previousInfo.getMax() != updatedSize) {
logger.debug("updating thread_pool [{}], type [{}], keep_alive [{}]", name, type, updatedKeepAlive);
if (!previousInfo.getKeepAlive().equals(updatedKeepAlive)) {
((EsThreadPoolExecutor) previousExecutorHolder.executor).setKeepAliveTime(updatedKeepAlive.millis(), TimeUnit.MILLISECONDS);
}
if (previousInfo.getMin() != updatedMin) {
((EsThreadPoolExecutor) previousExecutorHolder.executor).setCorePoolSize(updatedMin);
}
if (previousInfo.getMax() != updatedSize) {
((EsThreadPoolExecutor) previousExecutorHolder.executor).setMaximumPoolSize(updatedSize);
}
return new ExecutorHolder(previousExecutorHolder.executor, new Info(name, type, updatedMin, updatedSize, updatedKeepAlive, null));
}
return previousExecutorHolder;
}
if (previousInfo.getKeepAlive() != null) {
defaultKeepAlive = previousInfo.getKeepAlive();
}
if (previousInfo.getMin() >= 0) {
defaultMin = previousInfo.getMin();
}
if (previousInfo.getMax() >= 0) {
defaultSize = previousInfo.getMax();
}
}
TimeValue keepAlive = settings.getAsTime("keep_alive", defaultKeepAlive);
int min = settings.getAsInt("min", defaultMin);
int size = settings.getAsInt("max", settings.getAsInt("size", defaultSize));
if (previousExecutorHolder != null) {
logger.debug("updating thread_pool [{}], type [{}], min [{}], size [{}], keep_alive [{}]", name, type, min, size, keepAlive);
} else {
logger.debug("creating thread_pool [{}], type [{}], min [{}], size [{}], keep_alive [{}]", name, type, min, size, keepAlive);
}
Executor executor = EsExecutors.newScaling(min, size, keepAlive.millis(), TimeUnit.MILLISECONDS, threadFactory);
return new ExecutorHolder(executor, new Info(name, type, min, size, keepAlive, null));
}
throw new ElasticsearchIllegalArgumentException("No type found [" + type + "], for [" + name + "]");
}
public void updateSettings(Settings settings) {
Map<String, Settings> groupSettings = settings.getGroups("threadpool");
if (groupSettings.isEmpty()) {
return;
}
for (Map.Entry<String, Settings> executor : defaultExecutorTypeSettings.entrySet()) {
Settings updatedSettings = groupSettings.get(executor.getKey());
if (updatedSettings == null) {
continue;
}
ExecutorHolder oldExecutorHolder = executors.get(executor.getKey());
ExecutorHolder newExecutorHolder = rebuild(executor.getKey(), oldExecutorHolder, updatedSettings, executor.getValue());
if (!oldExecutorHolder.equals(newExecutorHolder)) {
executors = newMapBuilder(executors).put(executor.getKey(), newExecutorHolder).immutableMap();
if (!oldExecutorHolder.executor.equals(newExecutorHolder.executor) && oldExecutorHolder.executor instanceof EsThreadPoolExecutor) {
retiredExecutors.add(oldExecutorHolder);
((EsThreadPoolExecutor) oldExecutorHolder.executor).shutdown(new ExecutorShutdownListener(oldExecutorHolder));
}
}
}
}
class ExecutorShutdownListener implements EsThreadPoolExecutor.ShutdownListener {
private ExecutorHolder holder;
public ExecutorShutdownListener(ExecutorHolder holder) {
this.holder = holder;
}
@Override
public void onTerminated() {
retiredExecutors.remove(holder);
}
}
class LoggingRunnable implements Runnable {
private final Runnable runnable;
LoggingRunnable(Runnable runnable) {
this.runnable = runnable;
}
@Override
public void run() {
try {
runnable.run();
} catch (Exception e) {
logger.warn("failed to run {}", e, runnable.toString());
}
}
@Override
public int hashCode() {
return runnable.hashCode();
}
@Override
public boolean equals(Object obj) {
return runnable.equals(obj);
}
@Override
public String toString() {
return "[threaded] " + runnable.toString();
}
}
class ThreadedRunnable implements Runnable {
private final Runnable runnable;
private final Executor executor;
ThreadedRunnable(Runnable runnable, Executor executor) {
this.runnable = runnable;
this.executor = executor;
}
@Override
public void run() {
executor.execute(runnable);
}
@Override
public int hashCode() {
return runnable.hashCode();
}
@Override
public boolean equals(Object obj) {
return runnable.equals(obj);
}
@Override
public String toString() {
return "[threaded] " + runnable.toString();
}
}
static class EstimatedTimeThread extends Thread {
final long interval;
volatile boolean running = true;
volatile long estimatedTimeInMillis;
EstimatedTimeThread(String name, long interval) {
super(name);
this.interval = interval;
setDaemon(true);
}
public long estimatedTimeInMillis() {
return this.estimatedTimeInMillis;
}
@Override
public void run() {
while (running) {
estimatedTimeInMillis = System.currentTimeMillis();
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
running = false;
return;
}
try {
FileSystemUtils.checkMkdirsStall(estimatedTimeInMillis);
} catch (Exception e) {
// ignore
}
}
}
}
static class ExecutorHolder {
public final Executor executor;
public final Info info;
ExecutorHolder(Executor executor, Info info) {
this.executor = executor;
this.info = info;
}
}
public static class Info implements Streamable, ToXContent {
private String name;
private String type;
private int min;
private int max;
private TimeValue keepAlive;
private SizeValue queueSize;
Info() {
}
public Info(String name, String type) {
this(name, type, -1);
}
public Info(String name, String type, int size) {
this(name, type, size, size, null, null);
}
public Info(String name, String type, int min, int max, @Nullable TimeValue keepAlive, @Nullable SizeValue queueSize) {
this.name = name;
this.type = type;
this.min = min;
this.max = max;
this.keepAlive = keepAlive;
this.queueSize = queueSize;
}
public String getName() {
return this.name;
}
public String getType() {
return this.type;
}
public int getMin() {
return this.min;
}
public int getMax() {
return this.max;
}
@Nullable
public TimeValue getKeepAlive() {
return this.keepAlive;
}
@Nullable
public SizeValue getQueueSize() {
return this.queueSize;
}
@Override
public void readFrom(StreamInput in) throws IOException {
name = in.readString();
type = in.readString();
min = in.readInt();
max = in.readInt();
if (in.readBoolean()) {
keepAlive = TimeValue.readTimeValue(in);
}
if (in.readBoolean()) {
queueSize = SizeValue.readSizeValue(in);
}
in.readBoolean(); // here to conform with removed waitTime
in.readBoolean(); // here to conform with removed rejected setting
in.readBoolean(); // here to conform with queue type
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
out.writeString(type);
out.writeInt(min);
out.writeInt(max);
if (keepAlive == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
keepAlive.writeTo(out);
}
if (queueSize == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
queueSize.writeTo(out);
}
out.writeBoolean(false); // here to conform with removed waitTime
out.writeBoolean(false); // here to conform with removed rejected setting
out.writeBoolean(false); // here to conform with queue type
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name, XContentBuilder.FieldCaseConversion.NONE);
builder.field(Fields.TYPE, type);
if (min != -1) {
builder.field(Fields.MIN, min);
}
if (max != -1) {
builder.field(Fields.MAX, max);
}
if (keepAlive != null) {
builder.field(Fields.KEEP_ALIVE, keepAlive.toString());
}
if (queueSize != null) {
builder.field(Fields.QUEUE_SIZE, queueSize.toString());
}
builder.endObject();
return builder;
}
static final class Fields {
static final XContentBuilderString TYPE = new XContentBuilderString("type");
static final XContentBuilderString MIN = new XContentBuilderString("min");
static final XContentBuilderString MAX = new XContentBuilderString("max");
static final XContentBuilderString KEEP_ALIVE = new XContentBuilderString("keep_alive");
static final XContentBuilderString QUEUE_SIZE = new XContentBuilderString("queue_size");
}
}
class ApplySettings implements NodeSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
updateSettings(settings);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_threadpool_ThreadPool.java
|
2,541 |
abstract class AbstractIOSelector extends Thread implements IOSelector {
private static final int TIMEOUT = 3;
private static final int WAIT_TIME = 5000;
protected final ILogger logger;
protected final Queue<Runnable> selectorQueue = new ConcurrentLinkedQueue<Runnable>();
protected final IOService ioService;
protected final int waitTime;
protected final Selector selector;
protected boolean live = true;
private final CountDownLatch shutdownLatch = new CountDownLatch(1);
protected AbstractIOSelector(IOService ioService, String tname) {
super(ioService.getThreadGroup(), tname);
this.ioService = ioService;
this.logger = ioService.getLogger(getClass().getName());
// WARNING: This value has significant effect on idle CPU usage!
this.waitTime = WAIT_TIME;
Selector selectorTemp = null;
try {
selectorTemp = Selector.open();
} catch (final IOException e) {
handleSelectorException(e);
}
this.selector = selectorTemp;
}
public final void shutdown() {
selectorQueue.clear();
try {
addTask(new Runnable() {
public void run() {
live = false;
shutdownLatch.countDown();
}
});
interrupt();
} catch (Throwable ignored) {
}
}
public final void awaitShutdown() {
try {
shutdownLatch.await(TIMEOUT, TimeUnit.SECONDS);
} catch (InterruptedException ignored) {
}
}
public final void addTask(Runnable runnable) {
selectorQueue.add(runnable);
}
private void processSelectionQueue() {
//noinspection WhileLoopSpinsOnField
while (live) {
final Runnable runnable = selectorQueue.poll();
if (runnable == null) {
return;
}
runnable.run();
}
}
public final void run() {
try {
//noinspection WhileLoopSpinsOnField
while (live) {
processSelectionQueue();
if (!live || isInterrupted()) {
if (logger.isFinestEnabled()) {
logger.finest(getName() + " is interrupted!");
}
live = false;
return;
}
int selectedKeyCount;
try {
selectedKeyCount = selector.select(waitTime);
} catch (Throwable e) {
logger.warning(e.toString());
continue;
}
if (selectedKeyCount == 0) {
continue;
}
final Set<SelectionKey> setSelectedKeys = selector.selectedKeys();
final Iterator<SelectionKey> it = setSelectedKeys.iterator();
while (it.hasNext()) {
final SelectionKey sk = it.next();
try {
it.remove();
handleSelectionKey(sk);
} catch (Throwable e) {
handleSelectorException(e);
}
}
}
} catch (OutOfMemoryError e) {
ioService.onOutOfMemory(e);
} catch (Throwable e) {
logger.warning("Unhandled exception in " + getName(), e);
} finally {
try {
if (logger.isFinestEnabled()) {
logger.finest("Closing selector " + getName());
}
selector.close();
} catch (final Exception ignored) {
}
}
}
protected abstract void handleSelectionKey(SelectionKey sk);
private void handleSelectorException(final Throwable e) {
String msg = "Selector exception at " + getName() + ", cause= " + e.toString();
logger.warning(msg, e);
if (e instanceof OutOfMemoryError) {
ioService.onOutOfMemory((OutOfMemoryError) e);
}
}
public final Selector getSelector() {
return selector;
}
public final void wakeup() {
selector.wakeup();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_AbstractIOSelector.java
|
1,483 |
public class OSQLFunctionShortestPath extends OSQLFunctionPathFinder<Integer> {
public static final String NAME = "shortestPath";
private static final Integer MIN = new Integer(0);
private static final Integer DISTANCE = new Integer(1);
public OSQLFunctionShortestPath() {
super(NAME, 2, 3);
}
public Object execute(final OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters,
final OCommandContext iContext) {
final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph();
final ORecordInternal<?> record = (ORecordInternal<?>) (iCurrentRecord != null ? iCurrentRecord.getRecord() : null);
Object source = iParameters[0];
if (OMultiValue.isMultiValue(source)) {
if (OMultiValue.getSize(source) > 1)
throw new IllegalArgumentException("Only one sourceVertex is allowed");
source = OMultiValue.getFirstValue(source);
}
paramSourceVertex = graph.getVertex((OIdentifiable) OSQLHelper.getValue(source, record, iContext));
Object dest = iParameters[1];
if (OMultiValue.isMultiValue(dest)) {
if (OMultiValue.getSize(dest) > 1)
throw new IllegalArgumentException("Only one destinationVertex is allowed");
dest = OMultiValue.getFirstValue(dest);
}
paramDestinationVertex = graph.getVertex((OIdentifiable) OSQLHelper.getValue(dest, record, iContext));
if (iParameters.length > 2)
paramDirection = Direction.valueOf(iParameters[2].toString().toUpperCase());
return super.execute(iParameters, iContext);
}
public String getSyntax() {
return "Syntax error: shortestPath(<sourceVertex>, <destinationVertex>, [<direction>])";
}
@Override
protected Integer getShortestDistance(final Vertex destination) {
if (destination == null)
return Integer.MAX_VALUE;
final Integer d = distance.get(destination);
return d == null ? Integer.MAX_VALUE : d;
}
@Override
protected Integer getMinimumDistance() {
return MIN;
}
protected Integer getDistance(final Vertex node, final Vertex target) {
return DISTANCE;
}
@Override
protected Integer sumDistances(final Integer iDistance1, final Integer iDistance2) {
return iDistance1.intValue() + iDistance2.intValue();
}
}
| 1no label
|
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_functions_OSQLFunctionShortestPath.java
|
499 |
public final class ClientPartitionServiceImpl implements ClientPartitionService {
private static final ILogger LOGGER = Logger.getLogger(ClientPartitionService.class);
private static final long PERIOD = 10;
private static final long INITIAL_DELAY = 10;
private final HazelcastClient client;
private final ConcurrentHashMap<Integer, Address> partitions = new ConcurrentHashMap<Integer, Address>(271, 0.75f, 1);
private final AtomicBoolean updating = new AtomicBoolean(false);
private volatile int partitionCount;
public ClientPartitionServiceImpl(HazelcastClient client) {
this.client = client;
}
public void start() {
getInitialPartitions();
client.getClientExecutionService().scheduleWithFixedDelay(new RefreshTask(), INITIAL_DELAY, PERIOD, TimeUnit.SECONDS);
}
public void refreshPartitions() {
try {
client.getClientExecutionService().executeInternal(new RefreshTask());
} catch (RejectedExecutionException ignored) {
}
}
private class RefreshTask implements Runnable {
public void run() {
if (updating.compareAndSet(false, true)) {
try {
final ClientClusterService clusterService = client.getClientClusterService();
final Address master = clusterService.getMasterAddress();
final PartitionsResponse response = getPartitionsFrom(master);
if (response != null) {
processPartitionResponse(response);
}
} catch (HazelcastInstanceNotActiveException ignored) {
} finally {
updating.set(false);
}
}
}
}
private void getInitialPartitions() {
final ClientClusterService clusterService = client.getClientClusterService();
final Collection<MemberImpl> memberList = clusterService.getMemberList();
for (MemberImpl member : memberList) {
final Address target = member.getAddress();
PartitionsResponse response = getPartitionsFrom(target);
if (response != null) {
processPartitionResponse(response);
return;
}
}
throw new IllegalStateException("Cannot get initial partitions!");
}
private PartitionsResponse getPartitionsFrom(Address address) {
try {
final Future<PartitionsResponse> future =
client.getInvocationService().invokeOnTarget(new GetPartitionsRequest(), address);
return client.getSerializationService().toObject(future.get());
} catch (Exception e) {
LOGGER.severe("Error while fetching cluster partition table!", e);
}
return null;
}
private void processPartitionResponse(PartitionsResponse response) {
final Address[] members = response.getMembers();
final int[] ownerIndexes = response.getOwnerIndexes();
if (partitionCount == 0) {
partitionCount = ownerIndexes.length;
}
for (int partitionId = 0; partitionId < partitionCount; partitionId++) {
final int ownerIndex = ownerIndexes[partitionId];
if (ownerIndex > -1) {
partitions.put(partitionId, members[ownerIndex]);
}
}
}
public void stop() {
partitions.clear();
}
@Override
public Address getPartitionOwner(int partitionId) {
return partitions.get(partitionId);
}
@Override
public int getPartitionId(Data key) {
final int pc = partitionCount;
if (pc <= 0) {
return 0;
}
int hash = key.getPartitionHash();
return (hash == Integer.MIN_VALUE) ? 0 : Math.abs(hash) % pc;
}
@Override
public int getPartitionId(Object key) {
final Data data = client.getSerializationService().toData(key);
return getPartitionId(data);
}
@Override
public int getPartitionCount() {
return partitionCount;
}
@Override
public Partition getPartition(int partitionId) {
return new PartitionImpl(partitionId);
}
private final class PartitionImpl implements Partition {
private final int partitionId;
private PartitionImpl(int partitionId) {
this.partitionId = partitionId;
}
public int getPartitionId() {
return partitionId;
}
public Member getOwner() {
final Address owner = getPartitionOwner(partitionId);
if (owner != null) {
return client.getClientClusterService().getMember(owner);
}
return null;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("PartitionImpl{");
sb.append("partitionId=").append(partitionId);
sb.append('}');
return sb.toString();
}
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientPartitionServiceImpl.java
|
34 |
static final class ThenPropagate extends Completion {
final CompletableFuture<?> src;
final CompletableFuture<Void> dst;
ThenPropagate(CompletableFuture<?> src,
CompletableFuture<Void> dst) {
this.src = src; this.dst = dst;
}
public final void run() {
final CompletableFuture<?> a;
final CompletableFuture<Void> dst;
Object r; Throwable ex;
if ((dst = this.dst) != null &&
(a = this.src) != null &&
(r = a.result) != null &&
compareAndSet(0, 1)) {
if (r instanceof AltResult)
ex = ((AltResult)r).ex;
else
ex = null;
dst.internalComplete(null, ex);
}
}
private static final long serialVersionUID = 5232453952276885070L;
}
| 0true
|
src_main_java_jsr166e_CompletableFuture.java
|
298 |
transportService.sendRequest(node, action.name(), request, transportOptions, new BaseTransportResponseHandler<Response>() {
@Override
public Response newInstance() {
return action.newResponse();
}
@Override
public String executor() {
if (request.listenerThreaded()) {
return ThreadPool.Names.GENERIC;
}
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(Response response) {
listener.onResponse(response);
}
@Override
public void handleException(TransportException exp) {
listener.onFailure(exp);
}
});
| 0true
|
src_main_java_org_elasticsearch_action_TransportActionNodeProxy.java
|
127 |
{
@Override
public boolean accept( LogEntry item )
{
return !(item instanceof LogEntry.Done);
}
};
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestApplyTransactions.java
|
989 |
public abstract class TransportShardReplicationOperationAction<Request extends ShardReplicationOperationRequest, ReplicaRequest extends ActionRequest, Response extends ActionResponse> extends TransportAction<Request, Response> {
protected final TransportService transportService;
protected final ClusterService clusterService;
protected final IndicesService indicesService;
protected final ShardStateAction shardStateAction;
protected final ReplicationType defaultReplicationType;
protected final WriteConsistencyLevel defaultWriteConsistencyLevel;
protected final TransportRequestOptions transportOptions;
final String transportAction;
final String transportReplicaAction;
final String executor;
final boolean checkWriteConsistency;
protected TransportShardReplicationOperationAction(Settings settings, TransportService transportService,
ClusterService clusterService, IndicesService indicesService,
ThreadPool threadPool, ShardStateAction shardStateAction) {
super(settings, threadPool);
this.transportService = transportService;
this.clusterService = clusterService;
this.indicesService = indicesService;
this.shardStateAction = shardStateAction;
this.transportAction = transportAction();
this.transportReplicaAction = transportReplicaAction();
this.executor = executor();
this.checkWriteConsistency = checkWriteConsistency();
transportService.registerHandler(transportAction, new OperationTransportHandler());
transportService.registerHandler(transportReplicaAction, new ReplicaOperationTransportHandler());
this.transportOptions = transportOptions();
this.defaultReplicationType = ReplicationType.fromString(settings.get("action.replication_type", "sync"));
this.defaultWriteConsistencyLevel = WriteConsistencyLevel.fromString(settings.get("action.write_consistency", "quorum"));
}
@Override
protected void doExecute(Request request, ActionListener<Response> listener) {
new AsyncShardOperationAction(request, listener).start();
}
protected abstract Request newRequestInstance();
protected abstract ReplicaRequest newReplicaRequestInstance();
protected abstract Response newResponseInstance();
protected abstract String transportAction();
protected abstract String executor();
protected abstract PrimaryResponse<Response, ReplicaRequest> shardOperationOnPrimary(ClusterState clusterState, PrimaryOperationRequest shardRequest);
protected abstract void shardOperationOnReplica(ReplicaOperationRequest shardRequest);
/**
* Called once replica operations have been dispatched on the
*/
protected void postPrimaryOperation(Request request, PrimaryResponse<Response, ReplicaRequest> response) {
}
protected abstract ShardIterator shards(ClusterState clusterState, Request request) throws ElasticsearchException;
protected abstract boolean checkWriteConsistency();
protected abstract ClusterBlockException checkGlobalBlock(ClusterState state, Request request);
protected abstract ClusterBlockException checkRequestBlock(ClusterState state, Request request);
/**
* Resolves the request, by default, simply setting the concrete index (if its aliased one). If the resolve
* means a different execution, then return false here to indicate not to continue and execute this request.
*/
protected boolean resolveRequest(ClusterState state, Request request, ActionListener<Response> listener) {
request.index(state.metaData().concreteIndex(request.index()));
return true;
}
protected TransportRequestOptions transportOptions() {
return TransportRequestOptions.EMPTY;
}
/**
* Should the operations be performed on the replicas as well. Defaults to <tt>false</tt> meaning operations
* will be executed on the replica.
*/
protected boolean ignoreReplicas() {
return false;
}
private String transportReplicaAction() {
return transportAction() + "/replica";
}
protected boolean retryPrimaryException(Throwable e) {
return TransportActions.isShardNotAvailableException(e);
}
/**
* Should an exception be ignored when the operation is performed on the replica.
*/
boolean ignoreReplicaException(Throwable e) {
if (TransportActions.isShardNotAvailableException(e)) {
return true;
}
Throwable cause = ExceptionsHelper.unwrapCause(e);
if (cause instanceof ConnectTransportException) {
return true;
}
// on version conflict or document missing, it means
// that a news change has crept into the replica, and its fine
if (cause instanceof VersionConflictEngineException) {
return true;
}
// same here
if (cause instanceof DocumentAlreadyExistsException) {
return true;
}
return false;
}
class OperationTransportHandler extends BaseTransportRequestHandler<Request> {
@Override
public Request newInstance() {
return newRequestInstance();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void messageReceived(final Request request, final TransportChannel channel) throws Exception {
// no need to have a threaded listener since we just send back a response
request.listenerThreaded(false);
// if we have a local operation, execute it on a thread since we don't spawn
request.operationThreaded(true);
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response result) {
try {
channel.sendResponse(result);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Throwable e1) {
logger.warn("Failed to send response for " + transportAction, e1);
}
}
});
}
}
class ReplicaOperationTransportHandler extends BaseTransportRequestHandler<ReplicaOperationRequest> {
@Override
public ReplicaOperationRequest newInstance() {
return new ReplicaOperationRequest();
}
@Override
public String executor() {
return executor;
}
// we must never reject on because of thread pool capacity on replicas
@Override
public boolean isForceExecution() {
return true;
}
@Override
public void messageReceived(final ReplicaOperationRequest request, final TransportChannel channel) throws Exception {
shardOperationOnReplica(request);
channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
}
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);
}
}
protected class ReplicaOperationRequest extends TransportRequest {
public int shardId;
public ReplicaRequest request;
public ReplicaOperationRequest() {
}
public ReplicaOperationRequest(int shardId, ReplicaRequest request) {
super(request);
this.shardId = shardId;
this.request = request;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shardId = in.readVInt();
request = newReplicaRequestInstance();
request.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(shardId);
request.writeTo(out);
}
}
protected class AsyncShardOperationAction {
private final ActionListener<Response> listener;
private final Request request;
private volatile ClusterState clusterState;
private volatile ShardIterator shardIt;
private final AtomicBoolean primaryOperationStarted = new AtomicBoolean();
private final ReplicationType replicationType;
protected final long startTime = System.currentTimeMillis();
AsyncShardOperationAction(Request request, ActionListener<Response> listener) {
this.request = request;
this.listener = listener;
if (request.replicationType() != ReplicationType.DEFAULT) {
replicationType = request.replicationType();
} else {
replicationType = defaultReplicationType;
}
}
public void start() {
start(false);
}
/**
* Returns <tt>true</tt> if the action starting to be performed on the primary (or is done).
*/
public boolean start(final boolean fromClusterEvent) throws ElasticsearchException {
this.clusterState = clusterService.state();
try {
ClusterBlockException blockException = checkGlobalBlock(clusterState, request);
if (blockException != null) {
if (blockException.retryable()) {
logger.trace("cluster is blocked ({}), scheduling a retry", blockException.getMessage());
retry(fromClusterEvent, blockException);
return false;
} else {
throw blockException;
}
}
// check if we need to execute, and if not, return
if (!resolveRequest(clusterState, request, listener)) {
return true;
}
blockException = checkRequestBlock(clusterState, request);
if (blockException != null) {
if (blockException.retryable()) {
logger.trace("cluster is blocked ({}), scheduling a retry", blockException.getMessage());
retry(fromClusterEvent, blockException);
return false;
} else {
throw blockException;
}
}
shardIt = shards(clusterState, request);
} catch (Throwable e) {
listener.onFailure(e);
return true;
}
// no shardIt, might be in the case between index gateway recovery and shardIt initialization
if (shardIt.size() == 0) {
logger.trace("no shard instances known for shard [{}], scheduling a retry", shardIt.shardId());
retry(fromClusterEvent, null);
return false;
}
boolean foundPrimary = false;
ShardRouting shardX;
while ((shardX = shardIt.nextOrNull()) != null) {
final ShardRouting shard = shardX;
// we only deal with primary shardIt here...
if (!shard.primary()) {
continue;
}
if (!shard.active() || !clusterState.nodes().nodeExists(shard.currentNodeId())) {
logger.trace("primary shard [{}] is not yet active or we do not know the node it is assigned to [{}], scheduling a retry.", shard.shardId(), shard.currentNodeId());
retry(fromClusterEvent, null);
return false;
}
// check here for consistency
if (checkWriteConsistency) {
WriteConsistencyLevel consistencyLevel = defaultWriteConsistencyLevel;
if (request.consistencyLevel() != WriteConsistencyLevel.DEFAULT) {
consistencyLevel = request.consistencyLevel();
}
int requiredNumber = 1;
if (consistencyLevel == WriteConsistencyLevel.QUORUM && shardIt.size() > 2) {
// only for more than 2 in the number of shardIt it makes sense, otherwise its 1 shard with 1 replica, quorum is 1 (which is what it is initialized to)
requiredNumber = (shardIt.size() / 2) + 1;
} else if (consistencyLevel == WriteConsistencyLevel.ALL) {
requiredNumber = shardIt.size();
}
if (shardIt.sizeActive() < requiredNumber) {
logger.trace("not enough active copies of shard [{}] to meet write consistency of [{}] (have {}, needed {}), scheduling a retry.",
shard.shardId(), consistencyLevel, shardIt.sizeActive(), requiredNumber);
retry(fromClusterEvent, null);
return false;
}
}
if (!primaryOperationStarted.compareAndSet(false, true)) {
return true;
}
foundPrimary = true;
if (shard.currentNodeId().equals(clusterState.nodes().localNodeId())) {
try {
if (request.operationThreaded()) {
request.beforeLocalFork();
threadPool.executor(executor).execute(new Runnable() {
@Override
public void run() {
try {
performOnPrimary(shard.id(), shard, clusterState);
} catch (Throwable t) {
listener.onFailure(t);
}
}
});
} else {
performOnPrimary(shard.id(), shard, clusterState);
}
} catch (Throwable t) {
listener.onFailure(t);
}
} else {
DiscoveryNode node = clusterState.nodes().get(shard.currentNodeId());
transportService.sendRequest(node, transportAction, request, transportOptions, new BaseTransportResponseHandler<Response>() {
@Override
public Response newInstance() {
return newResponseInstance();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(Response response) {
listener.onResponse(response);
}
@Override
public void handleException(TransportException exp) {
// if we got disconnected from the node, or the node / shard is not in the right state (being closed)
if (exp.unwrapCause() instanceof ConnectTransportException || exp.unwrapCause() instanceof NodeClosedException ||
retryPrimaryException(exp)) {
primaryOperationStarted.set(false);
// we already marked it as started when we executed it (removed the listener) so pass false
// to re-add to the cluster listener
logger.trace("received an error from node the primary was assigned to ({}), scheduling a retry", exp.getMessage());
retry(false, null);
} else {
listener.onFailure(exp);
}
}
});
}
break;
}
// we won't find a primary if there are no shards in the shard iterator, retry...
if (!foundPrimary) {
logger.trace("couldn't find a eligible primary shard, scheduling for retry.");
retry(fromClusterEvent, null);
return false;
}
return true;
}
void retry(boolean fromClusterEvent, @Nullable final Throwable failure) {
if (fromClusterEvent) {
logger.trace("retry scheduling ignored as it as we already have a listener in place");
return;
}
// make it threaded operation so we fork on the discovery listener thread
request.beforeLocalFork();
request.operationThreaded(true);
TimeValue timeout = new TimeValue(request.timeout().millis() - (System.currentTimeMillis() - startTime));
if (timeout.millis() <= 0) {
raiseTimeoutFailure(timeout, failure);
return;
}
clusterService.add(timeout, new TimeoutClusterStateListener() {
@Override
public void postAdded() {
// check if state version changed while we were adding this listener
long sampledVersion = clusterState.version();
long currentVersion = clusterService.state().version();
if (sampledVersion != currentVersion) {
logger.trace("state change while we were trying to add listener, trying to start again, sampled_version [{}], current_version [{}]", sampledVersion, currentVersion);
if (start(true)) {
// if we managed to start and perform the operation on the primary, we can remove this listener
clusterService.remove(this);
}
}
}
@Override
public void onClose() {
clusterService.remove(this);
listener.onFailure(new NodeClosedException(clusterService.localNode()));
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
logger.trace("cluster changed (version {}), trying to start again", event.state().version());
if (start(true)) {
// if we managed to start and perform the operation on the primary, we can remove this listener
clusterService.remove(this);
}
}
@Override
public void onTimeout(TimeValue timeValue) {
// just to be on the safe side, see if we can start it now?
if (start(true)) {
clusterService.remove(this);
return;
}
clusterService.remove(this);
raiseTimeoutFailure(timeValue, failure);
}
});
}
void raiseTimeoutFailure(TimeValue timeout, @Nullable Throwable failure) {
if (failure == null) {
if (shardIt == null) {
failure = new UnavailableShardsException(null, "no available shards: Timeout waiting for [" + timeout + "], request: " + request.toString());
} else {
failure = new UnavailableShardsException(shardIt.shardId(), "[" + shardIt.size() + "] shardIt, [" + shardIt.sizeActive() + "] active : Timeout waiting for [" + timeout + "], request: " + request.toString());
}
}
listener.onFailure(failure);
}
void performOnPrimary(int primaryShardId, final ShardRouting shard, ClusterState clusterState) {
try {
PrimaryResponse<Response, ReplicaRequest> response = shardOperationOnPrimary(clusterState, new PrimaryOperationRequest(primaryShardId, request));
performReplicas(response);
} catch (Throwable e) {
// shard has not been allocated yet, retry it here
if (retryPrimaryException(e)) {
primaryOperationStarted.set(false);
logger.trace("had an error while performing operation on primary ({}), scheduling a retry.", e.getMessage());
retry(false, e);
return;
}
if (e instanceof ElasticsearchException && ((ElasticsearchException) e).status() == RestStatus.CONFLICT) {
if (logger.isTraceEnabled()) {
logger.trace(shard.shortSummary() + ": Failed to execute [" + request + "]", e);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug(shard.shortSummary() + ": Failed to execute [" + request + "]", e);
}
}
listener.onFailure(e);
}
}
void performReplicas(final PrimaryResponse<Response, ReplicaRequest> response) {
if (ignoreReplicas()) {
postPrimaryOperation(request, response);
listener.onResponse(response.response());
return;
}
ShardRouting shard;
// we double check on the state, if it got changed we need to make sure we take the latest one cause
// maybe a replica shard started its recovery process and we need to apply it there...
// we also need to make sure if the new state has a new primary shard (that we indexed to before) started
// and assigned to another node (while the indexing happened). In that case, we want to apply it on the
// new primary shard as well...
ClusterState newState = clusterService.state();
ShardRouting newPrimaryShard = null;
if (clusterState != newState) {
shardIt.reset();
ShardRouting originalPrimaryShard = null;
while ((shard = shardIt.nextOrNull()) != null) {
if (shard.primary()) {
originalPrimaryShard = shard;
break;
}
}
if (originalPrimaryShard == null || !originalPrimaryShard.active()) {
throw new ElasticsearchIllegalStateException("unexpected state, failed to find primary shard on an index operation that succeeded");
}
clusterState = newState;
shardIt = shards(newState, request);
while ((shard = shardIt.nextOrNull()) != null) {
if (shard.primary()) {
if (originalPrimaryShard.currentNodeId().equals(shard.currentNodeId())) {
newPrimaryShard = null;
} else {
newPrimaryShard = shard;
}
break;
}
}
}
// initialize the counter
int replicaCounter = shardIt.assignedReplicasIncludingRelocating();
if (newPrimaryShard != null) {
replicaCounter++;
}
if (replicaCounter == 0) {
postPrimaryOperation(request, response);
listener.onResponse(response.response());
return;
}
if (replicationType == ReplicationType.ASYNC) {
postPrimaryOperation(request, response);
// async replication, notify the listener
listener.onResponse(response.response());
// now, trick the counter so it won't decrease to 0 and notify the listeners
replicaCounter = Integer.MIN_VALUE;
}
// we add one to the replica count to do the postPrimaryOperation
replicaCounter++;
AtomicInteger counter = new AtomicInteger(replicaCounter);
IndexMetaData indexMetaData = clusterState.metaData().index(request.index());
if (newPrimaryShard != null) {
performOnReplica(response, counter, newPrimaryShard, newPrimaryShard.currentNodeId(), indexMetaData);
}
shardIt.reset(); // reset the iterator
while ((shard = shardIt.nextOrNull()) != null) {
// if its unassigned, nothing to do here...
if (shard.unassigned()) {
continue;
}
// if the shard is primary and relocating, add one to the counter since we perform it on the replica as well
// (and we already did it on the primary)
boolean doOnlyOnRelocating = false;
if (shard.primary()) {
if (shard.relocating()) {
doOnlyOnRelocating = true;
} else {
continue;
}
}
// we index on a replica that is initializing as well since we might not have got the event
// yet that it was started. We will get an exception IllegalShardState exception if its not started
// and that's fine, we will ignore it
if (!doOnlyOnRelocating) {
performOnReplica(response, counter, shard, shard.currentNodeId(), indexMetaData);
}
if (shard.relocating()) {
performOnReplica(response, counter, shard, shard.relocatingNodeId(), indexMetaData);
}
}
// now do the postPrimary operation, and check if the listener needs to be invoked
postPrimaryOperation(request, response);
// we also invoke here in case replicas finish before postPrimaryAction does
if (counter.decrementAndGet() == 0) {
listener.onResponse(response.response());
}
}
void performOnReplica(final PrimaryResponse<Response, ReplicaRequest> response, final AtomicInteger counter, final ShardRouting shard, String nodeId, final IndexMetaData indexMetaData) {
// if we don't have that node, it means that it might have failed and will be created again, in
// this case, we don't have to do the operation, and just let it failover
if (!clusterState.nodes().nodeExists(nodeId)) {
if (counter.decrementAndGet() == 0) {
listener.onResponse(response.response());
}
return;
}
final ReplicaOperationRequest shardRequest = new ReplicaOperationRequest(shardIt.shardId().id(), response.replicaRequest());
if (!nodeId.equals(clusterState.nodes().localNodeId())) {
DiscoveryNode node = clusterState.nodes().get(nodeId);
transportService.sendRequest(node, transportReplicaAction, shardRequest, transportOptions, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleResponse(TransportResponse.Empty vResponse) {
finishIfPossible();
}
@Override
public void handleException(TransportException exp) {
if (!ignoreReplicaException(exp.unwrapCause())) {
logger.warn("Failed to perform " + transportAction + " on replica " + shardIt.shardId(), exp);
shardStateAction.shardFailed(shard, indexMetaData.getUUID(),
"Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(exp) + "]");
}
finishIfPossible();
}
private void finishIfPossible() {
if (counter.decrementAndGet() == 0) {
listener.onResponse(response.response());
}
}
});
} else {
if (request.operationThreaded()) {
request.beforeLocalFork();
try {
threadPool.executor(executor).execute(new AbstractRunnable() {
@Override
public void run() {
try {
shardOperationOnReplica(shardRequest);
} catch (Throwable e) {
if (!ignoreReplicaException(e)) {
logger.warn("Failed to perform " + transportAction + " on replica " + shardIt.shardId(), e);
shardStateAction.shardFailed(shard, indexMetaData.getUUID(),
"Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(e) + "]");
}
}
if (counter.decrementAndGet() == 0) {
listener.onResponse(response.response());
}
}
// we must never reject on because of thread pool capacity on replicas
@Override
public boolean isForceExecution() {
return true;
}
});
} catch (Throwable e) {
if (!ignoreReplicaException(e)) {
logger.warn("Failed to perform " + transportAction + " on replica " + shardIt.shardId(), e);
shardStateAction.shardFailed(shard, indexMetaData.getUUID(),
"Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(e) + "]");
}
// we want to decrement the counter here, in teh failure handling, cause we got rejected
// from executing on the thread pool
if (counter.decrementAndGet() == 0) {
listener.onResponse(response.response());
}
}
} else {
try {
shardOperationOnReplica(shardRequest);
} catch (Throwable e) {
if (!ignoreReplicaException(e)) {
logger.warn("Failed to perform " + transportAction + " on replica" + shardIt.shardId(), e);
shardStateAction.shardFailed(shard, indexMetaData.getUUID(),
"Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(e) + "]");
}
}
if (counter.decrementAndGet() == 0) {
listener.onResponse(response.response());
}
}
}
}
}
public static class PrimaryResponse<Response, ReplicaRequest> {
private final ReplicaRequest replicaRequest;
private final Response response;
private final Object payload;
public PrimaryResponse(ReplicaRequest replicaRequest, Response response, Object payload) {
this.replicaRequest = replicaRequest;
this.response = response;
this.payload = payload;
}
public ReplicaRequest replicaRequest() {
return this.replicaRequest;
}
public Response response() {
return response;
}
public Object payload() {
return payload;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_support_replication_TransportShardReplicationOperationAction.java
|
837 |
private static class AppendFunction implements IFunction<String, String> {
private String add;
private AppendFunction(String add) {
this.add = add;
}
@Override
public String apply(String input) {
return input + add;
}
}
| 0true
|
hazelcast_src_test_java_com_hazelcast_concurrent_atomicreference_AtomicReferenceTest.java
|
586 |
public class RefreshResponse extends BroadcastOperationResponse {
RefreshResponse() {
}
RefreshResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
super(totalShards, successfulShards, failedShards, shardFailures);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_refresh_RefreshResponse.java
|
220 |
Arrays.sort(passages, new Comparator<Passage>() {
@Override
public int compare(Passage left, Passage right) {
return left.startOffset - right.startOffset;
}
});
| 0true
|
src_main_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighter.java
|
5,352 |
public class InternalAvg extends MetricsAggregation.SingleValue implements Avg {
public final static Type TYPE = new Type("avg");
public final static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public InternalAvg readResult(StreamInput in) throws IOException {
InternalAvg result = new InternalAvg();
result.readFrom(in);
return result;
}
};
public static void registerStreams() {
AggregationStreams.registerStream(STREAM, TYPE.stream());
}
private double sum;
private long count;
InternalAvg() {} // for serialization
public InternalAvg(String name, double sum, long count) {
super(name);
this.sum = sum;
this.count = count;
}
@Override
public double value() {
return getValue();
}
public double getValue() {
return sum / count;
}
@Override
public Type type() {
return TYPE;
}
@Override
public InternalAvg reduce(ReduceContext reduceContext) {
List<InternalAggregation> aggregations = reduceContext.aggregations();
if (aggregations.size() == 1) {
return (InternalAvg) aggregations.get(0);
}
InternalAvg reduced = null;
for (InternalAggregation aggregation : aggregations) {
if (reduced == null) {
reduced = (InternalAvg) aggregation;
} else {
reduced.count += ((InternalAvg) aggregation).count;
reduced.sum += ((InternalAvg) aggregation).sum;
}
}
return reduced;
}
@Override
public void readFrom(StreamInput in) throws IOException {
name = in.readString();
valueFormatter = ValueFormatterStreams.readOptional(in);
sum = in.readDouble();
count = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
ValueFormatterStreams.writeOptional(valueFormatter, out);
out.writeDouble(sum);
out.writeVLong(count);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
builder.field(CommonFields.VALUE, count != 0 ? getValue() : null);
if (count != 0 && valueFormatter != null) {
builder.field(CommonFields.VALUE_AS_STRING, valueFormatter.format(getValue()));
}
builder.endObject();
return builder;
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_metrics_avg_InternalAvg.java
|
59 |
public interface FieldDefinition extends Serializable {
public Long getId();
public void setId(Long id);
public String getName();
public void setName(String name);
public SupportedFieldType getFieldType();
public void setFieldType(SupportedFieldType fieldType);
public String getSecurityLevel();
public void setSecurityLevel(String securityLevel);
public Boolean getHiddenFlag();
public void setHiddenFlag(Boolean hiddenFlag);
public String getValidationRegEx();
public void setValidationRegEx(String validationRegEx);
public Integer getMaxLength();
public void setMaxLength(Integer maxLength);
public String getColumnWidth();
public void setColumnWidth(String columnWidth);
public Boolean getTextAreaFlag();
public void setTextAreaFlag(Boolean textAreaFlag);
public FieldEnumeration getFieldEnumeration();
public void setFieldEnumeration(FieldEnumeration fieldEnumeration);
public Boolean getAllowMultiples();
public void setAllowMultiples(Boolean allowMultiples);
public String getFriendlyName();
public void setFriendlyName(String friendlyName);
public String getValidationErrorMesageKey();
public void setValidationErrorMesageKey(String validationErrorMesageKey);
public FieldGroup getFieldGroup();
public void setFieldGroup(FieldGroup fieldGroup);
public int getFieldOrder();
public void setFieldOrder(int fieldOrder);
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_field_domain_FieldDefinition.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
|
134 |
class InvertBooleanProposal implements ICompletionProposal {
private final InvertBooleanRefactoringAction action;
public InvertBooleanProposal(CeylonEditor editor) {
action = new InvertBooleanRefactoringAction(editor);
}
@Override
public Image getImage() {
return CeylonLabelProvider.COMPOSITE_CHANGE;
}
@Override
public String getDisplayString() {
return "Invert boolean value of '" + action.getValueName() + "'";
}
@Override
public Point getSelection(IDocument doc) {
return null;
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument doc) {
action.run();
}
public static void add(Collection<ICompletionProposal> proposals, CeylonEditor editor) {
InvertBooleanProposal proposal = new InvertBooleanProposal(editor);
if (proposal.action.isEnabled()) {
proposals.add(proposal);
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_InvertBooleanProposal.java
|
1,432 |
public class MetaDataTests extends ElasticsearchTestCase {
@Test
public void testIndexOptions_strict() {
MetaData.Builder mdBuilder = MetaData.builder()
.put(indexBuilder("foo"))
.put(indexBuilder("foobar"))
.put(indexBuilder("foofoo").putAlias(AliasMetaData.builder("barbaz")));
MetaData md = mdBuilder.build();
IndicesOptions options = IndicesOptions.strict();
String[] results = md.concreteIndices(Strings.EMPTY_ARRAY, options);
assertEquals(3, results.length);
results = md.concreteIndices(new String[]{"foo"}, options);
assertEquals(1, results.length);
assertEquals("foo", results[0]);
try {
md.concreteIndices(new String[]{"bar"}, options);
fail();
} catch (IndexMissingException e) {}
results = md.concreteIndices(new String[]{"foofoo", "foobar"}, options);
assertEquals(2, results.length);
assertThat(results, arrayContainingInAnyOrder("foofoo", "foobar"));
try {
md.concreteIndices(new String[]{"foo", "bar"}, options);
fail();
} catch (IndexMissingException e) {}
results = md.concreteIndices(new String[]{"barbaz", "foobar"}, options);
assertEquals(2, results.length);
assertThat(results, arrayContainingInAnyOrder("foofoo", "foobar"));
try {
md.concreteIndices(new String[]{"barbaz", "bar"}, options);
fail();
} catch (IndexMissingException e) {}
results = md.concreteIndices(new String[]{"baz*"}, options);
assertThat(results, emptyArray());
results = md.concreteIndices(new String[]{"foo", "baz*"}, options);
assertEquals(1, results.length);
assertEquals("foo", results[0]);
}
@Test
public void testIndexOptions_lenient() {
MetaData.Builder mdBuilder = MetaData.builder()
.put(indexBuilder("foo"))
.put(indexBuilder("foobar"))
.put(indexBuilder("foofoo").putAlias(AliasMetaData.builder("barbaz")));
MetaData md = mdBuilder.build();
IndicesOptions options = IndicesOptions.lenient();
String[] results = md.concreteIndices(Strings.EMPTY_ARRAY, options);
assertEquals(3, results.length);
results = md.concreteIndices(new String[]{"foo"}, options);
assertEquals(1, results.length);
assertEquals("foo", results[0]);
results = md.concreteIndices(new String[]{"bar"}, options);
assertThat(results, emptyArray());
results = md.concreteIndices(new String[]{"foofoo", "foobar"}, options);
assertEquals(2, results.length);
assertThat(results, arrayContainingInAnyOrder("foofoo", "foobar"));
results = md.concreteIndices(new String[]{"foo", "bar"}, options);
assertEquals(1, results.length);
assertThat(results, arrayContainingInAnyOrder("foo"));
results = md.concreteIndices(new String[]{"barbaz", "foobar"}, options);
assertEquals(2, results.length);
assertThat(results, arrayContainingInAnyOrder("foofoo", "foobar"));
results = md.concreteIndices(new String[]{"barbaz", "bar"}, options);
assertEquals(1, results.length);
assertThat(results, arrayContainingInAnyOrder("foofoo"));
results = md.concreteIndices(new String[]{"baz*"}, options);
assertThat(results, emptyArray());
results = md.concreteIndices(new String[]{"foo", "baz*"}, options);
assertEquals(1, results.length);
assertEquals("foo", results[0]);
}
@Test
public void testIndexOptions_allowUnavailableExpandOpenDisAllowEmpty() {
MetaData.Builder mdBuilder = MetaData.builder()
.put(indexBuilder("foo"))
.put(indexBuilder("foobar"))
.put(indexBuilder("foofoo").putAlias(AliasMetaData.builder("barbaz")));
MetaData md = mdBuilder.build();
IndicesOptions options = IndicesOptions.fromOptions(true, false, true, false);
String[] results = md.concreteIndices(Strings.EMPTY_ARRAY, options);
assertEquals(3, results.length);
results = md.concreteIndices(new String[]{"foo"}, options);
assertEquals(1, results.length);
assertEquals("foo", results[0]);
results = md.concreteIndices(new String[]{"bar"}, options);
assertThat(results, emptyArray());
try {
md.concreteIndices(new String[]{"baz*"}, options);
fail();
} catch (IndexMissingException e) {}
try {
md.concreteIndices(new String[]{"foo", "baz*"}, options);
fail();
} catch (IndexMissingException e) {}
}
@Test
public void testIndexOptions_wildcardExpansion() {
MetaData.Builder mdBuilder = MetaData.builder()
.put(indexBuilder("foo").state(IndexMetaData.State.CLOSE))
.put(indexBuilder("bar"))
.put(indexBuilder("foobar").putAlias(AliasMetaData.builder("barbaz")));
MetaData md = mdBuilder.build();
// Only closed
IndicesOptions options = IndicesOptions.fromOptions(false, true, false, true);
String[] results = md.concreteIndices(Strings.EMPTY_ARRAY, options);
assertEquals(1, results.length);
assertEquals("foo", results[0]);
results = md.concreteIndices(new String[]{"foo*"}, options);
assertEquals(1, results.length);
assertEquals("foo", results[0]);
// no wildcards, so wildcard expansion don't apply
results = md.concreteIndices(new String[]{"bar"}, options);
assertEquals(1, results.length);
assertEquals("bar", results[0]);
// Only open
options = IndicesOptions.fromOptions(false, true, true, false);
results = md.concreteIndices(Strings.EMPTY_ARRAY, options);
assertEquals(2, results.length);
assertThat(results, arrayContainingInAnyOrder("bar", "foobar"));
results = md.concreteIndices(new String[]{"foo*"}, options);
assertEquals(1, results.length);
assertEquals("foobar", results[0]);
results = md.concreteIndices(new String[]{"bar"}, options);
assertEquals(1, results.length);
assertEquals("bar", results[0]);
// Open and closed
options = IndicesOptions.fromOptions(false, true, true, true);
results = md.concreteIndices(Strings.EMPTY_ARRAY, options);
assertEquals(3, results.length);
assertThat(results, arrayContainingInAnyOrder("bar", "foobar", "foo"));
results = md.concreteIndices(new String[]{"foo*"}, options);
assertEquals(2, results.length);
assertThat(results, arrayContainingInAnyOrder("foobar", "foo"));
results = md.concreteIndices(new String[]{"bar"}, options);
assertEquals(1, results.length);
assertEquals("bar", results[0]);
results = md.concreteIndices(new String[]{"-foo*"}, options);
assertEquals(1, results.length);
assertEquals("bar", results[0]);
results = md.concreteIndices(new String[]{"-*"}, options);
assertEquals(0, results.length);
options = IndicesOptions.fromOptions(false, false, true, true);
try {
md.concreteIndices(new String[]{"-*"}, options);
fail();
} catch (IndexMissingException e) {}
}
@Test
public void testIndexOptions_emptyCluster() {
MetaData md = MetaData.builder().build();
IndicesOptions options = IndicesOptions.strict();
String[] results = md.concreteIndices(Strings.EMPTY_ARRAY, options);
assertThat(results, emptyArray());
try {
md.concreteIndices(new String[]{"foo"}, options);
fail();
} catch (IndexMissingException e) {}
results = md.concreteIndices(new String[]{"foo*"}, options);
assertThat(results, emptyArray());
try {
md.concreteIndices(new String[]{"foo*", "bar"}, options);
fail();
} catch (IndexMissingException e) {}
options = IndicesOptions.lenient();
results = md.concreteIndices(Strings.EMPTY_ARRAY, options);
assertThat(results, emptyArray());
results = md.concreteIndices(new String[]{"foo"}, options);
assertThat(results, emptyArray());
results = md.concreteIndices(new String[]{"foo*"}, options);
assertThat(results, emptyArray());
results = md.concreteIndices(new String[]{"foo*", "bar"}, options);
assertThat(results, emptyArray());
options = IndicesOptions.fromOptions(true, false, true, false);
try {
md.concreteIndices(Strings.EMPTY_ARRAY, options);
} catch (IndexMissingException e) {}
}
@Test
public void convertWildcardsJustIndicesTests() {
MetaData.Builder mdBuilder = MetaData.builder()
.put(indexBuilder("testXXX"))
.put(indexBuilder("testXYY"))
.put(indexBuilder("testYYY"))
.put(indexBuilder("kuku"));
MetaData md = mdBuilder.build();
assertThat(newHashSet(md.convertFromWildcards(new String[]{"testXXX"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX")));
assertThat(newHashSet(md.convertFromWildcards(new String[]{"testXXX", "testYYY"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testYYY")));
assertThat(newHashSet(md.convertFromWildcards(new String[]{"testXXX", "ku*"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "kuku")));
assertThat(newHashSet(md.convertFromWildcards(new String[]{"test*"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY", "testYYY")));
assertThat(newHashSet(md.convertFromWildcards(new String[]{"testX*"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY")));
assertThat(newHashSet(md.convertFromWildcards(new String[]{"testX*", "kuku"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY", "kuku")));
}
@Test
public void convertWildcardsTests() {
MetaData.Builder mdBuilder = MetaData.builder()
.put(indexBuilder("testXXX").putAlias(AliasMetaData.builder("alias1")).putAlias(AliasMetaData.builder("alias2")))
.put(indexBuilder("testXYY").putAlias(AliasMetaData.builder("alias2")))
.put(indexBuilder("testYYY").putAlias(AliasMetaData.builder("alias3")))
.put(indexBuilder("kuku"));
MetaData md = mdBuilder.build();
assertThat(newHashSet(md.convertFromWildcards(new String[]{"testYY*", "alias*"}, IndicesOptions.lenient())), equalTo(newHashSet("alias1", "alias2", "alias3", "testYYY")));
assertThat(newHashSet(md.convertFromWildcards(new String[]{"-kuku"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY", "testYYY")));
assertThat(newHashSet(md.convertFromWildcards(new String[]{"+test*", "-testYYY"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY")));
assertThat(newHashSet(md.convertFromWildcards(new String[]{"+testX*", "+testYYY"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY", "testYYY")));
assertThat(newHashSet(md.convertFromWildcards(new String[]{"+testYYY", "+testX*"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX", "testXYY", "testYYY")));
}
private IndexMetaData.Builder indexBuilder(String index) {
return IndexMetaData.builder(index).settings(ImmutableSettings.settingsBuilder().put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0));
}
@Test(expected = IndexMissingException.class)
public void concreteIndicesIgnoreIndicesOneMissingIndex() {
MetaData.Builder mdBuilder = MetaData.builder()
.put(indexBuilder("testXXX"))
.put(indexBuilder("kuku"));
MetaData md = mdBuilder.build();
md.concreteIndices(new String[]{"testZZZ"}, IndicesOptions.strict());
}
@Test
public void concreteIndicesIgnoreIndicesOneMissingIndexOtherFound() {
MetaData.Builder mdBuilder = MetaData.builder()
.put(indexBuilder("testXXX"))
.put(indexBuilder("kuku"));
MetaData md = mdBuilder.build();
assertThat(newHashSet(md.concreteIndices(new String[]{"testXXX", "testZZZ"}, IndicesOptions.lenient())), equalTo(newHashSet("testXXX")));
}
@Test(expected = IndexMissingException.class)
public void concreteIndicesIgnoreIndicesAllMissing() {
MetaData.Builder mdBuilder = MetaData.builder()
.put(indexBuilder("testXXX"))
.put(indexBuilder("kuku"));
MetaData md = mdBuilder.build();
assertThat(newHashSet(md.concreteIndices(new String[]{"testMo", "testMahdy"}, IndicesOptions.strict())), equalTo(newHashSet("testXXX")));
}
@Test
public void concreteIndicesIgnoreIndicesEmptyRequest() {
MetaData.Builder mdBuilder = MetaData.builder()
.put(indexBuilder("testXXX"))
.put(indexBuilder("kuku"));
MetaData md = mdBuilder.build();
assertThat(newHashSet(md.concreteIndices(new String[]{}, IndicesOptions.lenient())), equalTo(Sets.<String>newHashSet("kuku", "testXXX")));
}
@Test
public void testIsAllIndices_null() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isAllIndices(null), equalTo(true));
}
@Test
public void testIsAllIndices_empty() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isAllIndices(new String[0]), equalTo(true));
}
@Test
public void testIsAllIndices_explicitAll() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isAllIndices(new String[]{"_all"}), equalTo(true));
}
@Test
public void testIsAllIndices_explicitAllPlusOther() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isAllIndices(new String[]{"_all", "other"}), equalTo(false));
}
@Test
public void testIsAllIndices_normalIndexes() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isAllIndices(new String[]{"index1", "index2", "index3"}), equalTo(false));
}
@Test
public void testIsAllIndices_wildcard() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isAllIndices(new String[]{"*"}), equalTo(false));
}
@Test
public void testIsExplicitAllIndices_null() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isExplicitAllPattern(null), equalTo(false));
}
@Test
public void testIsExplicitAllIndices_empty() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isExplicitAllPattern(new String[0]), equalTo(false));
}
@Test
public void testIsExplicitAllIndices_explicitAll() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isExplicitAllPattern(new String[]{"_all"}), equalTo(true));
}
@Test
public void testIsExplicitAllIndices_explicitAllPlusOther() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isExplicitAllPattern(new String[]{"_all", "other"}), equalTo(false));
}
@Test
public void testIsExplicitAllIndices_normalIndexes() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isExplicitAllPattern(new String[]{"index1", "index2", "index3"}), equalTo(false));
}
@Test
public void testIsExplicitAllIndices_wildcard() throws Exception {
MetaData metaData = MetaData.builder().build();
assertThat(metaData.isExplicitAllPattern(new String[]{"*"}), equalTo(false));
}
@Test
public void testIsPatternMatchingAllIndices_explicitList() throws Exception {
//even though it does identify all indices, it's not a pattern but just an explicit list of them
String[] concreteIndices = new String[]{"index1", "index2", "index3"};
String[] indicesOrAliases = concreteIndices;
String[] allConcreteIndices = concreteIndices;
MetaData metaData = metaDataBuilder(allConcreteIndices);
assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(false));
}
@Test
public void testIsPatternMatchingAllIndices_onlyWildcard() throws Exception {
String[] indicesOrAliases = new String[]{"*"};
String[] concreteIndices = new String[]{"index1", "index2", "index3"};
String[] allConcreteIndices = concreteIndices;
MetaData metaData = metaDataBuilder(allConcreteIndices);
assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(true));
}
@Test
public void testIsPatternMatchingAllIndices_matchingTrailingWildcard() throws Exception {
String[] indicesOrAliases = new String[]{"index*"};
String[] concreteIndices = new String[]{"index1", "index2", "index3"};
String[] allConcreteIndices = concreteIndices;
MetaData metaData = metaDataBuilder(allConcreteIndices);
assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(true));
}
@Test
public void testIsPatternMatchingAllIndices_nonMatchingTrailingWildcard() throws Exception {
String[] indicesOrAliases = new String[]{"index*"};
String[] concreteIndices = new String[]{"index1", "index2", "index3"};
String[] allConcreteIndices = new String[]{"index1", "index2", "index3", "a", "b"};
MetaData metaData = metaDataBuilder(allConcreteIndices);
assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(false));
}
@Test
public void testIsPatternMatchingAllIndices_matchingSingleExclusion() throws Exception {
String[] indicesOrAliases = new String[]{"-index1", "+index1"};
String[] concreteIndices = new String[]{"index1", "index2", "index3"};
String[] allConcreteIndices = concreteIndices;
MetaData metaData = metaDataBuilder(allConcreteIndices);
assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(true));
}
@Test
public void testIsPatternMatchingAllIndices_nonMatchingSingleExclusion() throws Exception {
String[] indicesOrAliases = new String[]{"-index1"};
String[] concreteIndices = new String[]{"index2", "index3"};
String[] allConcreteIndices = new String[]{"index1", "index2", "index3"};
MetaData metaData = metaDataBuilder(allConcreteIndices);
assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(false));
}
@Test
public void testIsPatternMatchingAllIndices_matchingTrailingWildcardAndExclusion() throws Exception {
String[] indicesOrAliases = new String[]{"index*", "-index1", "+index1"};
String[] concreteIndices = new String[]{"index1", "index2", "index3"};
String[] allConcreteIndices = concreteIndices;
MetaData metaData = metaDataBuilder(allConcreteIndices);
assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(true));
}
@Test
public void testIsPatternMatchingAllIndices_nonMatchingTrailingWildcardAndExclusion() throws Exception {
String[] indicesOrAliases = new String[]{"index*", "-index1"};
String[] concreteIndices = new String[]{"index2", "index3"};
String[] allConcreteIndices = new String[]{"index1", "index2", "index3"};
MetaData metaData = metaDataBuilder(allConcreteIndices);
assertThat(metaData.isPatternMatchingAllIndices(indicesOrAliases, concreteIndices), equalTo(false));
}
private MetaData metaDataBuilder(String... indices) {
MetaData.Builder mdBuilder = MetaData.builder();
for (String concreteIndex : indices) {
mdBuilder.put(indexBuilder(concreteIndex));
}
return mdBuilder.build();
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_metadata_MetaDataTests.java
|
5,959 |
public class SuggestBuilder implements ToXContent {
private final String name;
private String globalText;
private final List<SuggestionBuilder<?>> suggestions = new ArrayList<SuggestionBuilder<?>>();
public SuggestBuilder() {
this.name = null;
}
public SuggestBuilder(String name) {
this.name = name;
}
/**
* Sets the text to provide suggestions for. The suggest text is a required option that needs
* to be set either via this setter or via the {@link org.elasticsearch.search.suggest.SuggestBuilder.SuggestionBuilder#setText(String)} method.
* <p/>
* The suggest text gets analyzed by the suggest analyzer or the suggest field search analyzer.
* For each analyzed token, suggested terms are suggested if possible.
*/
public SuggestBuilder setText(String globalText) {
this.globalText = globalText;
return this;
}
/**
* Adds an {@link org.elasticsearch.search.suggest.SuggestBuilder.TermSuggestionBuilder} instance under a user defined name.
* The order in which the <code>Suggestions</code> are added, is the same as in the response.
*/
public SuggestBuilder addSuggestion(SuggestionBuilder<?> suggestion) {
suggestions.add(suggestion);
return this;
}
/**
* Returns all suggestions with the defined names.
*/
public List<SuggestionBuilder<?>> getSuggestion() {
return suggestions;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if(name == null) {
builder.startObject();
} else {
builder.startObject(name);
}
if (globalText != null) {
builder.field("text", globalText);
}
for (SuggestionBuilder<?> suggestion : suggestions) {
builder = suggestion.toXContent(builder, params);
}
builder.endObject();
return builder;
}
/**
* Convenience factory method.
*
* @param name The name of this suggestion. This is a required parameter.
*/
public static TermSuggestionBuilder termSuggestion(String name) {
return new TermSuggestionBuilder(name);
}
/**
* Convenience factory method.
*
* @param name The name of this suggestion. This is a required parameter.
*/
public static PhraseSuggestionBuilder phraseSuggestion(String name) {
return new PhraseSuggestionBuilder(name);
}
public static abstract class SuggestionBuilder<T> implements ToXContent {
private String name;
private String suggester;
private String text;
private String field;
private String analyzer;
private Integer size;
private Integer shardSize;
public SuggestionBuilder(String name, String suggester) {
this.name = name;
this.suggester = suggester;
}
/**
* Same as in {@link SuggestBuilder#setText(String)}, but in the suggestion scope.
*/
@SuppressWarnings("unchecked")
public T text(String text) {
this.text = text;
return (T) this;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
if (text != null) {
builder.field("text", text);
}
builder.startObject(suggester);
if (analyzer != null) {
builder.field("analyzer", analyzer);
}
if (field != null) {
builder.field("field", field);
}
if (size != null) {
builder.field("size", size);
}
if (shardSize != null) {
builder.field("shard_size", shardSize);
}
builder = innerToXContent(builder, params);
builder.endObject();
builder.endObject();
return builder;
}
protected abstract XContentBuilder innerToXContent(XContentBuilder builder, Params params) throws IOException;
/**
* Sets from what field to fetch the candidate suggestions from. This is an
* required option and needs to be set via this setter or
* {@link org.elasticsearch.search.suggest.SuggestBuilder.TermSuggestionBuilder#setField(String)}
* method
*/
@SuppressWarnings("unchecked")
public T field(String field) {
this.field = field;
return (T)this;
}
/**
* Sets the analyzer to analyse to suggest text with. Defaults to the search
* analyzer of the suggest field.
*/
@SuppressWarnings("unchecked")
public T analyzer(String analyzer) {
this.analyzer = analyzer;
return (T)this;
}
/**
* Sets the maximum suggestions to be returned per suggest text term.
*/
@SuppressWarnings("unchecked")
public T size(int size) {
if (size <= 0) {
throw new ElasticsearchIllegalArgumentException("Size must be positive");
}
this.size = size;
return (T)this;
}
/**
* Sets the maximum number of suggested term to be retrieved from each
* individual shard. During the reduce phase the only the top N suggestions
* are returned based on the <code>size</code> option. Defaults to the
* <code>size</code> option.
* <p/>
* Setting this to a value higher than the `size` can be useful in order to
* get a more accurate document frequency for suggested terms. Due to the
* fact that terms are partitioned amongst shards, the shard level document
* frequencies of suggestions may not be precise. Increasing this will make
* these document frequencies more precise.
*/
@SuppressWarnings("unchecked")
public T shardSize(Integer shardSize) {
this.shardSize = shardSize;
return (T)this;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_suggest_SuggestBuilder.java
|
2,073 |
public class MultipleEntryBackupOperation extends AbstractMapOperation implements BackupOperation, PartitionAwareOperation {
private Set<Data> keys;
private EntryBackupProcessor backupProcessor;
public MultipleEntryBackupOperation() {
}
public MultipleEntryBackupOperation(String name, Set<Data> keys, EntryBackupProcessor backupProcessor) {
super(name);
this.backupProcessor = backupProcessor;
this.keys = keys;
}
@Override
public void run() throws Exception {
final InternalPartitionService partitionService = getNodeEngine().getPartitionService();
final RecordStore recordStore = mapService.getRecordStore(getPartitionId(), name);
MapEntrySimple entry;
for (Data key : keys) {
if (partitionService.getPartitionId(key) != getPartitionId())
continue;
Object objectKey = mapService.toObject(key);
final Map.Entry<Data, Object> mapEntry = recordStore.getMapEntry(key);
final Object valueBeforeProcess = mapService.toObject(mapEntry.getValue());
entry = new MapEntrySimple(objectKey, valueBeforeProcess);
backupProcessor.processBackup(entry);
if (entry.getValue() == null) {
recordStore.removeBackup(key);
} else {
recordStore.putBackup(key, entry.getValue());
}
}
}
@Override
public boolean returnsResponse() {
return true;
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
backupProcessor = in.readObject();
int size = in.readInt();
keys = new HashSet<Data>(size);
for (int i = 0; i < size; i++) {
Data key = new Data();
key.readData(in);
keys.add(key);
}
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeObject(backupProcessor);
out.writeInt(keys.size());
for (Data key : keys) {
key.writeData(out);
}
}
@Override
public Object getResponse() {
return true;
}
@Override
public String toString() {
return "MultipleEntryBackupOperation{}";
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_map_operation_MultipleEntryBackupOperation.java
|
1,990 |
@Entity
@EntityListeners(value = { TemporalTimestampListener.class })
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_CUSTOMER_ROLE")
public class CustomerRoleImpl implements CustomerRole {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "CustomerRoleId")
@GenericGenerator(
name="CustomerRoleId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="CustomerRoleImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.profile.core.domain.CustomerRoleImpl")
}
)
@Column(name = "CUSTOMER_ROLE_ID")
protected Long id;
@ManyToOne(targetEntity = CustomerImpl.class, optional = false)
@JoinColumn(name = "CUSTOMER_ID")
@Index(name="CUSTROLE_CUSTOMER_INDEX", columnNames={"CUSTOMER_ID"})
protected Customer customer;
@ManyToOne(targetEntity = RoleImpl.class, optional = false)
@JoinColumn(name = "ROLE_ID")
@Index(name="CUSTROLE_ROLE_INDEX", columnNames={"ROLE_ID"})
protected Role role;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public Customer getCustomer() {
return customer;
}
@Override
public void setCustomer(Customer customer) {
this.customer = customer;
}
@Override
public Role getRole() {
return role;
}
@Override
public void setRole(Role role) {
this.role = role;
}
@Override
public String getRoleName() {
return role.getRoleName();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((customer == null) ? 0 : customer.hashCode());
result = prime * result + ((role == null) ? 0 : role.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomerRoleImpl other = (CustomerRoleImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (customer == null) {
if (other.customer != null)
return false;
} else if (!customer.equals(other.customer))
return false;
if (role == null) {
if (other.role != null)
return false;
} else if (!role.equals(other.role))
return false;
return true;
}
}
| 1no label
|
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_domain_CustomerRoleImpl.java
|
281 |
public class ActionModule extends AbstractModule {
private final Map<String, ActionEntry> actions = Maps.newHashMap();
static class ActionEntry<Request extends ActionRequest, Response extends ActionResponse> {
public final GenericAction<Request, Response> action;
public final Class<? extends TransportAction<Request, Response>> transportAction;
public final Class[] supportTransportActions;
ActionEntry(GenericAction<Request, Response> action, Class<? extends TransportAction<Request, Response>> transportAction, Class... supportTransportActions) {
this.action = action;
this.transportAction = transportAction;
this.supportTransportActions = supportTransportActions;
}
}
private final boolean proxy;
public ActionModule(boolean proxy) {
this.proxy = proxy;
}
/**
* Registers an action.
*
* @param action The action type.
* @param transportAction The transport action implementing the actual action.
* @param supportTransportActions Any support actions that are needed by the transport action.
* @param <Request> The request type.
* @param <Response> The response type.
*/
public <Request extends ActionRequest, Response extends ActionResponse> void registerAction(GenericAction<Request, Response> action, Class<? extends TransportAction<Request, Response>> transportAction, Class... supportTransportActions) {
actions.put(action.name(), new ActionEntry<Request, Response>(action, transportAction, supportTransportActions));
}
@Override
protected void configure() {
registerAction(NodesInfoAction.INSTANCE, TransportNodesInfoAction.class);
registerAction(NodesStatsAction.INSTANCE, TransportNodesStatsAction.class);
registerAction(NodesShutdownAction.INSTANCE, TransportNodesShutdownAction.class);
registerAction(NodesRestartAction.INSTANCE, TransportNodesRestartAction.class);
registerAction(NodesHotThreadsAction.INSTANCE, TransportNodesHotThreadsAction.class);
registerAction(ClusterStatsAction.INSTANCE, TransportClusterStatsAction.class);
registerAction(ClusterStateAction.INSTANCE, TransportClusterStateAction.class);
registerAction(ClusterHealthAction.INSTANCE, TransportClusterHealthAction.class);
registerAction(ClusterUpdateSettingsAction.INSTANCE, TransportClusterUpdateSettingsAction.class);
registerAction(ClusterRerouteAction.INSTANCE, TransportClusterRerouteAction.class);
registerAction(ClusterSearchShardsAction.INSTANCE, TransportClusterSearchShardsAction.class);
registerAction(PendingClusterTasksAction.INSTANCE, TransportPendingClusterTasksAction.class);
registerAction(PutRepositoryAction.INSTANCE, TransportPutRepositoryAction.class);
registerAction(GetRepositoriesAction.INSTANCE, TransportGetRepositoriesAction.class);
registerAction(DeleteRepositoryAction.INSTANCE, TransportDeleteRepositoryAction.class);
registerAction(GetSnapshotsAction.INSTANCE, TransportGetSnapshotsAction.class);
registerAction(DeleteSnapshotAction.INSTANCE, TransportDeleteSnapshotAction.class);
registerAction(CreateSnapshotAction.INSTANCE, TransportCreateSnapshotAction.class);
registerAction(RestoreSnapshotAction.INSTANCE, TransportRestoreSnapshotAction.class);
registerAction(IndicesStatsAction.INSTANCE, TransportIndicesStatsAction.class);
registerAction(IndicesStatusAction.INSTANCE, TransportIndicesStatusAction.class);
registerAction(IndicesSegmentsAction.INSTANCE, TransportIndicesSegmentsAction.class);
registerAction(CreateIndexAction.INSTANCE, TransportCreateIndexAction.class);
registerAction(DeleteIndexAction.INSTANCE, TransportDeleteIndexAction.class);
registerAction(OpenIndexAction.INSTANCE, TransportOpenIndexAction.class);
registerAction(CloseIndexAction.INSTANCE, TransportCloseIndexAction.class);
registerAction(IndicesExistsAction.INSTANCE, TransportIndicesExistsAction.class);
registerAction(TypesExistsAction.INSTANCE, TransportTypesExistsAction.class);
registerAction(GetMappingsAction.INSTANCE, TransportGetMappingsAction.class);
registerAction(GetFieldMappingsAction.INSTANCE, TransportGetFieldMappingsAction.class);
registerAction(PutMappingAction.INSTANCE, TransportPutMappingAction.class);
registerAction(DeleteMappingAction.INSTANCE, TransportDeleteMappingAction.class);
registerAction(IndicesAliasesAction.INSTANCE, TransportIndicesAliasesAction.class);
registerAction(UpdateSettingsAction.INSTANCE, TransportUpdateSettingsAction.class);
registerAction(AnalyzeAction.INSTANCE, TransportAnalyzeAction.class);
registerAction(PutIndexTemplateAction.INSTANCE, TransportPutIndexTemplateAction.class);
registerAction(GetIndexTemplatesAction.INSTANCE, TransportGetIndexTemplatesAction.class);
registerAction(DeleteIndexTemplateAction.INSTANCE, TransportDeleteIndexTemplateAction.class);
registerAction(ValidateQueryAction.INSTANCE, TransportValidateQueryAction.class);
registerAction(GatewaySnapshotAction.INSTANCE, TransportGatewaySnapshotAction.class);
registerAction(RefreshAction.INSTANCE, TransportRefreshAction.class);
registerAction(FlushAction.INSTANCE, TransportFlushAction.class);
registerAction(OptimizeAction.INSTANCE, TransportOptimizeAction.class);
registerAction(ClearIndicesCacheAction.INSTANCE, TransportClearIndicesCacheAction.class);
registerAction(PutWarmerAction.INSTANCE, TransportPutWarmerAction.class);
registerAction(DeleteWarmerAction.INSTANCE, TransportDeleteWarmerAction.class);
registerAction(GetWarmersAction.INSTANCE, TransportGetWarmersAction.class);
registerAction(GetAliasesAction.INSTANCE, TransportGetAliasesAction.class);
registerAction(AliasesExistAction.INSTANCE, TransportAliasesExistAction.class);
registerAction(GetSettingsAction.INSTANCE, TransportGetSettingsAction.class);
registerAction(IndexAction.INSTANCE, TransportIndexAction.class);
registerAction(GetAction.INSTANCE, TransportGetAction.class);
registerAction(TermVectorAction.INSTANCE, TransportSingleShardTermVectorAction.class);
registerAction(MultiTermVectorsAction.INSTANCE, TransportMultiTermVectorsAction.class,
TransportSingleShardMultiTermsVectorAction.class);
registerAction(DeleteAction.INSTANCE, TransportDeleteAction.class,
TransportIndexDeleteAction.class, TransportShardDeleteAction.class);
registerAction(CountAction.INSTANCE, TransportCountAction.class);
registerAction(SuggestAction.INSTANCE, TransportSuggestAction.class);
registerAction(UpdateAction.INSTANCE, TransportUpdateAction.class);
registerAction(MultiGetAction.INSTANCE, TransportMultiGetAction.class,
TransportShardMultiGetAction.class);
registerAction(BulkAction.INSTANCE, TransportBulkAction.class,
TransportShardBulkAction.class);
registerAction(DeleteByQueryAction.INSTANCE, TransportDeleteByQueryAction.class,
TransportIndexDeleteByQueryAction.class, TransportShardDeleteByQueryAction.class);
registerAction(SearchAction.INSTANCE, TransportSearchAction.class,
TransportSearchDfsQueryThenFetchAction.class,
TransportSearchQueryThenFetchAction.class,
TransportSearchDfsQueryAndFetchAction.class,
TransportSearchQueryAndFetchAction.class,
TransportSearchScanAction.class
);
registerAction(SearchScrollAction.INSTANCE, TransportSearchScrollAction.class,
TransportSearchScrollScanAction.class,
TransportSearchScrollQueryThenFetchAction.class,
TransportSearchScrollQueryAndFetchAction.class
);
registerAction(MultiSearchAction.INSTANCE, TransportMultiSearchAction.class);
registerAction(MoreLikeThisAction.INSTANCE, TransportMoreLikeThisAction.class);
registerAction(PercolateAction.INSTANCE, TransportPercolateAction.class);
registerAction(MultiPercolateAction.INSTANCE, TransportMultiPercolateAction.class, TransportShardMultiPercolateAction.class);
registerAction(ExplainAction.INSTANCE, TransportExplainAction.class);
registerAction(ClearScrollAction.INSTANCE, TransportClearScrollAction.class);
// register Name -> GenericAction Map that can be injected to instances.
MapBinder<String, GenericAction> actionsBinder
= MapBinder.newMapBinder(binder(), String.class, GenericAction.class);
for (Map.Entry<String, ActionEntry> entry : actions.entrySet()) {
actionsBinder.addBinding(entry.getKey()).toInstance(entry.getValue().action);
}
// register GenericAction -> transportAction Map that can be injected to instances.
// also register any supporting classes
if (!proxy) {
MapBinder<GenericAction, TransportAction> transportActionsBinder
= MapBinder.newMapBinder(binder(), GenericAction.class, TransportAction.class);
for (Map.Entry<String, ActionEntry> entry : actions.entrySet()) {
// bind the action as eager singleton, so the map binder one will reuse it
bind(entry.getValue().transportAction).asEagerSingleton();
transportActionsBinder.addBinding(entry.getValue().action).to(entry.getValue().transportAction).asEagerSingleton();
for (Class supportAction : entry.getValue().supportTransportActions) {
bind(supportAction).asEagerSingleton();
}
}
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_ActionModule.java
|
277 |
public class VersionTests extends ElasticsearchTestCase {
@Test
public void testVersions() throws Exception {
assertThat(V_0_20_0.before(V_0_90_0), is(true));
assertThat(V_0_20_0.before(V_0_20_0), is(false));
assertThat(V_0_90_0.before(V_0_20_0), is(false));
assertThat(V_0_20_0.onOrBefore(V_0_90_0), is(true));
assertThat(V_0_20_0.onOrBefore(V_0_20_0), is(true));
assertThat(V_0_90_0.onOrBefore(V_0_20_0), is(false));
assertThat(V_0_20_0.after(V_0_90_0), is(false));
assertThat(V_0_20_0.after(V_0_20_0), is(false));
assertThat(V_0_90_0.after(V_0_20_0), is(true));
assertThat(V_0_20_0.onOrAfter(V_0_90_0), is(false));
assertThat(V_0_20_0.onOrAfter(V_0_20_0), is(true));
assertThat(V_0_90_0.onOrAfter(V_0_20_0), is(true));
}
@Test
public void testVersionConstantPresent() {
assertThat(Version.CURRENT, sameInstance(Version.fromId(Version.CURRENT.id)));
assertThat(Version.CURRENT.luceneVersion.ordinal(), equalTo(org.apache.lucene.util.Version.LUCENE_CURRENT.ordinal() - 1));
final int iters = atLeast(20);
for (int i = 0; i < iters; i++) {
Version version = randomVersion();
assertThat(version, sameInstance(Version.fromId(version.id)));
assertThat(version.luceneVersion, sameInstance(Version.fromId(version.id).luceneVersion));
}
}
}
| 0true
|
src_test_java_org_elasticsearch_VersionTests.java
|
3,804 |
public class BoolQueryParser implements QueryParser {
public static final String NAME = "bool";
@Inject
public BoolQueryParser(Settings settings) {
BooleanQuery.setMaxClauseCount(settings.getAsInt("index.query.bool.max_clause_count", settings.getAsInt("indices.query.bool.max_clause_count", BooleanQuery.getMaxClauseCount())));
}
@Override
public String[] names() {
return new String[]{NAME};
}
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
boolean disableCoord = false;
float boost = 1.0f;
String minimumShouldMatch = null;
List<BooleanClause> clauses = newArrayList();
boolean adjustPureNegative = true;
String queryName = null;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("must".equals(currentFieldName)) {
Query query = parseContext.parseInnerQuery();
if (query != null) {
clauses.add(new BooleanClause(query, BooleanClause.Occur.MUST));
}
} else if ("must_not".equals(currentFieldName) || "mustNot".equals(currentFieldName)) {
Query query = parseContext.parseInnerQuery();
if (query != null) {
clauses.add(new BooleanClause(query, BooleanClause.Occur.MUST_NOT));
}
} else if ("should".equals(currentFieldName)) {
Query query = parseContext.parseInnerQuery();
if (query != null) {
clauses.add(new BooleanClause(query, BooleanClause.Occur.SHOULD));
}
} else {
throw new QueryParsingException(parseContext.index(), "[bool] query does not support [" + currentFieldName + "]");
}
} else if (token == XContentParser.Token.START_ARRAY) {
if ("must".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
Query query = parseContext.parseInnerQuery();
if (query != null) {
clauses.add(new BooleanClause(query, BooleanClause.Occur.MUST));
}
}
} else if ("must_not".equals(currentFieldName) || "mustNot".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
Query query = parseContext.parseInnerQuery();
if (query != null) {
clauses.add(new BooleanClause(query, BooleanClause.Occur.MUST_NOT));
}
}
} else if ("should".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
Query query = parseContext.parseInnerQuery();
if (query != null) {
clauses.add(new BooleanClause(query, BooleanClause.Occur.SHOULD));
}
}
} else {
throw new QueryParsingException(parseContext.index(), "bool query does not support [" + currentFieldName + "]");
}
} else if (token.isValue()) {
if ("disable_coord".equals(currentFieldName) || "disableCoord".equals(currentFieldName)) {
disableCoord = parser.booleanValue();
} else if ("minimum_should_match".equals(currentFieldName) || "minimumShouldMatch".equals(currentFieldName)) {
minimumShouldMatch = parser.textOrNull();
} else if ("boost".equals(currentFieldName)) {
boost = parser.floatValue();
} else if ("minimum_number_should_match".equals(currentFieldName) || "minimumNumberShouldMatch".equals(currentFieldName)) {
minimumShouldMatch = parser.textOrNull();
} else if ("adjust_pure_negative".equals(currentFieldName) || "adjustPureNegative".equals(currentFieldName)) {
adjustPureNegative = parser.booleanValue();
} else if ("_name".equals(currentFieldName)) {
queryName = parser.text();
} else {
throw new QueryParsingException(parseContext.index(), "[bool] query does not support [" + currentFieldName + "]");
}
}
}
if (clauses.isEmpty()) {
return null;
}
BooleanQuery booleanQuery = new BooleanQuery(disableCoord);
for (BooleanClause clause : clauses) {
booleanQuery.add(clause);
}
booleanQuery.setBoost(boost);
Queries.applyMinimumShouldMatch(booleanQuery, minimumShouldMatch);
Query query = optimizeQuery(adjustPureNegative ? fixNegativeQueryIfNeeded(booleanQuery) : booleanQuery);
if (queryName != null) {
parseContext.addNamedQuery(queryName, query);
}
return query;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_query_BoolQueryParser.java
|
1,462 |
public class IllegalShardRoutingStateException extends RoutingException {
private final ShardRouting shard;
public IllegalShardRoutingStateException(ShardRouting shard, String message) {
this(shard, message, null);
}
public IllegalShardRoutingStateException(ShardRouting shard, String message, Throwable cause) {
super(shard.shortSummary() + ": " + message, cause);
this.shard = shard;
}
/**
* Returns the shard instance referenced by this exception
* @return shard instance referenced by this exception
*/
public ShardRouting shard() {
return shard;
}
}
| 0true
|
src_main_java_org_elasticsearch_cluster_routing_IllegalShardRoutingStateException.java
|
357 |
future.andThen(new ExecutionCallback<Map<String, Integer>>() {
@Override
public void onResponse(Map<String, Integer> response) {
listenerResults.putAll(response);
semaphore.release();
}
@Override
public void onFailure(Throwable t) {
semaphore.release();
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_ClientMapReduceTest.java
|
238 |
public interface SystemPropertiesService {
public SystemProperty saveSystemProperty(SystemProperty systemProperty);
public void deleteSystemProperty(SystemProperty systemProperty);
public List<SystemProperty> findAllSystemProperties();
public SystemProperty findSystemPropertyByName(String name);
/**
* This method should not persist anything to the database. It should simply return the correct implementation of
* the SystemProperty interface.
* @return
*/
public SystemProperty createNewSystemProperty();
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_config_service_SystemPropertiesService.java
|
1,336 |
public abstract class ClusterStateUpdateRequest<T extends ClusterStateUpdateRequest<T>> {
private TimeValue ackTimeout;
private TimeValue masterNodeTimeout;
/**
* Returns the maximum time interval to wait for acknowledgements
*/
public TimeValue ackTimeout() {
return ackTimeout;
}
/**
* Sets the acknowledgement timeout
*/
@SuppressWarnings("unchecked")
public T ackTimeout(TimeValue ackTimeout) {
this.ackTimeout = ackTimeout;
return (T) this;
}
/**
* Returns the maximum time interval to wait for the request to
* be completed on the master node
*/
public TimeValue masterNodeTimeout() {
return masterNodeTimeout;
}
/**
* Sets the master node timeout
*/
@SuppressWarnings("unchecked")
public T masterNodeTimeout(TimeValue masterNodeTimeout) {
this.masterNodeTimeout = masterNodeTimeout;
return (T) this;
}
}
| 0true
|
src_main_java_org_elasticsearch_cluster_ack_ClusterStateUpdateRequest.java
|
1,053 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_PERSONAL_MESSAGE")
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
public class PersonalMessageImpl implements PersonalMessage {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "PersonalMessageId")
@GenericGenerator(
name="PersonalMessageId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="PersonalMessageImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.order.domain.PersonalMessageImpl")
}
)
@Column(name = "PERSONAL_MESSAGE_ID")
protected Long id;
@Column(name = "MESSAGE_TO")
@AdminPresentation(friendlyName = "PersonalMessageImpl_Message_To", order=1, group = "PersonalMessageImpl_Personal_Message")
protected String messageTo;
@Column(name = "MESSAGE_FROM")
@AdminPresentation(friendlyName = "PersonalMessageImpl_Message_From", order=2, group = "PersonalMessageImpl_Personal_Message")
protected String messageFrom;
@Column(name = "MESSAGE")
@AdminPresentation(friendlyName = "PersonalMessageImpl_Message", order=3, group = "PersonalMessageImpl_Personal_Message")
protected String message;
@Column(name = "OCCASION")
@AdminPresentation(friendlyName = "PersonalMessageImpl_Occasion", order=4, group = "PersonalMessageImpl_Personal_Message")
protected String occasion;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getMessageTo() {
return messageTo;
}
@Override
public void setMessageTo(String messageTo) {
this.messageTo = messageTo;
}
@Override
public String getMessageFrom() {
return messageFrom;
}
@Override
public void setMessageFrom(String messageFrom) {
this.messageFrom = messageFrom;
}
@Override
public String getMessage() {
return message;
}
@Override
public void setMessage(String message) {
this.message = message;
}
@Override
public String getOccasion() {
return occasion;
}
@Override
public void setOccasion(String occasion) {
this.occasion = occasion;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((message == null) ? 0 : message.hashCode());
result = prime * result + ((messageFrom == null) ? 0 : messageFrom.hashCode());
result = prime * result + ((messageTo == null) ? 0 : messageTo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PersonalMessageImpl other = (PersonalMessageImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (message == null) {
if (other.message != null)
return false;
} else if (!message.equals(other.message))
return false;
if (messageFrom == null) {
if (other.messageFrom != null)
return false;
} else if (!messageFrom.equals(other.messageFrom))
return false;
if (messageTo == null) {
if (other.messageTo != null)
return false;
} else if (!messageTo.equals(other.messageTo))
return false;
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_PersonalMessageImpl.java
|
9 |
@Component("blSkuCustomPersistenceHandler")
public class SkuCustomPersistenceHandler extends CustomPersistenceHandlerAdapter {
private static final Log LOG = LogFactory.getLog(SkuCustomPersistenceHandler.class);
public static String PRODUCT_OPTION_FIELD_PREFIX = "productOption";
@Resource(name="blAdornedTargetListPersistenceModule")
protected AdornedTargetListPersistenceModule adornedPersistenceModule;
/**
* This represents the field that all of the product option values will be stored in. This would be used in the case
* where there are a bunch of product options and displaying each option as a grid header would have everything
* squashed together. Filtering on this field is currently unsupported.
*/
public static String CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME = "consolidatedProductOptions";
public static String CONSOLIDATED_PRODUCT_OPTIONS_DELIMETER = "; ";
@Resource(name="blCatalogService")
protected CatalogService catalogService;
@Resource(name = "blSkuRestrictionFactory")
protected RestrictionFactory skuRestrictionFactory;
@Override
public Boolean canHandleInspect(PersistencePackage persistencePackage) {
return canHandle(persistencePackage, persistencePackage.getPersistencePerspective().getOperationTypes()
.getInspectType());
}
@Override
public Boolean canHandleFetch(PersistencePackage persistencePackage) {
OperationType fetchType = persistencePackage.getPersistencePerspective().getOperationTypes().getFetchType();
return canHandle(persistencePackage, fetchType);
}
@Override
public Boolean canHandleAdd(PersistencePackage persistencePackage) {
OperationType addType = persistencePackage.getPersistencePerspective().getOperationTypes().getAddType();
return canHandle(persistencePackage, addType);
}
@Override
public Boolean canHandleUpdate(PersistencePackage persistencePackage) {
OperationType updateType = persistencePackage.getPersistencePerspective().getOperationTypes().getUpdateType();
return canHandle(persistencePackage, updateType);
}
/**
* Since this is the default for all Skus, it's possible that we are providing custom criteria for this
* Sku lookup. In that case, we probably want to delegate to a child class, so only use this particular
* persistence handler if there is no custom criteria being used and the ceiling entity is an instance of Sku. The
* exception to this rule is when we are pulling back Media, since the admin actually uses Sku for the ceiling entity
* class name. That should be handled by the map structure module though, so only handle things in the Sku custom
* persistence handler for OperationType.BASIC
*
*/
protected Boolean canHandle(PersistencePackage persistencePackage, OperationType operationType) {
String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
try {
Class testClass = Class.forName(ceilingEntityFullyQualifiedClassname);
return Sku.class.isAssignableFrom(testClass) &&
//ArrayUtils.isEmpty(persistencePackage.getCustomCriteria()) &&
OperationType.BASIC.equals(operationType) &&
(persistencePackage.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST) == null);
} catch (ClassNotFoundException e) {
return false;
}
}
/**
* Build out the extra fields for the product options
*/
@Override
public DynamicResultSet inspect(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, InspectHelper helper) throws ServiceException {
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
Map<MergedPropertyType, Map<String, FieldMetadata>> allMergedProperties = new HashMap<MergedPropertyType, Map<String, FieldMetadata>>();
//Grab the default properties for the Sku
Map<String, FieldMetadata> properties = helper.getSimpleMergedProperties(Sku.class.getName(), persistencePerspective);
if (persistencePackage.getCustomCriteria() == null || persistencePackage.getCustomCriteria().length == 0) {
//look up all the ProductOptions and then create new fields for each of them
List<ProductOption> options = catalogService.readAllProductOptions();
int order = 0;
for (ProductOption option : options) {
//add this to the built Sku properties
FieldMetadata md = createIndividualOptionField(option, order);
if (md != null) {
properties.put("productOption" + option.getId(), md);
}
}
} else {
// If we have a product to filter the list of available product options, then use it
Long productId = Long.parseLong(persistencePackage.getCustomCriteria()[0]);
Product product = catalogService.findProductById(productId);
for (ProductOption option : product.getProductOptions()) {
FieldMetadata md = createIndividualOptionField(option, 0);
if (md != null) {
properties.put("productOption" + option.getId(), md);
}
}
}
//also build the consolidated field; if using the SkuBasicClientEntityModule then this field will be
//permanently hidden
properties.put(CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME, createConsolidatedOptionField(SkuImpl.class));
allMergedProperties.put(MergedPropertyType.PRIMARY, properties);
//allow the adorned list to contribute properties as well in the case of Sku bundle items
adornedPersistenceModule.setPersistenceManager((PersistenceManager)helper);
adornedPersistenceModule.updateMergedProperties(persistencePackage, allMergedProperties);
Class<?>[] entityClasses = dynamicEntityDao.getAllPolymorphicEntitiesFromCeiling(Sku.class);
ClassMetadata mergedMetadata = helper.getMergedClassMetadata(entityClasses, allMergedProperties);
DynamicResultSet results = new DynamicResultSet(mergedMetadata, null, null);
return results;
} catch (Exception e) {
ServiceException ex = new ServiceException("Unable to retrieve inspection results for " +
persistencePackage.getCeilingEntityFullyQualifiedClassname(), e);
throw ex;
}
}
/**
* Creates the metadata necessary for displaying all of the product option values in a single field. The display of this
* field is a single string with every product option value appended to it separated by a semicolon. This method should
* be invoked on an inspect for whatever is utilizing this so that the property will be ready to be populated on fetch.
*
* The metadata that is returned will also be set to prominent by default so that it will be ready to display on whatever
* grid is being inspected. If you do not want this behavior you will need to override this functionality in the metadata
* that is returned.
*
* @param inheritedFromType which type this should appear on. This would normally be SkuImpl.class, but if you want to
* display this field with a different entity then this should be that entity
* @return
*/
public static FieldMetadata createConsolidatedOptionField(Class<?> inheritedFromType) {
BasicFieldMetadata metadata = new BasicFieldMetadata();
metadata.setFieldType(SupportedFieldType.STRING);
metadata.setMutable(false);
metadata.setInheritedFromType(inheritedFromType.getName());
metadata.setAvailableToTypes(new String[] { SkuImpl.class.getName() });
metadata.setForeignKeyCollection(false);
metadata.setMergedPropertyType(MergedPropertyType.PRIMARY);
metadata.setName(CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME);
metadata.setFriendlyName(CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME);
metadata.setGroup("");
metadata.setExplicitFieldType(SupportedFieldType.UNKNOWN);
metadata.setProminent(true);
metadata.setVisibility(VisibilityEnum.FORM_HIDDEN);
metadata.setBroadleafEnumeration("");
metadata.setReadOnly(true);
metadata.setRequiredOverride(false);
metadata.setGridOrder(Integer.MAX_VALUE);
return metadata;
}
/**
* Returns a {@link Property} filled out with a delimited list of the <b>values</b> that are passed in. This should be
* invoked on a fetch and the returned property should be added to the fetched {@link Entity} dto.
*
* @param values
* @return
* @see {@link #createConsolidatedOptionField(Class)};
*/
public static Property getConsolidatedOptionProperty(List<ProductOptionValue> values) {
Property optionValueProperty = new Property();
optionValueProperty.setName(CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME);
//order the values by the display order of their correspond product option
// Collections.sort(values, new Comparator<ProductOptionValue>() {
//
// @Override
// public int compare(ProductOptionValue value1, ProductOptionValue value2) {
// return new CompareToBuilder().append(value1.getProductOption().getDisplayOrder(),
// value2.getProductOption().getDisplayOrder()).toComparison();
// }
// });
ArrayList<String> stringValues = new ArrayList<String>();
CollectionUtils.collect(values, new Transformer() {
@Override
public Object transform(Object input) {
return ((ProductOptionValue) input).getAttributeValue();
}
}, stringValues);
optionValueProperty.setValue(StringUtils.join(stringValues, CONSOLIDATED_PRODUCT_OPTIONS_DELIMETER));
return optionValueProperty;
}
/**
* @return a blank {@link Property} corresponding to the CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME
*/
public static Property getBlankConsolidatedOptionProperty() {
Property optionValueProperty = new Property();
optionValueProperty.setName(CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME);
optionValueProperty.setValue("");
return optionValueProperty;
}
/**
* <p>Creates an individual property for the specified product option. This should set up an enum field whose values will
* be the option values for this option. This is useful when you would like to display each product option in as its
* own field in a grid so that you can further filter by product option values.</p>
* <p>In order for these fields to be utilized property on the fetch, in the GWT frontend you must use the
* for your datasource.</p>
*
* @param option
* @param order
* @return
*/
public static FieldMetadata createIndividualOptionField(ProductOption option, int order) {
BasicFieldMetadata metadata = new BasicFieldMetadata();
List<ProductOptionValue> allowedValues = option.getAllowedValues();
if (CollectionUtils.isNotEmpty(allowedValues)) {
metadata.setFieldType(SupportedFieldType.EXPLICIT_ENUMERATION);
metadata.setMutable(true);
metadata.setInheritedFromType(SkuImpl.class.getName());
metadata.setAvailableToTypes(new String[] { SkuImpl.class.getName() });
metadata.setForeignKeyCollection(false);
metadata.setMergedPropertyType(MergedPropertyType.PRIMARY);
//Set up the enumeration based on the product option values
String[][] optionValues = new String[allowedValues.size()][2];
for (int i = 0; i < allowedValues.size(); i++) {
ProductOptionValue value = option.getAllowedValues().get(i);
optionValues[i][0] = value.getId().toString();
optionValues[i][1] = value.getAttributeValue();
}
metadata.setEnumerationValues(optionValues);
metadata.setName(PRODUCT_OPTION_FIELD_PREFIX + option.getId());
metadata.setFriendlyName(option.getLabel());
metadata.setGroup("productOption_group");
metadata.setGroupOrder(-1);
metadata.setOrder(order);
metadata.setExplicitFieldType(SupportedFieldType.UNKNOWN);
metadata.setProminent(false);
metadata.setVisibility(VisibilityEnum.FORM_EXPLICITLY_SHOWN);
metadata.setBroadleafEnumeration("");
metadata.setReadOnly(false);
metadata.setRequiredOverride(BooleanUtils.isFalse(option.getRequired()));
return metadata;
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
//get the default properties from Sku and its subclasses
Map<String, FieldMetadata> originalProps = helper.getSimpleMergedProperties(Sku.class.getName(), persistencePerspective);
//Pull back the Skus based on the criteria from the client
List<FilterMapping> filterMappings = helper.getFilterMappings(persistencePerspective, cto, ceilingEntityFullyQualifiedClassname, originalProps, skuRestrictionFactory);
//allow subclasses to provide additional criteria before executing the query
applyProductOptionValueCriteria(filterMappings, cto, persistencePackage, null);
applyAdditionalFetchCriteria(filterMappings, cto, persistencePackage);
List<Serializable> records = helper.getPersistentRecords(persistencePackage.getCeilingEntityFullyQualifiedClassname(), filterMappings, cto.getFirstResult(), cto.getMaxResults());
//Convert Skus into the client-side Entity representation
Entity[] payload = helper.getRecords(originalProps, records);
int totalRecords = helper.getTotalRecords(persistencePackage.getCeilingEntityFullyQualifiedClassname(), filterMappings);
//Now fill out the relevant properties for the product options for the Skus that were returned
for (int i = 0; i < records.size(); i++) {
Sku sku = (Sku) records.get(i);
Entity entity = payload[i];
List<ProductOptionValue> optionValues = sku.getProductOptionValues();
for (ProductOptionValue value : optionValues) {
Property optionProperty = new Property();
optionProperty.setName(PRODUCT_OPTION_FIELD_PREFIX + value.getProductOption().getId());
optionProperty.setValue(value.getId().toString());
entity.addProperty(optionProperty);
}
if (CollectionUtils.isNotEmpty(optionValues)) {
entity.addProperty(getConsolidatedOptionProperty(optionValues));
} else {
entity.addProperty(getBlankConsolidatedOptionProperty());
}
}
return new DynamicResultSet(payload, totalRecords);
} catch (Exception e) {
throw new ServiceException("Unable to perform fetch for entity: " + ceilingEntityFullyQualifiedClassname, e);
}
}
public static void applyProductOptionValueCriteria(List<FilterMapping> filterMappings, CriteriaTransferObject cto, PersistencePackage persistencePackage, String skuPropertyPrefix) {
//if the front
final List<Long> productOptionValueFilterIDs = new ArrayList<Long>();
for (String filterProperty : cto.getCriteriaMap().keySet()) {
if (filterProperty.startsWith(PRODUCT_OPTION_FIELD_PREFIX)) {
FilterAndSortCriteria criteria = cto.get(filterProperty);
productOptionValueFilterIDs.add(Long.parseLong(criteria.getFilterValues().get(0)));
}
}
//also determine if there is a consolidated POV query
final List<String> productOptionValueFilterValues = new ArrayList<String>();
FilterAndSortCriteria consolidatedCriteria = cto.get(CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME);
if (!consolidatedCriteria.getFilterValues().isEmpty()) {
//the criteria in this case would be a semi-colon delimeter value list
productOptionValueFilterValues.addAll(Arrays.asList(StringUtils.split(consolidatedCriteria.getFilterValues().get(0), CONSOLIDATED_PRODUCT_OPTIONS_DELIMETER)));
}
if (productOptionValueFilterIDs.size() > 0) {
FilterMapping filterMapping = new FilterMapping()
.withFieldPath(new FieldPath().withTargetProperty(StringUtils.isEmpty(skuPropertyPrefix)?"":skuPropertyPrefix + "productOptionValues.id"))
.withDirectFilterValues(productOptionValueFilterIDs)
.withRestriction(new Restriction()
.withPredicateProvider(new PredicateProvider() {
@Override
public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder,
From root, String ceilingEntity,
String fullPropertyName, Path explicitPath, List directValues) {
return explicitPath.as(Long.class).in(directValues);
}
})
);
filterMappings.add(filterMapping);
}
if (productOptionValueFilterValues.size() > 0) {
FilterMapping filterMapping = new FilterMapping()
.withFieldPath(new FieldPath().withTargetProperty(StringUtils.isEmpty(skuPropertyPrefix)?"":skuPropertyPrefix + "productOptionValues.attributeValue"))
.withDirectFilterValues(productOptionValueFilterValues)
.withRestriction(new Restriction()
.withPredicateProvider(new PredicateProvider() {
@Override
public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder,
From root, String ceilingEntity,
String fullPropertyName, Path explicitPath, List directValues) {
return explicitPath.as(String.class).in(directValues);
}
})
);
filterMappings.add(filterMapping);
}
}
/**
* <p>Available override point for subclasses if they would like to add additional criteria via the queryCritiera. At the
* point that this method has been called, criteria from the frontend has already been applied, thus allowing you to
* override from there as well.</p>
* <p>Subclasses that choose to override this should also call this super method so that correct filter criteria
* can be applied for product option values</p>
*
*/
public void applyAdditionalFetchCriteria(List<FilterMapping> filterMappings, CriteriaTransferObject cto, PersistencePackage persistencePackage) {
//unimplemented
}
@Override
public Entity add(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
Entity entity = persistencePackage.getEntity();
try {
//Fill out the Sku instance from the form
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
Sku adminInstance = (Sku) Class.forName(entity.getType()[0]).newInstance();
Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(Sku.class.getName(), persistencePerspective);
adminInstance = (Sku) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);
//Verify that there isn't already a Sku for this particular product option value combo
Entity errorEntity = validateUniqueProductOptionValueCombination(adminInstance.getProduct(),
getProductOptionProperties(entity),
null);
if (errorEntity != null) {
entity.setValidationErrors(errorEntity.getValidationErrors());
return entity;
}
//persist the newly-created Sku
adminInstance = (Sku) dynamicEntityDao.persist(adminInstance);
//associate the product option values
associateProductOptionValuesToSku(entity, adminInstance, dynamicEntityDao);
//After associating the product option values, save off the Sku
adminInstance = (Sku) dynamicEntityDao.merge(adminInstance);
//Fill out the DTO and add in the product option value properties to it
Entity result = helper.getRecord(adminProperties, adminInstance, null, null);
for (Property property : getProductOptionProperties(entity)) {
result.addProperty(property);
}
return result;
} catch (Exception e) {
throw new ServiceException("Unable to perform fetch for entity: " + Sku.class.getName(), e);
}
}
@Override
public Entity update(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
Entity entity = persistencePackage.getEntity();
try {
//Fill out the Sku instance from the form
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(Sku.class.getName(), persistencePerspective);
Object primaryKey = helper.getPrimaryKey(entity, adminProperties);
Sku adminInstance = (Sku) dynamicEntityDao.retrieve(Class.forName(entity.getType()[0]), primaryKey);
adminInstance = (Sku) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);
//Verify that there isn't already a Sku for this particular product option value combo
Entity errorEntity = validateUniqueProductOptionValueCombination(adminInstance.getProduct(),
getProductOptionProperties(entity),
adminInstance);
if (errorEntity != null) {
entity.setValidationErrors(errorEntity.getValidationErrors());
return entity;
}
associateProductOptionValuesToSku(entity, adminInstance, dynamicEntityDao);
adminInstance = (Sku) dynamicEntityDao.merge(adminInstance);
//Fill out the DTO and add in the product option value properties to it
Entity result = helper.getRecord(adminProperties, adminInstance, null, null);
for (Property property : getProductOptionProperties(entity)) {
result.addProperty(property);
}
return result;
} catch (Exception e) {
throw new ServiceException("Unable to perform fetch for entity: " + Sku.class.getName(), e);
}
}
/**
* This initially removes all of the product option values that are currently related to the Sku and then re-associates
* the {@link ProductOptionValue}s
* @param entity
* @param adminInstance
*/
protected void associateProductOptionValuesToSku(Entity entity, Sku adminInstance, DynamicEntityDao dynamicEntityDao) {
//Get the list of product option value ids that were selected from the form
List<Long> productOptionValueIds = new ArrayList<Long>();
for (Property property : getProductOptionProperties(entity)) {
productOptionValueIds.add(Long.parseLong(property.getValue()));
}
//remove the current list of product option values from the Sku
if (adminInstance.getProductOptionValues().size() > 0) {
adminInstance.getProductOptionValues().clear();
dynamicEntityDao.merge(adminInstance);
}
//Associate the product option values from the form with the Sku
List<ProductOption> productOptions = adminInstance.getProduct().getProductOptions();
for (ProductOption option : productOptions) {
for (ProductOptionValue value : option.getAllowedValues()) {
if (productOptionValueIds.contains(value.getId())) {
adminInstance.getProductOptionValues().add(value);
}
}
}
}
protected List<Property> getProductOptionProperties(Entity entity) {
List<Property> productOptionProperties = new ArrayList<Property>();
for (Property property : entity.getProperties()) {
if (property.getName().startsWith(PRODUCT_OPTION_FIELD_PREFIX)) {
productOptionProperties.add(property);
}
}
return productOptionProperties;
}
/**
* Ensures that the given list of {@link ProductOptionValue} IDs is unique for the given {@link Product}
* @param product
* @param productOptionValueIds
* @param currentSku - for update operations, this is the current Sku that is being updated; should be excluded from
* attempting validation
* @return <b>null</b> if successfully validation, the error entity otherwise
*/
protected Entity validateUniqueProductOptionValueCombination(Product product, List<Property> productOptionProperties, Sku currentSku) {
//do not attempt POV validation if no PO properties were passed in
if (CollectionUtils.isNotEmpty(productOptionProperties)) {
List<Long> productOptionValueIds = new ArrayList<Long>();
for (Property property : productOptionProperties) {
productOptionValueIds.add(Long.parseLong(property.getValue()));
}
boolean validated = true;
for (Sku sku : product.getAdditionalSkus()) {
if (currentSku == null || !sku.getId().equals(currentSku.getId())) {
List<Long> testList = new ArrayList<Long>();
for (ProductOptionValue optionValue : sku.getProductOptionValues()) {
testList.add(optionValue.getId());
}
if (CollectionUtils.isNotEmpty(testList) &&
productOptionValueIds.containsAll(testList) &&
productOptionValueIds.size() == testList.size()) {
validated = false;
break;
}
}
}
if (!validated) {
Entity errorEntity = new Entity();
for (Property productOptionProperty : productOptionProperties) {
errorEntity.addValidationError(productOptionProperty.getName(), "uniqueSkuError");
}
return errorEntity;
}
}
return null;
}
}
| 1no label
|
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_server_service_handler_SkuCustomPersistenceHandler.java
|
143 |
private abstract static class AbstractPruneStrategy implements LogPruneStrategy
{
protected final FileSystemAbstraction fileSystem;
AbstractPruneStrategy( FileSystemAbstraction fileSystem )
{
this.fileSystem = fileSystem;
}
@Override
public void prune( LogLoader source )
{
if ( source.getHighestLogVersion() == 0 )
return;
long upper = source.getHighestLogVersion()-1;
Threshold threshold = newThreshold();
boolean exceeded = false;
while ( upper >= 0 )
{
File file = source.getFileName( upper );
if ( !fileSystem.fileExists( file ) )
// There aren't logs to prune anything. Just return
return;
if ( fileSystem.getFileSize( file ) > LogIoUtils.LOG_HEADER_SIZE &&
threshold.reached( file, upper, source ) )
{
exceeded = true;
break;
}
upper--;
}
if ( !exceeded )
return;
// Find out which log is the earliest existing (lower bound to prune)
long lower = upper;
while ( fileSystem.fileExists( source.getFileName( lower-1 ) ) )
lower--;
// The reason we delete from lower to upper is that if it crashes in the middle
// we can be sure that no holes are created
for ( long version = lower; version < upper; version++ )
fileSystem.deleteFile( source.getFileName( version ) );
}
/**
* @return a {@link Threshold} which if returning {@code false} states that the log file
* is within the threshold and doesn't need to be pruned. The first time it returns
* {@code true} it says that the threshold has been reached and the log file it just
* returned {@code true} for should be kept, but all previous logs should be pruned.
*/
protected abstract Threshold newThreshold();
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
|
306 |
public abstract class AbstractMergeXMLApplicationContext extends AbstractXmlApplicationContext {
protected Resource[] configResources;
protected Resource[] getConfigResources() {
return this.configResources;
}
public AbstractMergeXMLApplicationContext(ApplicationContext parent) {
super(parent);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_AbstractMergeXMLApplicationContext.java
|
1,258 |
public static class RetryListener<Response> implements ActionListener<Response> {
private final NodeListenerCallback<Response> callback;
private final ActionListener<Response> listener;
private final ImmutableList<DiscoveryNode> nodes;
private final int index;
private volatile int i;
public RetryListener(NodeListenerCallback<Response> callback, ActionListener<Response> listener, ImmutableList<DiscoveryNode> nodes, int index) {
this.callback = callback;
this.listener = listener;
this.nodes = nodes;
this.index = index;
}
@Override
public void onResponse(Response response) {
listener.onResponse(response);
}
@Override
public void onFailure(Throwable e) {
if (ExceptionsHelper.unwrapCause(e) instanceof ConnectTransportException) {
int i = ++this.i;
if (i >= nodes.size()) {
listener.onFailure(new NoNodeAvailableException());
} else {
try {
callback.doWithNode(nodes.get((index + i) % nodes.size()), this);
} catch (Throwable e1) {
// retry the next one...
onFailure(e);
}
}
} else {
listener.onFailure(e);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_client_transport_TransportClientNodesService.java
|
96 |
class ConvertToGetterProposal extends CorrectionProposal {
ConvertToGetterProposal(Declaration dec, int offset,
TextChange change) {
super("Convert '" + dec.getName() + "' to getter",
change, new Region(offset, 0));
}
static void addConvertToGetterProposal(IDocument doc,
Collection<ICompletionProposal> proposals, IFile file,
Tree.AttributeDeclaration decNode) {
Value dec = decNode.getDeclarationModel();
final SpecifierOrInitializerExpression sie =
decNode.getSpecifierOrInitializerExpression();
if (dec!=null && sie!=null) {
if (dec.isParameter()) return;
if (!dec.isVariable()) { //TODO: temp restriction, autocreate setter!
TextChange change = new TextFileChange("Convert to Getter", file);
change.setEdit(new MultiTextEdit());
Integer offset = sie.getStartIndex();
String space;
try {
space = doc.getChar(offset-1)==' ' ? "" : " ";
}
catch (BadLocationException e) {
e.printStackTrace();
return;
}
change.addEdit(new ReplaceEdit(offset, 1, "=>"));
// change.addEdit(new ReplaceEdit(offset, 1, space + "{ return" + spaceAfter));
// change.addEdit(new InsertEdit(decNode.getStopIndex()+1, " }"));
proposals.add(new ConvertToGetterProposal(dec,
offset + space.length() + 2 , change));
}
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToGetterProposal.java
|
49 |
class ParameterContextValidator
implements IContextInformationValidator, IContextInformationPresenter {
private int position;
private IContextInformation information;
private int currentParameter;
private CeylonEditor editor;
ParameterContextValidator(CeylonEditor editor) {
this.editor = editor;
}
@Override
public boolean updatePresentation(int brokenPosition,
TextPresentation presentation) {
String s = information.getInformationDisplayString();
presentation.clear();
if (this.position==-1) {
presentation.addStyleRange(new StyleRange(0, s.length(),
null, null, SWT.BOLD));
addItalics(presentation, s);
return true;
}
int currentParameter = -1;
CeylonSourceViewer viewer = editor.getCeylonSourceViewer();
int position = viewer.getSelectedRange().x;
IDocument doc = viewer.getDocument();
try {
boolean namedInvocation = doc.getChar(this.position)=='{';
if (!namedInvocation) Assert.isTrue(doc.getChar(this.position)=='(');
// int paren = doc.get(this.position, position-this.position)
// .indexOf(namedInvocation?'{':'(');
// if (paren<0) { //TODO: is this really useful?
// this.position = doc.get(0, position).lastIndexOf('(');
// }
currentParameter = getCharCount(doc,
this.position+1, position,
namedInvocation?";":",", "", true);
}
catch (BadLocationException x) {
return false;
}
if (currentParameter != -1) {
if (this.currentParameter == currentParameter) {
return false;
}
}
presentation.clear();
this.currentParameter = currentParameter;
int[] commas = computeCommaPositions(s);
if (commas.length - 2 < currentParameter) {
presentation.addStyleRange(new StyleRange(0, s.length(),
null, null, SWT.NORMAL));
addItalics(presentation, s);
return true;
}
int start = commas[currentParameter] + 1;
int end = commas[currentParameter + 1];
if (start > 0) {
presentation.addStyleRange(new StyleRange(0, start,
null, null, SWT.NORMAL));
}
if (end > start) {
presentation.addStyleRange(new StyleRange(start, end - start,
null, null, SWT.BOLD));
}
if (end < s.length()) {
presentation.addStyleRange(new StyleRange(end, s.length() - end,
null, null, SWT.NORMAL));
}
addItalics(presentation, s);
return true;
}
private void addItalics(TextPresentation presentation, String s) {
Matcher m2 = p2.matcher(s);
while (m2.find()) {
presentation.mergeStyleRange(new StyleRange(m2.start(), m2.end()-m2.start(),
null, null, SWT.ITALIC));
}
// Matcher m1 = p1.matcher(s);
// while (m1.find()) {
// presentation.mergeStyleRange(new StyleRange(m1.start(), m1.end()-m1.start()+1,
// typeColor, null));
// }
}
// final Pattern p1 = Pattern.compile("\\b\\p{javaUpperCase}\\w*\\b");
final Pattern p2 = Pattern.compile("\\b\\p{javaLowerCase}\\w*\\b");
// final Color typeColor = color(getCurrentTheme().getColorRegistry(), TYPES);
@Override
public void install(IContextInformation info, ITextViewer viewer,
int documentPosition) {
if (info instanceof InvocationCompletionProposal.ParameterContextInformation) {
ParameterContextInformation pci =
(InvocationCompletionProposal.ParameterContextInformation) info;
this.position = pci.getArgumentListOffset();
}
else {
this.position = -1;
}
Assert.isTrue(viewer==editor.getCeylonSourceViewer());
this.information = info;
this.currentParameter= -1;
}
@Override
public boolean isContextInformationValid(int brokenPosition) {
if (editor.isInLinkedMode()) {
Object linkedModeOwner = editor.getLinkedModeOwner();
if (linkedModeOwner instanceof InvocationCompletionProposal ||
linkedModeOwner instanceof RefinementCompletionProposal) {
return true;
}
}
try {
CeylonSourceViewer viewer = editor.getCeylonSourceViewer();
int position = viewer.getSelectedRange().x;
if (position < this.position) {
return false;
}
IDocument document = viewer.getDocument();
IRegion line =
document.getLineInformationOfOffset(this.position);
if (position < line.getOffset() ||
position >= document.getLength()) {
return false;
}
// System.out.println(document.get(this.position, position-this.position));
int semiCount = getCharCount(document, this.position, position, ";", "", true);
int fenceCount = getCharCount(document, this.position, position, "{(", "})", false);
return semiCount==0 && fenceCount>0;
}
catch (BadLocationException x) {
return false;
}
}
/*@Override
public boolean isContextInformationValid(int offset) {
IContextInformation[] infos= computeContextInformation(viewer, offset);
if (infos != null && infos.length > 0) {
for (int i= 0; i < infos.length; i++)
if (information.equals(infos[i]))
return true;
}
return false;
}*/
private static final int NONE = 0;
private static final int BRACKET = 1;
private static final int BRACE = 2;
private static final int PAREN = 3;
private static final int ANGLE = 4;
private static int getCharCount(IDocument document,
final int start, final int end,
String increments, String decrements,
boolean considerNesting)
throws BadLocationException {
Assert.isTrue((increments.length() != 0 || decrements.length() != 0)
&& !increments.equals(decrements));
int nestingMode = NONE;
int nestingLevel = 0;
int charCount = 0;
int offset = start;
char prev = ' ';
while (offset < end) {
char curr = document.getChar(offset++);
switch (curr) {
case '/':
if (offset < end) {
char next = document.getChar(offset);
if (next == '*') {
// a comment starts, advance to the comment end
offset= getCommentEnd(document, offset + 1, end);
}
else if (next == '/') {
// '//'-comment: nothing to do anymore on this line
int nextLine= document.getLineOfOffset(offset) + 1;
if (nextLine == document.getNumberOfLines()) {
offset= end;
}
else {
offset= document.getLineOffset(nextLine);
}
}
}
break;
case '*':
if (offset < end) {
char next= document.getChar(offset);
if (next == '/') {
// we have been in a comment: forget what we read before
charCount= 0;
++ offset;
}
}
break;
case '"':
case '\'':
offset= getStringEnd(document, offset, end, curr);
break;
case '[':
if (considerNesting) {
if (nestingMode == BRACKET || nestingMode == NONE) {
nestingMode= BRACKET;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case ']':
if (considerNesting) {
if (nestingMode == BRACKET) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
case '(':
if (considerNesting) {
if (nestingMode == ANGLE) {
// generics heuristic failed
nestingMode=PAREN;
nestingLevel= 1;
}
if (nestingMode == PAREN || nestingMode == NONE) {
nestingMode= PAREN;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case ')':
if (considerNesting) {
if (nestingMode == PAREN) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
case '{':
if (considerNesting) {
if (nestingMode == ANGLE) {
// generics heuristic failed
nestingMode=BRACE;
nestingLevel= 1;
}
if (nestingMode == BRACE || nestingMode == NONE) {
nestingMode= BRACE;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case '}':
if (considerNesting) {
if (nestingMode == BRACE) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
case '<':
if (considerNesting) {
if (nestingMode == ANGLE || nestingMode == NONE
/*&& checkGenericsHeuristic(document, offset - 1, start - 1)*/) {
nestingMode= ANGLE;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case '>':
if (considerNesting
&& prev != '=') { //check that it's not a fat arrow
if (nestingMode == ANGLE) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
default:
if (nestingLevel==0) {
if (increments.indexOf(curr) >= 0) {
++ charCount;
}
if (decrements.indexOf(curr) >= 0) {
-- charCount;
}
}
}
}
return charCount;
}
static int findCharCount(int count, IDocument document,
final int start, final int end,
String increments, String decrements,
boolean considerNesting)
throws BadLocationException {
Assert.isTrue((increments.length() != 0 || decrements.length() != 0)
&& !increments.equals(decrements));
final int NONE= 0;
final int BRACKET= 1;
final int BRACE= 2;
final int PAREN= 3;
final int ANGLE= 4;
int nestingMode= NONE;
int nestingLevel= 0;
int charCount= 0;
int offset= start;
boolean lastWasEquals = false;
while (offset < end) {
if (nestingLevel == 0) {
if (count==charCount) {
return offset-1;
}
}
char curr= document.getChar(offset++);
switch (curr) {
case '/':
if (offset < end) {
char next= document.getChar(offset);
if (next == '*') {
// a comment starts, advance to the comment end
offset= getCommentEnd(document, offset + 1, end);
}
else if (next == '/') {
// '//'-comment: nothing to do anymore on this line
int nextLine= document.getLineOfOffset(offset) + 1;
if (nextLine == document.getNumberOfLines()) {
offset= end;
}
else {
offset= document.getLineOffset(nextLine);
}
}
}
break;
case '*':
if (offset < end) {
char next= document.getChar(offset);
if (next == '/') {
// we have been in a comment: forget what we read before
charCount= 0;
++ offset;
}
}
break;
case '"':
case '\'':
offset= getStringEnd(document, offset, end, curr);
break;
case '[':
if (considerNesting) {
if (nestingMode == BRACKET || nestingMode == NONE) {
nestingMode= BRACKET;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case ']':
if (considerNesting) {
if (nestingMode == BRACKET)
if (--nestingLevel == 0) {
nestingMode= NONE;
}
break;
}
//$FALL-THROUGH$
case '(':
if (considerNesting) {
if (nestingMode == ANGLE) {
// generics heuristic failed
nestingMode=PAREN;
nestingLevel= 1;
}
if (nestingMode == PAREN || nestingMode == NONE) {
nestingMode= PAREN;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case ')':
if (considerNesting) {
if (nestingMode == 0) {
return offset-1;
}
if (nestingMode == PAREN) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
case '{':
if (considerNesting) {
if (nestingMode == ANGLE) {
// generics heuristic failed
nestingMode=BRACE;
nestingLevel= 1;
}
if (nestingMode == BRACE || nestingMode == NONE) {
nestingMode= BRACE;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case '}':
if (considerNesting) {
if (nestingMode == 0) {
return offset-1;
}
if (nestingMode == BRACE) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
case '<':
if (considerNesting) {
if (nestingMode == ANGLE || nestingMode == NONE /*&& checkGenericsHeuristic(document, offset - 1, start - 1)*/) {
nestingMode= ANGLE;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case '>':
if (!lastWasEquals) {
if (nestingMode == 0) {
return offset-1;
}
if (considerNesting) {
if (nestingMode == ANGLE) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
}
//$FALL-THROUGH$
default:
if (nestingLevel == 0) {
if (increments.indexOf(curr) >= 0) {
++ charCount;
}
if (decrements.indexOf(curr) >= 0) {
-- charCount;
}
}
}
lastWasEquals = curr=='=';
}
return -1;
}
private static int[] computeCommaPositions(String code) {
final int length= code.length();
int pos = 0;
int angleLevel = 0;
List<Integer> positions= new ArrayList<Integer>();
positions.add(new Integer(-1));
char prev = ' ';
while (pos < length && pos != -1) {
char ch = code.charAt(pos);
switch (ch) {
case ',':
case ';':
if (angleLevel == 0) {
positions.add(new Integer(pos));
}
break;
case '<':
case '(':
case '{':
case '[':
angleLevel++;
break;
case '>':
if (prev=='=') break;
case ')':
case '}':
case ']':
angleLevel--;
break;
// case '[':
// pos= code.indexOf(']', pos);
// break;
default:
break;
}
if (pos != -1) {
pos++;
}
}
positions.add(new Integer(length));
int[] fields= new int[positions.size()];
for (int i= 0; i < fields.length; i++) {
fields[i]= positions.get(i).intValue();
}
return fields;
}
private static int getCommentEnd(IDocument d, int pos, int end)
throws BadLocationException {
while (pos < end) {
char curr= d.getChar(pos);
pos++;
if (curr == '*') {
if (pos < end && d.getChar(pos) == '/') {
return pos + 1;
}
}
}
return end;
}
private static int getStringEnd(IDocument d, int pos, int end, char ch)
throws BadLocationException {
while (pos < end) {
char curr= d.getChar(pos);
pos++;
if (curr == '\\') {
// ignore escaped characters
pos++;
}
else if (curr == ch) {
return pos;
}
}
return end;
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ParameterContextValidator.java
|
523 |
public class OSchemaException extends OException {
private static final long serialVersionUID = -8486291378415776372L;
public OSchemaException(String message, Throwable cause) {
super(message, cause);
}
public OSchemaException(String message) {
super(message);
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_exception_OSchemaException.java
|
593 |
public class JoinMessage implements DataSerializable {
protected byte packetVersion;
protected int buildNumber;
protected Address address;
protected String uuid;
protected ConfigCheck configCheck;
protected int memberCount;
public JoinMessage() {
}
public JoinMessage(byte packetVersion, int buildNumber, Address address, String uuid, ConfigCheck configCheck,
int memberCount) {
this.packetVersion = packetVersion;
this.buildNumber = buildNumber;
this.address = address;
this.uuid = uuid;
this.configCheck = configCheck;
this.memberCount = memberCount;
}
public byte getPacketVersion() {
return packetVersion;
}
public int getBuildNumber() {
return buildNumber;
}
public Address getAddress() {
return address;
}
public String getUuid() {
return uuid;
}
public ConfigCheck getConfigCheck() {
return configCheck;
}
public int getMemberCount() {
return memberCount;
}
@Override
public void readData(ObjectDataInput in) throws IOException {
packetVersion = in.readByte();
buildNumber = in.readInt();
address = new Address();
address.readData(in);
uuid = in.readUTF();
configCheck = new ConfigCheck();
configCheck.readData(in);
memberCount = in.readInt();
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeByte(packetVersion);
out.writeInt(buildNumber);
address.writeData(out);
out.writeUTF(uuid);
configCheck.writeData(out);
out.writeInt(memberCount);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("JoinMessage");
sb.append("{packetVersion=").append(packetVersion);
sb.append(", buildNumber=").append(buildNumber);
sb.append(", address=").append(address);
sb.append(", uuid='").append(uuid).append('\'');
sb.append('}');
return sb.toString();
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_cluster_JoinMessage.java
|
79 |
public abstract class OSharedResourceTimeout {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
protected int timeout;
public OSharedResourceTimeout(final int timeout) {
this.timeout = timeout;
}
protected void acquireSharedLock() throws OTimeoutException {
try {
if (timeout == 0) {
lock.readLock().lock();
return;
} else if (lock.readLock().tryLock(timeout, TimeUnit.MILLISECONDS))
// OK
return;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
throw new OTimeoutException("Timeout on acquiring shared lock against resource: " + this);
}
protected void releaseSharedLock() {
lock.readLock().unlock();
}
protected void acquireExclusiveLock() throws OTimeoutException {
try {
if (timeout == 0) {
lock.writeLock().lock();
return;
} else if (lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS))
// OK
return;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
throw new OTimeoutException("Timeout on acquiring exclusive lock against resource: " + this);
}
protected void releaseExclusiveLock() {
lock.writeLock().unlock();
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceTimeout.java
|
550 |
public class GetFieldMappingsRequestBuilder extends ClusterInfoRequestBuilder<GetFieldMappingsRequest, GetFieldMappingsResponse, GetFieldMappingsRequestBuilder> {
public GetFieldMappingsRequestBuilder(InternalGenericClient client, String... indices) {
super(client, new GetFieldMappingsRequest().indices(indices));
}
/** Sets the fields to retrieve. */
public GetFieldMappingsRequestBuilder setFields(String... fields) {
request.fields(fields);
return this;
}
/** Indicates whether default mapping settings should be returned */
public GetFieldMappingsRequestBuilder includeDefaults(boolean includeDefaults) {
request.includeDefaults(includeDefaults);
return this;
}
@Override
protected void doExecute(ActionListener<GetFieldMappingsResponse> listener) {
((IndicesAdminClient) client).getFieldMappings(request, listener);
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_GetFieldMappingsRequestBuilder.java
|
286 |
static abstract class LockTestThread extends Thread{
private static final int ITERATIONS = 1000*10;
private final Random random = new Random();
protected final ILock lock;
protected final AtomicInteger upTotal;
protected final AtomicInteger downTotal;
public LockTestThread(ILock lock, AtomicInteger upTotal, AtomicInteger downTotal){
this.lock = lock;
this.upTotal = upTotal;
this.downTotal = downTotal;
}
public void run() {
try{
for ( int i=0; i<ITERATIONS; i++ ) {
doRun();
}
}catch (Exception e){
throw new RuntimeException("LockTestThread throws: ", e);
}
}
abstract void doRun() throws Exception;
protected void work(){
int delta = random.nextInt(1000);
upTotal.addAndGet(delta);
downTotal.addAndGet(-delta);
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_lock_ClientConcurrentLockTest.java
|
306 |
new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
// UPDATE ALL THE OPENED STORAGES SETTING THE NEW STRATEGY
// for (OStorage s : com.orientechnologies.orient.core.Orient.instance().getStorages()) {
// s.getCache().setStrategy((Integer) iNewValue);
// }
}
}),
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_config_OGlobalConfiguration.java
|
11 |
public interface DataProvider extends FeedAggregator {
/**
* An enum which defines the various level of service (LOS) a data provider can provide.
*
*/
public static enum LOS {
/** Fast enum. */
fast,
/** Medium enum. */
medium,
/** Slow enum.*/
slow
}
/**
* Returns a map of data for each feed. This allows the data to be queried in batch and improves performance.
* @param feedIDs to retrieve data for
* @param startTime the start time of the return data set.
* @param endTime the end time of the return data set.
* @param timeUnit the time unit of startTime and endTime parameters.
* @return map of data for the specified feeds. Each entry in the map has data
* with a timestamp that is >= startTime and <= endTime ordered according to the time.
*/
public Map<String, SortedMap<Long, Map<String, String>>> getData(Set<String> feedIDs, long startTime, long endTime, TimeUnit timeUnit);
/**
* Check if a request can be fully serviced by a data provider.
* @param feedID feed that is requested
* @param startTime start time of the request
* @param timeUnit the time unit of startTime
* @return true if a request can be fully serviced by a data provider.
*/
public boolean isFullyWithinTimeSpan(String feedID, long startTime, TimeUnit timeUnit);
/**
* Return the level of service that a data retrieval provider can provide.
* @return the level of service.
*/
public LOS getLOS();
}
| 0true
|
mctcore_src_main_java_gov_nasa_arc_mct_api_feed_DataProvider.java
|
563 |
abstract class AbstractClusterOperation extends AbstractOperation implements JoinOperation {
@Override
public boolean returnsResponse() {
return false;
}
@Override
public final String getServiceName() {
return ClusterServiceImpl.SERVICE_NAME;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_cluster_AbstractClusterOperation.java
|
105 |
{
@Override
public Object doWork( State state )
{
node.setProperty( key, value );
return null;
}
}, 200, MILLISECONDS );
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestManualAcquireLock.java
|
1,182 |
@ElasticsearchIntegrationTest.ClusterScope(scope = ElasticsearchIntegrationTest.Scope.TEST)
public class SimpleBlocksTests extends ElasticsearchIntegrationTest {
@Test
public void verifyIndexAndClusterReadOnly() throws Exception {
// cluster.read_only = null: write and metadata not blocked
canCreateIndex("test1");
canIndexDocument("test1");
setIndexReadOnly("test1", "false");
canIndexExists("test1");
// cluster.read_only = true: block write and metadata
setClusterReadOnly("true");
canNotCreateIndex("test2");
// even if index has index.read_only = false
canNotIndexDocument("test1");
canNotIndexExists("test1");
// cluster.read_only = false: removes the block
setClusterReadOnly("false");
canCreateIndex("test2");
canIndexDocument("test2");
canIndexDocument("test1");
canIndexExists("test1");
// newly created an index has no blocks
canCreateIndex("ro");
canIndexDocument("ro");
canIndexExists("ro");
// adds index write and metadata block
setIndexReadOnly( "ro", "true");
canNotIndexDocument("ro");
canNotIndexExists("ro");
// other indices not blocked
canCreateIndex("rw");
canIndexDocument("rw");
canIndexExists("rw");
// blocks can be removed
setIndexReadOnly("ro", "false");
canIndexDocument("ro");
canIndexExists("ro");
}
@Test
public void testIndexReadWriteMetaDataBlocks() {
canCreateIndex("test1");
canIndexDocument("test1");
client().admin().indices().prepareUpdateSettings("test1")
.setSettings(settingsBuilder().put(IndexMetaData.SETTING_BLOCKS_WRITE, true))
.execute().actionGet();
canNotIndexDocument("test1");
client().admin().indices().prepareUpdateSettings("test1")
.setSettings(settingsBuilder().put(IndexMetaData.SETTING_BLOCKS_WRITE, false))
.execute().actionGet();
canIndexDocument("test1");
}
private void canCreateIndex(String index) {
try {
CreateIndexResponse r = client().admin().indices().prepareCreate(index).execute().actionGet();
assertThat(r, notNullValue());
} catch (ClusterBlockException e) {
fail();
}
}
private void canNotCreateIndex(String index) {
try {
client().admin().indices().prepareCreate(index).execute().actionGet();
fail();
} catch (ClusterBlockException e) {
// all is well
}
}
private void canIndexDocument(String index) {
try {
IndexRequestBuilder builder = client().prepareIndex(index, "zzz");
builder.setSource("foo", "bar");
IndexResponse r = builder.execute().actionGet();
assertThat(r, notNullValue());
} catch (ClusterBlockException e) {
fail();
}
}
private void canNotIndexDocument(String index) {
try {
IndexRequestBuilder builder = client().prepareIndex(index, "zzz");
builder.setSource("foo", "bar");
builder.execute().actionGet();
fail();
} catch (ClusterBlockException e) {
// all is well
}
}
private void canIndexExists(String index) {
try {
IndicesExistsResponse r = client().admin().indices().prepareExists(index).execute().actionGet();
assertThat(r, notNullValue());
} catch (ClusterBlockException e) {
fail();
}
}
private void canNotIndexExists(String index) {
try {
IndicesExistsResponse r = client().admin().indices().prepareExists(index).execute().actionGet();
fail();
} catch (ClusterBlockException e) {
// all is well
}
}
private void setClusterReadOnly(String value) {
Settings settings = settingsBuilder().put(MetaData.SETTING_READ_ONLY, value).build();
client().admin().cluster().prepareUpdateSettings().setTransientSettings(settings).execute().actionGet();
}
private void setIndexReadOnly(String index, Object value) {
HashMap<String, Object> newSettings = new HashMap<String, Object>();
newSettings.put(IndexMetaData.SETTING_READ_ONLY, value);
UpdateSettingsRequestBuilder settingsRequest = client().admin().indices().prepareUpdateSettings(index);
settingsRequest.setSettings(newSettings);
UpdateSettingsResponse settingsResponse = settingsRequest.execute().actionGet();
assertThat(settingsResponse, notNullValue());
}
}
| 0true
|
src_test_java_org_elasticsearch_blocks_SimpleBlocksTests.java
|
543 |
public class RecoverTransactionRequest extends CallableClientRequest {
private boolean commit;
private SerializableXID sXid;
public RecoverTransactionRequest() {
}
public RecoverTransactionRequest(SerializableXID sXid, boolean commit) {
this.sXid = sXid;
this.commit = commit;
}
@Override
public Object call() throws Exception {
TransactionManagerServiceImpl service = getService();
service.recoverClientTransaction(sXid, commit);
return null;
}
@Deprecated
public String getServiceName() {
return TransactionManagerServiceImpl.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return ClientTxnPortableHook.F_ID;
}
@Override
public int getClassId() {
return ClientTxnPortableHook.RECOVER;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeBoolean("c", commit);
ObjectDataOutput out = writer.getRawDataOutput();
sXid.writeData(out);
}
@Override
public void read(PortableReader reader) throws IOException {
commit = reader.readBoolean("c");
ObjectDataInput in = reader.getRawDataInput();
sXid = new SerializableXID();
sXid.readData(in);
}
@Override
public Permission getRequiredPermission() {
return new TransactionPermission();
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_txn_RecoverTransactionRequest.java
|
1,472 |
public class PlainShardsIterator implements ShardsIterator {
private final List<ShardRouting> shards;
private final int size;
private final int index;
private final int limit;
private volatile int counter;
public PlainShardsIterator(List<ShardRouting> shards) {
this(shards, 0);
}
public PlainShardsIterator(List<ShardRouting> shards, int index) {
this.shards = shards;
this.size = shards.size();
if (size == 0) {
this.index = 0;
} else {
this.index = Math.abs(index % size);
}
this.counter = this.index;
this.limit = this.index + size;
}
@Override
public void reset() {
this.counter = this.index;
}
@Override
public int remaining() {
return limit - counter;
}
@Override
public ShardRouting firstOrNull() {
if (size == 0) {
return null;
}
return shards.get(index);
}
@Override
public ShardRouting nextOrNull() {
if (size == 0) {
return null;
}
int counter = (this.counter);
if (counter >= size) {
if (counter >= limit) {
return null;
}
this.counter = counter + 1;
return shards.get(counter - size);
} else {
this.counter = counter + 1;
return shards.get(counter);
}
}
@Override
public int size() {
return size;
}
@Override
public int sizeActive() {
int count = 0;
for (int i = 0; i < size; i++) {
if (shards.get(i).active()) {
count++;
}
}
return count;
}
@Override
public int assignedReplicasIncludingRelocating() {
int count = 0;
for (int i = 0; i < size; i++) {
ShardRouting shard = shards.get(i);
if (shard.unassigned()) {
continue;
}
// if the shard is primary and relocating, add one to the counter since we perform it on the replica as well
// (and we already did it on the primary)
if (shard.primary()) {
if (shard.relocating()) {
count++;
}
} else {
count++;
// if we are relocating the replica, we want to perform the index operation on both the relocating
// shard and the target shard. This means that we won't loose index operations between end of recovery
// and reassignment of the shard by the master node
if (shard.relocating()) {
count++;
}
}
}
return count;
}
@Override
public Iterable<ShardRouting> asUnordered() {
return shards;
}
}
| 1no label
|
src_main_java_org_elasticsearch_cluster_routing_PlainShardsIterator.java
|
1,259 |
class ScheduledNodeSampler implements Runnable {
@Override
public void run() {
try {
nodesSampler.sample();
if (!closed) {
nodesSamplerFuture = threadPool.schedule(nodesSamplerInterval, ThreadPool.Names.GENERIC, this);
}
} catch (Exception e) {
logger.warn("failed to sample", e);
}
}
}
| 0true
|
src_main_java_org_elasticsearch_client_transport_TransportClientNodesService.java
|
1,699 |
public class ChannelBufferBytesReference implements BytesReference {
private final ChannelBuffer buffer;
public ChannelBufferBytesReference(ChannelBuffer buffer) {
this.buffer = buffer;
}
@Override
public byte get(int index) {
return buffer.getByte(buffer.readerIndex() + index);
}
@Override
public int length() {
return buffer.readableBytes();
}
@Override
public BytesReference slice(int from, int length) {
return new ChannelBufferBytesReference(buffer.slice(from, length));
}
@Override
public StreamInput streamInput() {
return ChannelBufferStreamInputFactory.create(buffer.duplicate());
}
@Override
public void writeTo(OutputStream os) throws IOException {
buffer.getBytes(buffer.readerIndex(), os, length());
}
@Override
public byte[] toBytes() {
return copyBytesArray().toBytes();
}
@Override
public BytesArray toBytesArray() {
if (buffer.hasArray()) {
return new BytesArray(buffer.array(), buffer.arrayOffset() + buffer.readerIndex(), buffer.readableBytes());
}
return copyBytesArray();
}
@Override
public BytesArray copyBytesArray() {
byte[] copy = new byte[buffer.readableBytes()];
buffer.getBytes(buffer.readerIndex(), copy);
return new BytesArray(copy);
}
@Override
public ChannelBuffer toChannelBuffer() {
return buffer.duplicate();
}
@Override
public boolean hasArray() {
return buffer.hasArray();
}
@Override
public byte[] array() {
return buffer.array();
}
@Override
public int arrayOffset() {
return buffer.arrayOffset() + buffer.readerIndex();
}
@Override
public String toUtf8() {
return buffer.toString(Charsets.UTF_8);
}
@Override
public BytesRef toBytesRef() {
if (buffer.hasArray()) {
return new BytesRef(buffer.array(), buffer.arrayOffset() + buffer.readerIndex(), buffer.readableBytes());
}
byte[] copy = new byte[buffer.readableBytes()];
buffer.getBytes(buffer.readerIndex(), copy);
return new BytesRef(copy);
}
@Override
public BytesRef copyBytesRef() {
byte[] copy = new byte[buffer.readableBytes()];
buffer.getBytes(buffer.readerIndex(), copy);
return new BytesRef(copy);
}
@Override
public int hashCode() {
return Helper.bytesHashCode(this);
}
@Override
public boolean equals(Object obj) {
return Helper.bytesEqual(this, (BytesReference) obj);
}
}
| 1no label
|
src_main_java_org_elasticsearch_common_bytes_ChannelBufferBytesReference.java
|
143 |
@Test
public class FloatSerializerTest {
private static final int FIELD_SIZE = 4;
private static final Float OBJECT = 3.14f;
private OFloatSerializer floatSerializer;
byte[] stream = new byte[FIELD_SIZE];
@BeforeClass
public void beforeClass() {
floatSerializer = new OFloatSerializer();
}
public void testFieldSize() {
Assert.assertEquals(floatSerializer.getObjectSize(null), FIELD_SIZE);
}
public void testSerialize() {
floatSerializer.serialize(OBJECT, stream, 0);
Assert.assertEquals(floatSerializer.deserialize(stream, 0), OBJECT);
}
public void testSerializeNative() {
floatSerializer.serializeNative(OBJECT, stream, 0);
Assert.assertEquals(floatSerializer.deserializeNative(stream, 0), OBJECT);
}
public void testNativeDirectMemoryCompatibility() {
floatSerializer.serializeNative(OBJECT, stream, 0);
ODirectMemoryPointer pointer = new ODirectMemoryPointer(stream);
try {
Assert.assertEquals(floatSerializer.deserializeFromDirectMemory(pointer, 0), OBJECT);
} finally {
pointer.free();
}
}
}
| 0true
|
commons_src_test_java_com_orientechnologies_common_serialization_types_FloatSerializerTest.java
|
1,421 |
public static class RemoveResponse {
private final boolean acknowledged;
public RemoveResponse(boolean acknowledged) {
this.acknowledged = acknowledged;
}
public boolean acknowledged() {
return acknowledged;
}
}
| 0true
|
src_main_java_org_elasticsearch_cluster_metadata_MetaDataIndexTemplateService.java
|
5,776 |
public class MatchedQueriesFetchSubPhase implements FetchSubPhase {
@Override
public Map<String, ? extends SearchParseElement> parseElements() {
return ImmutableMap.of();
}
@Override
public boolean hitsExecutionNeeded(SearchContext context) {
return false;
}
@Override
public void hitsExecute(SearchContext context, InternalSearchHit[] hits) throws ElasticsearchException {
}
@Override
public boolean hitExecutionNeeded(SearchContext context) {
return !context.parsedQuery().namedFilters().isEmpty()
|| (context.parsedPostFilter() !=null && !context.parsedPostFilter().namedFilters().isEmpty());
}
@Override
public void hitExecute(SearchContext context, HitContext hitContext) throws ElasticsearchException {
List<String> matchedQueries = Lists.newArrayListWithCapacity(2);
addMatchedQueries(hitContext, context.parsedQuery().namedFilters(), matchedQueries);
if (context.parsedPostFilter() != null) {
addMatchedQueries(hitContext, context.parsedPostFilter().namedFilters(), matchedQueries);
}
hitContext.hit().matchedQueries(matchedQueries.toArray(new String[matchedQueries.size()]));
}
private void addMatchedQueries(HitContext hitContext, ImmutableMap<String, Filter> namedFiltersAndQueries, List<String> matchedQueries) {
for (Map.Entry<String, Filter> entry : namedFiltersAndQueries.entrySet()) {
String name = entry.getKey();
Filter filter = entry.getValue();
try {
DocIdSet docIdSet = filter.getDocIdSet(hitContext.readerContext(), null); // null is fine, since we filter by hitContext.docId()
if (!DocIdSets.isEmpty(docIdSet)) {
Bits bits = docIdSet.bits();
if (bits != null) {
if (bits.get(hitContext.docId())) {
matchedQueries.add(name);
}
} else {
DocIdSetIterator iterator = docIdSet.iterator();
if (iterator != null) {
if (iterator.advance(hitContext.docId()) == hitContext.docId()) {
matchedQueries.add(name);
}
}
}
}
} catch (IOException e) {
// ignore
} finally {
SearchContext.current().clearReleasables();
}
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_fetch_matchedqueries_MatchedQueriesFetchSubPhase.java
|
553 |
public class GetMappingsAction extends IndicesAction<GetMappingsRequest, GetMappingsResponse, GetMappingsRequestBuilder> {
public static final GetMappingsAction INSTANCE = new GetMappingsAction();
public static final String NAME = "mappings/get";
private GetMappingsAction() {
super(NAME);
}
@Override
public GetMappingsRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new GetMappingsRequestBuilder((InternalGenericClient) client);
}
@Override
public GetMappingsResponse newResponse() {
return new GetMappingsResponse();
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_GetMappingsAction.java
|
3,708 |
public final class PoolExecutorThreadFactory extends AbstractExecutorThreadFactory {
private final String threadNamePrefix;
private final AtomicInteger idGen = new AtomicInteger(0);
// to reuse previous thread IDs
private final Queue<Integer> idQ = new LinkedBlockingQueue<Integer>(1000);
public PoolExecutorThreadFactory(ThreadGroup threadGroup, String threadNamePrefix, ClassLoader classLoader) {
super(threadGroup, classLoader);
this.threadNamePrefix = threadNamePrefix;
}
@Override
protected Thread createThread(Runnable r) {
Integer id = idQ.poll();
if (id == null) {
id = idGen.incrementAndGet();
}
String name = threadNamePrefix + id;
return new ManagedThread(r, name, id);
}
private class ManagedThread extends Thread {
protected final int id;
public ManagedThread(Runnable target, String name, int id) {
super(threadGroup, target, name);
this.id = id;
}
public void run() {
try {
super.run();
} catch (OutOfMemoryError e) {
OutOfMemoryErrorDispatcher.onOutOfMemory(e);
} finally {
try {
idQ.offer(id);
} catch (Throwable ignored) {
}
}
}
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_util_executor_PoolExecutorThreadFactory.java
|
224 |
public static class Echo extends HazelcastInstanceAwareObject implements Callable<String>, DataSerializable {
String input;
public Echo() {
}
public Echo(String input) {
this.input = input;
}
@Override
public String call() {
getHazelcastInstance().getCountDownLatch("latch").countDown();
return getHazelcastInstance().getCluster().getLocalMember().toString() + ":" + input;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(input);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
input = in.readUTF();
}
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_examples_ClientTestApp.java
|
970 |
transportService.sendRequest(node, transportNodeAction, nodeRequest, transportRequestOptions, new BaseTransportResponseHandler<NodeResponse>() {
@Override
public NodeResponse newInstance() {
return newNodeResponse();
}
@Override
public void handleResponse(NodeResponse response) {
onOperation(idx, response);
}
@Override
public void handleException(TransportException exp) {
onFailure(idx, node.id(), exp);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
});
| 0true
|
src_main_java_org_elasticsearch_action_support_nodes_TransportNodesOperationAction.java
|
247 |
public static class XBuilder {
private Builder<Pair<Long, BytesRef>> builder;
private int maxSurfaceFormsPerAnalyzedForm;
private IntsRef scratchInts = new IntsRef();
private final PairOutputs<Long, BytesRef> outputs;
private boolean hasPayloads;
private BytesRef analyzed = new BytesRef();
private final SurfaceFormAndPayload[] surfaceFormsAndPayload;
private int count;
private ObjectIntOpenHashMap<BytesRef> seenSurfaceForms = HppcMaps.Object.Integer.ensureNoNullKeys(256, 0.75f);
private int payloadSep;
public XBuilder(int maxSurfaceFormsPerAnalyzedForm, boolean hasPayloads, int payloadSep) {
this.payloadSep = payloadSep;
this.outputs = new PairOutputs<Long, BytesRef>(PositiveIntOutputs.getSingleton(), ByteSequenceOutputs.getSingleton());
this.builder = new Builder<Pair<Long, BytesRef>>(FST.INPUT_TYPE.BYTE1, outputs);
this.maxSurfaceFormsPerAnalyzedForm = maxSurfaceFormsPerAnalyzedForm;
this.hasPayloads = hasPayloads;
surfaceFormsAndPayload = new SurfaceFormAndPayload[maxSurfaceFormsPerAnalyzedForm];
}
public void startTerm(BytesRef analyzed) {
this.analyzed.copyBytes(analyzed);
this.analyzed.grow(analyzed.length+2);
}
private final static class SurfaceFormAndPayload implements Comparable<SurfaceFormAndPayload> {
BytesRef payload;
long weight;
public SurfaceFormAndPayload(BytesRef payload, long cost) {
super();
this.payload = payload;
this.weight = cost;
}
@Override
public int compareTo(SurfaceFormAndPayload o) {
int res = compare(weight, o.weight);
if (res == 0 ){
return payload.compareTo(o.payload);
}
return res;
}
public static int compare(long x, long y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
}
public void addSurface(BytesRef surface, BytesRef payload, long cost) throws IOException {
int surfaceIndex = -1;
long encodedWeight = cost == -1 ? cost : encodeWeight(cost);
/*
* we need to check if we have seen this surface form, if so only use the
* the surface form with the highest weight and drop the rest no matter if
* the payload differs.
*/
if (count >= maxSurfaceFormsPerAnalyzedForm) {
// More than maxSurfaceFormsPerAnalyzedForm
// dups: skip the rest:
return;
}
BytesRef surfaceCopy;
if (count > 0 && seenSurfaceForms.containsKey(surface)) {
surfaceIndex = seenSurfaceForms.lget();
SurfaceFormAndPayload surfaceFormAndPayload = surfaceFormsAndPayload[surfaceIndex];
if (encodedWeight >= surfaceFormAndPayload.weight) {
return;
}
surfaceCopy = BytesRef.deepCopyOf(surface);
} else {
surfaceIndex = count++;
surfaceCopy = BytesRef.deepCopyOf(surface);
seenSurfaceForms.put(surfaceCopy, surfaceIndex);
}
BytesRef payloadRef;
if (!hasPayloads) {
payloadRef = surfaceCopy;
} else {
int len = surface.length + 1 + payload.length;
final BytesRef br = new BytesRef(len);
System.arraycopy(surface.bytes, surface.offset, br.bytes, 0, surface.length);
br.bytes[surface.length] = (byte) payloadSep;
System.arraycopy(payload.bytes, payload.offset, br.bytes, surface.length + 1, payload.length);
br.length = len;
payloadRef = br;
}
if (surfaceFormsAndPayload[surfaceIndex] == null) {
surfaceFormsAndPayload[surfaceIndex] = new SurfaceFormAndPayload(payloadRef, encodedWeight);
} else {
surfaceFormsAndPayload[surfaceIndex].payload = payloadRef;
surfaceFormsAndPayload[surfaceIndex].weight = encodedWeight;
}
}
public void finishTerm(long defaultWeight) throws IOException {
ArrayUtil.timSort(surfaceFormsAndPayload, 0, count);
int deduplicator = 0;
analyzed.bytes[analyzed.offset + analyzed.length] = 0;
analyzed.length += 2;
for (int i = 0; i < count; i++) {
analyzed.bytes[analyzed.offset + analyzed.length - 1 ] = (byte) deduplicator++;
Util.toIntsRef(analyzed, scratchInts);
SurfaceFormAndPayload candiate = surfaceFormsAndPayload[i];
long cost = candiate.weight == -1 ? encodeWeight(Math.min(Integer.MAX_VALUE, defaultWeight)) : candiate.weight;
builder.add(scratchInts, outputs.newPair(cost, candiate.payload));
}
seenSurfaceForms.clear();
count = 0;
}
public FST<Pair<Long, BytesRef>> build() throws IOException {
return builder.finish();
}
public boolean hasPayloads() {
return hasPayloads;
}
public int maxSurfaceFormsPerAnalyzedForm() {
return maxSurfaceFormsPerAnalyzedForm;
}
}
| 0true
|
src_main_java_org_apache_lucene_search_suggest_analyzing_XAnalyzingSuggester.java
|
919 |
public class PlainListenableActionFuture<T> extends AbstractListenableActionFuture<T, T> {
public PlainListenableActionFuture(boolean listenerThreaded, ThreadPool threadPool) {
super(listenerThreaded, threadPool);
}
@Override
protected T convert(T response) {
return response;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_PlainListenableActionFuture.java
|
412 |
public class GetSnapshotsAction extends ClusterAction<GetSnapshotsRequest, GetSnapshotsResponse, GetSnapshotsRequestBuilder> {
public static final GetSnapshotsAction INSTANCE = new GetSnapshotsAction();
public static final String NAME = "cluster/snapshot/get";
private GetSnapshotsAction() {
super(NAME);
}
@Override
public GetSnapshotsResponse newResponse() {
return new GetSnapshotsResponse();
}
@Override
public GetSnapshotsRequestBuilder newRequestBuilder(ClusterAdminClient client) {
return new GetSnapshotsRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_get_GetSnapshotsAction.java
|
3 |
public interface CommandParser extends TextCommandConstants {
TextCommand parser(SocketTextReader socketTextReader, String cmd, int space);
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_ascii_CommandParser.java
|
1,238 |
public class Requests {
/**
* The content type used to generate request builders (query / search).
*/
public static XContentType CONTENT_TYPE = XContentType.SMILE;
/**
* The default content type to use to generate source documents when indexing.
*/
public static XContentType INDEX_CONTENT_TYPE = XContentType.JSON;
public static IndexRequest indexRequest() {
return new IndexRequest();
}
/**
* Create an index request against a specific index. Note the {@link IndexRequest#type(String)} must be
* set as well and optionally the {@link IndexRequest#id(String)}.
*
* @param index The index name to index the request against
* @return The index request
* @see org.elasticsearch.client.Client#index(org.elasticsearch.action.index.IndexRequest)
*/
public static IndexRequest indexRequest(String index) {
return new IndexRequest(index);
}
/**
* Creates a delete request against a specific index. Note the {@link DeleteRequest#type(String)} and
* {@link DeleteRequest#id(String)} must be set.
*
* @param index The index name to delete from
* @return The delete request
* @see org.elasticsearch.client.Client#delete(org.elasticsearch.action.delete.DeleteRequest)
*/
public static DeleteRequest deleteRequest(String index) {
return new DeleteRequest(index);
}
/**
* Creats a new bulk request.
*/
public static BulkRequest bulkRequest() {
return new BulkRequest();
}
/**
* Creates a delete by query request. Note, the query itself must be set either by setting the JSON source
* of the query, or by using a {@link org.elasticsearch.index.query.QueryBuilder} (using {@link org.elasticsearch.index.query.QueryBuilders}).
*
* @param indices The indices the delete by query against. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The delete by query request
* @see org.elasticsearch.client.Client#deleteByQuery(org.elasticsearch.action.deletebyquery.DeleteByQueryRequest)
*/
public static DeleteByQueryRequest deleteByQueryRequest(String... indices) {
return new DeleteByQueryRequest(indices);
}
/**
* Creates a get request to get the JSON source from an index based on a type and id. Note, the
* {@link GetRequest#type(String)} and {@link GetRequest#id(String)} must be set.
*
* @param index The index to get the JSON source from
* @return The get request
* @see org.elasticsearch.client.Client#get(org.elasticsearch.action.get.GetRequest)
*/
public static GetRequest getRequest(String index) {
return new GetRequest(index);
}
/**
* Creates a count request which counts the hits matched against a query. Note, the query itself must be set
* either using the JSON source of the query, or using a {@link org.elasticsearch.index.query.QueryBuilder} (using {@link org.elasticsearch.index.query.QueryBuilders}).
*
* @param indices The indices to count matched documents against a query. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The count request
* @see org.elasticsearch.client.Client#count(org.elasticsearch.action.count.CountRequest)
*/
public static CountRequest countRequest(String... indices) {
return new CountRequest(indices);
}
/**
* More like this request represents a request to search for documents that are "like" the provided (fetched)
* document.
*
* @param index The index to load the document from
* @return The more like this request
* @see org.elasticsearch.client.Client#moreLikeThis(org.elasticsearch.action.mlt.MoreLikeThisRequest)
*/
public static MoreLikeThisRequest moreLikeThisRequest(String index) {
return new MoreLikeThisRequest(index);
}
/**
* Creates a search request against one or more indices. Note, the search source must be set either using the
* actual JSON search source, or the {@link org.elasticsearch.search.builder.SearchSourceBuilder}.
*
* @param indices The indices to search against. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The search request
* @see org.elasticsearch.client.Client#search(org.elasticsearch.action.search.SearchRequest)
*/
public static SearchRequest searchRequest(String... indices) {
return new SearchRequest(indices);
}
/**
* Creates a search scroll request allowing to continue searching a previous search request.
*
* @param scrollId The scroll id representing the scrollable search
* @return The search scroll request
* @see org.elasticsearch.client.Client#searchScroll(org.elasticsearch.action.search.SearchScrollRequest)
*/
public static SearchScrollRequest searchScrollRequest(String scrollId) {
return new SearchScrollRequest(scrollId);
}
/**
* Creates an indices status request.
*
* @param indices The indices to query status about. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The indices status request
* @see org.elasticsearch.client.IndicesAdminClient#status(org.elasticsearch.action.admin.indices.status.IndicesStatusRequest)
*/
public static IndicesStatusRequest indicesStatusRequest(String... indices) {
return new IndicesStatusRequest(indices);
}
public static IndicesSegmentsRequest indicesSegmentsRequest(String... indices) {
return new IndicesSegmentsRequest(indices);
}
/**
* Creates an indices exists request.
*
* @param indices The indices to check if they exists or not.
* @return The indices exists request
* @see org.elasticsearch.client.IndicesAdminClient#exists(org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest)
*/
public static IndicesExistsRequest indicesExistsRequest(String... indices) {
return new IndicesExistsRequest(indices);
}
/**
* Creates a create index request.
*
* @param index The index to create
* @return The index create request
* @see org.elasticsearch.client.IndicesAdminClient#create(org.elasticsearch.action.admin.indices.create.CreateIndexRequest)
*/
public static CreateIndexRequest createIndexRequest(String index) {
return new CreateIndexRequest(index);
}
/**
* Creates a delete index request.
*
* @param index The index to delete
* @return The delete index request
* @see org.elasticsearch.client.IndicesAdminClient#delete(org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest)
*/
public static DeleteIndexRequest deleteIndexRequest(String index) {
return new DeleteIndexRequest(index);
}
/**
* Creates a close index request.
*
* @param index The index to close
* @return The delete index request
* @see org.elasticsearch.client.IndicesAdminClient#close(org.elasticsearch.action.admin.indices.close.CloseIndexRequest)
*/
public static CloseIndexRequest closeIndexRequest(String index) {
return new CloseIndexRequest(index);
}
/**
* Creates an open index request.
*
* @param index The index to open
* @return The delete index request
* @see org.elasticsearch.client.IndicesAdminClient#open(org.elasticsearch.action.admin.indices.open.OpenIndexRequest)
*/
public static OpenIndexRequest openIndexRequest(String index) {
return new OpenIndexRequest(index);
}
/**
* Create a create mapping request against one or more indices.
*
* @param indices The indices to create mapping. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The create mapping request
* @see org.elasticsearch.client.IndicesAdminClient#putMapping(org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest)
*/
public static PutMappingRequest putMappingRequest(String... indices) {
return new PutMappingRequest(indices);
}
/**
* Deletes mapping (and all its data) from one or more indices.
*
* @param indices The indices the mapping will be deleted from. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The create mapping request
* @see org.elasticsearch.client.IndicesAdminClient#deleteMapping(org.elasticsearch.action.admin.indices.mapping.delete.DeleteMappingRequest)
*/
public static DeleteMappingRequest deleteMappingRequest(String... indices) {
return new DeleteMappingRequest(indices);
}
/**
* Creates an index aliases request allowing to add and remove aliases.
*
* @return The index aliases request
*/
public static IndicesAliasesRequest indexAliasesRequest() {
return new IndicesAliasesRequest();
}
/**
* Creates a refresh indices request.
*
* @param indices The indices to refresh. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The refresh request
* @see org.elasticsearch.client.IndicesAdminClient#refresh(org.elasticsearch.action.admin.indices.refresh.RefreshRequest)
*/
public static RefreshRequest refreshRequest(String... indices) {
return new RefreshRequest(indices);
}
/**
* Creates a flush indices request.
*
* @param indices The indices to flush. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The flush request
* @see org.elasticsearch.client.IndicesAdminClient#flush(org.elasticsearch.action.admin.indices.flush.FlushRequest)
*/
public static FlushRequest flushRequest(String... indices) {
return new FlushRequest(indices);
}
/**
* Creates an optimize request.
*
* @param indices The indices to optimize. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The optimize request
* @see org.elasticsearch.client.IndicesAdminClient#optimize(org.elasticsearch.action.admin.indices.optimize.OptimizeRequest)
*/
public static OptimizeRequest optimizeRequest(String... indices) {
return new OptimizeRequest(indices);
}
/**
* Creates a gateway snapshot indices request.
*
* @param indices The indices the gateway snapshot will be performed on. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The gateway snapshot request
* @see org.elasticsearch.client.IndicesAdminClient#gatewaySnapshot(org.elasticsearch.action.admin.indices.gateway.snapshot.GatewaySnapshotRequest)
* @deprecated Use snapshot/restore API instead
*/
@Deprecated
public static GatewaySnapshotRequest gatewaySnapshotRequest(String... indices) {
return new GatewaySnapshotRequest(indices);
}
/**
* Creates a clean indices cache request.
*
* @param indices The indices to clean their caches. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The request
*/
public static ClearIndicesCacheRequest clearIndicesCacheRequest(String... indices) {
return new ClearIndicesCacheRequest(indices);
}
/**
* A request to update indices settings.
*
* @param indices The indices to update the settings for. Use <tt>null</tt> or <tt>_all</tt> to executed against all indices.
* @return The request
*/
public static UpdateSettingsRequest updateSettingsRequest(String... indices) {
return new UpdateSettingsRequest(indices);
}
/**
* Creates a cluster state request.
*
* @return The cluster state request.
* @see org.elasticsearch.client.ClusterAdminClient#state(org.elasticsearch.action.admin.cluster.state.ClusterStateRequest)
*/
public static ClusterStateRequest clusterStateRequest() {
return new ClusterStateRequest();
}
public static ClusterRerouteRequest clusterRerouteRequest() {
return new ClusterRerouteRequest();
}
public static ClusterUpdateSettingsRequest clusterUpdateSettingsRequest() {
return new ClusterUpdateSettingsRequest();
}
/**
* Creates a cluster health request.
*
* @param indices The indices to provide additional cluster health information for. Use <tt>null</tt> or <tt>_all</tt> to execute against all indices
* @return The cluster health request
* @see org.elasticsearch.client.ClusterAdminClient#health(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest)
*/
public static ClusterHealthRequest clusterHealthRequest(String... indices) {
return new ClusterHealthRequest(indices);
}
/**
* List all shards for the give search
*/
public static ClusterSearchShardsRequest clusterSearchShardsRequest() {
return new ClusterSearchShardsRequest();
}
/**
* List all shards for the give search
*/
public static ClusterSearchShardsRequest clusterSearchShardsRequest(String... indices) {
return new ClusterSearchShardsRequest(indices);
}
/**
* Creates a nodes info request against all the nodes.
*
* @return The nodes info request
* @see org.elasticsearch.client.ClusterAdminClient#nodesInfo(org.elasticsearch.action.admin.cluster.node.info.NodesInfoRequest)
*/
public static NodesInfoRequest nodesInfoRequest() {
return new NodesInfoRequest();
}
/**
* Creates a nodes info request against one or more nodes. Pass <tt>null</tt> or an empty array for all nodes.
*
* @param nodesIds The nodes ids to get the status for
* @return The nodes info request
* @see org.elasticsearch.client.ClusterAdminClient#nodesStats(org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequest)
*/
public static NodesInfoRequest nodesInfoRequest(String... nodesIds) {
return new NodesInfoRequest(nodesIds);
}
/**
* Creates a nodes stats request against one or more nodes. Pass <tt>null</tt> or an empty array for all nodes.
*
* @param nodesIds The nodes ids to get the stats for
* @return The nodes info request
* @see org.elasticsearch.client.ClusterAdminClient#nodesStats(org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequest)
*/
public static NodesStatsRequest nodesStatsRequest(String... nodesIds) {
return new NodesStatsRequest(nodesIds);
}
/**
* Creates a cluster stats request.
*
* @return The cluster stats request
* @see org.elasticsearch.client.ClusterAdminClient#clusterStats(org.elasticsearch.action.admin.cluster.stats.ClusterStatsRequest)
*/
public static ClusterStatsRequest clusterStatsRequest() {
return new ClusterStatsRequest();
}
/**
* Shuts down all nodes in the cluster.
*/
public static NodesShutdownRequest nodesShutdownRequest() {
return new NodesShutdownRequest();
}
/**
* Shuts down the specified nodes in the cluster.
*
* @param nodesIds The nodes ids to get the status for
* @return The nodes info request
* @see org.elasticsearch.client.ClusterAdminClient#nodesShutdown(org.elasticsearch.action.admin.cluster.node.shutdown.NodesShutdownRequest)
*/
public static NodesShutdownRequest nodesShutdownRequest(String... nodesIds) {
return new NodesShutdownRequest(nodesIds);
}
/**
* Restarts all nodes in the cluster.
*/
public static NodesRestartRequest nodesRestartRequest() {
return new NodesRestartRequest();
}
/**
* Restarts specific nodes in the cluster.
*
* @param nodesIds The nodes ids to restart
* @return The nodes info request
* @see org.elasticsearch.client.ClusterAdminClient#nodesRestart(org.elasticsearch.action.admin.cluster.node.restart.NodesRestartRequest)
*/
public static NodesRestartRequest nodesRestartRequest(String... nodesIds) {
return new NodesRestartRequest(nodesIds);
}
/**
* Registers snapshot repository
*
* @param name repository name
* @return repository registration request
*/
public static PutRepositoryRequest putRepositoryRequest(String name) {
return new PutRepositoryRequest(name);
}
/**
* Gets snapshot repository
*
* @param repositories names of repositories
* @return get repository request
*/
public static GetRepositoriesRequest getRepositoryRequest(String... repositories) {
return new GetRepositoriesRequest(repositories);
}
/**
* Deletes registration for snapshot repository
*
* @param name repository name
* @return delete repository request
*/
public static DeleteRepositoryRequest deleteRepositoryRequest(String name) {
return new DeleteRepositoryRequest(name);
}
/**
* Creates new snapshot
*
* @param repository repository name
* @param snapshot snapshot name
* @return create snapshot request
*/
public static CreateSnapshotRequest createSnapshotRequest(String repository, String snapshot) {
return new CreateSnapshotRequest(repository, snapshot);
}
/**
* Gets snapshots from repository
*
* @param repository repository name
* @return get snapshot request
*/
public static GetSnapshotsRequest getSnapshotsRequest(String repository) {
return new GetSnapshotsRequest(repository);
}
/**
* Restores new snapshot
*
* @param repository repository name
* @param snapshot snapshot name
* @return snapshot creation request
*/
public static RestoreSnapshotRequest restoreSnapshotRequest(String repository, String snapshot) {
return new RestoreSnapshotRequest(repository, snapshot);
}
/**
* Restores new snapshot
*
* @param snapshot snapshot name
* @param repository repository name
* @return delete snapshot request
*/
public static DeleteSnapshotRequest deleteSnapshotRequest(String repository, String snapshot) {
return new DeleteSnapshotRequest(repository, snapshot);
}
}
| 0true
|
src_main_java_org_elasticsearch_client_Requests.java
|
1,598 |
public class ServerRun {
protected String rootPath;
protected final String serverId;
protected OServer server;
public ServerRun(final String iRootPath, final String serverId) {
this.rootPath = iRootPath;
this.serverId = serverId;
}
protected ODatabaseDocumentTx createDatabase(final String iName) {
OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(false);
String dbPath = getDatabasePath(iName);
new File(dbPath).mkdirs();
final ODatabaseDocumentTx database = new ODatabaseDocumentTx("local:" + dbPath);
if (database.exists()) {
System.out.println("Dropping previous database '" + iName + "' under: " + dbPath + "...");
OFileUtils.deleteRecursively(new File(dbPath));
}
System.out.println("Creating database '" + iName + "' under: " + dbPath + "...");
database.create();
return database;
}
protected void copyDatabase(final String iDatabaseName, final String iDestinationDirectory) throws IOException {
// COPY THE DATABASE TO OTHER DIRECTORIES
System.out.println("Dropping any previous database '" + iDatabaseName + "' under: " + iDatabaseName + "...");
OFileUtils.deleteRecursively(new File(iDestinationDirectory));
System.out.println("Copying database folder " + iDatabaseName + " to " + iDestinationDirectory + "...");
OFileUtils.copyDirectory(new File(getDatabasePath(iDatabaseName)), new File(iDestinationDirectory));
}
public OServer getServerInstance() {
return server;
}
public String getServerId() {
return serverId;
}
protected OServer startServer(final String iConfigFile) throws Exception, InstantiationException, IllegalAccessException,
ClassNotFoundException, InvocationTargetException, NoSuchMethodException, IOException {
System.out.println("Starting server " + serverId + " from " + getServerHome() + "...");
System.setProperty("ORIENTDB_HOME", getServerHome());
server = new OServer();
server.startup(getClass().getClassLoader().getResourceAsStream(iConfigFile));
server.activate();
return server;
}
protected void shutdownServer() {
if (server != null)
server.shutdown();
}
protected String getServerHome() {
return getServerHome(serverId);
}
protected String getDatabasePath(final String iDatabaseName) {
return getDatabasePath(serverId, iDatabaseName);
}
public String getBinaryProtocolAddress() {
return server.getListenerByProtocol(ONetworkProtocolBinary.class).getListeningAddress();
}
public static String getServerHome(final String iServerId) {
return "target/server" + iServerId;
}
public static String getDatabasePath(final String iServerId, final String iDatabaseName) {
return getServerHome(iServerId) + "/databases/" + iDatabaseName;
}
}
| 1no label
|
distributed_src_test_java_com_orientechnologies_orient_server_distributed_ServerRun.java
|
520 |
public class OMemoryLockException extends ODatabaseException {
private static final long serialVersionUID = 1L;
public OMemoryLockException(String message, Throwable cause) {
super(message, cause);
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_exception_OMemoryLockException.java
|
140 |
public interface TitanSchemaType extends TitanSchemaElement {
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_schema_TitanSchemaType.java
|
1,711 |
@Service("blAdminEntityService")
public class AdminEntityServiceImpl implements AdminEntityService {
@Resource(name = "blDynamicEntityRemoteService")
protected DynamicEntityService service;
@Resource(name = "blPersistencePackageFactory")
protected PersistencePackageFactory persistencePackageFactory;
@PersistenceContext(unitName = "blPU")
protected EntityManager em;
@Resource(name = "blEntityConfiguration")
protected EntityConfiguration entityConfiguration;
protected DynamicDaoHelper dynamicDaoHelper = new DynamicDaoHelperImpl();
@Override
public ClassMetadata getClassMetadata(PersistencePackageRequest request)
throws ServiceException {
ClassMetadata cmd = inspect(request).getClassMetaData();
cmd.setCeilingType(request.getCeilingEntityClassname());
return cmd;
}
@Override
public DynamicResultSet getRecords(PersistencePackageRequest request) throws ServiceException {
return fetch(request);
}
@Override
public Entity getRecord(PersistencePackageRequest request, String id, ClassMetadata cmd, boolean isCollectionRequest)
throws ServiceException {
String idProperty = getIdProperty(cmd);
FilterAndSortCriteria fasc = new FilterAndSortCriteria(idProperty);
fasc.setFilterValue(id);
request.addFilterAndSortCriteria(fasc);
Entity[] entities = fetch(request).getRecords();
Assert.isTrue(entities != null && entities.length == 1, "Entity not found");
Entity entity = entities[0];
return entity;
}
@Override
public Entity addEntity(EntityForm entityForm, String[] customCriteria)
throws ServiceException {
PersistencePackageRequest ppr = getRequestForEntityForm(entityForm, customCriteria);
// If the entity form has dynamic forms inside of it, we need to persist those as well.
// They are typically done in their own custom persistence handlers, which will get triggered
// based on the criteria specific in the PersistencePackage.
for (Entry<String, EntityForm> entry : entityForm.getDynamicForms().entrySet()) {
DynamicEntityFormInfo info = entityForm.getDynamicFormInfo(entry.getKey());
customCriteria = new String[] {info.getCriteriaName()};
PersistencePackageRequest subRequest = getRequestForEntityForm(entry.getValue(), customCriteria);
ppr.addSubRequest(info.getPropertyName(), subRequest);
}
return add(ppr);
}
@Override
public Entity updateEntity(EntityForm entityForm, String[] customCriteria)
throws ServiceException {
PersistencePackageRequest ppr = getRequestForEntityForm(entityForm, customCriteria);
// If the entity form has dynamic forms inside of it, we need to persist those as well.
// They are typically done in their own custom persistence handlers, which will get triggered
// based on the criteria specific in the PersistencePackage.
for (Entry<String, EntityForm> entry : entityForm.getDynamicForms().entrySet()) {
DynamicEntityFormInfo info = entityForm.getDynamicFormInfo(entry.getKey());
String propertyName = info.getPropertyName();
String propertyValue = entityForm.getFields().get(propertyName).getValue();
customCriteria = new String[] { info.getCriteriaName(), entityForm.getId(), propertyName, propertyValue };
PersistencePackageRequest subRequest = getRequestForEntityForm(entry.getValue(), customCriteria);
ppr.addSubRequest(info.getPropertyName(), subRequest);
}
return update(ppr);
}
@Override
public void removeEntity(EntityForm entityForm, String[] customCriteria)
throws ServiceException {
PersistencePackageRequest ppr = getRequestForEntityForm(entityForm, customCriteria);
remove(ppr);
}
protected List<Property> getPropertiesFromEntityForm(EntityForm entityForm) {
List<Property> properties = new ArrayList<Property>(entityForm.getFields().size());
for (Entry<String, Field> entry : entityForm.getFields().entrySet()) {
Property p = new Property();
p.setName(entry.getKey());
p.setValue(entry.getValue().getValue());
properties.add(p);
}
return properties;
}
protected PersistencePackageRequest getRequestForEntityForm(EntityForm entityForm, String[] customCriteria) {
// Ensure the ID property is on the form
Field idField = entityForm.getFields().get(entityForm.getIdProperty());
if (idField == null) {
idField = new Field();
idField.setName(entityForm.getIdProperty());
idField.setValue(entityForm.getId());
entityForm.getFields().put(entityForm.getIdProperty(), idField);
} else {
idField.setValue(entityForm.getId());
}
List<Property> propList = getPropertiesFromEntityForm(entityForm);
Property[] properties = new Property[propList.size()];
properties = propList.toArray(properties);
Entity entity = new Entity();
entity.setProperties(properties);
String entityType = entityForm.getEntityType();
if (StringUtils.isEmpty(entityType)) {
entityType = entityForm.getCeilingEntityClassname();
}
entity.setType(new String[] { entityType });
PersistencePackageRequest ppr = PersistencePackageRequest.standard()
.withEntity(entity)
.withCustomCriteria(customCriteria)
.withCeilingEntityClassname(entityForm.getCeilingEntityClassname());
return ppr;
}
@Override
public Entity getAdvancedCollectionRecord(ClassMetadata containingClassMetadata, Entity containingEntity,
Property collectionProperty, String collectionItemId)
throws ServiceException {
PersistencePackageRequest ppr = PersistencePackageRequest.fromMetadata(collectionProperty.getMetadata());
FieldMetadata md = collectionProperty.getMetadata();
String containingEntityId = getContextSpecificRelationshipId(containingClassMetadata, containingEntity,
collectionProperty.getName());
Entity entity = null;
if (md instanceof AdornedTargetCollectionMetadata) {
FilterAndSortCriteria fasc = new FilterAndSortCriteria(ppr.getAdornedList().getCollectionFieldName());
fasc.setFilterValue(containingEntityId);
ppr.addFilterAndSortCriteria(fasc);
fasc = new FilterAndSortCriteria(ppr.getAdornedList().getCollectionFieldName() + "Target");
fasc.setFilterValue(collectionItemId);
ppr.addFilterAndSortCriteria(fasc);
Entity[] entities = fetch(ppr).getRecords();
Assert.isTrue(entities != null && entities.length == 1, "Entity not found");
entity = entities[0];
} else if (md instanceof MapMetadata) {
MapMetadata mmd = (MapMetadata) md;
FilterAndSortCriteria fasc = new FilterAndSortCriteria(ppr.getForeignKey().getManyToField());
fasc.setFilterValue(containingEntityId);
ppr.addFilterAndSortCriteria(fasc);
Entity[] entities = fetch(ppr).getRecords();
for (Entity e : entities) {
String idProperty = getIdProperty(containingClassMetadata);
if (mmd.isSimpleValue()) {
idProperty = "key";
}
Property p = e.getPMap().get(idProperty);
if (p.getValue().equals(collectionItemId)) {
entity = e;
break;
}
}
} else {
throw new IllegalArgumentException(String.format("The specified field [%s] for class [%s] was not an " +
"advanced collection field.", collectionProperty.getName(), containingClassMetadata.getCeilingType()));
}
if (entity == null) {
throw new NoResultException(String.format("Could not find record for class [%s], field [%s], main entity id " +
"[%s], collection entity id [%s]", containingClassMetadata.getCeilingType(),
collectionProperty.getName(), containingEntityId, collectionItemId));
}
return entity;
}
@Override
public DynamicResultSet getRecordsForCollection(ClassMetadata containingClassMetadata, Entity containingEntity,
Property collectionProperty, FilterAndSortCriteria[] fascs, Integer startIndex, Integer maxIndex)
throws ServiceException {
return getRecordsForCollection(containingClassMetadata, containingEntity, collectionProperty, fascs, startIndex,
maxIndex, null);
}
@Override
public DynamicResultSet getRecordsForCollection(ClassMetadata containingClassMetadata, Entity containingEntity,
Property collectionProperty, FilterAndSortCriteria[] fascs, Integer startIndex, Integer maxIndex,
String idValueOverride) throws ServiceException {
PersistencePackageRequest ppr = PersistencePackageRequest.fromMetadata(collectionProperty.getMetadata())
.withFilterAndSortCriteria(fascs)
.withStartIndex(startIndex)
.withMaxIndex(maxIndex);
FilterAndSortCriteria fasc;
FieldMetadata md = collectionProperty.getMetadata();
if (md instanceof BasicCollectionMetadata) {
fasc = new FilterAndSortCriteria(ppr.getForeignKey().getManyToField());
} else if (md instanceof AdornedTargetCollectionMetadata) {
fasc = new FilterAndSortCriteria(ppr.getAdornedList().getCollectionFieldName());
} else if (md instanceof MapMetadata) {
fasc = new FilterAndSortCriteria(ppr.getForeignKey().getManyToField());
} else {
throw new IllegalArgumentException(String.format("The specified field [%s] for class [%s] was not a " +
"collection field.", collectionProperty.getName(), containingClassMetadata.getCeilingType()));
}
String id;
if (idValueOverride == null) {
id = getContextSpecificRelationshipId(containingClassMetadata, containingEntity, collectionProperty.getName());
} else {
id = idValueOverride;
}
fasc.setFilterValue(id);
ppr.addFilterAndSortCriteria(fasc);
return fetch(ppr);
}
@Override
public Map<String, DynamicResultSet> getRecordsForAllSubCollections(PersistencePackageRequest ppr, Entity containingEntity)
throws ServiceException {
Map<String, DynamicResultSet> map = new HashMap<String, DynamicResultSet>();
ClassMetadata cmd = getClassMetadata(ppr);
for (Property p : cmd.getProperties()) {
if (p.getMetadata() instanceof CollectionMetadata) {
DynamicResultSet drs = getRecordsForCollection(cmd, containingEntity, p, null, null, null);
map.put(p.getName(), drs);
}
}
return map;
}
@Override
public Entity addSubCollectionEntity(EntityForm entityForm, ClassMetadata mainMetadata, Property field,
Entity parentEntity)
throws ServiceException, ClassNotFoundException {
// Assemble the properties from the entity form
List<Property> properties = new ArrayList<Property>();
for (Entry<String, Field> entry : entityForm.getFields().entrySet()) {
Property p = new Property();
p.setName(entry.getKey());
p.setValue(entry.getValue().getValue());
properties.add(p);
}
FieldMetadata md = field.getMetadata();
PersistencePackageRequest ppr = PersistencePackageRequest.fromMetadata(md)
.withEntity(new Entity());
if (md instanceof BasicCollectionMetadata) {
BasicCollectionMetadata fmd = (BasicCollectionMetadata) md;
ppr.getEntity().setType(new String[] { entityForm.getEntityType() });
// If we're looking up an entity instead of trying to create one on the fly, let's make sure
// that we're not changing the target entity at all and only creating the association to the id
if (fmd.getAddMethodType().equals(AddMethodType.LOOKUP)) {
List<String> fieldsToRemove = new ArrayList<String>();
String idProp = getIdProperty(mainMetadata);
for (String key : entityForm.getFields().keySet()) {
if (!idProp.equals(key)) {
fieldsToRemove.add(key);
}
}
for (String key : fieldsToRemove) {
ListIterator<Property> li = properties.listIterator();
while (li.hasNext()) {
if (li.next().getName().equals(key)) {
li.remove();
}
}
}
ppr.setValidateUnsubmittedProperties(false);
}
Property fp = new Property();
fp.setName(ppr.getForeignKey().getManyToField());
fp.setValue(getContextSpecificRelationshipId(mainMetadata, parentEntity, field.getName()));
properties.add(fp);
} else if (md instanceof AdornedTargetCollectionMetadata) {
ppr.getEntity().setType(new String[] { ppr.getAdornedList().getAdornedTargetEntityClassname() });
String[] maintainedFields = ((AdornedTargetCollectionMetadata) md).getMaintainedAdornedTargetFields();
if (maintainedFields == null || maintainedFields.length == 0) {
ppr.setValidateUnsubmittedProperties(false);
}
} else if (md instanceof MapMetadata) {
ppr.getEntity().setType(new String[] { entityForm.getEntityType() });
Property p = new Property();
p.setName("symbolicId");
p.setValue(getContextSpecificRelationshipId(mainMetadata, parentEntity, field.getName()));
properties.add(p);
} else {
throw new IllegalArgumentException(String.format("The specified field [%s] for class [%s] was" +
" not a collection field.", field.getName(), mainMetadata.getCeilingType()));
}
ppr.setCeilingEntityClassname(ppr.getEntity().getType()[0]);
Property[] propArr = new Property[properties.size()];
properties.toArray(propArr);
ppr.getEntity().setProperties(propArr);
return add(ppr);
}
@Override
public Entity updateSubCollectionEntity(EntityForm entityForm, ClassMetadata mainMetadata, Property field,
Entity parentEntity, String collectionItemId)
throws ServiceException, ClassNotFoundException {
List<Property> properties = getPropertiesFromEntityForm(entityForm);
FieldMetadata md = field.getMetadata();
PersistencePackageRequest ppr = PersistencePackageRequest.fromMetadata(md)
.withEntity(new Entity());
if (md instanceof BasicCollectionMetadata) {
BasicCollectionMetadata fmd = (BasicCollectionMetadata) md;
ppr.getEntity().setType(new String[] { fmd.getCollectionCeilingEntity() });
Property fp = new Property();
fp.setName(ppr.getForeignKey().getManyToField());
fp.setValue(getContextSpecificRelationshipId(mainMetadata, parentEntity, field.getName()));
properties.add(fp);
} else if (md instanceof AdornedTargetCollectionMetadata) {
ppr.getEntity().setType(new String[] { ppr.getAdornedList().getAdornedTargetEntityClassname() });
} else if (md instanceof MapMetadata) {
ppr.getEntity().setType(new String[] { entityForm.getEntityType() });
Property p = new Property();
p.setName("symbolicId");
p.setValue(getContextSpecificRelationshipId(mainMetadata, parentEntity, field.getName()));
properties.add(p);
} else {
throw new IllegalArgumentException(String.format("The specified field [%s] for class [%s] was" +
" not a collection field.", field.getName(), mainMetadata.getCeilingType()));
}
ppr.setCeilingEntityClassname(ppr.getEntity().getType()[0]);
Property p = new Property();
p.setName(entityForm.getIdProperty());
p.setValue(collectionItemId);
properties.add(p);
Property[] propArr = new Property[properties.size()];
properties.toArray(propArr);
ppr.getEntity().setProperties(propArr);
return update(ppr);
}
@Override
public void removeSubCollectionEntity(ClassMetadata mainMetadata, Property field, Entity parentEntity, String itemId,
String priorKey)
throws ServiceException {
List<Property> properties = new ArrayList<Property>();
Property p;
String parentId = getContextSpecificRelationshipId(mainMetadata, parentEntity, field.getName());
Entity entity = new Entity();
PersistencePackageRequest ppr = PersistencePackageRequest.fromMetadata(field.getMetadata())
.withEntity(entity);
if (field.getMetadata() instanceof BasicCollectionMetadata) {
BasicCollectionMetadata fmd = (BasicCollectionMetadata) field.getMetadata();
p = new Property();
p.setName("id");
p.setValue(itemId);
properties.add(p);
p = new Property();
p.setName(ppr.getForeignKey().getManyToField());
p.setValue(parentId);
properties.add(p);
entity.setType(new String[] { fmd.getCollectionCeilingEntity() });
} else if (field.getMetadata() instanceof AdornedTargetCollectionMetadata) {
AdornedTargetList adornedList = ppr.getAdornedList();
p = new Property();
p.setName(adornedList.getLinkedObjectPath() + "." + adornedList.getLinkedIdProperty());
p.setValue(parentId);
properties.add(p);
p = new Property();
p.setName(adornedList.getTargetObjectPath() + "." + adornedList.getTargetIdProperty());
p.setValue(itemId);
properties.add(p);
entity.setType(new String[] { adornedList.getAdornedTargetEntityClassname() });
} else if (field.getMetadata() instanceof MapMetadata) {
MapMetadata fmd = (MapMetadata) field.getMetadata();
p = new Property();
p.setName("symbolicId");
p.setValue(getContextSpecificRelationshipId(mainMetadata, parentEntity, field.getName()));
properties.add(p);
p = new Property();
p.setName("priorKey");
p.setValue(priorKey);
properties.add(p);
MapStructure mapStructure = ppr.getMapStructure();
p = new Property();
p.setName(mapStructure.getKeyPropertyName());
p.setValue(itemId);
properties.add(p);
entity.setType(new String[] { fmd.getTargetClass() });
}
Property[] propArr = new Property[properties.size()];
properties.toArray(propArr);
ppr.getEntity().setProperties(propArr);
remove(ppr);
}
@Override
public String getContextSpecificRelationshipId(ClassMetadata cmd, Entity entity, String propertyName) {
String prefix;
if (propertyName.contains(".")) {
prefix = propertyName.substring(0, propertyName.lastIndexOf("."));
} else {
prefix = "";
}
if (prefix.equals("")) {
return entity.findProperty("id").getValue();
} else {
//we need to check all the parts of the prefix. For example, the prefix could include an @Embedded class like
//defaultSku.dimension. In this case, we want the id from the defaultSku property, since the @Embedded does
//not have an id property - nor should it.
String[] prefixParts = prefix.split("\\.");
for (int j = 0; j < prefixParts.length; j++) {
StringBuilder sb = new StringBuilder();
for (int x = 0; x < prefixParts.length - j; x++) {
sb.append(prefixParts[x]);
if (x < prefixParts.length - j - 1) {
sb.append(".");
}
}
String tempPrefix = sb.toString();
for (Property property : entity.getProperties()) {
if (property.getName().startsWith(tempPrefix)) {
BasicFieldMetadata md = (BasicFieldMetadata) cmd.getPMap().get(property.getName()).getMetadata();
if (md.getFieldType().equals(SupportedFieldType.ID)) {
return property.getValue();
}
}
}
}
}
if (!prefix.contains(".")) {
//this may be an embedded class directly on the root entity (e.g. embeddablePriceList.restrictedPriceLists on OfferImpl)
return entity.findProperty("id").getValue();
}
throw new RuntimeException("Unable to establish a relationship id");
}
@Override
public String getIdProperty(ClassMetadata cmd) throws ServiceException {
for (Property p : cmd.getProperties()) {
if (p.getMetadata() instanceof BasicFieldMetadata) {
BasicFieldMetadata fmd = (BasicFieldMetadata) p.getMetadata();
//check for ID type and also make sure the field we're looking at is not a "ToOne" association
if (SupportedFieldType.ID.equals(fmd.getFieldType()) && !p.getName().contains(".")) {
return p.getName();
}
}
}
throw new ServiceException("Could not determine ID field for " + cmd.getCeilingType());
}
protected Entity add(PersistencePackageRequest request)
throws ServiceException {
PersistencePackage pkg = persistencePackageFactory.create(request);
try {
return service.add(pkg);
} catch (ValidationException e) {
return e.getEntity();
}
}
protected Entity update(PersistencePackageRequest request)
throws ServiceException {
PersistencePackage pkg = persistencePackageFactory.create(request);
try {
return service.update(pkg);
} catch (ValidationException e) {
return e.getEntity();
}
}
protected DynamicResultSet inspect(PersistencePackageRequest request)
throws ServiceException {
PersistencePackage pkg = persistencePackageFactory.create(request);
return service.inspect(pkg);
}
protected void remove(PersistencePackageRequest request)
throws ServiceException {
PersistencePackage pkg = persistencePackageFactory.create(request);
service.remove(pkg);
}
protected DynamicResultSet fetch(PersistencePackageRequest request)
throws ServiceException {
PersistencePackage pkg = persistencePackageFactory.create(request);
CriteriaTransferObject cto = getDefaultCto();
if (request.getFilterAndSortCriteria() != null) {
cto.addAll(Arrays.asList(request.getFilterAndSortCriteria()));
}
if (request.getStartIndex() == null) {
cto.setFirstResult(0);
} else {
cto.setFirstResult(request.getStartIndex());
}
if (request.getMaxIndex() != null) {
int requestedMaxResults = request.getMaxIndex() - request.getStartIndex() + 1;
if (requestedMaxResults >= 0 && requestedMaxResults < cto.getMaxResults()) {
cto.setMaxResults(requestedMaxResults);
}
}
return service.fetch(pkg, cto);
}
protected CriteriaTransferObject getDefaultCto() {
CriteriaTransferObject cto = new CriteriaTransferObject();
cto.setMaxResults(50);
return cto;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_AdminEntityServiceImpl.java
|
130 |
final ClientListener clientListener = new ClientListener() {
@Override
public void clientConnected(Client client) {
totalAdd.incrementAndGet();
latchAdd.countDown();
}
@Override
public void clientDisconnected(Client client) {
latchRemove.countDown();
}
};
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_ClientServiceTest.java
|
53 |
final class ReturnValueContextInfo implements IContextInformation {
@Override
public String getInformationDisplayString() {
if (declaration instanceof TypedDeclaration) {
return getType().getProducedTypeName(getUnit());
}
else {
return null;
}
}
@Override
public Image getImage() {
return getImageForDeclaration(declaration);
}
@Override
public String getContextDisplayString() {
return "Return value of '" + declaration.getName() + "'";
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_RefinementCompletionProposal.java
|
6,272 |
public class LengthAssertion extends Assertion {
private static final ESLogger logger = Loggers.getLogger(LengthAssertion.class);
public LengthAssertion(String field, Object expectedValue) {
super(field, expectedValue);
}
@Override
protected void doAssert(Object actualValue, Object expectedValue) {
logger.trace("assert that [{}] has length [{}]", actualValue, expectedValue);
assertThat(expectedValue, instanceOf(Number.class));
int length = ((Number) expectedValue).intValue();
if (actualValue instanceof String) {
assertThat(errorMessage(), ((String) actualValue).length(), equalTo(length));
} else if (actualValue instanceof List) {
assertThat(errorMessage(), ((List) actualValue).size(), equalTo(length));
} else if (actualValue instanceof Map) {
assertThat(errorMessage(), ((Map) actualValue).keySet().size(), equalTo(length));
} else {
throw new UnsupportedOperationException("value is of unsupported type [" + actualValue.getClass().getSimpleName() + "]");
}
}
private String errorMessage() {
return "field [" + getField() + "] doesn't have length [" + getExpectedValue() + "]";
}
}
| 1no label
|
src_test_java_org_elasticsearch_test_rest_section_LengthAssertion.java
|
775 |
public class ORecordIteratorCluster<REC extends ORecordInternal<?>> extends OIdentifiableIterator<REC> {
private ORecord<?> currentRecord;
public ORecordIteratorCluster(final ODatabaseRecord iDatabase, final ODatabaseRecordAbstract iLowLevelDatabase,
final int iClusterId, final boolean iUseCache) {
this(iDatabase, iLowLevelDatabase, iClusterId, OClusterPosition.INVALID_POSITION, OClusterPosition.INVALID_POSITION, iUseCache,
false);
}
public ORecordIteratorCluster(final ODatabaseRecord iDatabase, final ODatabaseRecordAbstract iLowLevelDatabase,
final int iClusterId, final OClusterPosition firstClusterEntry, final OClusterPosition lastClusterEntry,
final boolean iUseCache, final boolean iterateThroughTombstones) {
super(iDatabase, iLowLevelDatabase, iUseCache, iterateThroughTombstones);
if (iClusterId == ORID.CLUSTER_ID_INVALID)
throw new IllegalArgumentException("The clusterId is invalid");
current.clusterId = iClusterId;
final OClusterPosition[] range = database.getStorage().getClusterDataRange(current.clusterId);
if (firstClusterEntry.equals(OClusterPosition.INVALID_POSITION))
this.firstClusterEntry = range[0];
else
this.firstClusterEntry = firstClusterEntry.compareTo(range[0]) > 0 ? firstClusterEntry : range[0];
if (lastClusterEntry.equals(OClusterPosition.INVALID_POSITION))
this.lastClusterEntry = range[1];
else
this.lastClusterEntry = lastClusterEntry.compareTo(range[1]) < 0 ? lastClusterEntry : range[1];
totalAvailableRecords = database.countClusterElements(current.clusterId, iterateThroughTombstones);
txEntries = iDatabase.getTransaction().getNewRecordEntriesByClusterIds(new int[] { iClusterId });
if (txEntries != null)
// ADJUST TOTAL ELEMENT BASED ON CURRENT TRANSACTION'S ENTRIES
for (ORecordOperation entry : txEntries) {
switch (entry.type) {
case ORecordOperation.CREATED:
totalAvailableRecords++;
break;
case ORecordOperation.DELETED:
totalAvailableRecords--;
break;
}
}
begin();
}
@Override
public boolean hasPrevious() {
checkDirection(false);
updateRangesOnLiveUpdate();
if (currentRecord != null) {
return true;
}
if (limit > -1 && browsedRecords >= limit)
// LIMIT REACHED
return false;
boolean thereAreRecordsToBrowse = getCurrentEntry().compareTo(firstClusterEntry) > 0;
if (thereAreRecordsToBrowse) {
ORecordInternal<?> record = getRecord();
currentRecord = readCurrentRecord(record, -1);
}
return currentRecord != null;
}
private void updateRangesOnLiveUpdate() {
if (liveUpdated) {
OClusterPosition[] range = database.getStorage().getClusterDataRange(current.clusterId);
firstClusterEntry = range[0];
lastClusterEntry = range[1];
}
}
public boolean hasNext() {
checkDirection(true);
if (Thread.interrupted())
// INTERRUPTED
return false;
updateRangesOnLiveUpdate();
if (currentRecord != null) {
return true;
}
if (limit > -1 && browsedRecords >= limit)
// LIMIT REACHED
return false;
if (browsedRecords >= totalAvailableRecords)
return false;
if (!current.clusterPosition.isTemporary() && getCurrentEntry().compareTo(lastClusterEntry) < 0) {
ORecordInternal<?> record = getRecord();
currentRecord = readCurrentRecord(record, +1);
if (currentRecord != null)
return true;
}
// CHECK IN TX IF ANY
if (txEntries != null)
return txEntries.size() - (currentTxEntryPosition + 1) > 0;
return false;
}
/**
* Return the element at the current position and move backward the cursor to the previous position available.
*
* @return the previous record found, otherwise the NoSuchElementException exception is thrown when no more records are found.
*/
@SuppressWarnings("unchecked")
@Override
public REC previous() {
checkDirection(false);
if (currentRecord != null) {
try {
return (REC) currentRecord;
} finally {
currentRecord = null;
}
}
// ITERATE UNTIL THE PREVIOUS GOOD RECORD
while (hasPrevious()) {
try {
return (REC) currentRecord;
} finally {
currentRecord = null;
}
}
return null;
}
/**
* Return the element at the current position and move forward the cursor to the next position available.
*
* @return the next record found, otherwise the NoSuchElementException exception is thrown when no more records are found.
*/
@SuppressWarnings("unchecked")
public REC next() {
checkDirection(true);
ORecordInternal<?> record;
// ITERATE UNTIL THE NEXT GOOD RECORD
while (hasNext()) {
// FOUND
if (currentRecord != null) {
try {
return (REC) currentRecord;
} finally {
currentRecord = null;
}
}
record = getTransactionEntry();
if (record != null)
return (REC) record;
}
return null;
}
/**
* Move the iterator to the begin of the range. If no range was specified move to the first record of the cluster.
*
* @return The object itself
*/
@Override
public ORecordIteratorCluster<REC> begin() {
updateRangesOnLiveUpdate();
resetCurrentPosition();
currentRecord = readCurrentRecord(getRecord(), +1);
return this;
}
/**
* Move the iterator to the end of the range. If no range was specified move to the last record of the cluster.
*
* @return The object itself
*/
@Override
public ORecordIteratorCluster<REC> last() {
updateRangesOnLiveUpdate();
resetCurrentPosition();
currentRecord = readCurrentRecord(getRecord(), -1);
return this;
}
/**
* Tell to the iterator that the upper limit must be checked at every cycle. Useful when concurrent deletes or additions change
* the size of the cluster while you're browsing it. Default is false.
*
* @param iLiveUpdated
* True to activate it, otherwise false (default)
* @see #isLiveUpdated()
*/
@Override
public ORecordIteratorCluster<REC> setLiveUpdated(boolean iLiveUpdated) {
super.setLiveUpdated(iLiveUpdated);
// SET THE RANGE LIMITS
if (iLiveUpdated) {
firstClusterEntry = OClusterPositionFactory.INSTANCE.valueOf(0);
lastClusterEntry = OClusterPositionFactory.INSTANCE.getMaxValue();
} else {
OClusterPosition[] range = database.getStorage().getClusterDataRange(current.clusterId);
firstClusterEntry = range[0];
lastClusterEntry = range[1];
}
totalAvailableRecords = database.countClusterElements(current.clusterId, isIterateThroughTombstones());
return this;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_iterator_ORecordIteratorCluster.java
|
828 |
@Entity
@Table(name = "BLC_ORDER_ADJUSTMENT")
@Inheritance(strategy=InheritanceType.JOINED)
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
@AdminPresentationMergeOverrides(
{
@AdminPresentationMergeOverride(name = "", mergeEntries =
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.READONLY,
booleanOverrideValue = true))
}
)
@AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "OrderAdjustmentImpl_baseOrderAdjustment")
public class OrderAdjustmentImpl implements OrderAdjustment, CurrencyCodeIdentifiable {
public static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator= "OrderAdjustmentId")
@GenericGenerator(
name="OrderAdjustmentId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="OrderAdjustmentImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.offer.domain.OrderAdjustmentImpl")
}
)
@Column(name = "ORDER_ADJUSTMENT_ID")
protected Long id;
@ManyToOne(targetEntity = OrderImpl.class)
@JoinColumn(name = "ORDER_ID")
@Index(name="ORDERADJUST_ORDER_INDEX", columnNames={"ORDER_ID"})
@AdminPresentation(excluded = true)
protected Order order;
@ManyToOne(targetEntity = OfferImpl.class, optional=false)
@JoinColumn(name = "OFFER_ID")
@Index(name="ORDERADJUST_OFFER_INDEX", columnNames={"OFFER_ID"})
@AdminPresentation(friendlyName = "OrderAdjustmentImpl_Offer", order=1000,
prominent = true, gridOrder = 1000)
@AdminPresentationToOneLookup()
protected Offer offer;
@Column(name = "ADJUSTMENT_REASON", nullable=false)
@AdminPresentation(friendlyName = "OrderAdjustmentImpl_Order_Adjustment_Reason", order=2000)
protected String reason;
@Column(name = "ADJUSTMENT_VALUE", nullable=false, precision=19, scale=5)
@AdminPresentation(friendlyName = "OrderAdjustmentImpl_Order_Adjustment_Value", order=3000,
fieldType = SupportedFieldType.MONEY, prominent = true,
gridOrder = 2000)
protected BigDecimal value = Money.ZERO.getAmount();
@Override
public void init(Order order, Offer offer, String reason){
this.order = order;
this.offer = offer;
this.reason = reason;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public Order getOrder() {
return order;
}
@Override
public void setOrder(Order order) {
this.order = order;
}
@Override
public Offer getOffer() {
return offer;
}
public void setOffer(Offer offer) {
this.offer = offer;
}
@Override
public String getReason() {
return reason;
}
@Override
public void setReason(String reason) {
this.reason = reason;
}
@Override
public Money getValue() {
return value == null ? null : BroadleafCurrencyUtils.getMoney(value, getOrder().getCurrency());
}
@Override
public void setValue(Money value) {
this.value = value.getAmount();
}
@Override
public String getCurrencyCode() {
if (order.getCurrency() != null) {
return order.getCurrency().getCurrencyCode();
}
return null;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((offer == null) ? 0 : offer.hashCode());
result = prime * result + ((order == null) ? 0 : order.hashCode());
result = prime * result + ((reason == null) ? 0 : reason.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
OrderAdjustmentImpl other = (OrderAdjustmentImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (offer == null) {
if (other.offer != null) {
return false;
}
} else if (!offer.equals(other.offer)) {
return false;
}
if (order == null) {
if (other.order != null) {
return false;
}
} else if (!order.equals(other.order)) {
return false;
}
if (reason == null) {
if (other.reason != null) {
return false;
}
} else if (!reason.equals(other.reason)) {
return false;
}
if (value == null) {
if (other.value != null) {
return false;
}
} else if (!value.equals(other.value)) {
return false;
}
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OrderAdjustmentImpl.java
|
706 |
constructors[TXN_SET_REMOVE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new TxnSetRemoveRequest();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
|
283 |
public class OCommandScriptException extends OException {
private String text;
private int position;
private static final long serialVersionUID = -7430575036316163711L;
public OCommandScriptException(String iMessage) {
super(iMessage, null);
}
public OCommandScriptException(String iMessage, Throwable cause) {
super(iMessage, cause);
}
public OCommandScriptException(String iMessage, String iText, int iPosition, Throwable cause) {
super(iMessage, cause);
text = iText;
position = iPosition < 0 ? 0 : iPosition;
}
public OCommandScriptException(String iMessage, String iText, int iPosition) {
super(iMessage);
text = iText;
position = iPosition < 0 ? 0 : iPosition;
}
@Override
public String getMessage() {
if (text == null)
return super.getMessage();
final StringBuilder buffer = new StringBuilder();
buffer.append("Error on parsing script at position #");
buffer.append(position);
buffer.append(": " + super.getMessage());
buffer.append("\nScript: ");
buffer.append(text);
buffer.append("\n------");
for (int i = 0; i < position - 1; ++i)
buffer.append("-");
buffer.append("^");
return buffer.toString();
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_command_script_OCommandScriptException.java
|
211 |
public class HydratedCacheEventListenerFactory extends CacheEventListenerFactory {
private static HydratedCacheManager manager = null;
@Override
public CacheEventListener createCacheEventListener(Properties props) {
try {
if (props == null || props.isEmpty()) {
manager = EhcacheHydratedCacheManagerImpl.getInstance();
} else {
String managerClass = props.getProperty("managerClass");
Class<?> clazz = Class.forName(managerClass);
Method method = clazz.getDeclaredMethod("getInstance");
manager = (HydratedCacheManager) method.invoke(null);
}
} catch (Exception e) {
throw new RuntimeException("Unable to create a CacheEventListener instance", e);
}
return (CacheEventListener) manager;
}
public static HydratedCacheManager getConfiguredManager() {
return manager;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_cache_engine_HydratedCacheEventListenerFactory.java
|
113 |
HazelcastTestSupport.assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
final NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
assertEquals(remainingSize, stats.getOwnedEntryCount());
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_ClientNearCacheTest.java
|
813 |
@SuppressWarnings("unchecked")
public class OSchemaShared extends ODocumentWrapperNoClass implements OSchema, OCloseable {
private static final long serialVersionUID = 1L;
public static final int CURRENT_VERSION_NUMBER = 4;
private static final String DROP_INDEX_QUERY = "drop index ";
protected Map<String, OClass> classes = new HashMap<String, OClass>();
public OSchemaShared(final int schemaClusterId) {
super(new ODocument());
}
public int countClasses() {
getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ);
return getDatabase().getStorage().callInLock(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return classes.size();
}
}, false);
}
public OClass createClass(final Class<?> iClass) {
final Class<?> superClass = iClass.getSuperclass();
final OClass cls;
if (superClass != null && superClass != Object.class && existsClass(superClass.getSimpleName()))
cls = getClass(superClass.getSimpleName());
else
cls = null;
return createClass(iClass.getSimpleName(), cls, OStorage.CLUSTER_TYPE.PHYSICAL);
}
public OClass createClass(final Class<?> iClass, final int iDefaultClusterId) {
final Class<?> superClass = iClass.getSuperclass();
final OClass cls;
if (superClass != null && superClass != Object.class && existsClass(superClass.getSimpleName()))
cls = getClass(superClass.getSimpleName());
else
cls = null;
return createClass(iClass.getSimpleName(), cls, iDefaultClusterId);
}
public OClass createClass(final String iClassName) {
return createClass(iClassName, null, OStorage.CLUSTER_TYPE.PHYSICAL);
}
public OClass createClass(final String iClassName, final OClass iSuperClass) {
return createClass(iClassName, iSuperClass, OStorage.CLUSTER_TYPE.PHYSICAL);
}
public OClass createClass(final String iClassName, final OClass iSuperClass, final OStorage.CLUSTER_TYPE iType) {
if (getDatabase().getTransaction().isActive())
throw new IllegalStateException("Cannot create class " + iClassName + " inside a transaction");
int clusterId = getDatabase().getClusterIdByName(iClassName);
if (clusterId == -1)
// CREATE A NEW CLUSTER
clusterId = createCluster(iType.toString(), iClassName);
return createClass(iClassName, iSuperClass, clusterId);
}
public OClass createClass(final String iClassName, final int iDefaultClusterId) {
return createClass(iClassName, null, new int[] { iDefaultClusterId });
}
public OClass createClass(final String iClassName, final OClass iSuperClass, final int iDefaultClusterId) {
return createClass(iClassName, iSuperClass, new int[] { iDefaultClusterId });
}
public OClass getOrCreateClass(final String iClassName) {
return getOrCreateClass(iClassName, null);
}
public OClass getOrCreateClass(final String iClassName, final OClass iSuperClass) {
return getDatabase().getStorage().callInLock(new Callable<OClass>() {
@Override
public OClass call() throws Exception {
OClass cls = classes.get(iClassName.toLowerCase());
if (cls == null)
cls = createClass(iClassName, iSuperClass);
else if (iSuperClass != null && !cls.isSubClassOf(iSuperClass))
throw new IllegalArgumentException("Class '" + iClassName + "' is not an instance of " + iSuperClass.getShortName());
return cls;
}
}, true);
}
@Override
public OClass createAbstractClass(final Class<?> iClass) {
final Class<?> superClass = iClass.getSuperclass();
final OClass cls;
if (superClass != null && superClass != Object.class && existsClass(superClass.getSimpleName()))
cls = getClass(superClass.getSimpleName());
else
cls = null;
return createClass(iClass.getSimpleName(), cls, -1);
}
@Override
public OClass createAbstractClass(final String iClassName) {
return createClass(iClassName, null, -1);
}
@Override
public OClass createAbstractClass(final String iClassName, final OClass iSuperClass) {
return createClass(iClassName, iSuperClass, -1);
}
private int createCluster(String iType, String iClassName) {
return getDatabase().command(new OCommandSQL("create cluster " + iClassName + " " + iType)).<Integer> execute();
}
public OClass createClass(final String iClassName, final OClass iSuperClass, final int[] iClusterIds) {
getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_CREATE);
final String key = iClassName.toLowerCase();
return getDatabase().getStorage().callInLock(new Callable<OClass>() {
@Override
public OClass call() throws Exception {
if (classes.containsKey(key))
throw new OSchemaException("Class " + iClassName + " already exists in current database");
final StringBuilder cmd = new StringBuilder("create class ");
cmd.append(iClassName);
if (iSuperClass != null) {
cmd.append(" extends ");
cmd.append(iSuperClass.getName());
}
if (iClusterIds != null) {
if (iClusterIds.length == 1 && iClusterIds[0] == -1)
cmd.append(" abstract");
else {
cmd.append(" cluster ");
for (int i = 0; i < iClusterIds.length; ++i) {
if (i > 0)
cmd.append(',');
else
cmd.append(' ');
cmd.append(iClusterIds[i]);
}
}
}
getDatabase().command(new OCommandSQL(cmd.toString())).execute();
if (!(getDatabase().getStorage() instanceof OStorageEmbedded))
getDatabase().reload();
if (classes.containsKey(key))
return classes.get(key);
else
// ADD IT LOCALLY AVOIDING TO RELOAD THE ENTIRE SCHEMA
createClassInternal(iClassName, iSuperClass, iClusterIds);
return classes.get(key);
}
}, true);
}
public OClass createClassInternal(final String iClassName, final OClass superClass, final int[] iClusterIds) {
if (iClassName == null || iClassName.length() == 0)
throw new OSchemaException("Found class name null");
final Character wrongCharacter = checkNameIfValid(iClassName);
if (wrongCharacter != null)
throw new OSchemaException("Found invalid class name. Character '" + wrongCharacter + "' cannot be used in class name.");
final ODatabaseRecord database = getDatabase();
final int[] clusterIds;
if (iClusterIds == null || iClusterIds.length == 0)
// CREATE A NEW CLUSTER
clusterIds = new int[] { database.addCluster(CLUSTER_TYPE.PHYSICAL.toString(), iClassName, null, null) };
else
clusterIds = iClusterIds;
database.checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_CREATE);
final String key = iClassName.toLowerCase();
final OSchemaShared me = this;
return getDatabase().getStorage().callInLock(new Callable<OClass>() {
@Override
public OClass call() throws Exception {
if (classes.containsKey(key))
throw new OSchemaException("Class " + iClassName + " already exists in current database");
final OClassImpl cls = new OClassImpl(me, iClassName, clusterIds);
classes.put(key, cls);
if (cls.getShortName() != null)
// BIND SHORT NAME TOO
classes.put(cls.getShortName().toLowerCase(), cls);
if (superClass != null) {
cls.setSuperClassInternal(superClass);
// UPDATE INDEXES
final int[] clustersToIndex = superClass.getPolymorphicClusterIds();
final String[] clusterNames = new String[clustersToIndex.length];
for (int i = 0; i < clustersToIndex.length; i++)
clusterNames[i] = database.getClusterNameById(clustersToIndex[i]);
for (OIndex<?> index : superClass.getIndexes())
for (String clusterName : clusterNames)
if (clusterName != null)
database.getMetadata().getIndexManager().addClusterToIndex(clusterName, index.getName());
}
return cls;
}
}, true);
}
public static Character checkNameIfValid(String iName) {
if (iName == null)
throw new IllegalArgumentException("Name is null");
iName = iName.trim();
final int nameSize = iName.length();
if (nameSize == 0)
throw new IllegalArgumentException("Name is empty");
for (int i = 0; i < nameSize; ++i) {
final char c = iName.charAt(i);
if (c == ':' || c == ',' || c == ' ')
// INVALID CHARACTER
return c;
}
// for (char c : iName.toCharArray())
// if (!Character.isJavaIdentifierPart(c))
// return c;
return null;
}
/*
* (non-Javadoc)
*
* @see com.orientechnologies.orient.core.metadata.schema.OSchema#dropClass(java.lang.String)
*/
public void dropClass(final String iClassName) {
if (getDatabase().getTransaction().isActive())
throw new IllegalStateException("Cannot drop a class inside a transaction");
if (iClassName == null)
throw new IllegalArgumentException("Class name is null");
getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_DELETE);
final String key = iClassName.toLowerCase();
getDatabase().getStorage().callInLock(new Callable<Object>() {
@Override
public Object call() throws Exception {
final OClass cls = classes.get(key);
if (cls == null)
throw new OSchemaException("Class " + iClassName + " was not found in current database");
if (cls.getBaseClasses().hasNext())
throw new OSchemaException("Class " + iClassName
+ " cannot be dropped because it has sub classes. Remove the dependencies before trying to drop it again");
final StringBuilder cmd = new StringBuilder("drop class ");
cmd.append(iClassName);
Object result = getDatabase().command(new OCommandSQL(cmd.toString())).execute();
if (result instanceof Boolean && (Boolean) result) {
classes.remove(key);
}
getDatabase().reload();
reload();
return null;
}
}, true);
}
public void dropClassInternal(final String iClassName) {
if (getDatabase().getTransaction().isActive())
throw new IllegalStateException("Cannot drop a class inside a transaction");
if (iClassName == null)
throw new IllegalArgumentException("Class name is null");
getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_DELETE);
final String key = iClassName.toLowerCase();
getDatabase().getStorage().callInLock(new Callable<Object>() {
@Override
public Object call() throws Exception {
final OClass cls = classes.get(key);
if (cls == null)
throw new OSchemaException("Class " + iClassName + " was not found in current database");
if (cls.getBaseClasses().hasNext())
throw new OSchemaException("Class " + iClassName
+ " cannot be dropped because it has sub classes. Remove the dependencies before trying to drop it again");
if (cls.getSuperClass() != null) {
// REMOVE DEPENDENCY FROM SUPERCLASS
((OClassImpl) cls.getSuperClass()).removeBaseClassInternal(cls);
}
dropClassIndexes(cls);
classes.remove(key);
if (cls.getShortName() != null)
// REMOVE THE ALIAS TOO
classes.remove(cls.getShortName().toLowerCase());
return null;
}
}, true);
}
private void dropClassIndexes(final OClass cls) {
for (final OIndex<?> index : getDatabase().getMetadata().getIndexManager().getClassIndexes(cls.getName())) {
getDatabase().command(new OCommandSQL(DROP_INDEX_QUERY + index.getName()));
}
}
/**
* Reloads the schema inside a storage's shared lock.
*/
@Override
public <RET extends ODocumentWrapper> RET reload() {
getDatabase().getStorage().callInLock(new Callable<Object>() {
@Override
public Object call() throws Exception {
reload(null);
return null;
}
}, true);
return (RET) this;
}
public boolean existsClass(final String iClassName) {
return getDatabase().getStorage().callInLock(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return classes.containsKey(iClassName.toLowerCase());
}
}, false);
}
/*
* (non-Javadoc)
*
* @see com.orientechnologies.orient.core.metadata.schema.OSchema#getClass(java.lang.Class)
*/
public OClass getClass(final Class<?> iClass) {
return getClass(iClass.getSimpleName());
}
/*
* (non-Javadoc)
*
* @see com.orientechnologies.orient.core.metadata.schema.OSchema#getClass(java.lang.String)
*/
public OClass getClass(final String iClassName) {
if (iClassName == null)
return null;
OClass cls;
cls = getDatabase().getStorage().callInLock(new Callable<OClass>() {
@Override
public OClass call() throws Exception {
return classes.get(iClassName.toLowerCase());
}
}, false);
if (cls == null && getDatabase().getDatabaseOwner() instanceof ODatabaseObject) {
cls = getDatabase().getStorage().callInLock(new Callable<OClass>() {
@Override
public OClass call() throws Exception {
OClass cls = classes.get(iClassName.toLowerCase());
if (cls == null) {
// CHECK IF CAN AUTO-CREATE IT
final ODatabase ownerDb = getDatabase().getDatabaseOwner();
if (ownerDb instanceof ODatabaseObject) {
final Class<?> javaClass = ((ODatabaseObject) ownerDb).getEntityManager().getEntityClass(iClassName);
if (javaClass != null) {
// AUTO REGISTER THE CLASS AT FIRST USE
cls = cascadeCreate(javaClass);
}
}
}
return cls;
}
}, true);
}
return cls;
}
public void changeClassName(final String iOldName, final String iNewName) {
getDatabase().getStorage().callInLock(new Callable<Object>() {
@Override
public Object call() throws Exception {
final OClass clazz = classes.remove(iOldName.toLowerCase());
classes.put(iNewName.toLowerCase(), clazz);
return null;
}
}, true);
}
/**
* Binds ODocument to POJO.
*/
@Override
public void fromStream() {
final OSchemaShared me = this;
getDatabase().getStorage().callInLock(new Callable<Object>() {
@Override
public Object call() throws Exception {
// READ CURRENT SCHEMA VERSION
final Integer schemaVersion = (Integer) document.field("schemaVersion");
if (schemaVersion == null) {
OLogManager
.instance()
.error(
this,
"Database's schema is empty! Recreating the system classes and allow the opening of the database but double check the integrity of the database");
return null;
} else if (schemaVersion.intValue() != CURRENT_VERSION_NUMBER) {
// HANDLE SCHEMA UPGRADE
throw new OConfigurationException(
"Database schema is different. Please export your old database with the previous version of OrientDB and reimport it using the current one.");
}
// REGISTER ALL THE CLASSES
classes.clear();
OClassImpl cls;
Collection<ODocument> storedClasses = document.field("classes");
for (ODocument c : storedClasses) {
cls = new OClassImpl(me, c);
cls.fromStream();
classes.put(cls.getName().toLowerCase(), cls);
if (cls.getShortName() != null)
classes.put(cls.getShortName().toLowerCase(), cls);
}
// REBUILD THE INHERITANCE TREE
String superClassName;
OClass superClass;
for (ODocument c : storedClasses) {
superClassName = c.field("superClass");
if (superClassName != null) {
// HAS A SUPER CLASS
cls = (OClassImpl) classes.get(((String) c.field("name")).toLowerCase());
superClass = classes.get(superClassName.toLowerCase());
if (superClass == null)
throw new OConfigurationException("Super class '" + superClassName + "' was declared in class '" + cls.getName()
+ "' but was not found in schema. Remove the dependency or create the class to continue.");
cls.setSuperClassInternal(superClass);
}
}
return null;
}
}, true);
}
/**
* Binds POJO to ODocument.
*/
@Override
@OBeforeSerialization
public ODocument toStream() {
return getDatabase().getStorage().callInLock(new Callable<ODocument>() {
@Override
public ODocument call() throws Exception {
document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
try {
document.field("schemaVersion", CURRENT_VERSION_NUMBER);
Set<ODocument> cc = new HashSet<ODocument>();
for (OClass c : classes.values())
cc.add(((OClassImpl) c).toStream());
document.field("classes", cc, OType.EMBEDDEDSET);
} finally {
document.setInternalStatus(ORecordElement.STATUS.LOADED);
}
return document;
}
}, false);
}
public Collection<OClass> getClasses() {
getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ);
return getDatabase().getStorage().callInLock(new Callable<Collection<OClass>>() {
@Override
public HashSet<OClass> call() throws Exception {
return new HashSet<OClass>(classes.values());
}
}, false);
}
@Override
public Set<OClass> getClassesRelyOnCluster(final String iClusterName) {
getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ);
return getDatabase().getStorage().callInLock(new Callable<Set<OClass>>() {
@Override
public Set<OClass> call() throws Exception {
final int clusterId = getDatabase().getClusterIdByName(iClusterName);
final Set<OClass> result = new HashSet<OClass>();
for (OClass c : classes.values()) {
if (OArrays.contains(c.getPolymorphicClusterIds(), clusterId))
result.add(c);
}
return result;
}
}, false);
}
@Override
public OSchemaShared load() {
getDatabase().getStorage().callInLock(new Callable<Object>() {
@Override
public Object call() throws Exception {
getDatabase();
((ORecordId) document.getIdentity()).fromString(getDatabase().getStorage().getConfiguration().schemaRecordId);
reload("*:-1 index:0");
return null;
}
}, true);
return this;
}
public void create() {
final ODatabaseRecord db = getDatabase();
super.save(OMetadataDefault.CLUSTER_INTERNAL_NAME);
db.getStorage().getConfiguration().schemaRecordId = document.getIdentity().toString();
db.getStorage().getConfiguration().update();
}
public void close() {
classes.clear();
document.clear();
}
public void saveInternal() {
final ODatabaseRecord db = getDatabase();
if (db.getTransaction().isActive())
throw new OSchemaException("Cannot change the schema while a transaction is active. Schema changes are not transactional");
db.getStorage().callInLock(new Callable<Object>() {
@Override
public Object call() throws Exception {
saveInternal(OMetadataDefault.CLUSTER_INTERNAL_NAME);
return null;
}
}, true);
}
@Deprecated
public int getVersion() {
return getDatabase().getStorage().callInLock(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return document.getRecordVersion().getCounter();
}
}, false);
}
public ORID getIdentity() {
return document.getIdentity();
}
/**
* Avoid to handle this by user API.
*/
@Override
public <RET extends ODocumentWrapper> RET save() {
return (RET) this;
}
/**
* Avoid to handle this by user API.
*/
@Override
public <RET extends ODocumentWrapper> RET save(final String iClusterName) {
return (RET) this;
}
public OSchemaShared setDirty() {
document.setDirty();
return this;
}
private OClass cascadeCreate(final Class<?> javaClass) {
final OClassImpl cls = (OClassImpl) createClass(javaClass.getSimpleName());
final Class<?> javaSuperClass = javaClass.getSuperclass();
if (javaSuperClass != null && !javaSuperClass.getName().equals("java.lang.Object")
&& !javaSuperClass.getName().startsWith("com.orientechnologies")) {
OClass superClass = classes.get(javaSuperClass.getSimpleName().toLowerCase());
if (superClass == null)
superClass = cascadeCreate(javaSuperClass);
cls.setSuperClass(superClass);
}
return cls;
}
private ODatabaseRecord getDatabase() {
return ODatabaseRecordThreadLocal.INSTANCE.get();
}
private void saveInternal(final String iClusterName) {
document.setDirty();
for (int retry = 0; retry < 10; retry++)
try {
super.save(OMetadataDefault.CLUSTER_INTERNAL_NAME);
break;
} catch (OConcurrentModificationException e) {
reload(null, true);
}
super.save(OMetadataDefault.CLUSTER_INTERNAL_NAME);
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OSchemaShared.java
|
557 |
public final class AddressHelper {
private static final int MAX_PORT_TRIES = 3;
private static final int INITIAL_FIRST_PORT = 5701;
private AddressHelper() {
}
public static Collection<InetSocketAddress> getSocketAddresses(String address) {
final AddressHolder addressHolder = AddressUtil.getAddressHolder(address, -1);
final String scopedAddress = addressHolder.getScopeId() != null
? addressHolder.getAddress() + "%" + addressHolder.getScopeId()
: addressHolder.getAddress();
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getByName(scopedAddress);
} catch (UnknownHostException ignored) {
Logger.getLogger(AddressHelper.class).finest("Address not available", ignored);
}
return getPossibleSocketAddresses(inetAddress, addressHolder.getPort(), scopedAddress);
}
public static Collection<InetSocketAddress> getPossibleSocketAddresses(
InetAddress inetAddress, int port, String scopedAddress) {
int possiblePort = port;
int portTryCount = 1;
if (possiblePort == -1) {
portTryCount = MAX_PORT_TRIES;
possiblePort = INITIAL_FIRST_PORT;
}
final Collection<InetSocketAddress> socketAddresses = new LinkedList<InetSocketAddress>();
if (inetAddress == null) {
for (int i = 0; i < portTryCount; i++) {
socketAddresses.add(new InetSocketAddress(scopedAddress, possiblePort + i));
}
} else if (inetAddress instanceof Inet4Address) {
for (int i = 0; i < portTryCount; i++) {
socketAddresses.add(new InetSocketAddress(inetAddress, possiblePort + i));
}
} else if (inetAddress instanceof Inet6Address) {
final Collection<Inet6Address> addresses = getPossibleInetAddressesFor((Inet6Address) inetAddress);
for (Inet6Address inet6Address : addresses) {
for (int i = 0; i < portTryCount; i++) {
socketAddresses.add(new InetSocketAddress(inet6Address, possiblePort + i));
}
}
}
return socketAddresses;
}
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_util_AddressHelper.java
|
49 |
public interface DoubleByDoubleToDouble { double apply(double a, double b); }
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
620 |
public class NullBroadleafSiteResolver implements BroadleafSiteResolver {
@Override
public Site resolveSite(HttpServletRequest request) {
return resolveSite(new ServletWebRequest(request));
}
@Override
public Site resolveSite(WebRequest request) {
return null;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_web_NullBroadleafSiteResolver.java
|
9 |
private class HTTPCommunicator {
final HazelcastInstance instance;
final String address;
HTTPCommunicator(HazelcastInstance instance) {
this.instance = instance;
this.address = "http:/" + instance.getCluster().getLocalMember().getInetSocketAddress().toString() + "/hazelcast/rest/";
}
public String poll(String queueName, long timeout) {
String url = address + "queues/" + queueName + "/" + String.valueOf(timeout);
String result = doGet(url);
return result;
}
public int size(String queueName) {
String url = address + "queues/" + queueName + "/size";
Integer result = Integer.parseInt(doGet(url));
return result;
}
public int offer(String queueName, String data) throws IOException {
String url = address + "queues/" + queueName;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
/** post the data */
OutputStream out = null;
out = urlConnection.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(data);
writer.close();
out.close();
return urlConnection.getResponseCode();
}
public String get(String mapName, String key) {
String url = address + "maps/" + mapName + "/" + key;
String result = doGet(url);
return result;
}
public int put(String mapName, String key, String value) throws IOException {
String url = address + "maps/" + mapName + "/" + key;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
/** post the data */
OutputStream out = urlConnection.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(value);
writer.close();
out.close();
return urlConnection.getResponseCode();
}
public int deleteAll(String mapName) throws IOException {
String url = address + "maps/" + mapName;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("DELETE");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
return urlConnection.getResponseCode();
}
public int delete(String mapName, String key) throws IOException {
String url = address + "maps/" + mapName + "/" + key;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("DELETE");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
return urlConnection.getResponseCode();
}
private String doGet(final String url) {
String result = null;
try {
HttpURLConnection httpUrlConnection = (HttpURLConnection) (new URL(url)).openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
StringBuilder data = new StringBuilder(150);
String line;
while ((line = rd.readLine()) != null) data.append(line);
rd.close();
result = data.toString();
httpUrlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
| 0true
|
hazelcast_src_test_java_com_hazelcast_ascii_RestTest.java
|
1,101 |
@SuppressWarnings("serial")
public class AboutLicensesDialog extends JDialog {
private static ImageIcon mctLogoIcon = new ImageIcon(ClassLoader.getSystemResource("images/mctlogo.png"));
public AboutLicensesDialog(JFrame frame) {
super(frame);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Image image = mctLogoIcon.getImage().getScaledInstance(320, 80, Image.SCALE_SMOOTH);
JLabel label = new JLabel(new ImageIcon(image));
JPanel labelPanel = new JPanel();
labelPanel.setBackground(Color.white);
labelPanel.add(label, BorderLayout.CENTER);
labelPanel.setBorder(new EmptyBorder(5,5,5,5));
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(labelPanel, BorderLayout.NORTH);
// Modified the AboutDialog to add the Version and Build numbers to the screen - JOe...
JTextArea license = new JTextArea(100, 100);
license.setText("Mission Control Technologies, Copyright (c) 2009-2012, United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All rights reserved.\n\nThe MCT platform is licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this application except in compliance with the License. You may obtain a copy of the License at\nhttp://www.apache.org/licenses/LICENSE-2.0.\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\nMCT includes source code licensed under additional open source licenses, as described below. See the MCT Open Source Licenses file included with this distribution for additional information.\n\n\u2022 Apache Ant, Apache Batik, Apache Commons Collection, Apache Commons Codec, Apache Derby, Apache Felix, and Apache log4j are Copyright (c) 1999-2012, the Apache Software Foundation. Licensed under the Apache 2.0 license.\nhttp://www.apache.org/licenses/LICENSE-2.0\n\n\u2022 ANTR 3 is Copyright (c) 2010 Terence Parr. All rights reserved. Licensed under the ANTR 3 BSD license.\nhttp://www.antlr.org/license.html\n\n\u2022 Hibernate, c3po, dom4j, javassist, and Java Transaction API are Copyright (c) 2001-2012 by Red Hat, Inc. All rights reserved. Licensed under the GNU Lesser General Public License.\nhttp://olex.openlogic.com/licenses/lgpl-v2_1-license\n\n\u2022 MySQL is Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. Licensed under the GNU General Public License.\nhttp://www.gnu.org/licenses/gpl.html.\n\n\u2022 Oracle Berkeley DB Java Edition is Copyright (c) 2002, 2012 Oracle and/or its affiliates. All rights reserved.\nLicensed under the Open Source License for Oracle Berkeley DB Java Edition.\nhttp://www.oracle.com/technetwork/database/berkeleydb/downloads/jeoslicense-086837.html\n\n\u2022 slf4j is Copyright (c) 2004-2011 QOS.ch All rights reserved. Licensed under the MIT license.\nhttp://www.slf4j.org/license.html");
license.setLineWrap(true);
license.setWrapStyleWord(true);
license.setEditable(false);
JPanel licensePanel = new JPanel(new GridLayout(0, 1));
licensePanel.add(license);
licensePanel.setBackground(Color.white);
licensePanel.setBorder(BorderFactory.createEmptyBorder(20,40, 20, 40));
contentPane.add(licensePanel, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.setBackground(Color.white);
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AboutLicensesDialog.this.setVisible(false);
}
});
panel.add(close);
contentPane.add(panel, BorderLayout.SOUTH);
setBackground(Color.WHITE);
setSize(800, 730);
setResizable(false);
setLocationRelativeTo(frame);
setTitle("About MCT Licenses");
}
public static String getBuildNumber() {
String buildnumber = "Not Found";
try {
Properties p = new Properties();
p.load(ClassLoader.getSystemResourceAsStream("properties/version.properties"));
buildnumber = p.getProperty("build.number");
} catch (Exception e) {
// if not found, just ignore any exceptions - it's not critical...
}
return buildnumber;
}
}
| 1no label
|
platform_src_main_java_gov_nasa_arc_mct_gui_dialogs_AboutLicensesDialog.java
|
120 |
archivePageTemplate.send(archivePageDestination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(basePageKey);
}
});
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_message_jms_JMSArchivedPagePublisher.java
|
123 |
client.getLifecycleService().addLifecycleListener(new LifecycleListener() {
@Override
public void stateChanged(LifecycleEvent event) {
connectedLatch.countDown();
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_ClientReconnectTest.java
|
1,292 |
clusterService.submitStateUpdateTask("test", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return true;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
allNodesAcked.set(true);
latch.countDown();
}
@Override
public void onAckTimeout() {
ackTimeout.set(true);
latch.countDown();
}
@Override
public TimeValue ackTimeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public TimeValue timeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
processedLatch.countDown();
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
executed.set(true);
return ClusterState.builder(currentState).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("failed to execute callback in test {}", t, source);
onFailure.set(true);
latch.countDown();
}
});
| 0true
|
src_test_java_org_elasticsearch_cluster_ClusterServiceTests.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.