Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
151 | systemConfig = getGlobalConfiguration(new BackendOperation.TransactionalProvider() {
@Override
public StoreTransaction openTx() throws BackendException {
return storeManagerLocking.beginTransaction(StandardBaseTransactionConfig.of(
configuration.get(TIMESTAMP_PROVIDER),
storeFeatures.getKeyConsistentTxConfig()));
}
@Override
public void close() throws BackendException {
//Do nothing, storeManager is closed explicitly by Backend
}
},systemConfigStore,configuration); | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java |
1,194 | public interface PaymentInfoService {
public PaymentInfo save(PaymentInfo paymentInfo);
public PaymentResponseItem save(PaymentResponseItem paymentResponseItem);
public PaymentLog save(PaymentLog log);
public PaymentInfo readPaymentInfoById(Long paymentId);
public List<PaymentInfo> readPaymentInfosForOrder(Order order);
public PaymentInfo create();
public void delete(PaymentInfo paymentInfo);
public PaymentResponseItem createResponseItem();
public PaymentLog createLog();
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_PaymentInfoService.java |
262 | @Category(SerialTests.class)
public class EmbeddedLogTest extends KCVSLogTest {
@BeforeClass
public static void startCassandra() {
CassandraStorageSetup.startCleanEmbedded();
}
@Override
public KeyColumnValueStoreManager openStorageManager() throws BackendException {
return new CassandraEmbeddedStoreManager(CassandraStorageSetup.getEmbeddedConfiguration(getClass().getSimpleName()));
}
} | 0true
| titan-cassandra_src_test_java_com_thinkaurelius_titan_diskstorage_cassandra_embedded_EmbeddedLogTest.java |
2,102 | public abstract class StreamInput extends InputStream {
private static final ThreadLocal<SoftReference<char[]>> charCache = new ThreadLocal<SoftReference<char[]>>();
private static char[] charCache(int size) {
SoftReference<char[]> ref = charCache.get();
char[] arr = (ref == null) ? null : ref.get();
if (arr == null || arr.length < size) {
arr = new char[ArrayUtil.oversize(size, RamUsageEstimator.NUM_BYTES_CHAR)];
charCache.set(new SoftReference<char[]>(arr));
}
return arr;
}
private Version version = Version.CURRENT;
public Version getVersion() {
return this.version;
}
public StreamInput setVersion(Version version) {
this.version = version;
return this;
}
/**
* Reads and returns a single byte.
*/
public abstract byte readByte() throws IOException;
/**
* Reads a specified number of bytes into an array at the specified offset.
*
* @param b the array to read bytes into
* @param offset the offset in the array to start storing bytes
* @param len the number of bytes to read
*/
public abstract void readBytes(byte[] b, int offset, int len) throws IOException;
/**
* Reads a bytes reference from this stream, might hold an actual reference to the underlying
* bytes of the stream.
*/
public BytesReference readBytesReference() throws IOException {
int length = readVInt();
return readBytesReference(length);
}
/**
* Reads a bytes reference from this stream, might hold an actual reference to the underlying
* bytes of the stream.
*/
public BytesReference readBytesReference(int length) throws IOException {
if (length == 0) {
return BytesArray.EMPTY;
}
byte[] bytes = new byte[length];
readBytes(bytes, 0, length);
return new BytesArray(bytes, 0, length);
}
public BytesRef readBytesRef() throws IOException {
int length = readVInt();
return readBytesRef(length);
}
public BytesRef readBytesRef(int length) throws IOException {
if (length == 0) {
return new BytesRef();
}
byte[] bytes = new byte[length];
readBytes(bytes, 0, length);
return new BytesRef(bytes, 0, length);
}
public void readFully(byte[] b) throws IOException {
readBytes(b, 0, b.length);
}
public short readShort() throws IOException {
return (short) (((readByte() & 0xFF) << 8) | (readByte() & 0xFF));
}
/**
* Reads four bytes and returns an int.
*/
public int readInt() throws IOException {
return ((readByte() & 0xFF) << 24) | ((readByte() & 0xFF) << 16)
| ((readByte() & 0xFF) << 8) | (readByte() & 0xFF);
}
/**
* Reads an int stored in variable-length format. Reads between one and
* five bytes. Smaller values take fewer bytes. Negative numbers
* will always use all 5 bytes and are therefore better serialized
* using {@link #readInt}
*/
public int readVInt() throws IOException {
byte b = readByte();
int i = b & 0x7F;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
i |= (b & 0x7F) << 7;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
i |= (b & 0x7F) << 14;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
i |= (b & 0x7F) << 21;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
assert (b & 0x80) == 0;
return i | ((b & 0x7F) << 28);
}
/**
* Reads eight bytes and returns a long.
*/
public long readLong() throws IOException {
return (((long) readInt()) << 32) | (readInt() & 0xFFFFFFFFL);
}
/**
* Reads a long stored in variable-length format. Reads between one and
* nine bytes. Smaller values take fewer bytes. Negative numbers are not
* supported.
*/
public long readVLong() throws IOException {
byte b = readByte();
long i = b & 0x7FL;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
i |= (b & 0x7FL) << 7;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
i |= (b & 0x7FL) << 14;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
i |= (b & 0x7FL) << 21;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
i |= (b & 0x7FL) << 28;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
i |= (b & 0x7FL) << 35;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
i |= (b & 0x7FL) << 42;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
i |= (b & 0x7FL) << 49;
if ((b & 0x80) == 0) {
return i;
}
b = readByte();
assert (b & 0x80) == 0;
return i | ((b & 0x7FL) << 56);
}
@Nullable
public Text readOptionalText() throws IOException {
int length = readInt();
if (length == -1) {
return null;
}
return new StringAndBytesText(readBytesReference(length));
}
public Text readText() throws IOException {
// use StringAndBytes so we can cache the string if its ever converted to it
int length = readInt();
return new StringAndBytesText(readBytesReference(length));
}
public Text[] readTextArray() throws IOException {
int size = readVInt();
if (size == 0) {
return StringText.EMPTY_ARRAY;
}
Text[] ret = new Text[size];
for (int i = 0; i < size; i++) {
ret[i] = readText();
}
return ret;
}
public Text readSharedText() throws IOException {
return readText();
}
@Nullable
public String readOptionalString() throws IOException {
if (readBoolean()) {
return readString();
}
return null;
}
@Nullable
public String readOptionalSharedString() throws IOException {
if (readBoolean()) {
return readSharedString();
}
return null;
}
public String readString() throws IOException {
int charCount = readVInt();
char[] chars = charCache(charCount);
int c, charIndex = 0;
while (charIndex < charCount) {
c = readByte() & 0xff;
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
chars[charIndex++] = (char) c;
break;
case 12:
case 13:
chars[charIndex++] = (char) ((c & 0x1F) << 6 | readByte() & 0x3F);
break;
case 14:
chars[charIndex++] = (char) ((c & 0x0F) << 12 | (readByte() & 0x3F) << 6 | (readByte() & 0x3F) << 0);
break;
}
}
return new String(chars, 0, charCount);
}
public String readSharedString() throws IOException {
return readString();
}
public final float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
public final double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
/**
* Reads a boolean.
*/
public final boolean readBoolean() throws IOException {
return readByte() != 0;
}
@Nullable
public final Boolean readOptionalBoolean() throws IOException {
byte val = readByte();
if (val == 2) {
return null;
}
if (val == 1) {
return true;
}
return false;
}
/**
* Resets the stream.
*/
public abstract void reset() throws IOException;
/**
* Closes the stream to further operations.
*/
public abstract void close() throws IOException;
// // IS
//
// @Override public int read() throws IOException {
// return readByte();
// }
//
// // Here, we assume that we always can read the full byte array
//
// @Override public int read(byte[] b, int off, int len) throws IOException {
// readBytes(b, off, len);
// return len;
// }
public String[] readStringArray() throws IOException {
int size = readVInt();
if (size == 0) {
return Strings.EMPTY_ARRAY;
}
String[] ret = new String[size];
for (int i = 0; i < size; i++) {
ret[i] = readString();
}
return ret;
}
@Nullable
public Map<String, Object> readMap() throws IOException {
return (Map<String, Object>) readGenericValue();
}
@SuppressWarnings({"unchecked"})
@Nullable
public Object readGenericValue() throws IOException {
byte type = readByte();
switch (type) {
case -1:
return null;
case 0:
return readString();
case 1:
return readInt();
case 2:
return readLong();
case 3:
return readFloat();
case 4:
return readDouble();
case 5:
return readBoolean();
case 6:
int bytesSize = readVInt();
byte[] value = new byte[bytesSize];
readBytes(value, 0, bytesSize);
return value;
case 7:
int size = readVInt();
List list = new ArrayList(size);
for (int i = 0; i < size; i++) {
list.add(readGenericValue());
}
return list;
case 8:
int size8 = readVInt();
Object[] list8 = new Object[size8];
for (int i = 0; i < size8; i++) {
list8[i] = readGenericValue();
}
return list8;
case 9:
int size9 = readVInt();
Map map9 = new LinkedHashMap(size9);
for (int i = 0; i < size9; i++) {
map9.put(readSharedString(), readGenericValue());
}
return map9;
case 10:
int size10 = readVInt();
Map map10 = new HashMap(size10);
for (int i = 0; i < size10; i++) {
map10.put(readSharedString(), readGenericValue());
}
return map10;
case 11:
return readByte();
case 12:
return new Date(readLong());
case 13:
return new DateTime(readLong());
case 14:
return readBytesReference();
case 15:
return readText();
case 16:
return readShort();
case 17:
return readPrimitiveIntArray();
case 18:
return readPrimitiveLongArray();
case 19:
return readPrimitiveFloatArray();
case 20:
return readPrimitiveDoubleArray();
default:
throw new IOException("Can't read unknown type [" + type + "]");
}
}
private Object readPrimitiveIntArray() throws IOException {
int length = readVInt();
int[] values = new int[length];
for(int i=0; i<length; i++) {
values[i] = readInt();
}
return values;
}
private Object readPrimitiveLongArray() throws IOException {
int length = readVInt();
long[] values = new long[length];
for(int i=0; i<length; i++) {
values[i] = readLong();
}
return values;
}
private Object readPrimitiveFloatArray() throws IOException {
int length = readVInt();
float[] values = new float[length];
for(int i=0; i<length; i++) {
values[i] = readFloat();
}
return values;
}
private Object readPrimitiveDoubleArray() throws IOException {
int length = readVInt();
double[] values = new double[length];
for(int i=0; i<length; i++) {
values[i] = readDouble();
}
return values;
}
/**
* Serializes a potential null value.
*/
public <T extends Streamable> T readOptionalStreamable(T streamable) throws IOException {
if (readBoolean()) {
streamable.readFrom(this);
return streamable;
} else {
return null;
}
}
} | 0true
| src_main_java_org_elasticsearch_common_io_stream_StreamInput.java |
3,570 | public static class Builder extends NumberFieldMapper.Builder<Builder, DateFieldMapper> {
protected TimeUnit timeUnit = Defaults.TIME_UNIT;
protected String nullValue = Defaults.NULL_VALUE;
protected FormatDateTimeFormatter dateTimeFormatter = Defaults.DATE_TIME_FORMATTER;
private Locale locale;
public Builder(String name) {
super(name, new FieldType(Defaults.FIELD_TYPE));
builder = this;
// do *NOT* rely on the default locale
locale = Locale.ROOT;
}
public Builder timeUnit(TimeUnit timeUnit) {
this.timeUnit = timeUnit;
return this;
}
public Builder nullValue(String nullValue) {
this.nullValue = nullValue;
return this;
}
public Builder dateTimeFormatter(FormatDateTimeFormatter dateTimeFormatter) {
this.dateTimeFormatter = dateTimeFormatter;
return this;
}
@Override
public DateFieldMapper build(BuilderContext context) {
boolean roundCeil = Defaults.ROUND_CEIL;
if (context.indexSettings() != null) {
Settings settings = context.indexSettings();
roundCeil = settings.getAsBoolean("index.mapping.date.round_ceil", settings.getAsBoolean("index.mapping.date.parse_upper_inclusive", Defaults.ROUND_CEIL));
}
fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f);
if (!locale.equals(dateTimeFormatter.locale())) {
dateTimeFormatter = new FormatDateTimeFormatter(dateTimeFormatter.format(), dateTimeFormatter.parser(), dateTimeFormatter.printer(), locale);
}
DateFieldMapper fieldMapper = new DateFieldMapper(buildNames(context), dateTimeFormatter,
precisionStep, boost, fieldType, docValues, nullValue, timeUnit, roundCeil, ignoreMalformed(context), coerce(context),
postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, context.indexSettings(),
multiFieldsBuilder.build(this, context), copyTo);
fieldMapper.includeInAll(includeInAll);
return fieldMapper;
}
public Builder locale(Locale locale) {
this.locale = locale;
return this;
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_core_DateFieldMapper.java |
425 | public class IndexQuery extends BaseQuery implements BackendQuery<IndexQuery> {
public static final ImmutableList<OrderEntry> NO_ORDER = ImmutableList.of();
private final String store;
private final Condition condition;
private final ImmutableList<OrderEntry> orders;
private final int hashcode;
public IndexQuery(String store, Condition condition, ImmutableList<OrderEntry> orders, int limit) {
super(limit);
Preconditions.checkNotNull(store);
Preconditions.checkNotNull(condition);
Preconditions.checkArgument(orders != null);
Preconditions.checkArgument(QueryUtil.isQueryNormalForm(condition));
this.condition = condition;
this.orders = orders;
this.store = store;
this.hashcode = new HashCodeBuilder().append(condition).append(store).append(orders).append(limit).toHashCode();
}
public IndexQuery(String store, Condition condition, ImmutableList<OrderEntry> orders) {
this(store, condition, orders, Query.NO_LIMIT);
}
public IndexQuery(String store, Condition condition) {
this(store, condition, NO_ORDER, Query.NO_LIMIT);
}
public IndexQuery(String store, Condition condition, int limit) {
this(store, condition, NO_ORDER, limit);
}
public Condition<TitanElement> getCondition() {
return condition;
}
public List<OrderEntry> getOrder() {
return orders;
}
public String getStore() {
return store;
}
@Override
public IndexQuery setLimit(int limit) {
throw new UnsupportedOperationException();
}
@Override
public IndexQuery updateLimit(int newLimit) {
return new IndexQuery(store, condition, orders, newLimit);
}
@Override
public int hashCode() {
return hashcode;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
else if (other == null) return false;
else if (!getClass().isInstance(other)) return false;
IndexQuery oth = (IndexQuery) other;
return store.equals(oth.store) && orders.equals(oth.orders)
&& condition.equals(oth.condition) && getLimit() == oth.getLimit();
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("[").append(condition.toString()).append("]");
if (!orders.isEmpty()) b.append(orders);
if (hasLimit()) b.append("(").append(getLimit()).append(")");
b.append(":").append(store);
return b.toString();
}
public static class OrderEntry {
private final String key;
private final Order order;
private final Class<?> datatype;
public OrderEntry(String key, Order order, Class<?> datatype) {
Preconditions.checkNotNull(key);
Preconditions.checkNotNull(order);
Preconditions.checkNotNull(datatype);
this.key = key;
this.order = order;
this.datatype = datatype;
}
public String getKey() {
return key;
}
public Order getOrder() {
return order;
}
public Class<?> getDatatype() {
return datatype;
}
@Override
public int hashCode() {
return key.hashCode() * 4021 + order.hashCode();
}
@Override
public boolean equals(Object oth) {
if (this == oth) return true;
else if (oth == null) return false;
else if (!getClass().isInstance(oth)) return false;
OrderEntry o = (OrderEntry) oth;
return key.equals(o.key) && order == o.order;
}
@Override
public String toString() {
return order + "(" + key + ")";
}
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexQuery.java |
89 | RenameRefactoring refactoring = new RenameRefactoring(editor) {
@Override
public String getName() {
return "Convert method to getter";
};
@Override
protected void renameNode(TextChange tfc, Node node, Tree.CompilationUnit root) {
Integer startIndex = null;
Integer stopIndex = null;
if (node instanceof Tree.AnyMethod) {
ParameterList parameterList = ((Tree.AnyMethod) node).getParameterLists().get(0);
startIndex = parameterList.getStartIndex();
stopIndex = parameterList.getStopIndex();
} else {
FindInvocationVisitor fiv = new FindInvocationVisitor(node);
fiv.visit(root);
if (fiv.result != null && fiv.result.getPrimary() == node) {
startIndex = fiv.result.getPositionalArgumentList().getStartIndex();
stopIndex = fiv.result.getPositionalArgumentList().getStopIndex();
}
}
if (startIndex != null && stopIndex != null) {
tfc.addEdit(new DeleteEdit(startIndex, stopIndex - startIndex + 1));
}
}
}; | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertMethodToGetterProposal.java |
220 | }, SERIALIZABLE {
@Override
void configure(TransactionConfig cfg) {
cfg.setSerializableIsolation(true);
}
}; | 0true
| titan-berkeleyje_src_main_java_com_thinkaurelius_titan_diskstorage_berkeleyje_BerkeleyJEStoreManager.java |
1,417 | new OProfilerHookValue() {
public Object getValue() {
return metricReceivedBytes;
}
}, dictProfilerMetric + ".receivedBytes"); | 0true
| enterprise_src_main_java_com_orientechnologies_orient_enterprise_channel_OChannel.java |
1,123 | public class WanTargetClusterConfig {
String groupName = "dev";
String groupPassword = "dev-pass";
String replicationImpl;
Object replicationImplObject;
List<String> endpoints; // ip:port
public String getGroupName() {
return groupName;
}
public WanTargetClusterConfig setGroupName(String groupName) {
this.groupName = groupName;
return this;
}
public String getGroupPassword() {
return groupPassword;
}
public WanTargetClusterConfig setGroupPassword(String groupPassword) {
this.groupPassword = groupPassword;
return this;
}
public List<String> getEndpoints() {
return endpoints;
}
public WanTargetClusterConfig setEndpoints(List<String> list) {
endpoints = list;
return this;
}
public WanTargetClusterConfig addEndpoint(String address) {
if (endpoints == null) {
endpoints = new ArrayList<String>(2);
}
endpoints.add(address);
return this;
}
public String getReplicationImpl() {
return replicationImpl;
}
public WanTargetClusterConfig setReplicationImpl(String replicationImpl) {
this.replicationImpl = replicationImpl;
return this;
}
public Object getReplicationImplObject() {
return replicationImplObject;
}
public WanTargetClusterConfig setReplicationImplObject(Object replicationImplObject) {
this.replicationImplObject = replicationImplObject;
return this;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("WanTargetClusterConfig");
sb.append("{groupName='").append(groupName).append('\'');
sb.append(", replicationImpl='").append(replicationImpl).append('\'');
sb.append(", replicationImplObject=").append(replicationImplObject);
sb.append(", endpoints=").append(endpoints);
sb.append('}');
return sb.toString();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_config_WanTargetClusterConfig.java |
190 | new ThreadLocal<ThreadLocalRandom>() {
protected ThreadLocalRandom initialValue() {
return new ThreadLocalRandom();
}
}; | 0true
| src_main_java_jsr166y_ThreadLocalRandom.java |
467 | static class TrySemaphoreThread extends SemaphoreTestThread{
public TrySemaphoreThread(ISemaphore semaphore, AtomicInteger upTotal, AtomicInteger downTotal){
super(semaphore, upTotal, downTotal);
}
public void iterativelyRun() throws Exception{
if(semaphore.tryAcquire()){
work();
semaphore.release();
}
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_semaphore_ClientSemaphoreThreadedTest.java |
816 | 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); | 0true
| core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OSchemaShared.java |
1,655 | public class OQueryExecutorsFactory {
public static final OQueryExecutorsFactory INSTANCE = new OQueryExecutorsFactory();
private static final Set<Class> ALWAYS_DISTRIBUTABLE = new HashSet<Class>(Arrays.<Class> asList(
OCommandExecutorSQLCreateClass.class,// int
OCommandExecutorSQLAlterClass.class,// null
OCommandExecutorSQLTruncateClass.class,// long
OCommandExecutorSQLDropClass.class,// boolean
OCommandExecutorSQLCreateCluster.class,// int
OCommandExecutorSQLAlterCluster.class,// null
OCommandExecutorSQLTruncateCluster.class,// long
OCommandExecutorSQLDropCluster.class,// boolean
OCommandExecutorSQLCreateProperty.class,// int
OCommandExecutorSQLAlterProperty.class,// null
OCommandExecutorSQLDropProperty.class,// null
OCommandExecutorSQLCreateIndex.class,// long
OCommandExecutorSQLRebuildIndex.class,// long
OCommandExecutorSQLDropIndex.class// null
));
private OQueryExecutorsFactory() {
}
public OQueryExecutor getExecutor(OCommandRequestText iCommand, OStorageEmbedded wrapped, ServerInstance serverInstance,
Set<Integer> undistributedClusters) {
final OCommandExecutor executorDelegate = OCommandManager.instance().getExecutor(iCommand);
executorDelegate.parse(iCommand);
final OCommandExecutor actualExecutor = executorDelegate instanceof OCommandExecutorSQLDelegate ? ((OCommandExecutorSQLDelegate) executorDelegate)
.getDelegate() : executorDelegate;
if (actualExecutor instanceof OCommandExecutorSQLSelect) {
final OCommandExecutorSQLSelect selectExecutor = (OCommandExecutorSQLSelect) actualExecutor;
if (isSelectDistributable(selectExecutor, undistributedClusters)) {
return new ODistributedSelectQueryExecutor(iCommand, selectExecutor, wrapped, serverInstance);
} else {
return new OLocalQueryExecutor(iCommand, wrapped);
}
} else {
if (isCommandDistributable(actualExecutor)) {
return new ODistributedQueryExecutor(iCommand, wrapped, serverInstance);
} else {
return new OLocalQueryExecutor(iCommand, wrapped);
}
}
}
private static boolean isSelectDistributable(OCommandExecutorSQLSelect selectExecutor, Set<Integer> undistributedClusters) {
for (Integer c : selectExecutor.getInvolvedClusters()) {
if (undistributedClusters.contains(c)) {
return false;
}
}
return true;
}
private static boolean isCommandDistributable(OCommandExecutor executor) {
return ALWAYS_DISTRIBUTABLE.contains(executor.getClass());
}
} | 0true
| distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_oldsharding_OQueryExecutorsFactory.java |
1,447 | public class CategoryBreadcrumbTei extends TagExtraInfo {
@Override
public VariableInfo[] getVariableInfo(TagData tagData) {
List<VariableInfo> infos = new ArrayList<VariableInfo>(2);
String variableName = tagData.getAttributeString("var");
infos.add(new VariableInfo(variableName, String.class.getName(), true, VariableInfo.NESTED));
variableName = tagData.getAttributeString("categoryId");
if (variableName != null) {
variableName = CategoryBreadCrumbTag.toVariableName(variableName);
infos.add(new VariableInfo(variableName, String.class.getName(), true, VariableInfo.NESTED));
}
return infos.toArray(new VariableInfo[infos.size()]);
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_catalog_taglib_tei_CategoryBreadcrumbTei.java |
165 | @Test
public abstract class SpeedTestAbstract implements SpeedTest {
protected final SpeedTestData data;
protected SpeedTestAbstract() {
data = new SpeedTestData();
}
protected SpeedTestAbstract(final long iCycles) {
data = new SpeedTestData(iCycles);
}
protected SpeedTestAbstract(final SpeedTestGroup iGroup) {
data = new SpeedTestData(iGroup);
}
public abstract void cycle() throws Exception;
public void init() throws Exception {
}
public void deinit() throws Exception {
}
public void beforeCycle() throws Exception {
}
public void afterCycle() throws Exception {
}
@Test
public void test() {
data.go(this);
}
public SpeedTestAbstract config(final Object... iArgs) {
data.configuration = iArgs;
return this;
}
/*
* (non-Javadoc)
*
* @see com.orientechnologies.common.test.SpeedTest#executeCycle(java.lang.reflect.Method, java.lang.Object)
*/
public long executeCycle(final Method iMethod, final Object... iArgs) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
data.startTimer(getClass().getSimpleName());
int percent = 0;
for (data.cyclesDone = 0; data.cyclesDone < data.cycles; ++data.cyclesDone) {
iMethod.invoke(this, iArgs);
if (data.cycles > 10 && data.cyclesDone % (data.cycles / 10) == 0)
System.out.print(++percent);
}
return data.takeTimer();
}
public SpeedTestData data() {
return data;
}
} | 0true
| commons_src_test_java_com_orientechnologies_common_test_SpeedTestAbstract.java |
1,959 | public final class LinkedBindingImpl<T> extends BindingImpl<T> implements LinkedKeyBinding<T> {
final Key<? extends T> targetKey;
public LinkedBindingImpl(Injector injector, Key<T> key, Object source,
InternalFactory<? extends T> internalFactory, Scoping scoping,
Key<? extends T> targetKey) {
super(injector, key, source, internalFactory, scoping);
this.targetKey = targetKey;
}
public LinkedBindingImpl(Object source, Key<T> key, Scoping scoping, Key<? extends T> targetKey) {
super(source, key, scoping);
this.targetKey = targetKey;
}
public <V> V acceptTargetVisitor(BindingTargetVisitor<? super T, V> visitor) {
return visitor.visit(this);
}
public Key<? extends T> getLinkedKey() {
return targetKey;
}
public BindingImpl<T> withScoping(Scoping scoping) {
return new LinkedBindingImpl<T>(getSource(), getKey(), scoping, targetKey);
}
public BindingImpl<T> withKey(Key<T> key) {
return new LinkedBindingImpl<T>(getSource(), key, getScoping(), targetKey);
}
public void applyTo(Binder binder) {
getScoping().applyTo(binder.withSource(getSource()).bind(getKey()).to(getLinkedKey()));
}
@Override
public String toString() {
return new ToStringBuilder(LinkedKeyBinding.class)
.add("key", getKey())
.add("source", getSource())
.add("scope", getScoping())
.add("target", targetKey)
.toString();
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_internal_LinkedBindingImpl.java |
3,031 | public class MemoryDocValuesFormatProvider extends AbstractDocValuesFormatProvider {
private final DocValuesFormat docValuesFormat;
@Inject
public MemoryDocValuesFormatProvider(@Assisted String name, @Assisted Settings docValuesFormatSettings) {
super(name);
this.docValuesFormat = new MemoryDocValuesFormat();
}
@Override
public DocValuesFormat get() {
return docValuesFormat;
}
} | 0true
| src_main_java_org_elasticsearch_index_codec_docvaluesformat_MemoryDocValuesFormatProvider.java |
481 | public class CsrfFilter extends GenericFilterBean {
protected static final Log LOG = LogFactory.getLog(CsrfFilter.class);
@Resource(name="blExploitProtectionService")
protected ExploitProtectionService exploitProtectionService;
protected List<String> excludedRequestPatterns;
@Override
public void doFilter(ServletRequest baseRequest, ServletResponse baseResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) baseRequest;
HttpServletResponse response = (HttpServletResponse) baseResponse;
boolean excludedRequestFound = false;
if (excludedRequestPatterns != null && excludedRequestPatterns.size() > 0) {
for (String pattern : excludedRequestPatterns) {
RequestMatcher matcher = new AntPathRequestMatcher(pattern);
if (matcher.matches(request)){
excludedRequestFound = true;
break;
}
}
}
// We only validate CSRF tokens on POST
if (request.getMethod().equals("POST") && !excludedRequestFound) {
String requestToken = request.getParameter(exploitProtectionService.getCsrfTokenParameter());
try {
exploitProtectionService.compareToken(requestToken);
} catch (ServiceException e) {
throw new ServletException(e);
}
}
chain.doFilter(request, response);
}
public List<String> getExcludedRequestPatterns() {
return excludedRequestPatterns;
}
/**
* This allows you to declaratively set a list of excluded Request Patterns
*
* <bean id="blCsrfFilter" class="org.broadleafcommerce.common.security.handler.CsrfFilter" >
* <property name="excludedRequestPatterns">
* <list>
* <value>/exclude-me/**</value>
* </list>
* </property>
* </bean>
*
**/
public void setExcludedRequestPatterns(List<String> excludedRequestPatterns) {
this.excludedRequestPatterns = excludedRequestPatterns;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_security_handler_CsrfFilter.java |
260 | public interface OCommand {
/**
* Executes command.
*
* @return The result of command if any, otherwise null
*/
public Object execute();
public OCommandContext getContext();
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_command_OCommand.java |
1,467 | binder.registerCustomEditor(Country.class, "address.country", new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
Country country = countryService.findCountryByAbbreviation(text);
setValue(country);
}
}); | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_account_BroadleafManageCustomerAddressesController.java |
1,438 | public class CategoryTagTest extends BaseTagLibTest {
private CategoryTag categoryTag;
private Category category;
public void test_categoryTag() throws JspException {
categoryTag.setJspContext(pageContext);
categoryTag.setVar("categoryVar");
categoryTag.setCatalogService(catalogService);
pageContext.setAttribute("categoryVar", category);
EasyMock.expect(pageContext.getAttribute("categoryVar")).andReturn(category);
categoryTag.setCategoryId(0L);
EasyMock.expect(catalogService.findCategoryById(0L)).andReturn(category);
super.replayAdditionalMockObjects(category);
categoryTag.doTag();
Category ret = (Category) pageContext.getAttribute("categoryVar");
assert(category.equals(ret));
super.verifyBaseMockObjects(category);
}
@Override
public void setup() {
categoryTag = new CategoryTag();
category = EasyMock.createMock(Category.class);
}
} | 0true
| core_broadleaf-framework-web_src_test_java_org_broadleafcommerce_core_web_catalog_taglib_CategoryTagTest.java |
4,045 | public class ChildrenConstantScoreQuery extends Query {
private final Query originalChildQuery;
private final String parentType;
private final String childType;
private final Filter parentFilter;
private final int shortCircuitParentDocSet;
private final Filter nonNestedDocsFilter;
private Query rewrittenChildQuery;
private IndexReader rewriteIndexReader;
public ChildrenConstantScoreQuery(Query childQuery, String parentType, String childType, Filter parentFilter, int shortCircuitParentDocSet, Filter nonNestedDocsFilter) {
this.parentFilter = parentFilter;
this.parentType = parentType;
this.childType = childType;
this.originalChildQuery = childQuery;
this.shortCircuitParentDocSet = shortCircuitParentDocSet;
this.nonNestedDocsFilter = nonNestedDocsFilter;
}
@Override
// See TopChildrenQuery#rewrite
public Query rewrite(IndexReader reader) throws IOException {
if (rewrittenChildQuery == null) {
rewrittenChildQuery = originalChildQuery.rewrite(reader);
rewriteIndexReader = reader;
}
return this;
}
@Override
public void extractTerms(Set<Term> terms) {
rewrittenChildQuery.extractTerms(terms);
}
@Override
public Weight createWeight(IndexSearcher searcher) throws IOException {
SearchContext searchContext = SearchContext.current();
searchContext.idCache().refresh(searcher.getTopReaderContext().leaves());
Recycler.V<ObjectOpenHashSet<HashedBytesArray>> collectedUids = searchContext.cacheRecycler().hashSet(-1);
UidCollector collector = new UidCollector(parentType, searchContext, collectedUids.v());
final Query childQuery;
if (rewrittenChildQuery == null) {
childQuery = rewrittenChildQuery = searcher.rewrite(originalChildQuery);
} else {
assert rewriteIndexReader == searcher.getIndexReader();
childQuery = rewrittenChildQuery;
}
IndexSearcher indexSearcher = new IndexSearcher(searcher.getIndexReader());
indexSearcher.setSimilarity(searcher.getSimilarity());
indexSearcher.search(childQuery, collector);
int remaining = collectedUids.v().size();
if (remaining == 0) {
return Queries.newMatchNoDocsQuery().createWeight(searcher);
}
Filter shortCircuitFilter = null;
if (remaining == 1) {
BytesRef id = collectedUids.v().iterator().next().value.toBytesRef();
shortCircuitFilter = new TermFilter(new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(parentType, id)));
} else if (remaining <= shortCircuitParentDocSet) {
shortCircuitFilter = new ParentIdsFilter(parentType, collectedUids.v().keys, collectedUids.v().allocated, nonNestedDocsFilter);
}
ParentWeight parentWeight = new ParentWeight(parentFilter, shortCircuitFilter, searchContext, collectedUids);
searchContext.addReleasable(parentWeight);
return parentWeight;
}
private final class ParentWeight extends Weight implements Releasable {
private final Filter parentFilter;
private final Filter shortCircuitFilter;
private final SearchContext searchContext;
private final Recycler.V<ObjectOpenHashSet<HashedBytesArray>> collectedUids;
private int remaining;
private float queryNorm;
private float queryWeight;
public ParentWeight(Filter parentFilter, Filter shortCircuitFilter, SearchContext searchContext, Recycler.V<ObjectOpenHashSet<HashedBytesArray>> collectedUids) {
this.parentFilter = new ApplyAcceptedDocsFilter(parentFilter);
this.shortCircuitFilter = shortCircuitFilter;
this.searchContext = searchContext;
this.collectedUids = collectedUids;
this.remaining = collectedUids.v().size();
}
@Override
public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
return new Explanation(getBoost(), "not implemented yet...");
}
@Override
public Query getQuery() {
return ChildrenConstantScoreQuery.this;
}
@Override
public float getValueForNormalization() throws IOException {
queryWeight = getBoost();
return queryWeight * queryWeight;
}
@Override
public void normalize(float norm, float topLevelBoost) {
this.queryNorm = norm * topLevelBoost;
queryWeight *= this.queryNorm;
}
@Override
public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException {
if (remaining == 0) {
return null;
}
if (shortCircuitFilter != null) {
DocIdSet docIdSet = shortCircuitFilter.getDocIdSet(context, acceptDocs);
if (!DocIdSets.isEmpty(docIdSet)) {
DocIdSetIterator iterator = docIdSet.iterator();
if (iterator != null) {
return ConstantScorer.create(iterator, this, queryWeight);
}
}
return null;
}
DocIdSet parentDocIdSet = this.parentFilter.getDocIdSet(context, acceptDocs);
if (!DocIdSets.isEmpty(parentDocIdSet)) {
IdReaderTypeCache idReaderTypeCache = searchContext.idCache().reader(context.reader()).type(parentType);
// We can't be sure of the fact that liveDocs have been applied, so we apply it here. The "remaining"
// count down (short circuit) logic will then work as expected.
parentDocIdSet = BitsFilteredDocIdSet.wrap(parentDocIdSet, context.reader().getLiveDocs());
if (idReaderTypeCache != null) {
DocIdSetIterator innerIterator = parentDocIdSet.iterator();
if (innerIterator != null) {
ParentDocIdIterator parentDocIdIterator = new ParentDocIdIterator(innerIterator, collectedUids.v(), idReaderTypeCache);
return ConstantScorer.create(parentDocIdIterator, this, queryWeight);
}
}
}
return null;
}
@Override
public boolean release() throws ElasticsearchException {
Releasables.release(collectedUids);
return true;
}
private final class ParentDocIdIterator extends FilteredDocIdSetIterator {
private final ObjectOpenHashSet<HashedBytesArray> parents;
private final IdReaderTypeCache typeCache;
private ParentDocIdIterator(DocIdSetIterator innerIterator, ObjectOpenHashSet<HashedBytesArray> parents, IdReaderTypeCache typeCache) {
super(innerIterator);
this.parents = parents;
this.typeCache = typeCache;
}
@Override
protected boolean match(int doc) {
if (remaining == 0) {
try {
advance(DocIdSetIterator.NO_MORE_DOCS);
} catch (IOException e) {
throw new RuntimeException(e);
}
return false;
}
boolean match = parents.contains(typeCache.idByDoc(doc));
if (match) {
remaining--;
}
return match;
}
}
}
private final static class UidCollector extends ParentIdCollector {
private final ObjectOpenHashSet<HashedBytesArray> collectedUids;
UidCollector(String parentType, SearchContext context, ObjectOpenHashSet<HashedBytesArray> collectedUids) {
super(parentType, context);
this.collectedUids = collectedUids;
}
@Override
public void collect(int doc, HashedBytesArray parentIdByDoc) {
collectedUids.add(parentIdByDoc);
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
ChildrenConstantScoreQuery that = (ChildrenConstantScoreQuery) obj;
if (!originalChildQuery.equals(that.originalChildQuery)) {
return false;
}
if (!childType.equals(that.childType)) {
return false;
}
if (shortCircuitParentDocSet != that.shortCircuitParentDocSet) {
return false;
}
if (getBoost() != that.getBoost()) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = originalChildQuery.hashCode();
result = 31 * result + childType.hashCode();
result = 31 * result + shortCircuitParentDocSet;
result = 31 * result + Float.floatToIntBits(getBoost());
return result;
}
@Override
public String toString(String field) {
StringBuilder sb = new StringBuilder();
sb.append("child_filter[").append(childType).append("/").append(parentType).append("](").append(originalChildQuery).append(')');
return sb.toString();
}
} | 1no label
| src_main_java_org_elasticsearch_index_search_child_ChildrenConstantScoreQuery.java |
876 | public class OrderOfferComparator implements Comparator<PromotableCandidateOrderOffer> {
public static OrderOfferComparator INSTANCE = new OrderOfferComparator();
public int compare(PromotableCandidateOrderOffer p1, PromotableCandidateOrderOffer p2) {
Integer priority1 = p1.getPriority();
Integer priority2 = p2.getPriority();
int result = priority1.compareTo(priority2);
if (result == 0) {
// highest potential savings wins
return p2.getPotentialSavings().compareTo(p1.getPotentialSavings());
}
return result;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_OrderOfferComparator.java |
749 | public class TxnListRemoveRequest extends TxnCollectionRequest {
public TxnListRemoveRequest() {
}
public TxnListRemoveRequest(String name, Data value) {
super(name, value);
}
@Override
public Object innerCall() throws Exception {
return getEndpoint().getTransactionContext(txnId).getList(name).remove(value);
}
@Override
public String getServiceName() {
return ListService.SERVICE_NAME;
}
@Override
public int getClassId() {
return CollectionPortableHook.TXN_LIST_REMOVE;
}
@Override
public Permission getRequiredPermission() {
return new ListPermission(name, ActionConstants.ACTION_REMOVE);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_client_TxnListRemoveRequest.java |
1,955 | public class MapRemoveRequest extends KeyBasedClientRequest implements Portable, SecureRequest {
protected String name;
protected Data key;
protected long threadId;
protected transient long startTime;
public MapRemoveRequest() {
}
public MapRemoveRequest(String name, Data key, long threadId) {
this.name = name;
this.key = key;
this.threadId = threadId;
}
public int getFactoryId() {
return MapPortableHook.F_ID;
}
public int getClassId() {
return MapPortableHook.REMOVE;
}
public Object getKey() {
return key;
}
@Override
protected void beforeProcess() {
startTime = System.currentTimeMillis();
}
@Override
protected void afterResponse() {
final long latency = System.currentTimeMillis() - startTime;
final MapService mapService = getService();
MapContainer mapContainer = mapService.getMapContainer(name);
if (mapContainer.getMapConfig().isStatisticsEnabled()) {
mapService.getLocalMapStatsImpl(name).incrementRemoves(latency);
}
}
protected Operation prepareOperation() {
RemoveOperation op = new RemoveOperation(name, key);
op.setThreadId(threadId);
return op;
}
public String getServiceName() {
return MapService.SERVICE_NAME;
}
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
writer.writeLong("t", threadId);
final ObjectDataOutput out = writer.getRawDataOutput();
key.writeData(out);
}
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
threadId = reader.readLong("t");
final ObjectDataInput in = reader.getRawDataInput();
key = new Data();
key.readData(in);
}
public Permission getRequiredPermission() {
return new MapPermission(name, ActionConstants.ACTION_REMOVE);
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_map_client_MapRemoveRequest.java |
988 | public static class Order {
public static final int OrderItems = 2000;
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_DiscreteOrderItemImpl.java |
282 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ClientRandomLBTest {
@AfterClass
public static void destroy() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testRandomLB_withoutMembers() {
RandomLB lb = new RandomLB();
Member m = lb.next();
assertNull(m);
}
@Test
public void testRandomLB_withMembers() {
RandomLB randomLB = new RandomLB();
TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);
HazelcastInstance server = factory.newHazelcastInstance();
Cluster cluster = server.getCluster();
ClientConfig clientConfig = new ClientConfig();
clientConfig.setLoadBalancer(randomLB);
randomLB.init(cluster, clientConfig);
Member member = cluster.getLocalMember();
Member nextMember = randomLB.next();
assertEquals(member, nextMember);
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_loadBalancer_ClientRandomLBTest.java |
612 | new OIndexEngine.ValuesResultListener() {
@Override
public boolean addResult(OIdentifiable identifiable) {
return resultListener.addResult(identifiable);
}
}); | 1no label
| core_src_main_java_com_orientechnologies_orient_core_index_OIndexMultiValues.java |
3,093 | static class Optimize {
private boolean waitForMerge = true;
private int maxNumSegments = -1;
private boolean onlyExpungeDeletes = false;
private boolean flush = false;
public Optimize() {
}
public boolean waitForMerge() {
return waitForMerge;
}
public Optimize waitForMerge(boolean waitForMerge) {
this.waitForMerge = waitForMerge;
return this;
}
public int maxNumSegments() {
return maxNumSegments;
}
public Optimize maxNumSegments(int maxNumSegments) {
this.maxNumSegments = maxNumSegments;
return this;
}
public boolean onlyExpungeDeletes() {
return onlyExpungeDeletes;
}
public Optimize onlyExpungeDeletes(boolean onlyExpungeDeletes) {
this.onlyExpungeDeletes = onlyExpungeDeletes;
return this;
}
public boolean flush() {
return flush;
}
public Optimize flush(boolean flush) {
this.flush = flush;
return this;
}
@Override
public String toString() {
return "waitForMerge[" + waitForMerge + "], maxNumSegments[" + maxNumSegments + "], onlyExpungeDeletes[" + onlyExpungeDeletes + "], flush[" + flush + "]";
}
} | 0true
| src_main_java_org_elasticsearch_index_engine_Engine.java |
922 | final Iterator<?> myIterator = makeDbCall(iMyDb, new ODbRelatedCall<Iterator<?>>() {
public Iterator<?> call() {
return mySet.iterator();
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java |
410 | public class TransportDeleteSnapshotAction extends TransportMasterNodeOperationAction<DeleteSnapshotRequest, DeleteSnapshotResponse> {
private final SnapshotsService snapshotsService;
@Inject
public TransportDeleteSnapshotAction(Settings settings, TransportService transportService, ClusterService clusterService,
ThreadPool threadPool, SnapshotsService snapshotsService) {
super(settings, transportService, clusterService, threadPool);
this.snapshotsService = snapshotsService;
}
@Override
protected String executor() {
return ThreadPool.Names.GENERIC;
}
@Override
protected String transportAction() {
return DeleteSnapshotAction.NAME;
}
@Override
protected DeleteSnapshotRequest newRequest() {
return new DeleteSnapshotRequest();
}
@Override
protected DeleteSnapshotResponse newResponse() {
return new DeleteSnapshotResponse();
}
@Override
protected ClusterBlockException checkBlock(DeleteSnapshotRequest request, ClusterState state) {
return state.blocks().indexBlockedException(ClusterBlockLevel.METADATA, "");
}
@Override
protected void masterOperation(final DeleteSnapshotRequest request, ClusterState state, final ActionListener<DeleteSnapshotResponse> listener) throws ElasticsearchException {
SnapshotId snapshotIds = new SnapshotId(request.repository(), request.snapshot());
snapshotsService.deleteSnapshot(snapshotIds, new SnapshotsService.DeleteSnapshotListener() {
@Override
public void onResponse() {
listener.onResponse(new DeleteSnapshotResponse(true));
}
@Override
public void onFailure(Throwable t) {
listener.onFailure(t);
}
});
}
} | 1no label
| src_main_java_org_elasticsearch_action_admin_cluster_snapshots_delete_TransportDeleteSnapshotAction.java |
1,413 | @XmlRootElement(name = "product")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class ProductWrapper extends BaseWrapper implements APIWrapper<Product> {
@XmlElement
protected Long id;
@XmlElement
protected String name;
@XmlElement
protected String description;
@XmlElement
protected String longDescription;
@XmlElement
protected Money retailPrice;
@XmlElement
protected Money salePrice;
@XmlElement
protected MediaWrapper primaryMedia;
@XmlElement
protected Boolean active;
@XmlElement(name = "productOption")
@XmlElementWrapper(name = "productOptions")
protected List<ProductOptionWrapper> productOptions;
// For bundles
@XmlElement
protected Integer priority;
@XmlElement
protected Money bundleItemsRetailPrice;
@XmlElement
protected Money bundleItemsSalePrice;
//End for bundles
@XmlElement
@XmlJavaTypeAdapter(ISO8601DateAdapter.class)
protected Date activeStartDate;
@XmlElement
@XmlJavaTypeAdapter(ISO8601DateAdapter.class)
protected Date activeEndDate;
@XmlElement
protected String manufacturer;
@XmlElement
protected String model;
@XmlElement
protected String promoMessage;
@XmlElement
protected Long defaultCategoryId;
@XmlElement(name = "upsaleProduct")
@XmlElementWrapper(name = "upsaleProducts")
protected List<RelatedProductWrapper> upsaleProducts;
@XmlElement(name = "crossSaleProduct")
@XmlElementWrapper(name = "crossSaleProducts")
protected List<RelatedProductWrapper> crossSaleProducts;
@XmlElement(name = "productAttribute")
@XmlElementWrapper(name = "productAttributes")
protected List<ProductAttributeWrapper> productAttributes;
@XmlElement(name = "media")
@XmlElementWrapper(name = "mediaItems")
protected List<MediaWrapper> media;
@XmlElement(name = "skuBundleItem")
@XmlElementWrapper(name = "skuBundleItems")
protected List<SkuBundleItemWrapper> skuBundleItems;
@Override
public void wrapDetails(Product model, HttpServletRequest request) {
this.id = model.getId();
this.name = model.getName();
this.description = model.getDescription();
this.longDescription = model.getLongDescription();
this.activeStartDate = model.getActiveStartDate();
this.activeEndDate = model.getActiveEndDate();
this.manufacturer = model.getManufacturer();
this.model = model.getModel();
this.promoMessage = model.getPromoMessage();
this.active = model.isActive();
if (model instanceof ProductBundle) {
ProductBundle bundle = (ProductBundle) model;
this.priority = bundle.getPriority();
this.bundleItemsRetailPrice = bundle.getBundleItemsRetailPrice();
this.bundleItemsSalePrice = bundle.getBundleItemsSalePrice();
if (bundle.getSkuBundleItems() != null) {
this.skuBundleItems = new ArrayList<SkuBundleItemWrapper>();
List<SkuBundleItem> bundleItems = bundle.getSkuBundleItems();
for (SkuBundleItem item : bundleItems) {
SkuBundleItemWrapper skuBundleItemsWrapper = (SkuBundleItemWrapper) context.getBean(SkuBundleItemWrapper.class.getName());
skuBundleItemsWrapper.wrapSummary(item, request);
this.skuBundleItems.add(skuBundleItemsWrapper);
}
}
} else {
this.retailPrice = model.getDefaultSku().getRetailPrice();
this.salePrice = model.getDefaultSku().getSalePrice();
}
if (model.getProductOptions() != null && !model.getProductOptions().isEmpty()) {
this.productOptions = new ArrayList<ProductOptionWrapper>();
List<ProductOption> options = model.getProductOptions();
for (ProductOption option : options) {
ProductOptionWrapper optionWrapper = (ProductOptionWrapper) context.getBean(ProductOptionWrapper.class.getName());
optionWrapper.wrapSummary(option, request);
this.productOptions.add(optionWrapper);
}
}
if (model.getMedia() != null && !model.getMedia().isEmpty()) {
Media media = model.getMedia().get("primary");
if (media != null) {
StaticAssetService staticAssetService = (StaticAssetService) this.context.getBean("blStaticAssetService");
primaryMedia = (MediaWrapper) context.getBean(MediaWrapper.class.getName());
primaryMedia.wrapDetails(media, request);
if (primaryMedia.isAllowOverrideUrl()) {
primaryMedia.setUrl(staticAssetService.convertAssetPath(media.getUrl(), request.getContextPath(), request.isSecure()));
}
}
}
if (model.getDefaultCategory() != null) {
this.defaultCategoryId = model.getDefaultCategory().getId();
}
if (model.getUpSaleProducts() != null && !model.getUpSaleProducts().isEmpty()) {
upsaleProducts = new ArrayList<RelatedProductWrapper>();
for (RelatedProduct p : model.getUpSaleProducts()) {
RelatedProductWrapper upsaleProductWrapper =
(RelatedProductWrapper) context.getBean(RelatedProductWrapper.class.getName());
upsaleProductWrapper.wrapSummary(p, request);
upsaleProducts.add(upsaleProductWrapper);
}
}
if (model.getCrossSaleProducts() != null && !model.getCrossSaleProducts().isEmpty()) {
crossSaleProducts = new ArrayList<RelatedProductWrapper>();
for (RelatedProduct p : model.getCrossSaleProducts()) {
RelatedProductWrapper crossSaleProductWrapper =
(RelatedProductWrapper) context.getBean(RelatedProductWrapper.class.getName());
crossSaleProductWrapper.wrapSummary(p, request);
crossSaleProducts.add(crossSaleProductWrapper);
}
}
if (model.getProductAttributes() != null && !model.getProductAttributes().isEmpty()) {
productAttributes = new ArrayList<ProductAttributeWrapper>();
if (model.getProductAttributes() != null) {
for (Map.Entry<String, ProductAttribute> entry : model.getProductAttributes().entrySet()) {
ProductAttributeWrapper wrapper = (ProductAttributeWrapper) context.getBean(ProductAttributeWrapper.class.getName());
wrapper.wrapSummary(entry.getValue(), request);
productAttributes.add(wrapper);
}
}
}
if (model.getMedia() != null && !model.getMedia().isEmpty()) {
Map<String, Media> mediaMap = model.getMedia();
media = new ArrayList<MediaWrapper>();
StaticAssetService staticAssetService = (StaticAssetService) this.context.getBean("blStaticAssetService");
for (Media med : mediaMap.values()) {
MediaWrapper wrapper = (MediaWrapper) context.getBean(MediaWrapper.class.getName());
wrapper.wrapSummary(med, request);
if (wrapper.isAllowOverrideUrl()) {
wrapper.setUrl(staticAssetService.convertAssetPath(med.getUrl(), request.getContextPath(), request.isSecure()));
}
media.add(wrapper);
}
}
}
@Override
public void wrapSummary(Product model, HttpServletRequest request) {
this.id = model.getId();
this.name = model.getName();
this.description = model.getDescription();
this.longDescription = model.getLongDescription();
this.active = model.isActive();
if (model instanceof ProductBundle) {
ProductBundle bundle = (ProductBundle) model;
this.priority = bundle.getPriority();
this.bundleItemsRetailPrice = bundle.getBundleItemsRetailPrice();
this.bundleItemsSalePrice = bundle.getBundleItemsSalePrice();
} else {
this.retailPrice = model.getDefaultSku().getRetailPrice();
this.salePrice = model.getDefaultSku().getSalePrice();
}
if (model.getProductOptions() != null && !model.getProductOptions().isEmpty()) {
this.productOptions = new ArrayList<ProductOptionWrapper>();
List<ProductOption> options = model.getProductOptions();
for (ProductOption option : options) {
ProductOptionWrapper optionWrapper = (ProductOptionWrapper) context.getBean(ProductOptionWrapper.class.getName());
optionWrapper.wrapSummary(option, request);
this.productOptions.add(optionWrapper);
}
}
if (model.getMedia() != null && !model.getMedia().isEmpty()) {
Media media = model.getMedia().get("primary");
if (media != null) {
StaticAssetService staticAssetService = (StaticAssetService) this.context.getBean("blStaticAssetService");
primaryMedia = (MediaWrapper) context.getBean(MediaWrapper.class.getName());
primaryMedia.wrapDetails(media, request);
if (primaryMedia.isAllowOverrideUrl()) {
primaryMedia.setUrl(staticAssetService.convertAssetPath(media.getUrl(), request.getContextPath(), request.isSecure()));
}
}
}
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_ProductWrapper.java |
1,218 | public class TitanSchemaVertex extends CacheVertex implements SchemaSource {
public TitanSchemaVertex(StandardTitanTx tx, long id, byte lifecycle) {
super(tx, id, lifecycle);
}
private String name = null;
@Override
public String getName() {
if (name == null) {
TitanProperty p;
if (isLoaded()) {
StandardTitanTx tx = tx();
p = (TitanProperty) Iterables.getOnlyElement(RelationConstructor.readRelation(this,
tx.getGraph().getSchemaCache().getSchemaRelations(getLongId(), BaseKey.SchemaName, Direction.OUT, tx()),
tx), null);
} else {
p = Iterables.getOnlyElement(query().type(BaseKey.SchemaName).properties(), null);
}
Preconditions.checkState(p!=null,"Could not find type for id: %s", getLongId());
name = p.getValue();
}
assert name != null;
return TitanSchemaCategory.getName(name);
}
@Override
protected Vertex getVertexLabelInternal() {
return null;
}
private TypeDefinitionMap definition = null;
@Override
public TypeDefinitionMap getDefinition() {
TypeDefinitionMap def = definition;
if (def == null) {
def = new TypeDefinitionMap();
Iterable<TitanProperty> ps;
if (isLoaded()) {
StandardTitanTx tx = tx();
ps = (Iterable)RelationConstructor.readRelation(this,
tx.getGraph().getSchemaCache().getSchemaRelations(getLongId(), BaseKey.SchemaDefinitionProperty, Direction.OUT, tx()),
tx);
} else {
ps = query().type(BaseKey.SchemaDefinitionProperty).properties();
}
for (TitanProperty property : ps) {
TypeDefinitionDescription desc = property.getProperty(BaseKey.SchemaDefinitionDesc);
Preconditions.checkArgument(desc!=null && desc.getCategory().isProperty());
def.setValue(desc.getCategory(), property.getValue());
}
assert def.size()>0;
definition = def;
}
assert def!=null;
return def;
}
private ListMultimap<TypeDefinitionCategory,Entry> outRelations = null;
private ListMultimap<TypeDefinitionCategory,Entry> inRelations = null;
@Override
public Iterable<Entry> getRelated(TypeDefinitionCategory def, Direction dir) {
assert dir==Direction.OUT || dir==Direction.IN;
ListMultimap<TypeDefinitionCategory,Entry> rels = dir==Direction.OUT?outRelations:inRelations;
if (rels==null) {
ImmutableListMultimap.Builder<TypeDefinitionCategory,Entry> b = ImmutableListMultimap.builder();
Iterable<TitanEdge> edges;
if (isLoaded()) {
StandardTitanTx tx = tx();
edges = (Iterable)RelationConstructor.readRelation(this,
tx.getGraph().getSchemaCache().getSchemaRelations(getLongId(), BaseLabel.SchemaDefinitionEdge, dir, tx()),
tx);
} else {
edges = query().type(BaseLabel.SchemaDefinitionEdge).direction(dir).titanEdges();
}
for (TitanEdge edge: edges) {
TitanVertex oth = edge.getVertex(dir.opposite());
assert oth instanceof TitanSchemaVertex;
TypeDefinitionDescription desc = edge.getProperty(BaseKey.SchemaDefinitionDesc);
Object modifier = null;
if (desc.getCategory().hasDataType()) {
assert desc.getModifier()!=null && desc.getModifier().getClass().equals(desc.getCategory().getDataType());
modifier = desc.getModifier();
}
b.put(desc.getCategory(), new Entry((TitanSchemaVertex) oth, modifier));
}
rels = b.build();
if (dir==Direction.OUT) outRelations=rels;
else inRelations=rels;
}
assert rels!=null;
return rels.get(def);
}
/**
* Resets the internal caches used to speed up lookups on this index type.
* This is needed when the type gets modified in the {@link com.thinkaurelius.titan.graphdb.database.management.ManagementSystem}.
*/
public void resetCache() {
name = null;
definition=null;
outRelations=null;
inRelations=null;
}
public Iterable<TitanEdge> getEdges(final TypeDefinitionCategory def, final Direction dir) {
return getEdges(def,dir,null);
}
public Iterable<TitanEdge> getEdges(final TypeDefinitionCategory def, final Direction dir, TitanSchemaVertex other) {
TitanVertexQuery query = query().type(BaseLabel.SchemaDefinitionEdge).direction(dir);
if (other!=null) query.adjacent(other);
return Iterables.filter(query.titanEdges(),new Predicate<TitanEdge>() {
@Override
public boolean apply(@Nullable TitanEdge edge) {
TypeDefinitionDescription desc = edge.getProperty(BaseKey.SchemaDefinitionDesc);
return desc.getCategory()==def;
}
});
}
@Override
public String toString() {
return getName();
}
@Override
public SchemaStatus getStatus() {
return getDefinition().getValue(TypeDefinitionCategory.STATUS,SchemaStatus.class);
}
@Override
public IndexType asIndexType() {
Preconditions.checkArgument(getDefinition().containsKey(TypeDefinitionCategory.INTERNAL_INDEX),"Schema vertex is not a type vertex: [%s,%s]", getLongId(),getName());
if (getDefinition().getValue(TypeDefinitionCategory.INTERNAL_INDEX)) {
return new CompositeIndexTypeWrapper(this);
} else {
return new MixedIndexTypeWrapper(this);
}
}
} | 1no label
| titan-core_src_main_java_com_thinkaurelius_titan_graphdb_types_vertices_TitanSchemaVertex.java |
3,168 | return new DoubleValues(values.isMultiValued()) {
@Override
public int setDocument(int docId) {
return values.setDocument(docId);
}
@Override
public double nextValue() {
return (double) values.nextValue();
}
}; | 0true
| src_main_java_org_elasticsearch_index_fielddata_DoubleValues.java |
2,170 | public static class IteratorBasedIterator extends DocIdSetIterator {
private final int max;
private DocIdSetIterator it1;
private int lastReturn = -1;
private int innerDocid = -1;
private final long cost;
IteratorBasedIterator(int max, DocIdSetIterator it) throws IOException {
this.max = max;
this.it1 = it;
this.cost = it1.cost();
if ((innerDocid = it1.nextDoc()) == DocIdSetIterator.NO_MORE_DOCS) {
it1 = null;
}
}
@Override
public int docID() {
return lastReturn;
}
@Override
public int nextDoc() throws IOException {
return advance(0);
}
@Override
public int advance(int target) throws IOException {
if (lastReturn == DocIdSetIterator.NO_MORE_DOCS) {
return DocIdSetIterator.NO_MORE_DOCS;
}
if (target <= lastReturn) target = lastReturn + 1;
if (it1 != null && innerDocid < target) {
if ((innerDocid = it1.advance(target)) == DocIdSetIterator.NO_MORE_DOCS) {
it1 = null;
}
}
while (it1 != null && innerDocid == target) {
target++;
if (target >= max) {
return (lastReturn = DocIdSetIterator.NO_MORE_DOCS);
}
if ((innerDocid = it1.advance(target)) == DocIdSetIterator.NO_MORE_DOCS) {
it1 = null;
}
}
// ADDED THIS, bug in original code
if (target >= max) {
return (lastReturn = DocIdSetIterator.NO_MORE_DOCS);
}
return (lastReturn = target);
}
@Override
public long cost() {
return cost;
}
} | 0true
| src_main_java_org_elasticsearch_common_lucene_docset_NotDocIdSet.java |
1,581 | static class Log4jLogger extends AbstractLogger {
private final Logger logger;
private final Level level;
public Log4jLogger(Logger logger) {
this.logger = logger;
if (logger.getLevel() == org.apache.log4j.Level.DEBUG) {
level = Level.FINEST;
} else if (logger.getLevel() == org.apache.log4j.Level.INFO) {
level = Level.INFO;
} else if (logger.getLevel() == org.apache.log4j.Level.WARN) {
level = Level.WARNING;
} else if (logger.getLevel() == org.apache.log4j.Level.FATAL) {
level = Level.SEVERE;
} else {
level = Level.INFO;
}
}
@Override
public void log(Level level, String message) {
if (Level.FINEST == level) {
logger.debug(message);
} else if (Level.SEVERE == level) {
logger.fatal(message);
} else if (Level.WARNING == level) {
logger.warn(message);
} else {
logger.info(message);
}
}
@Override
public Level getLevel() {
return level;
}
@Override
public boolean isLoggable(Level level) {
if (Level.OFF == level) {
return false;
} else if (Level.FINEST == level) {
return logger.isDebugEnabled();
} else if (Level.WARNING == level) {
return logger.isEnabledFor(org.apache.log4j.Level.WARN);
} else if (Level.SEVERE == level) {
return logger.isEnabledFor(org.apache.log4j.Level.FATAL);
} else {
return logger.isEnabledFor(org.apache.log4j.Level.INFO);
}
}
@Override
public void log(Level level, String message, Throwable thrown) {
if (Level.FINEST == level) {
logger.debug(message, thrown);
} else if (Level.WARNING == level) {
logger.warn(message, thrown);
} else if (Level.SEVERE == level) {
logger.fatal(message, thrown);
} else {
logger.info(message, thrown);
}
}
@Override
public void log(LogEvent logEvent) {
LogRecord logRecord = logEvent.getLogRecord();
String name = logEvent.getLogRecord().getLoggerName();
org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(name);
org.apache.log4j.Level level;
if (logRecord.getLevel() == Level.FINEST) {
level = org.apache.log4j.Level.DEBUG;
} else if (logRecord.getLevel() == Level.INFO) {
level = org.apache.log4j.Level.INFO;
} else if (logRecord.getLevel() == Level.WARNING) {
level = org.apache.log4j.Level.WARN;
} else if (logRecord.getLevel() == Level.SEVERE) {
level = org.apache.log4j.Level.FATAL;
} else {
level = org.apache.log4j.Level.INFO;
}
String message = logRecord.getMessage();
Throwable throwable = logRecord.getThrown();
logger.callAppenders(new LoggingEvent(name, logger, level, message, throwable));
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_logging_Log4jFactory.java |
1,927 | public interface AnnotatedElementBuilder {
/**
* See the EDSL examples at {@link org.elasticsearch.common.inject.Binder}.
*/
void annotatedWith(Class<? extends Annotation> annotationType);
/**
* See the EDSL examples at {@link org.elasticsearch.common.inject.Binder}.
*/
void annotatedWith(Annotation annotation);
} | 0true
| src_main_java_org_elasticsearch_common_inject_binder_AnnotatedElementBuilder.java |
1,234 | @SuppressWarnings("deprecation")
public class PricingTest extends BaseTest {
@Resource
private CustomerService customerService;
@Resource(name = "blOrderService")
private OrderService orderService;
@Resource
private ShippingRateService shippingRateService;
@Resource
private CatalogService catalogService;
@Resource(name = "blOrderItemService")
private OrderItemService orderItemService;
@Resource
private OfferService offerService;
@Resource
private CountryService countryService;
@Resource
private StateService stateService;
@Test(groups = {"testShippingInsert"}, dataProvider = "basicShippingRates", dataProviderClass = ShippingRateDataProvider.class)
@Rollback(false)
public void testShippingInsert(ShippingRate shippingRate, ShippingRate sr2) throws Exception {
shippingRate = shippingRateService.save(shippingRate);
sr2 = shippingRateService.save(sr2);
}
@Test(groups = {"testPricing"}, dependsOnGroups = { "testShippingInsert", "createCustomerIdGeneration" })
@Transactional
public void testPricing() throws Exception {
Order order = orderService.createNewCartForCustomer(createCustomer());
customerService.saveCustomer(order.getCustomer());
Country country = new CountryImpl();
country.setAbbreviation("US");
country.setName("United States");
country = countryService.save(country);
State state = new StateImpl();
state.setAbbreviation("TX");
state.setName("Texas");
state.setCountry(country);
state = stateService.save(state);
Address address = new AddressImpl();
address.setAddressLine1("123 Test Rd");
address.setCity("Dallas");
address.setFirstName("Jeff");
address.setLastName("Fischer");
address.setPostalCode("75240");
address.setPrimaryPhone("972-978-9067");
address.setState(state);
address.setCountry(country);
FulfillmentGroup group = new FulfillmentGroupImpl();
group.setAddress(address);
List<FulfillmentGroup> groups = new ArrayList<FulfillmentGroup>();
group.setMethod("standard");
group.setService(ShippingServiceType.BANDED_SHIPPING.getType());
group.setOrder(order);
groups.add(group);
order.setFulfillmentGroups(groups);
Money total = new Money(8.5D);
group.setShippingPrice(total);
{
DiscreteOrderItem item = new DiscreteOrderItemImpl();
Sku sku = new SkuImpl();
sku.setName("Test Sku");
sku.setRetailPrice(new Money(10D));
sku.setDiscountable(true);
SkuFee fee = new SkuFeeImpl();
fee.setFeeType(SkuFeeType.FULFILLMENT);
fee.setName("fee test");
fee.setAmount(new Money(10D));
fee = catalogService.saveSkuFee(fee);
List<SkuFee> fees = new ArrayList<SkuFee>();
fees.add(fee);
sku.setFees(fees);
sku = catalogService.saveSku(sku);
item.setSku(sku);
item.setQuantity(2);
item.setOrder(order);
item = (DiscreteOrderItem) orderItemService.saveOrderItem(item);
order.addOrderItem(item);
FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl();
fgItem.setFulfillmentGroup(group);
fgItem.setOrderItem(item);
fgItem.setQuantity(2);
//fgItem.setPrice(new Money(0D));
group.addFulfillmentGroupItem(fgItem);
}
{
DiscreteOrderItem item = new DiscreteOrderItemImpl();
Sku sku = new SkuImpl();
sku.setName("Test Product 2");
sku.setRetailPrice(new Money(20D));
sku.setDiscountable(true);
sku = catalogService.saveSku(sku);
item.setSku(sku);
item.setQuantity(1);
item.setOrder(order);
item = (DiscreteOrderItem) orderItemService.saveOrderItem(item);
order.addOrderItem(item);
FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl();
fgItem.setFulfillmentGroup(group);
fgItem.setOrderItem(item);
fgItem.setQuantity(1);
//fgItem.setPrice(new Money(0D));
group.addFulfillmentGroupItem(fgItem);
}
order.addOfferCode(createOfferCode("20 Percent Off Item Offer", OfferType.ORDER_ITEM, OfferDiscountType.PERCENT_OFF, 20, null, "discreteOrderItem.sku.name==\"Test Sku\""));
order.addOfferCode(createOfferCode("3 Dollars Off Item Offer", OfferType.ORDER_ITEM, OfferDiscountType.AMOUNT_OFF, 3, null, "discreteOrderItem.sku.name!=\"Test Sku\""));
order.addOfferCode(createOfferCode("1.20 Dollars Off Order Offer", OfferType.ORDER, OfferDiscountType.AMOUNT_OFF, 1.20, null, null));
order.setTotalShipping(new Money(0D));
orderService.save(order, true);
assert order.getSubTotal().subtract(order.getOrderAdjustmentsValue()).equals(new Money(31.80D));
assert (order.getTotal().greaterThan(order.getSubTotal()));
assert (order.getTotalTax().equals(order.getSubTotal().subtract(order.getOrderAdjustmentsValue()).multiply(0.05D))); // Shipping is not taxable
//determine the total cost of the fulfillment group fees
Money fulfillmentGroupFeeTotal = getFulfillmentGroupFeeTotal(order);
assert (order.getTotal().equals(order.getSubTotal().add(order.getTotalTax()).add(order.getTotalShipping()).add(fulfillmentGroupFeeTotal).subtract(order.getOrderAdjustmentsValue())));
}
public Money getFulfillmentGroupFeeTotal(Order order) {
Money result = new Money(BigDecimal.ZERO);
for (FulfillmentGroup group : order.getFulfillmentGroups()) {
for (FulfillmentGroupFee fee : group.getFulfillmentGroupFees()) {
result = result.add(fee.getAmount());
}
}
return result;
}
@Test(groups = { "testShipping" }, dependsOnGroups = { "testShippingInsert", "createCustomerIdGeneration"})
@Transactional
public void testShipping() throws Exception {
Order order = orderService.createNewCartForCustomer(createCustomer());
customerService.saveCustomer(order.getCustomer());
FulfillmentGroup group1 = new FulfillmentGroupImpl();
FulfillmentGroup group2 = new FulfillmentGroupImpl();
// setup group1 - standard
group1.setMethod("standard");
group1.setService(ShippingServiceType.BANDED_SHIPPING.getType());
Country country = new CountryImpl();
country.setAbbreviation("US");
country.setName("United States");
country = countryService.save(country);
State state = new StateImpl();
state.setAbbreviation("TX");
state.setName("Texas");
state.setCountry(country);
state = stateService.save(state);
Address address = new AddressImpl();
address.setAddressLine1("123 Test Rd");
address.setCity("Dallas");
address.setFirstName("Jeff");
address.setLastName("Fischer");
address.setPostalCode("75240");
address.setPrimaryPhone("972-978-9067");
address.setState(state);
address.setCountry(country);
group1.setAddress(address);
group1.setOrder(order);
// setup group2 - truck
group2.setMethod("truck");
group2.setService(ShippingServiceType.BANDED_SHIPPING.getType());
group2.setOrder(order);
List<FulfillmentGroup> groups = new ArrayList<FulfillmentGroup>();
groups.add(group1);
//groups.add(group2);
order.setFulfillmentGroups(groups);
Money total = new Money(8.5D);
group1.setShippingPrice(total);
group2.setShippingPrice(total);
//group1.setTotalTax(new Money(1D));
//group2.setTotalTax(new Money(1D));
order.setSubTotal(total);
order.setTotal(total);
DiscreteOrderItem item = new DiscreteOrderItemImpl();
Sku sku = new SkuImpl();
sku.setRetailPrice(new Money(15D));
sku.setDiscountable(true);
sku.setName("Test Sku");
sku = catalogService.saveSku(sku);
item.setSku(sku);
item.setQuantity(1);
item.setOrder(order);
item = (DiscreteOrderItem) orderItemService.saveOrderItem(item);
List<OrderItem> items = new ArrayList<OrderItem>();
items.add(item);
order.setOrderItems(items);
for (OrderItem orderItem : items) {
FulfillmentGroupItem fgi = new FulfillmentGroupItemImpl();
fgi.setOrderItem(orderItem);
fgi.setQuantity(orderItem.getQuantity());
fgi.setFulfillmentGroup(group1);
//fgi.setRetailPrice(new Money(15D));
group1.addFulfillmentGroupItem(fgi);
}
order.setTotalShipping(new Money(0D));
orderService.save(order, true);
assert (order.getTotal().greaterThan(order.getSubTotal()));
assert (order.getTotalTax().equals(order.getSubTotal().multiply(0.05D))); // Shipping price is not taxable
assert (order.getTotal().equals(order.getSubTotal().add(order.getTotalTax().add(order.getTotalShipping()))));
}
@Test(groups = { "createCustomerIdGeneration" })
@Rollback(false)
public void createCustomerIdGeneration() {
IdGeneration idGeneration = new IdGenerationImpl();
idGeneration.setType("org.broadleafcommerce.profile.core.domain.Customer");
idGeneration.setBatchStart(1L);
idGeneration.setBatchSize(10L);
em.persist(idGeneration);
}
public Customer createCustomer() {
Customer customer = customerService.createCustomerFromId(null);
return customer;
}
private OfferCode createOfferCode(String offerName, OfferType offerType, OfferDiscountType discountType, double value, String customerRule, String orderRule) {
OfferCode offerCode = new OfferCodeImpl();
Offer offer = createOffer(offerName, offerType, discountType, value, customerRule, orderRule);
offerCode.setOffer(offer);
offerCode.setOfferCode("OPRAH");
offerCode = offerService.saveOfferCode(offerCode);
return offerCode;
}
private Offer createOffer(String offerName, OfferType offerType, OfferDiscountType discountType, double value, String customerRule, String orderRule) {
Offer offer = new OfferImpl();
offer.setName(offerName);
offer.setStartDate(SystemTime.asDate());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
offer.setStartDate(calendar.getTime());
calendar.add(Calendar.DATE, 2);
offer.setEndDate(calendar.getTime());
offer.setType(offerType);
offer.setDiscountType(discountType);
offer.setValue(BigDecimal.valueOf(value));
offer.setDeliveryType(OfferDeliveryType.CODE);
offer.setStackable(true);
offer.setAppliesToOrderRules(orderRule);
offer.setAppliesToCustomerRules(customerRule);
offer.setCombinableWithOtherOffers(true);
offer = offerService.save(offer);
offer.setMaxUses(50);
return offer;
}
} | 0true
| integration_src_test_java_org_broadleafcommerce_core_pricing_service_PricingTest.java |
4,486 | threadPool.generic().execute(new Runnable() {
@Override
public void run() {
doRecovery(request, status, listener);
}
}); | 1no label
| src_main_java_org_elasticsearch_indices_recovery_RecoveryTarget.java |
3,160 | return new BytesValues(values.isMultiValued()) {
@Override
public int setDocument(int docId) {
this.docId = docId;
return values.setDocument(docId);
}
@Override
public BytesRef nextValue() {
GeoPoint value = values.nextValue();
scratch.copyChars(GeoHashUtils.encode(value.lat(), value.lon()));
return scratch;
}
}; | 0true
| src_main_java_org_elasticsearch_index_fielddata_AtomicGeoPointFieldData.java |
1,554 | @ManagedDescription("ILock")
public class LockMBean extends HazelcastMBean<ILock> {
protected LockMBean(ILock managedObject, ManagementService service) {
super(managedObject, service);
objectName = service.createObjectName("ILock", managedObject.getName());
}
@ManagedAnnotation("name")
@ManagedDescription("Name of the DistributedObject")
public String getName() {
return managedObject.getName();
}
@ManagedAnnotation("lockObject")
@ManagedDescription("Lock Object as String")
public String getLockObject() {
Object lockObject = managedObject.getName();
if (lockObject == null) {
return null;
} else {
return lockObject.toString();
}
}
@ManagedAnnotation("partitionKey")
@ManagedDescription("the partitionKey")
public String getPartitionKey() {
return managedObject.getPartitionKey();
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_jmx_LockMBean.java |
485 | @Service("blExploitProtectionService")
public class ExploitProtectionServiceImpl implements ExploitProtectionService {
private static final String CSRFTOKEN = "csrfToken";
private static final String CSRFTOKENPARAMETER = "csrfToken";
private static final Log LOG = LogFactory.getLog(ExploitProtectionServiceImpl.class);
private static class Handler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL u) throws IOException {
URL resourceUrl = getClass().getClassLoader().getResource(u.getPath());
return resourceUrl.openConnection();
}
}
private static Policy getAntiSamyPolicy(String policyFileLocation) {
try {
URL url = new URL(null, policyFileLocation, new Handler());
return Policy.getInstance(url);
} catch (Exception e) {
throw new RuntimeException("Unable to create URL", e);
}
}
private static final String DEFAULTANTISAMYPOLICYFILELOCATION = "classpath:antisamy-myspace-1.4.4.xml";
protected String antiSamyPolicyFileLocation = DEFAULTANTISAMYPOLICYFILELOCATION;
//this is thread safe
private Policy antiSamyPolicy = getAntiSamyPolicy(antiSamyPolicyFileLocation);
//this is thread safe for the usage of scan()
private AntiSamy as = new AntiSamy();
protected boolean xsrfProtectionEnabled = true;
protected boolean xssProtectionEnabled = true;
@Override
public String cleanString(String string) throws ServiceException {
if (!xssProtectionEnabled || StringUtils.isEmpty(string)) {
return string;
}
try {
CleanResults results = as.scan(string, antiSamyPolicy);
return results.getCleanHTML();
} catch (Exception e) {
LOG.error("Unable to clean the passed in entity values", e);
throw new ServiceException("Unable to clean the passed in entity values", e);
}
}
@Override
public String cleanStringWithResults(String string) throws ServiceException {
if (!xssProtectionEnabled || StringUtils.isEmpty(string)) {
return string;
}
try {
CleanResults results = as.scan(string, antiSamyPolicy);
if (results.getNumberOfErrors() > 0) {
throw new CleanStringException(results);
}
return results.getCleanHTML();
} catch (CleanStringException e) {
throw e;
} catch (Exception e) {
StringBuilder sb = new StringBuilder();
sb.append("Unable to clean the passed in entity values");
sb.append("\nNote - ");
sb.append(getAntiSamyPolicyFileLocation());
sb.append(" policy in effect. Set a new policy file to modify validation behavior/strictness.");
LOG.error(sb.toString(), e);
throw new ServiceException(sb.toString(), e);
}
}
@Override
public void compareToken(String passedToken) throws ServiceException {
if (xsrfProtectionEnabled) {
if (!getCSRFToken().equals(passedToken)) {
throw new ServiceException("XSRF token mismatch (" + passedToken + "). Session may be expired.");
} else {
LOG.debug("Validated CSRF token");
}
}
}
@Override
public String getCSRFToken() throws ServiceException {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession session = request.getSession();
String token = (String) session.getAttribute(CSRFTOKEN);
if (StringUtils.isEmpty(token)) {
try {
token = RandomGenerator.generateRandomId("SHA1PRNG", 32);
} catch (NoSuchAlgorithmException e) {
LOG.error("Unable to generate random number", e);
throw new ServiceException("Unable to generate random number", e);
}
session.setAttribute(CSRFTOKEN, token);
}
return token;
}
@Override
public String getAntiSamyPolicyFileLocation() {
return antiSamyPolicyFileLocation;
}
@Override
public void setAntiSamyPolicyFileLocation(String antiSamyPolicyFileLocation) {
this.antiSamyPolicyFileLocation = antiSamyPolicyFileLocation;
antiSamyPolicy = getAntiSamyPolicy(antiSamyPolicyFileLocation);
}
public boolean isXsrfProtectionEnabled() {
return xsrfProtectionEnabled;
}
public void setXsrfProtectionEnabled(boolean xsrfProtectionEnabled) {
this.xsrfProtectionEnabled = xsrfProtectionEnabled;
}
public boolean isXssProtectionEnabled() {
return xssProtectionEnabled;
}
public void setXssProtectionEnabled(boolean xssProtectionEnabled) {
this.xssProtectionEnabled = xssProtectionEnabled;
}
@Override
public String getCsrfTokenParameter() {
return CSRFTOKENPARAMETER;
}
} | 1no label
| common_src_main_java_org_broadleafcommerce_common_security_service_ExploitProtectionServiceImpl.java |
457 | el[5] = StaticArrayEntryList.of(Iterables.transform(entries.entrySet(),new Function<Map.Entry<Integer, Long>, Entry>() {
@Nullable
@Override
public Entry apply(@Nullable Map.Entry<Integer, Long> entry) {
return StaticArrayEntry.ofByteBuffer(entry, BBEntryGetter.INSTANCE);
}
})); | 0true
| titan-test_src_test_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_StaticArrayEntryTest.java |
804 | public static enum ATTRIBUTES {
NAME, SHORTNAME, SUPERCLASS, OVERSIZE, STRICTMODE, ADDCLUSTER, REMOVECLUSTER, CUSTOM, ABSTRACT
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OClass.java |
60 | @Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_FLD_DEF")
@Cache(usage= CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blCMSElements")
public class FieldDefinitionImpl implements FieldDefinition {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "FieldDefinitionId")
@GenericGenerator(
name="FieldDefinitionId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="FieldDefinitionImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.cms.field.domain.FieldDefinitionImpl")
}
)
@Column(name = "FLD_DEF_ID")
protected Long id;
@Column (name = "NAME")
protected String name;
@Column (name = "FRIENDLY_NAME")
protected String friendlyName;
@Column (name = "FLD_TYPE")
protected String fieldType;
@Column (name = "SECURITY_LEVEL")
protected String securityLevel;
@Column (name = "HIDDEN_FLAG")
protected Boolean hiddenFlag = false;
@Column (name = "VLDTN_REGEX")
protected String validationRegEx;
@Column (name = "VLDTN_ERROR_MSSG_KEY")
protected String validationErrorMesageKey;
@Column (name = "MAX_LENGTH")
protected Integer maxLength;
@Column (name = "COLUMN_WIDTH")
protected String columnWidth;
@Column (name = "TEXT_AREA_FLAG")
protected Boolean textAreaFlag = false;
@ManyToOne (targetEntity = FieldEnumerationImpl.class)
@JoinColumn(name = "FLD_ENUM_ID")
protected FieldEnumeration fieldEnumeration;
@Column (name = "ALLOW_MULTIPLES")
protected Boolean allowMultiples = false;
@ManyToOne(targetEntity = FieldGroupImpl.class)
@JoinColumn(name = "FLD_GROUP_ID")
protected FieldGroup fieldGroup;
@Column(name="FLD_ORDER")
protected int fieldOrder;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public SupportedFieldType getFieldType() {
return fieldType!=null?SupportedFieldType.valueOf(fieldType):null;
}
@Override
public void setFieldType(SupportedFieldType fieldType) {
this.fieldType = fieldType!=null?fieldType.toString():null;
}
@Override
public String getSecurityLevel() {
return securityLevel;
}
@Override
public void setSecurityLevel(String securityLevel) {
this.securityLevel = securityLevel;
}
@Override
public Boolean getHiddenFlag() {
return hiddenFlag;
}
@Override
public void setHiddenFlag(Boolean hiddenFlag) {
this.hiddenFlag = hiddenFlag;
}
@Override
public String getValidationRegEx() {
return validationRegEx;
}
@Override
public void setValidationRegEx(String validationRegEx) {
this.validationRegEx = validationRegEx;
}
@Override
public Integer getMaxLength() {
return maxLength;
}
@Override
public void setMaxLength(Integer maxLength) {
this.maxLength = maxLength;
}
@Override
public String getColumnWidth() {
return columnWidth;
}
@Override
public void setColumnWidth(String columnWidth) {
this.columnWidth = columnWidth;
}
@Override
public Boolean getTextAreaFlag() {
return textAreaFlag;
}
@Override
public void setTextAreaFlag(Boolean textAreaFlag) {
this.textAreaFlag = textAreaFlag;
}
@Override
public Boolean getAllowMultiples() {
return allowMultiples;
}
@Override
public void setAllowMultiples(Boolean allowMultiples) {
this.allowMultiples = allowMultiples;
}
@Override
public String getFriendlyName() {
return friendlyName;
}
@Override
public void setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
}
@Override
public String getValidationErrorMesageKey() {
return validationErrorMesageKey;
}
@Override
public void setValidationErrorMesageKey(String validationErrorMesageKey) {
this.validationErrorMesageKey = validationErrorMesageKey;
}
@Override
public FieldGroup getFieldGroup() {
return fieldGroup;
}
@Override
public void setFieldGroup(FieldGroup fieldGroup) {
this.fieldGroup = fieldGroup;
}
@Override
public int getFieldOrder() {
return fieldOrder;
}
@Override
public void setFieldOrder(int fieldOrder) {
this.fieldOrder = fieldOrder;
}
@Override
public FieldEnumeration getFieldEnumeration() {
return fieldEnumeration;
}
@Override
public void setFieldEnumeration(FieldEnumeration fieldEnumeration) {
this.fieldEnumeration = fieldEnumeration;
}
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_field_domain_FieldDefinitionImpl.java |
1,341 | Collections.sort(products, new Comparator<Product>() {
public int compare(Product o1, Product o2) {
return new Integer(productIds.indexOf(o1.getId())).compareTo(productIds.indexOf(o2.getId()));
}
}); | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_service_solr_SolrSearchServiceImpl.java |
52 | @Controller("blAdminAssetUploadController")
@RequestMapping("/{sectionKey}")
public class AdminAssetUploadController extends AdminAbstractController {
@Resource(name = "blEntityConfiguration")
protected EntityConfiguration entityConfiguration;
@Resource(name = "blStaticAssetStorageService")
protected StaticAssetStorageService staticAssetStorageService;
@Resource(name = "blStaticAssetService")
protected StaticAssetService staticAssetService;
@Resource(name = "blAdminAssetController")
protected AdminAssetController assetController;
@RequestMapping(value = "/{id}/chooseAsset", method = RequestMethod.GET)
public String chooseMediaForMapKey(HttpServletRequest request, HttpServletResponse response, Model model,
@PathVariable(value = "sectionKey") String sectionKey,
@PathVariable(value = "id") String id,
@RequestParam MultiValueMap<String, String> requestParams) throws Exception {
Map<String, String> pathVars = new HashMap<String, String>();
pathVars.put("sectionKey", AdminAssetController.SECTION_KEY);
assetController.viewEntityList(request, response, model, pathVars, requestParams);
ListGrid listGrid = (ListGrid) model.asMap().get("listGrid");
listGrid.setPathOverride("/" + sectionKey + "/" + id + "/chooseAsset");
listGrid.setListGridType(Type.ASSET);
String userAgent = request.getHeader("User-Agent");
model.addAttribute("isIE", userAgent.contains("MSIE"));
model.addAttribute("viewType", "modal/selectAsset");
model.addAttribute("currentUrl", request.getRequestURL().toString());
model.addAttribute("modalHeaderType", "selectAsset");
model.addAttribute("currentParams", new ObjectMapper().writeValueAsString(requestParams));
// We need these attributes to be set appropriately here
model.addAttribute("entityId", id);
model.addAttribute("sectionKey", sectionKey);
return "modules/modalContainer";
}
@RequestMapping(value = "/{id}/uploadAsset", method = RequestMethod.POST)
public ResponseEntity<Map<String, Object>> upload(HttpServletRequest request,
@RequestParam("file") MultipartFile file,
@PathVariable(value="sectionKey") String sectionKey, @PathVariable(value="id") String id) throws IOException {
Map<String, Object> responseMap = new HashMap<String, Object>();
Map<String, String> properties = new HashMap<String, String>();
properties.put("entityType", sectionKey);
properties.put("entityId", id);
StaticAsset staticAsset = staticAssetService.createStaticAssetFromFile(file, properties);
staticAssetStorageService.createStaticAssetStorageFromFile(file, staticAsset);
String staticAssetUrlPrefix = staticAssetService.getStaticAssetUrlPrefix();
if (staticAssetUrlPrefix != null && !staticAssetUrlPrefix.startsWith("/")) {
staticAssetUrlPrefix = "/" + staticAssetUrlPrefix;
}
String assetUrl = staticAssetUrlPrefix + staticAsset.getFullUrl();
responseMap.put("adminDisplayAssetUrl", request.getContextPath() + assetUrl);
responseMap.put("assetUrl", assetUrl);
if (staticAsset instanceof ImageStaticAssetImpl) {
responseMap.put("image", Boolean.TRUE);
responseMap.put("assetThumbnail", assetUrl + "?smallAdminThumbnail");
responseMap.put("assetLarge", assetUrl + "?largeAdminThumbnail");
} else {
responseMap.put("image", Boolean.FALSE);
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/html; charset=utf-8");
return new ResponseEntity<Map<String, Object>>(responseMap, responseHeaders, HttpStatus.OK);
}
@RequestMapping(value = "/uploadAsset", method = RequestMethod.POST)
/**
* Used by the Asset list view to upload an asset and then immediately show the
* edit form for that record.
*
* @param request
* @param file
* @param sectionKey
* @return
* @throws IOException
*/
public String upload(HttpServletRequest request,
@RequestParam("file") MultipartFile file,
@PathVariable(value="sectionKey") String sectionKey) throws IOException {
StaticAsset staticAsset = staticAssetService.createStaticAssetFromFile(file, null);
staticAssetStorageService.createStaticAssetStorageFromFile(file, staticAsset);
String staticAssetUrlPrefix = staticAssetService.getStaticAssetUrlPrefix();
if (staticAssetUrlPrefix != null && !staticAssetUrlPrefix.startsWith("/")) {
staticAssetUrlPrefix = "/" + staticAssetUrlPrefix;
}
return "redirect:/assets/" + staticAsset.getId();
}
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_admin_web_controller_AdminAssetUploadController.java |
2,570 | threadPool.generic().execute(new Runnable() {
@Override
public void run() {
currentJoinThread = Thread.currentThread();
try {
innerJoinCluster();
} finally {
currentJoinThread = null;
}
}
}); | 0true
| src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java |
308 | new Processor() {
@Override
public void visit(Tree.Expression that) {
super.visit(that);
if (that.getStopIndex()<=endOfCodeInLine &&
that.getStartIndex()>=startOfCodeInLine) {
Token et = that.getMainEndToken();
Token st = that.getMainToken();
if (st!=null && st.getType()==CeylonLexer.LPAREN &&
(et==null || et.getType()!=CeylonLexer.RPAREN)) {
if (!change.getEdit().hasChildren()) {
change.addEdit(new InsertEdit(that.getStopIndex()+1,
")"));
}
}
}
}
@Override
public void visit(Tree.ParameterList that) {
super.visit(that);
terminate(that, CeylonLexer.RPAREN, ")");
}
public void visit(Tree.IndexExpression that) {
super.visit(that);
terminate(that, CeylonLexer.RBRACKET, "]");
}
@Override
public void visit(Tree.TypeParameterList that) {
super.visit(that);
terminate(that, CeylonLexer.LARGER_OP, ">");
}
@Override
public void visit(Tree.TypeArgumentList that) {
super.visit(that);
terminate(that, CeylonLexer.LARGER_OP, ">");
}
@Override
public void visit(Tree.PositionalArgumentList that) {
super.visit(that);
Token t = that.getToken();
if (t!=null && t.getType()==CeylonLexer.LPAREN) { //for infix function syntax
terminate(that, CeylonLexer.RPAREN, ")");
}
}
@Override
public void visit(Tree.NamedArgumentList that) {
super.visit(that);
terminate(that, CeylonLexer.RBRACE, " }");
}
@Override
public void visit(Tree.SequenceEnumeration that) {
super.visit(that);
terminate(that, CeylonLexer.RBRACE, " }");
}
@Override
public void visit(Tree.IterableType that) {
super.visit(that);
terminate(that, CeylonLexer.RBRACE, "}");
}
@Override
public void visit(Tree.Tuple that) {
super.visit(that);
terminate(that, CeylonLexer.RBRACKET, "]");
}
@Override
public void visit(Tree.TupleType that) {
super.visit(that);
terminate(that, CeylonLexer.RBRACKET, "]");
}
@Override
public void visit(Tree.ConditionList that) {
super.visit(that);
if (!that.getMainToken().getText().startsWith("<missing ")) {
terminate(that, CeylonLexer.RPAREN, ")");
}
}
@Override
public void visit(Tree.ForIterator that) {
super.visit(that);
if (!that.getMainToken().getText().startsWith("<missing ")) {
terminate(that, CeylonLexer.RPAREN, ")");
}
}
@Override
public void visit(Tree.ImportMemberOrTypeList that) {
super.visit(that);
terminate(that, CeylonLexer.RBRACE, " }");
}
@Override
public void visit(Tree.Import that) {
if (that.getImportMemberOrTypeList()==null||
that.getImportMemberOrTypeList()
.getMainToken().getText().startsWith("<missing ")) {
if (!change.getEdit().hasChildren()) {
if (that.getImportPath()!=null &&
that.getImportPath().getStopIndex()<=endOfCodeInLine) {
change.addEdit(new InsertEdit(that.getImportPath().getStopIndex()+1,
" { ... }"));
}
}
}
super.visit(that);
}
@Override
public void visit(Tree.ImportModule that) {
super.visit(that);
if (that.getImportPath()!=null) {
terminate(that, CeylonLexer.SEMICOLON, ";");
}
if (that.getVersion()==null) {
if (!change.getEdit().hasChildren()) {
if (that.getImportPath()!=null &&
that.getImportPath().getStopIndex()<=endOfCodeInLine) {
change.addEdit(new InsertEdit(that.getImportPath().getStopIndex()+1,
" \"1.0.0\""));
}
}
}
}
@Override
public void visit(Tree.ImportModuleList that) {
super.visit(that);
terminate(that, CeylonLexer.RBRACE, " }");
}
@Override
public void visit(Tree.PackageDescriptor that) {
super.visit(that);
terminate(that, CeylonLexer.SEMICOLON, ";");
}
@Override
public void visit(Tree.Directive that) {
super.visit(that);
terminate(that, CeylonLexer.SEMICOLON, ";");
}
@Override
public void visit(Tree.Body that) {
super.visit(that);
terminate(that, CeylonLexer.RBRACE, " }");
}
@Override
public void visit(Tree.MetaLiteral that) {
super.visit(that);
terminate(that, CeylonLexer.BACKTICK, "`");
}
@Override
public void visit(Tree.StatementOrArgument that) {
super.visit(that);
if (/*that instanceof Tree.ExecutableStatement &&
!(that instanceof Tree.ControlStatement) ||
that instanceof Tree.AttributeDeclaration ||
that instanceof Tree.MethodDeclaration ||
that instanceof Tree.ClassDeclaration ||
that instanceof Tree.InterfaceDeclaration ||*/
that instanceof Tree.SpecifiedArgument) {
terminate(that, CeylonLexer.SEMICOLON, ";");
}
}
private boolean inLine(Node that) {
return that.getStartIndex()>=startOfCodeInLine &&
that.getStartIndex()<=endOfCodeInLine;
}
/*private void initiate(Node that, int tokenType, String ch) {
if (inLine(that)) {
Token mt = that.getMainToken();
if (mt==null || mt.getType()!=tokenType ||
mt.getText().startsWith("<missing ")) {
if (!change.getEdit().hasChildren()) {
change.addEdit(new InsertEdit(that.getStartIndex(), ch));
}
}
}
}*/
private void terminate(Node that, int tokenType, String ch) {
if (inLine(that)) {
Token et = that.getMainEndToken();
if ((et==null || et.getType()!=tokenType) ||
that.getStopIndex()>endOfCodeInLine) {
if (!change.getEdit().hasChildren()) {
change.addEdit(new InsertEdit(min(endOfCodeInLine,that.getStopIndex())+1, ch));
}
}
}
}
@Override
public void visit(Tree.AnyClass that) {
super.visit(that);
if (that.getParameterList()==null) {
if (!change.getEdit().hasChildren()) {
change.addEdit(new InsertEdit(that.getIdentifier().getStopIndex()+1, "()"));
}
}
}
@Override
public void visit(Tree.AnyMethod that) {
super.visit(that);
if (that.getParameterLists().isEmpty()) {
if (!change.getEdit().hasChildren()) {
change.addEdit(new InsertEdit(that.getIdentifier().getStopIndex()+1, "()"));
}
}
}
}.visit(rootNode); | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_TerminateStatementAction.java |
435 | static final class Fields {
static final XContentBuilderString SHARDS = new XContentBuilderString("shards");
static final XContentBuilderString TOTAL = new XContentBuilderString("total");
static final XContentBuilderString PRIMARIES = new XContentBuilderString("primaries");
static final XContentBuilderString REPLICATION = new XContentBuilderString("replication");
static final XContentBuilderString MIN = new XContentBuilderString("min");
static final XContentBuilderString MAX = new XContentBuilderString("max");
static final XContentBuilderString AVG = new XContentBuilderString("avg");
static final XContentBuilderString INDEX = new XContentBuilderString("index");
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsIndices.java |
1,668 | runnable = new Runnable() { public void run() { map.get(null); } }; | 0true
| hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java |
277 | public class Attachment implements Serializable {
private static final long serialVersionUID = 1L;
private String filename;
private byte[] data;
private String mimeType;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_email_service_message_Attachment.java |
1,110 | public class ServicesConfig {
private boolean enableDefaults = true;
private final Map<String, ServiceConfig> services = new HashMap<String, ServiceConfig>();
public ServicesConfig() {
}
public boolean isEnableDefaults() {
return enableDefaults;
}
public ServicesConfig setEnableDefaults(final boolean enableDefaults) {
this.enableDefaults = enableDefaults;
return this;
}
public ServicesConfig clear() {
services.clear();
return this;
}
public Collection<ServiceConfig> getServiceConfigs() {
return Collections.unmodifiableCollection(services.values());
}
public ServicesConfig setServiceConfigs(Collection<ServiceConfig> services) {
clear();
for (ServiceConfig service : services) {
addServiceConfig(service);
}
return this;
}
public ServicesConfig addServiceConfig(ServiceConfig service) {
services.put(service.getName(), service);
return this;
}
public ServiceConfig getServiceConfig(String name) {
return services.get(name);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ServicesConfig{");
sb.append("enableDefaults=").append(enableDefaults);
sb.append(", services=").append(services);
sb.append('}');
return sb.toString();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_config_ServicesConfig.java |
2,238 | public class ScriptScoreFunction extends ScoreFunction {
private final String sScript;
private final Map<String, Object> params;
private final SearchScript script;
public ScriptScoreFunction(String sScript, Map<String, Object> params, SearchScript script) {
super(CombineFunction.REPLACE);
this.sScript = sScript;
this.params = params;
this.script = script;
}
@Override
public void setNextReader(AtomicReaderContext ctx) {
script.setNextReader(ctx);
}
@Override
public double score(int docId, float subQueryScore) {
script.setNextDocId(docId);
script.setNextScore(subQueryScore);
return script.runAsDouble();
}
@Override
public Explanation explainScore(int docId, Explanation subQueryExpl) {
Explanation exp;
if (script instanceof ExplainableSearchScript) {
script.setNextDocId(docId);
script.setNextScore(subQueryExpl.getValue());
exp = ((ExplainableSearchScript) script).explain(subQueryExpl);
} else {
double score = score(docId, subQueryExpl.getValue());
exp = new Explanation(CombineFunction.toFloat(score), "script score function: composed of:");
exp.addDetail(subQueryExpl);
}
return exp;
}
@Override
public String toString() {
return "script[" + sScript + "], params [" + params + "]";
}
} | 1no label
| src_main_java_org_elasticsearch_common_lucene_search_function_ScriptScoreFunction.java |
5,807 | private static class CustomWeightedSpanTermExtractor extends WeightedSpanTermExtractor {
public CustomWeightedSpanTermExtractor() {
super();
}
public CustomWeightedSpanTermExtractor(String defaultField) {
super(defaultField);
}
@Override
protected void extractUnknownQuery(Query query,
Map<String, WeightedSpanTerm> terms) throws IOException {
if (query instanceof FunctionScoreQuery) {
query = ((FunctionScoreQuery) query).getSubQuery();
extract(query, terms);
} else if (query instanceof FiltersFunctionScoreQuery) {
query = ((FiltersFunctionScoreQuery) query).getSubQuery();
extract(query, terms);
} else if (query instanceof XFilteredQuery) {
query = ((XFilteredQuery) query).getQuery();
extract(query, terms);
}
}
} | 1no label
| src_main_java_org_elasticsearch_search_highlight_CustomQueryScorer.java |
49 | @SuppressWarnings("restriction")
public class OUnsafeByteArrayComparator implements Comparator<byte[]> {
public static final OUnsafeByteArrayComparator INSTANCE = new OUnsafeByteArrayComparator();
private static final Unsafe unsafe;
private static final int BYTE_ARRAY_OFFSET;
private static final boolean littleEndian = ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN);
private static final int LONG_SIZE = Long.SIZE / Byte.SIZE;
static {
unsafe = (Unsafe) AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return f.get(null);
} catch (NoSuchFieldException e) {
throw new Error();
} catch (IllegalAccessException e) {
throw new Error();
}
}
});
BYTE_ARRAY_OFFSET = unsafe.arrayBaseOffset(byte[].class);
final int byteArrayScale = unsafe.arrayIndexScale(byte[].class);
if (byteArrayScale != 1)
throw new Error();
}
public int compare(byte[] arrayOne, byte[] arrayTwo) {
if (arrayOne.length > arrayTwo.length)
return 1;
if (arrayOne.length < arrayTwo.length)
return -1;
final int WORDS = arrayOne.length / LONG_SIZE;
for (int i = 0; i < WORDS * LONG_SIZE; i += LONG_SIZE) {
final long index = i + BYTE_ARRAY_OFFSET;
final long wOne = unsafe.getLong(arrayOne, index);
final long wTwo = unsafe.getLong(arrayTwo, index);
if (wOne == wTwo)
continue;
if (littleEndian)
return lessThanUnsigned(Long.reverseBytes(wOne), Long.reverseBytes(wTwo)) ? -1 : 1;
return lessThanUnsigned(wOne, wTwo) ? -1 : 1;
}
for (int i = WORDS * LONG_SIZE; i < arrayOne.length; i++) {
int diff = compareUnsignedByte(arrayOne[i], arrayTwo[i]);
if (diff != 0)
return diff;
}
return 0;
}
private static boolean lessThanUnsigned(long longOne, long longTwo) {
return (longOne + Long.MIN_VALUE) < (longTwo + Long.MIN_VALUE);
}
private static int compareUnsignedByte(byte byteOne, byte byteTwo) {
final int valOne = byteOne & 0xFF;
final int valTwo = byteTwo & 0xFF;
return valOne - valTwo;
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_comparator_OUnsafeByteArrayComparator.java |
990 | @SuppressWarnings("serial")
public class ORecordSerializerJSON extends ORecordSerializerStringAbstract {
public static final String NAME = "json";
public static final ORecordSerializerJSON INSTANCE = new ORecordSerializerJSON();
public static final String ATTRIBUTE_FIELD_TYPES = "@fieldTypes";
public static final char[] PARAMETER_SEPARATOR = new char[] { ':', ',' };
private static final Long MAX_INT = new Long(Integer.MAX_VALUE);
private static final Long MIN_INT = new Long(Integer.MIN_VALUE);
private static final Double MAX_FLOAT = new Double(Float.MAX_VALUE);
private static final Double MIN_FLOAT = new Double(Float.MIN_VALUE);
public class FormatSettings {
public boolean includeVer;
public boolean includeType;
public boolean includeId;
public boolean includeClazz;
public boolean attribSameRow;
public boolean alwaysFetchEmbeddedDocuments;
public int indentLevel;
public String fetchPlan = null;
public boolean keepTypes = true;
public boolean dateAsLong = false;
public boolean prettyPrint = false;
public FormatSettings(final String iFormat) {
if (iFormat == null) {
includeType = true;
includeVer = true;
includeId = true;
includeClazz = true;
attribSameRow = true;
indentLevel = 1;
fetchPlan = "";
keepTypes = true;
alwaysFetchEmbeddedDocuments = true;
} else {
includeType = false;
includeVer = false;
includeId = false;
includeClazz = false;
attribSameRow = false;
alwaysFetchEmbeddedDocuments = false;
indentLevel = 1;
keepTypes = false;
final String[] format = iFormat.split(",");
for (String f : format)
if (f.equals("type"))
includeType = true;
else if (f.equals("rid"))
includeId = true;
else if (f.equals("version"))
includeVer = true;
else if (f.equals("class"))
includeClazz = true;
else if (f.equals("attribSameRow"))
attribSameRow = true;
else if (f.startsWith("indent"))
indentLevel = Integer.parseInt(f.substring(f.indexOf(':') + 1));
else if (f.startsWith("fetchPlan"))
fetchPlan = f.substring(f.indexOf(':') + 1);
else if (f.startsWith("keepTypes"))
keepTypes = true;
else if (f.startsWith("alwaysFetchEmbedded"))
alwaysFetchEmbeddedDocuments = true;
else if (f.startsWith("dateAsLong"))
dateAsLong = true;
else if (f.startsWith("prettyPrint"))
prettyPrint = true;
}
}
}
public ORecordInternal<?> fromString(String iSource, ORecordInternal<?> iRecord, final String[] iFields, boolean needReload) {
return fromString(iSource, iRecord, iFields, null, needReload);
}
@Override
public ORecordInternal<?> fromString(String iSource, ORecordInternal<?> iRecord, final String[] iFields) {
return fromString(iSource, iRecord, iFields, null, false);
}
public ORecordInternal<?> fromString(String iSource, ORecordInternal<?> iRecord, final String[] iFields, final String iOptions,
boolean needReload) {
if (iSource == null)
throw new OSerializationException("Error on unmarshalling JSON content: content is null");
iSource = iSource.trim();
if (!iSource.startsWith("{") || !iSource.endsWith("}"))
throw new OSerializationException("Error on unmarshalling JSON content: content must be between { }");
if (iRecord != null)
// RESET ALL THE FIELDS
iRecord.clear();
iSource = iSource.substring(1, iSource.length() - 1).trim();
// PARSE OPTIONS
boolean noMap = false;
if (iOptions != null) {
final String[] format = iOptions.split(",");
for (String f : format)
if (f.equals("noMap"))
noMap = true;
}
final List<String> fields = OStringSerializerHelper.smartSplit(iSource, PARAMETER_SEPARATOR, 0, -1, true, true, false, ' ',
'\n', '\r', '\t');
if (fields.size() % 2 != 0)
throw new OSerializationException("Error on unmarshalling JSON content: wrong format. Use <field> : <value>");
Map<String, Character> fieldTypes = null;
if (fields != null && fields.size() > 0) {
// SEARCH FOR FIELD TYPES IF ANY
for (int i = 0; i < fields.size(); i += 2) {
final String fieldName = OStringSerializerHelper.getStringContent(fields.get(i));
final String fieldValue = fields.get(i + 1);
final String fieldValueAsString = OStringSerializerHelper.getStringContent(fieldValue);
if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) {
// LOAD THE FIELD TYPE MAP
final String[] fieldTypesParts = fieldValueAsString.split(",");
if (fieldTypesParts.length > 0) {
fieldTypes = new HashMap<String, Character>();
String[] part;
for (String f : fieldTypesParts) {
part = f.split("=");
if (part.length == 2)
fieldTypes.put(part[0], part[1].charAt(0));
}
}
} else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_TYPE)) {
if (iRecord == null || iRecord.getRecordType() != fieldValueAsString.charAt(0)) {
// CREATE THE RIGHT RECORD INSTANCE
iRecord = Orient.instance().getRecordFactoryManager().newInstance((byte) fieldValueAsString.charAt(0));
}
} else if (needReload && fieldName.equals(ODocumentHelper.ATTRIBUTE_RID) && iRecord instanceof ODocument) {
if (fieldValue != null && fieldValue.length() > 0) {
ORecordInternal<?> localRecord = ODatabaseRecordThreadLocal.INSTANCE.get().load(new ORecordId(fieldValueAsString));
if (localRecord != null)
iRecord = localRecord;
}
} else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_CLASS) && iRecord instanceof ODocument) {
((ODocument) iRecord).setClassNameIfExists("null".equals(fieldValueAsString) ? null : fieldValueAsString);
}
}
try {
int recordVersion = 0;
long timestamp = 0L;
long macAddress = 0L;
for (int i = 0; i < fields.size(); i += 2) {
final String fieldName = OStringSerializerHelper.getStringContent(fields.get(i));
final String fieldValue = fields.get(i + 1);
final String fieldValueAsString = OStringSerializerHelper.getStringContent(fieldValue);
// RECORD ATTRIBUTES
if (fieldName.equals(ODocumentHelper.ATTRIBUTE_RID))
iRecord.setIdentity(new ORecordId(fieldValueAsString));
else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_VERSION))
if (OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean())
recordVersion = Integer.parseInt(fieldValue);
else
iRecord.getRecordVersion().setCounter(Integer.parseInt(fieldValue));
else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_VERSION_TIMESTAMP)) {
if (OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean())
timestamp = Long.parseLong(fieldValue);
} else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_VERSION_MACADDRESS)) {
if (OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean())
macAddress = Long.parseLong(fieldValue);
} else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_TYPE)) {
continue;
} else if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument)
// JUMP IT
continue;
// RECORD VALUE(S)
else if (fieldName.equals("value") && !(iRecord instanceof ODocument)) {
if ("null".equals(fieldValue))
iRecord.fromStream(new byte[] {});
else if (iRecord instanceof ORecordBytes) {
// BYTES
iRecord.fromStream(OBase64Utils.decode(fieldValueAsString));
} else if (iRecord instanceof ORecordStringable) {
((ORecordStringable) iRecord).value(fieldValueAsString);
}
} else {
if (iRecord instanceof ODocument) {
final ODocument doc = ((ODocument) iRecord);
// DETERMINE THE TYPE FROM THE SCHEMA
OType type = null;
final OClass cls = doc.getSchemaClass();
if (cls != null) {
final OProperty prop = cls.getProperty(fieldName);
if (prop != null)
type = prop.getType();
}
final Object v = getValue(doc, fieldName, fieldValue, fieldValueAsString, type, null, fieldTypes, noMap, iOptions);
if (v != null)
if (v instanceof Collection<?> && !((Collection<?>) v).isEmpty()) {
if (v instanceof ORecordLazyMultiValue)
((ORecordLazyMultiValue) v).setAutoConvertToRecord(false);
// CHECK IF THE COLLECTION IS EMBEDDED
if (type == null) {
// TRY TO UNDERSTAND BY FIRST ITEM
Object first = ((Collection<?>) v).iterator().next();
if (first != null && first instanceof ORecord<?> && !((ORecord<?>) first).getIdentity().isValid())
type = v instanceof Set<?> ? OType.EMBEDDEDSET : OType.EMBEDDEDLIST;
}
if (type != null) {
// TREAT IT AS EMBEDDED
doc.field(fieldName, v, type);
continue;
}
} else if (v instanceof Map<?, ?> && !((Map<?, ?>) v).isEmpty()) {
// CHECK IF THE MAP IS EMBEDDED
Object first = ((Map<?, ?>) v).values().iterator().next();
if (first != null && first instanceof ORecord<?> && !((ORecord<?>) first).getIdentity().isValid()) {
doc.field(fieldName, v, OType.EMBEDDEDMAP);
continue;
}
} else if (v instanceof ODocument && type != null && type.isLink()) {
String className = ((ODocument) v).getClassName();
if (className != null && className.length() > 0)
((ODocument) v).save();
}
if (type == null && fieldTypes != null && fieldTypes.containsKey(fieldName))
type = ORecordSerializerStringAbstract.getType(fieldValue, fieldTypes.get(fieldName));
if (type != null)
doc.field(fieldName, v, type);
else
doc.field(fieldName, v);
}
}
}
if (timestamp != 0 && OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean()) {
((ODistributedVersion) iRecord.getRecordVersion()).update(recordVersion, timestamp, macAddress);
}
} catch (Exception e) {
e.printStackTrace();
throw new OSerializationException("Error on unmarshalling JSON content for record " + iRecord.getIdentity(), e);
}
}
return iRecord;
}
@SuppressWarnings("unchecked")
private Object getValue(final ODocument iRecord, String iFieldName, String iFieldValue, String iFieldValueAsString, OType iType,
OType iLinkedType, final Map<String, Character> iFieldTypes, final boolean iNoMap, final String iOptions) {
if (iFieldValue.equals("null"))
return null;
if (iFieldName != null)
if (iRecord.getSchemaClass() != null) {
final OProperty p = iRecord.getSchemaClass().getProperty(iFieldName);
if (p != null) {
iType = p.getType();
iLinkedType = p.getLinkedType();
}
}
if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}")) {
// OBJECT OR MAP. CHECK THE TYPE ATTRIBUTE TO KNOW IT
iFieldValueAsString = iFieldValue.substring(1, iFieldValue.length() - 1);
final String[] fields = OStringParser.getWords(iFieldValueAsString, ":,", true);
if (fields == null || fields.length == 0)
// EMPTY, RETURN an EMPTY HASHMAP
return new HashMap<String, Object>();
if (iNoMap || hasTypeField(fields)) {
// OBJECT
final ORecordInternal<?> recordInternal = fromString(iFieldValue, new ODocument(), null, iOptions, false);
if (iType != null && iType.isLink()) {
} else if (recordInternal instanceof ODocument)
((ODocument) recordInternal).addOwner(iRecord);
return recordInternal;
} else {
if (fields.length % 2 == 1)
throw new OSerializationException("Bad JSON format on map. Expected pairs of field:value but received '"
+ iFieldValueAsString + "'");
// MAP
final Map<String, Object> embeddedMap = new LinkedHashMap<String, Object>();
for (int i = 0; i < fields.length; i += 2) {
iFieldName = fields[i];
if (iFieldName.length() >= 2)
iFieldName = iFieldName.substring(1, iFieldName.length() - 1);
iFieldValue = fields[i + 1];
iFieldValueAsString = OStringSerializerHelper.getStringContent(iFieldValue);
embeddedMap.put(iFieldName,
getValue(iRecord, null, iFieldValue, iFieldValueAsString, iLinkedType, null, iFieldTypes, iNoMap, iOptions));
}
return embeddedMap;
}
} else if (iFieldValue.startsWith("[") && iFieldValue.endsWith("]")) {
// EMBEDDED VALUES
final Collection<?> embeddedCollection;
if (iType == OType.LINKSET)
embeddedCollection = new OMVRBTreeRIDSet(iRecord);
else if (iType == OType.EMBEDDEDSET)
embeddedCollection = new OTrackedSet<Object>(iRecord);
else if (iType == OType.LINKLIST)
embeddedCollection = new ORecordLazyList(iRecord);
else
embeddedCollection = new OTrackedList<Object>(iRecord);
iFieldValue = iFieldValue.substring(1, iFieldValue.length() - 1);
if (!iFieldValue.isEmpty()) {
// EMBEDDED VALUES
List<String> items = OStringSerializerHelper.smartSplit(iFieldValue, ',');
Object collectionItem;
for (String item : items) {
iFieldValue = item.trim();
if (!(iLinkedType == OType.DATE || iLinkedType == OType.BYTE || iLinkedType == OType.INTEGER || iLinkedType == OType.LONG
|| iLinkedType == OType.DATETIME || iLinkedType == OType.DECIMAL || iLinkedType == OType.DOUBLE || iLinkedType == OType.FLOAT))
iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue;
else
iFieldValueAsString = iFieldValue;
collectionItem = getValue(iRecord, null, iFieldValue, iFieldValueAsString, iLinkedType, null, iFieldTypes, iNoMap,
iOptions);
if (iType != null && iType.isLink()) {
// LINK
} else if (collectionItem instanceof ODocument && iRecord instanceof ODocument)
// SET THE OWNER
((ODocument) collectionItem).addOwner(iRecord);
if (collectionItem instanceof String && ((String) collectionItem).length() == 0)
continue;
((Collection<Object>) embeddedCollection).add(collectionItem);
}
}
return embeddedCollection;
}
if (iType == null)
// TRY TO DETERMINE THE CONTAINED TYPE from THE FIRST VALUE
if (iFieldValue.charAt(0) != '\"' && iFieldValue.charAt(0) != '\'') {
if (iFieldValue.equalsIgnoreCase("false") || iFieldValue.equalsIgnoreCase("true"))
iType = OType.BOOLEAN;
else {
Character c = null;
if (iFieldTypes != null) {
c = iFieldTypes.get(iFieldName);
if (c != null)
iType = ORecordSerializerStringAbstract.getType(iFieldValue + c);
}
if (c == null && !iFieldValue.isEmpty()) {
// TRY TO AUTODETERMINE THE BEST TYPE
if (iFieldValue.charAt(0) == ORID.PREFIX && iFieldValue.contains(":"))
iType = OType.LINK;
else if (OStringSerializerHelper.contains(iFieldValue, '.')) {
// DECIMAL FORMAT: DETERMINE IF DOUBLE OR FLOAT
final Double v = new Double(OStringSerializerHelper.getStringContent(iFieldValue));
if (v.doubleValue() > 0) {
// POSITIVE NUMBER
if (v.compareTo(MAX_FLOAT) <= 0)
return v.floatValue();
} else if (v.compareTo(MIN_FLOAT) >= 0)
// NEGATIVE NUMBER
return v.floatValue();
return v;
} else {
final Long v = new Long(OStringSerializerHelper.getStringContent(iFieldValue));
// INTEGER FORMAT: DETERMINE IF DOUBLE OR FLOAT
if (v.longValue() > 0) {
// POSITIVE NUMBER
if (v.compareTo(MAX_INT) <= 0)
return v.intValue();
} else if (v.compareTo(MIN_INT) >= 0)
// NEGATIVE NUMBER
return v.intValue();
return v;
}
}
}
} else if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}"))
iType = OType.EMBEDDED;
else {
if (iFieldValueAsString.length() >= 4 && iFieldValueAsString.charAt(0) == ORID.PREFIX && iFieldValueAsString.contains(":")) {
// IS IT A LINK?
final List<String> parts = OStringSerializerHelper.split(iFieldValueAsString, 1, -1, ':');
if (parts.size() == 2)
try {
Short.parseShort(parts.get(0));
// YES, IT'S A LINK
if (parts.get(1).matches("\\d+")) {
iType = OType.LINK;
}
} catch (Exception e) {
}
}
if (iFieldTypes != null) {
Character c = null;
c = iFieldTypes.get(iFieldName);
if (c != null)
iType = ORecordSerializerStringAbstract.getType(iFieldValueAsString, c);
}
if (iType == null) {
if (iFieldValueAsString.length() == ODateHelper.getDateFormat().length())
// TRY TO PARSE AS DATE
try {
return ODateHelper.getDateFormatInstance().parseObject(iFieldValueAsString);
} catch (Exception e) {
// IGNORE IT
}
if (iFieldValueAsString.length() == ODateHelper.getDateTimeFormat().length())
// TRY TO PARSE AS DATETIME
try {
return ODateHelper.getDateTimeFormatInstance().parseObject(iFieldValueAsString);
} catch (Exception e) {
// IGNORE IT
}
iType = OType.STRING;
}
}
if (iType != null)
switch (iType) {
case STRING:
return decodeJSON(iFieldValueAsString);
case LINK:
final int pos = iFieldValueAsString.indexOf('@');
if (pos > -1)
// CREATE DOCUMENT
return new ODocument(iFieldValueAsString.substring(1, pos), new ORecordId(iFieldValueAsString.substring(pos + 1)));
else {
// CREATE SIMPLE RID
return new ORecordId(iFieldValueAsString);
}
case EMBEDDED:
return fromString(iFieldValueAsString);
case DATE:
if (iFieldValueAsString == null || iFieldValueAsString.equals(""))
return null;
try {
// TRY TO PARSE AS LONG
return Long.parseLong(iFieldValueAsString);
} catch (NumberFormatException e) {
try {
// TRY TO PARSE AS DATE
return ODateHelper.getDateFormatInstance().parseObject(iFieldValueAsString);
} catch (ParseException ex) {
throw new OSerializationException("Unable to unmarshall date (format=" + ODateHelper.getDateFormat() + ") : "
+ iFieldValueAsString, e);
}
}
case DATETIME:
if (iFieldValueAsString == null || iFieldValueAsString.equals(""))
return null;
try {
// TRY TO PARSE AS LONG
return Long.parseLong(iFieldValueAsString);
} catch (NumberFormatException e) {
try {
// TRY TO PARSE AS DATETIME
return ODateHelper.getDateTimeFormatInstance().parseObject(iFieldValueAsString);
} catch (ParseException ex) {
throw new OSerializationException("Unable to unmarshall datetime (format=" + ODateHelper.getDateTimeFormat() + ") : "
+ iFieldValueAsString, e);
}
}
case BINARY:
return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValueAsString);
default:
return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValue);
}
return iFieldValueAsString;
}
private String decodeJSON(String iFieldValueAsString) {
iFieldValueAsString = OStringParser.replaceAll(iFieldValueAsString, "\\\\", "\\");
iFieldValueAsString = OStringParser.replaceAll(iFieldValueAsString, "\\\"", "\"");
iFieldValueAsString = OStringParser.replaceAll(iFieldValueAsString, "\\/", "/");
return iFieldValueAsString;
}
@Override
public StringBuilder toString(final ORecordInternal<?> iRecord, final StringBuilder iOutput, final String iFormat,
final OUserObject2RecordHandler iObjHandler, final Set<ODocument> iMarshalledRecords, boolean iOnlyDelta,
boolean autoDetectCollectionType) {
try {
final StringWriter buffer = new StringWriter();
final OJSONWriter json = new OJSONWriter(buffer, iFormat);
final FormatSettings settings = new FormatSettings(iFormat);
json.beginObject();
OJSONFetchContext context = new OJSONFetchContext(json, settings);
context.writeSignature(json, iRecord);
if (iRecord instanceof ORecordSchemaAware<?>) {
OFetchHelper.fetch(iRecord, null, OFetchHelper.buildFetchPlan(settings.fetchPlan), new OJSONFetchListener(), context,
iFormat);
} else if (iRecord instanceof ORecordStringable) {
// STRINGABLE
final ORecordStringable record = (ORecordStringable) iRecord;
json.writeAttribute(settings.indentLevel + 1, true, "value", record.value());
} else if (iRecord instanceof ORecordBytes) {
// BYTES
final ORecordBytes record = (ORecordBytes) iRecord;
json.writeAttribute(settings.indentLevel + 1, true, "value", OBase64Utils.encodeBytes(record.toStream()));
} else
throw new OSerializationException("Error on marshalling record of type '" + iRecord.getClass()
+ "' to JSON. The record type cannot be exported to JSON");
json.endObject(0, true);
iOutput.append(buffer);
return iOutput;
} catch (IOException e) {
throw new OSerializationException("Error on marshalling of record to JSON", e);
}
}
private boolean hasTypeField(final String[] fields) {
for (int i = 0; i < fields.length; i = i + 2) {
if (fields[i].equals("\"@type\"") || fields[i].equals("'@type'")) {
return true;
}
}
return false;
}
@Override
public String toString() {
return NAME;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_record_string_ORecordSerializerJSON.java |
2,540 | public class SimpleQueryTests extends ElasticsearchIntegrationTest {
@Test
public void passQueryAsStringTest() throws Exception {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
client().prepareIndex("test", "type1", "1").setSource("field1", "value1_1", "field2", "value2_1").setRefresh(true).get();
CountResponse countResponse = client().prepareCount().setSource(new BytesArray("{ \"query\" : { \"term\" : { \"field1\" : \"value1_1\" }}}").array()).get();
assertHitCount(countResponse, 1l);
}
@Test
public void testIndexOptions() throws Exception {
assertAcked(prepareCreate("test")
.addMapping("type1", "field1", "type=string,index_options=docs")
.setSettings("index.number_of_shards", 1));
client().prepareIndex("test", "type1", "1").setSource("field1", "quick brown fox", "field2", "quick brown fox").get();
client().prepareIndex("test", "type1", "2").setSource("field1", "quick lazy huge brown fox", "field2", "quick lazy huge brown fox").setRefresh(true).get();
CountResponse countResponse = client().prepareCount().setQuery(QueryBuilders.matchQuery("field2", "quick brown").type(Type.PHRASE).slop(0)).get();
assertHitCount(countResponse, 1l);
try {
client().prepareCount().setQuery(QueryBuilders.matchQuery("field1", "quick brown").type(Type.PHRASE).slop(0)).get();
} catch (SearchPhaseExecutionException e) {
assertTrue("wrong exception message " + e.getMessage(), e.getMessage().endsWith("IllegalStateException[field \"field1\" was indexed without position data; cannot run PhraseQuery (term=quick)]; }"));
}
}
@Test
public void testCommonTermsQuery() throws Exception {
assertAcked(prepareCreate("test")
.addMapping("type1", "field1", "type=string,analyzer=whitespace")
.setSettings(SETTING_NUMBER_OF_SHARDS, 1));
indexRandom(true,
client().prepareIndex("test", "type1", "3").setSource("field1", "quick lazy huge brown pidgin", "field2", "the quick lazy huge brown fox jumps over the tree"),
client().prepareIndex("test", "type1", "1").setSource("field1", "the quick brown fox"),
client().prepareIndex("test", "type1", "2").setSource("field1", "the quick lazy huge brown fox jumps over the tree") );
CountResponse countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3).lowFreqOperator(Operator.OR)).get();
assertHitCount(countResponse, 3l);
countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3).lowFreqOperator(Operator.AND)).get();
assertHitCount(countResponse, 2l);
// Default
countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3)).get();
assertHitCount(countResponse, 3l);
countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the huge fox").lowFreqMinimumShouldMatch("2")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the lazy fox brown").cutoffFrequency(1).highFreqMinimumShouldMatch("3")).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the lazy fox brown").cutoffFrequency(1).highFreqMinimumShouldMatch("4")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setSource(new BytesArray("{ \"query\" : { \"common\" : { \"field1\" : { \"query\" : \"the lazy fox brown\", \"cutoff_frequency\" : 1, \"minimum_should_match\" : { \"high_freq\" : 4 } } } } }").array()).get();
assertHitCount(countResponse, 1l);
// Default
countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the lazy fox brown").cutoffFrequency(1)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3).analyzer("standard")).get();
assertHitCount(countResponse, 3l);
// standard drops "the" since its a stopword
// try the same with match query
countResponse = client().prepareCount().setQuery(QueryBuilders.matchQuery("field1", "the quick brown").cutoffFrequency(3).operator(MatchQueryBuilder.Operator.AND)).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(QueryBuilders.matchQuery("field1", "the quick brown").cutoffFrequency(3).operator(MatchQueryBuilder.Operator.OR)).get();
assertHitCount(countResponse, 3l);
countResponse = client().prepareCount().setQuery(QueryBuilders.matchQuery("field1", "the quick brown").cutoffFrequency(3).operator(MatchQueryBuilder.Operator.AND).analyzer("stop")).get();
assertHitCount(countResponse, 3l);
// standard drops "the" since its a stopword
// try the same with multi match query
countResponse = client().prepareCount().setQuery(QueryBuilders.multiMatchQuery("the quick brown", "field1", "field2").cutoffFrequency(3).operator(MatchQueryBuilder.Operator.AND)).get();
assertHitCount(countResponse, 3l);
}
@Test
public void queryStringAnalyzedWildcard() throws Exception {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
client().prepareIndex("test", "type1", "1").setSource("field1", "value_1", "field2", "value_2").get();
refresh();
CountResponse countResponse = client().prepareCount().setQuery(queryString("value*").analyzeWildcard(true)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("*ue*").analyzeWildcard(true)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("*ue_1").analyzeWildcard(true)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("val*e_1").analyzeWildcard(true)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("v?l*e?1").analyzeWildcard(true)).get();
assertHitCount(countResponse, 1l);
}
@Test
public void testLowercaseExpandedTerms() {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
client().prepareIndex("test", "type1", "1").setSource("field1", "value_1", "field2", "value_2").get();
refresh();
CountResponse countResponse = client().prepareCount().setQuery(queryString("VALUE_3~1").lowercaseExpandedTerms(true)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("VALUE_3~1").lowercaseExpandedTerms(false)).get();
assertHitCount(countResponse, 0l);
countResponse = client().prepareCount().setQuery(queryString("ValUE_*").lowercaseExpandedTerms(true)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("vAl*E_1")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("[VALUE_1 TO VALUE_3]")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("[VALUE_1 TO VALUE_3]").lowercaseExpandedTerms(false)).get();
assertHitCount(countResponse, 0l);
}
@Test
public void testDateRangeInQueryString() {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
String aMonthAgo = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).minusMonths(1));
String aMonthFromNow = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).plusMonths(1));
client().prepareIndex("test", "type", "1").setSource("past", aMonthAgo, "future", aMonthFromNow).get();
refresh();
CountResponse countResponse = client().prepareCount().setQuery(queryString("past:[now-2M/d TO now/d]")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("future:[now/d TO now+2M/d]").lowercaseExpandedTerms(false)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("future:[now/D TO now+2M/d]").lowercaseExpandedTerms(false)).get();
//D is an unsupported unit in date math
assertThat(countResponse.getSuccessfulShards(), equalTo(0));
assertThat(countResponse.getFailedShards(), equalTo(1));
assertThat(countResponse.getShardFailures().length, equalTo(1));
assertThat(countResponse.getShardFailures()[0].reason(), allOf(containsString("Failed to parse"), containsString("unit [D] not supported for date math")));
}
@Test
public void typeFilterTypeIndexedTests() throws Exception {
typeFilterTests("not_analyzed");
}
@Test
public void typeFilterTypeNotIndexedTests() throws Exception {
typeFilterTests("no");
}
private void typeFilterTests(String index) throws Exception {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1)
.addMapping("type1", jsonBuilder().startObject().startObject("type1")
.startObject("_type").field("index", index).endObject()
.endObject().endObject())
.addMapping("type2", jsonBuilder().startObject().startObject("type2")
.startObject("_type").field("index", index).endObject()
.endObject().endObject()));
indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("field1", "value1"),
client().prepareIndex("test", "type2", "1").setSource("field1", "value1"),
client().prepareIndex("test", "type1", "2").setSource("field1", "value1"),
client().prepareIndex("test", "type2", "2").setSource("field1", "value1"),
client().prepareIndex("test", "type2", "3").setSource("field1", "value1"));
assertHitCount(client().prepareCount().setQuery(filteredQuery(matchAllQuery(), typeFilter("type1"))).get(), 2l);
assertHitCount(client().prepareCount().setQuery(filteredQuery(matchAllQuery(), typeFilter("type2"))).get(), 3l);
assertHitCount(client().prepareCount().setTypes("type1").setQuery(matchAllQuery()).get(), 2l);
assertHitCount(client().prepareCount().setTypes("type2").setQuery(matchAllQuery()).get(), 3l);
assertHitCount(client().prepareCount().setTypes("type1", "type2").setQuery(matchAllQuery()).get(), 5l);
}
@Test
public void idsFilterTestsIdIndexed() throws Exception {
idsFilterTests("not_analyzed");
}
@Test
public void idsFilterTestsIdNotIndexed() throws Exception {
idsFilterTests("no");
}
private void idsFilterTests(String index) throws Exception {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1)
.addMapping("type1", jsonBuilder().startObject().startObject("type1")
.startObject("_id").field("index", index).endObject()
.endObject().endObject()));
indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("field1", "value1"),
client().prepareIndex("test", "type1", "2").setSource("field1", "value2"),
client().prepareIndex("test", "type1", "3").setSource("field1", "value3"));
CountResponse countResponse = client().prepareCount().setQuery(constantScoreQuery(idsFilter("type1").ids("1", "3"))).get();
assertHitCount(countResponse, 2l);
// no type
countResponse = client().prepareCount().setQuery(constantScoreQuery(idsFilter().ids("1", "3"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(idsQuery("type1").ids("1", "3")).get();
assertHitCount(countResponse, 2l);
// no type
countResponse = client().prepareCount().setQuery(idsQuery().ids("1", "3")).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(idsQuery("type1").ids("7", "10")).get();
assertHitCount(countResponse, 0l);
// repeat..., with terms
countResponse = client().prepareCount().setTypes("type1").setQuery(constantScoreQuery(termsFilter("_id", "1", "3"))).get();
assertHitCount(countResponse, 2l);
}
@Test
public void testLimitFilter() throws Exception {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("field1", "value1_1"),
client().prepareIndex("test", "type1", "2").setSource("field1", "value1_2"),
client().prepareIndex("test", "type1", "3").setSource("field2", "value2_3"),
client().prepareIndex("test", "type1", "4").setSource("field3", "value3_4"));
CountResponse countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), limitFilter(2))).get();
assertHitCount(countResponse, 2l);
}
@Test
public void filterExistsMissingTests() throws Exception {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
indexRandom(true,
client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject().startObject("obj1").field("obj1_val", "1").endObject().field("x1", "x_1").field("field1", "value1_1").field("field2", "value2_1").endObject()),
client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject().startObject("obj1").field("obj1_val", "1").endObject().field("x2", "x_2").field("field1", "value1_2").endObject()),
client().prepareIndex("test", "type1", "3").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y1", "y_1").field("field2", "value2_3").endObject()),
client().prepareIndex("test", "type1", "4").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y2", "y_2").field("field3", "value3_4").endObject()));
CountResponse countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field1"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(constantScoreQuery(existsFilter("field1"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(queryString("_exists_:field1")).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field2"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("field3"))).get();
assertHitCount(countResponse, 1l);
// wildcard check
countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("x*"))).get();
assertHitCount(countResponse, 2l);
// object check
countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), existsFilter("obj1"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("field1"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("field1"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(constantScoreQuery(missingFilter("field1"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(queryString("_missing_:field1")).get();
assertHitCount(countResponse, 2l);
// wildcard check
countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("x*"))).get();
assertHitCount(countResponse, 2l);
// object check
countResponse = client().prepareCount().setQuery(filteredQuery(matchAllQuery(), missingFilter("obj1"))).get();
assertHitCount(countResponse, 2l);
}
@Test
public void passQueryAsJSONStringTest() throws Exception {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
client().prepareIndex("test", "type1", "1").setSource("field1", "value1_1", "field2", "value2_1").setRefresh(true).get();
WrapperQueryBuilder wrapper = new WrapperQueryBuilder("{ \"term\" : { \"field1\" : \"value1_1\" } }");
assertHitCount(client().prepareCount().setQuery(wrapper).get(), 1l);
BoolQueryBuilder bool = boolQuery().must(wrapper).must(new TermQueryBuilder("field2", "value2_1"));
assertHitCount(client().prepareCount().setQuery(bool).get(), 1l);
}
@Test
public void testFiltersWithCustomCacheKey() throws Exception {
createIndex("test");
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get();
refresh();
CountResponse countResponse = client().prepareCount("test").setQuery(constantScoreQuery(termsFilter("field1", "value1").cacheKey("test1"))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(constantScoreQuery(termsFilter("field1", "value1").cacheKey("test1"))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(constantScoreQuery(termsFilter("field1", "value1"))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(constantScoreQuery(termsFilter("field1", "value1"))).get();
assertHitCount(countResponse, 1l);
}
@Test
public void testMatchQueryNumeric() throws Exception {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
client().prepareIndex("test", "type1", "1").setSource("long", 1l, "double", 1.0d).get();
client().prepareIndex("test", "type1", "2").setSource("long", 2l, "double", 2.0d).get();
client().prepareIndex("test", "type1", "3").setSource("long", 3l, "double", 3.0d).get();
refresh();
CountResponse countResponse = client().prepareCount().setQuery(matchQuery("long", "1")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(matchQuery("double", "2")).get();
assertHitCount(countResponse, 1l);
}
@Test
public void testMultiMatchQuery() throws Exception {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
client().prepareIndex("test", "type1", "1").setSource("field1", "value1", "field2", "value4", "field3", "value3").get();
client().prepareIndex("test", "type1", "2").setSource("field1", "value2", "field2", "value5", "field3", "value2").get();
client().prepareIndex("test", "type1", "3").setSource("field1", "value3", "field2", "value6", "field3", "value1").get();
refresh();
MultiMatchQueryBuilder builder = QueryBuilders.multiMatchQuery("value1 value2 value4", "field1", "field2");
CountResponse countResponse = client().prepareCount().setQuery(builder).get();
assertHitCount(countResponse, 2l);
refresh();
builder = QueryBuilders.multiMatchQuery("value1", "field1", "field2")
.operator(MatchQueryBuilder.Operator.AND); // Operator only applies on terms inside a field! Fields are always OR-ed together.
countResponse = client().prepareCount().setQuery(builder).get();
assertHitCount(countResponse, 1l);
refresh();
builder = QueryBuilders.multiMatchQuery("value1", "field1", "field3^1.5")
.operator(MatchQueryBuilder.Operator.AND); // Operator only applies on terms inside a field! Fields are always OR-ed together.
countResponse = client().prepareCount().setQuery(builder).get();
assertHitCount(countResponse, 2l);
refresh();
builder = QueryBuilders.multiMatchQuery("value1").field("field1").field("field3", 1.5f)
.operator(MatchQueryBuilder.Operator.AND); // Operator only applies on terms inside a field! Fields are always OR-ed together.
countResponse = client().prepareCount().setQuery(builder).get();
assertHitCount(countResponse, 2l);
// Test lenient
client().prepareIndex("test", "type1", "3").setSource("field1", "value7", "field2", "value8", "field4", 5).get();
refresh();
builder = QueryBuilders.multiMatchQuery("value1", "field1", "field2", "field4");
builder.lenient(true);
countResponse = client().prepareCount().setQuery(builder).get();
assertHitCount(countResponse, 1l);
}
@Test
public void testMatchQueryZeroTermsQuery() {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1)
.addMapping("type1", "field1", "type=string,analyzer=classic", "field2", "type=string,analyzer=classic"));
client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get();
client().prepareIndex("test", "type1", "2").setSource("field1", "value2").get();
refresh();
BoolQueryBuilder boolQuery = boolQuery()
.must(matchQuery("field1", "a").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.NONE))
.must(matchQuery("field1", "value1").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.NONE));
CountResponse countResponse = client().prepareCount().setQuery(boolQuery).get();
assertHitCount(countResponse, 0l);
boolQuery = boolQuery()
.must(matchQuery("field1", "a").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL))
.must(matchQuery("field1", "value1").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL));
countResponse = client().prepareCount().setQuery(boolQuery).get();
assertHitCount(countResponse, 1l);
boolQuery = boolQuery().must(matchQuery("field1", "a").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL));
countResponse = client().prepareCount().setQuery(boolQuery).get();
assertHitCount(countResponse, 2l);
}
@Test
public void testMultiMatchQueryZeroTermsQuery() {
assertAcked(client().admin().indices().prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1)
.addMapping("type1", "field1", "type=string,analyzer=classic", "field2", "type=string,analyzer=classic"));
client().prepareIndex("test", "type1", "1").setSource("field1", "value1", "field2", "value2").get();
client().prepareIndex("test", "type1", "2").setSource("field1", "value3", "field2", "value4").get();
refresh();
BoolQueryBuilder boolQuery = boolQuery()
.must(multiMatchQuery("a", "field1", "field2").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.NONE))
.must(multiMatchQuery("value1", "field1", "field2").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.NONE)); // Fields are ORed together
CountResponse countResponse = client().prepareCount().setQuery(boolQuery).get();
assertHitCount(countResponse, 0l);
boolQuery = boolQuery()
.must(multiMatchQuery("a", "field1", "field2").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL))
.must(multiMatchQuery("value4", "field1", "field2").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL));
countResponse = client().prepareCount().setQuery(boolQuery).get();
assertHitCount(countResponse, 1l);
boolQuery = boolQuery().must(multiMatchQuery("a", "field1").zeroTermsQuery(MatchQueryBuilder.ZeroTermsQuery.ALL));
countResponse = client().prepareCount().setQuery(boolQuery).get();
assertHitCount(countResponse, 2l);
}
@Test
public void testMultiMatchQueryMinShouldMatch() {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
client().prepareIndex("test", "type1", "1").setSource("field1", new String[]{"value1", "value2", "value3"}).get();
client().prepareIndex("test", "type1", "2").setSource("field2", "value1").get();
refresh();
MultiMatchQueryBuilder multiMatchQuery = multiMatchQuery("value1 value2 foo", "field1", "field2");
multiMatchQuery.useDisMax(true);
multiMatchQuery.minimumShouldMatch("70%");
CountResponse countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
assertHitCount(countResponse, 1l);
multiMatchQuery.minimumShouldMatch("30%");
countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
assertHitCount(countResponse, 2l);
multiMatchQuery.useDisMax(false);
multiMatchQuery.minimumShouldMatch("70%");
countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
assertHitCount(countResponse, 1l);
multiMatchQuery.minimumShouldMatch("30%");
countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
assertHitCount(countResponse, 2l);
multiMatchQuery = multiMatchQuery("value1 value2 bar", "field1");
multiMatchQuery.minimumShouldMatch("100%");
countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
assertHitCount(countResponse, 0l);
multiMatchQuery.minimumShouldMatch("70%");
countResponse = client().prepareCount().setQuery(multiMatchQuery).get();
assertHitCount(countResponse, 1l);
}
@Test
public void testFuzzyQueryString() {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
client().prepareIndex("test", "type1", "1").setSource("str", "kimchy", "date", "2012-02-01", "num", 12).get();
client().prepareIndex("test", "type1", "2").setSource("str", "shay", "date", "2012-02-05", "num", 20).get();
refresh();
CountResponse countResponse = client().prepareCount().setQuery(queryString("str:kimcy~1")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("num:11~1")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("date:2012-02-02~1d")).get();
assertHitCount(countResponse, 1l);
}
@Test
public void testSpecialRangeSyntaxInQueryString() {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1));
client().prepareIndex("test", "type1", "1").setSource("str", "kimchy", "date", "2012-02-01", "num", 12).get();
client().prepareIndex("test", "type1", "2").setSource("str", "shay", "date", "2012-02-05", "num", 20).get();
refresh();
CountResponse countResponse = client().prepareCount().setQuery(queryString("num:>19")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("num:>20")).get();
assertHitCount(countResponse, 0l);
countResponse = client().prepareCount().setQuery(queryString("num:>=20")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("num:>11")).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(queryString("num:<20")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(queryString("num:<=20")).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(queryString("+num:>11 +num:<20")).get();
assertHitCount(countResponse, 1l);
}
@Test
public void testEmptyTermsFilter() throws Exception {
assertAcked(prepareCreate("test").addMapping("type", "terms", "type=string"));
ensureGreen();
client().prepareIndex("test", "type", "1").setSource("term", "1").get();
client().prepareIndex("test", "type", "2").setSource("term", "2").get();
client().prepareIndex("test", "type", "3").setSource("term", "3").get();
client().prepareIndex("test", "type", "4").setSource("term", "4").get();
refresh();
CountResponse countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), termsFilter("term", new String[0]))).get();
assertHitCount(countResponse, 0l);
countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), idsFilter())).get();
assertHitCount(countResponse, 0l);
}
@Test
public void testTermsLookupFilter() throws Exception {
assertAcked(prepareCreate("lookup").addMapping("type", "terms", "type=string", "other", "type=string"));
assertAcked(prepareCreate("lookup2").addMapping("type",
jsonBuilder().startObject().startObject("type").startObject("properties")
.startObject("arr").startObject("properties").startObject("term").field("type", "string")
.endObject().endObject().endObject().endObject().endObject().endObject()));
assertAcked(prepareCreate("test").addMapping("type", "term", "type=string"));
ensureGreen();
indexRandom(true, client().prepareIndex("lookup", "type", "1").setSource("terms", new String[]{"1", "3"}),
client().prepareIndex("lookup", "type", "2").setSource("terms", new String[]{"2"}),
client().prepareIndex("lookup", "type", "3").setSource("terms", new String[]{"2", "4"}),
client().prepareIndex("lookup", "type", "4").setSource("other", "value"),
client().prepareIndex("lookup2", "type", "1").setSource(XContentFactory.jsonBuilder().startObject()
.startArray("arr")
.startObject().field("term", "1").endObject()
.startObject().field("term", "3").endObject()
.endArray()
.endObject()),
client().prepareIndex("lookup2", "type", "2").setSource(XContentFactory.jsonBuilder().startObject()
.startArray("arr")
.startObject().field("term", "2").endObject()
.endArray()
.endObject()),
client().prepareIndex("lookup2", "type", "3").setSource(XContentFactory.jsonBuilder().startObject()
.startArray("arr")
.startObject().field("term", "2").endObject()
.startObject().field("term", "4").endObject()
.endArray()
.endObject()),
client().prepareIndex("test", "type", "1").setSource("term", "1"),
client().prepareIndex("test", "type", "2").setSource("term", "2"),
client().prepareIndex("test", "type", "3").setSource("term", "3"),
client().prepareIndex("test", "type", "4").setSource("term", "4"));
CountResponse countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get();
assertHitCount(countResponse, 2l);
// same as above, just on the _id...
countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("_id").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get();
assertHitCount(countResponse, 2l);
// another search with same parameters...
countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("1").lookupPath("terms"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("2").lookupPath("terms"))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("3").lookupPath("terms"))
).get();
assertNoFailures(countResponse);
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup").lookupType("type").lookupId("4").lookupPath("terms"))).get();
assertHitCount(countResponse, 0l);
countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("1").lookupPath("arr.term"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("2").lookupPath("arr.term"))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("term").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount("test")
.setQuery(filteredQuery(matchAllQuery(), termsLookupFilter("not_exists").lookupIndex("lookup2").lookupType("type").lookupId("3").lookupPath("arr.term"))).get();
assertHitCount(countResponse, 0l);
}
@Test
public void testBasicFilterById() throws Exception {
createIndex("test");
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get();
client().prepareIndex("test", "type2", "2").setSource("field1", "value2").get();
refresh();
CountResponse countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter("type1", "type2").ids("1", "2"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter().ids("1", "2"))).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter("type1").ids("1", "2"))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter().ids("1"))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter(null).ids("1"))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.idsFilter("type1", "type2", "type3").ids("1", "2", "3", "4"))).get();
assertHitCount(countResponse, 2l);
}
@Test
public void testBasicQueryById() throws Exception {
createIndex("test");
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get();
client().prepareIndex("test", "type2", "2").setSource("field1", "value2").get();
refresh();
CountResponse countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery("type1", "type2").ids("1", "2")).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery().ids("1")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery().ids("1", "2")).get();
assertHitCount(countResponse, 2l);
countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery("type1").ids("1", "2")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery().ids("1")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery(null).ids("1")).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount().setQuery(QueryBuilders.idsQuery("type1", "type2", "type3").ids("1", "2", "3", "4")).get();
assertHitCount(countResponse, 2l);
}
@Test
public void testNumericTermsAndRanges() throws Exception {
assertAcked(client().admin().indices().prepareCreate("test")
.setSettings(SETTING_NUMBER_OF_SHARDS, 1)
.addMapping("type1",
"num_byte", "type=byte", "num_short", "type=short",
"num_integer", "type=integer", "num_long", "type=long",
"num_float", "type=float", "num_double", "type=double"));
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource("num_byte", 1, "num_short", 1, "num_integer", 1,
"num_long", 1, "num_float", 1, "num_double", 1).get();
client().prepareIndex("test", "type1", "2").setSource("num_byte", 2, "num_short", 2, "num_integer", 2,
"num_long", 2, "num_float", 2, "num_double", 2).get();
client().prepareIndex("test", "type1", "17").setSource("num_byte", 17, "num_short", 17, "num_integer", 17,
"num_long", 17, "num_float", 17, "num_double", 17).get();
refresh();
CountResponse countResponse;
logger.info("--> term query on 1");
countResponse = client().prepareCount("test").setQuery(termQuery("num_byte", 1)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(termQuery("num_short", 1)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(termQuery("num_integer", 1)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(termQuery("num_long", 1)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(termQuery("num_float", 1)).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(termQuery("num_double", 1)).get();
assertHitCount(countResponse, 1l);
logger.info("--> terms query on 1");
countResponse = client().prepareCount("test").setQuery(termsQuery("num_byte", new int[]{1})).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(termsQuery("num_short", new int[]{1})).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(termsQuery("num_integer", new int[]{1})).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(termsQuery("num_long", new int[]{1})).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(termsQuery("num_float", new double[]{1})).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(termsQuery("num_double", new double[]{1})).get();
assertHitCount(countResponse, 1l);
logger.info("--> term filter on 1");
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_byte", 1))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_short", 1))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_integer", 1))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_long", 1))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_float", 1))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termFilter("num_double", 1))).get();
assertHitCount(countResponse, 1l);
logger.info("--> terms filter on 1");
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_byte", new int[]{1}))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_short", new int[]{1}))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_integer", new int[]{1}))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_long", new int[]{1}))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_float", new int[]{1}))).get();
assertHitCount(countResponse, 1l);
countResponse = client().prepareCount("test").setQuery(filteredQuery(matchAllQuery(), termsFilter("num_double", new int[]{1}))).get();
assertHitCount(countResponse, 1l);
}
@Test // see #2994
public void testSimpleSpan() throws ElasticsearchException, IOException {
assertAcked(prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1, SETTING_NUMBER_OF_REPLICAS, 0));
ensureGreen();
client().prepareIndex("test", "test", "1").setSource("description", "foo other anything bar").get();
client().prepareIndex("test", "test", "2").setSource("description", "foo other anything").get();
client().prepareIndex("test", "test", "3").setSource("description", "foo other").get();
client().prepareIndex("test", "test", "4").setSource("description", "foo").get();
refresh();
CountResponse response = client().prepareCount("test")
.setQuery(QueryBuilders.spanOrQuery().clause(QueryBuilders.spanTermQuery("description", "bar"))).get();
assertHitCount(response, 1l);
response = client().prepareCount("test")
.setQuery(QueryBuilders.spanOrQuery().clause(QueryBuilders.spanTermQuery("test.description", "bar"))).get();
assertHitCount(response, 1l);
response = client().prepareCount("test").setQuery(
QueryBuilders.spanNearQuery()
.clause(QueryBuilders.spanTermQuery("description", "foo"))
.clause(QueryBuilders.spanTermQuery("test.description", "other"))
.slop(3)).get();
assertHitCount(response, 3l);
}
} | 0true
| src_test_java_org_elasticsearch_count_query_SimpleQueryTests.java |
966 | public final class LockRequest extends AbstractLockRequest {
public LockRequest() {
}
public LockRequest(Data key, long threadId, long ttl, long timeout) {
super(key, threadId, ttl, timeout);
}
@Override
protected InternalLockNamespace getNamespace() {
String name = getName();
return new InternalLockNamespace(name);
}
@Override
public int getFactoryId() {
return LockPortableHook.FACTORY_ID;
}
@Override
public int getClassId() {
return LockPortableHook.LOCK;
}
@Override
public Permission getRequiredPermission() {
String name = getName();
return new LockPermission(name, ActionConstants.ACTION_LOCK);
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_client_LockRequest.java |
2,094 | public class BytesStreamOutput extends StreamOutput implements BytesStream {
public static final int DEFAULT_SIZE = 2 * 1024;
public static final int OVERSIZE_LIMIT = 256 * 1024;
/**
* The buffer where data is stored.
*/
protected byte buf[];
/**
* The number of valid bytes in the buffer.
*/
protected int count;
public BytesStreamOutput() {
this(DEFAULT_SIZE);
}
public BytesStreamOutput(int size) {
this.buf = new byte[size];
}
@Override
public boolean seekPositionSupported() {
return true;
}
@Override
public long position() throws IOException {
return count;
}
@Override
public void seek(long position) throws IOException {
if (position > Integer.MAX_VALUE) {
throw new UnsupportedOperationException();
}
count = (int) position;
}
@Override
public void writeByte(byte b) throws IOException {
int newcount = count + 1;
if (newcount > buf.length) {
buf = grow(newcount);
}
buf[count] = b;
count = newcount;
}
public void skip(int length) {
int newcount = count + length;
if (newcount > buf.length) {
buf = grow(newcount);
}
count = newcount;
}
@Override
public void writeBytes(byte[] b, int offset, int length) throws IOException {
if (length == 0) {
return;
}
int newcount = count + length;
if (newcount > buf.length) {
buf = grow(newcount);
}
System.arraycopy(b, offset, buf, count, length);
count = newcount;
}
private byte[] grow(int newCount) {
// try and grow faster while we are small...
if (newCount < OVERSIZE_LIMIT) {
newCount = Math.max(buf.length << 1, newCount);
}
return ArrayUtil.grow(buf, newCount);
}
public void seek(int seekTo) {
count = seekTo;
}
public void reset() {
count = 0;
}
public int bufferSize() {
return buf.length;
}
@Override
public void flush() throws IOException {
// nothing to do there
}
@Override
public void close() throws IOException {
// nothing to do here
}
@Override
public BytesReference bytes() {
return new BytesArray(buf, 0, count);
}
/**
* Returns the current size of the buffer.
*
* @return the value of the <code>count</code> field, which is the number
* of valid bytes in this output stream.
* @see java.io.ByteArrayOutputStream#count
*/
public int size() {
return count;
}
} | 1no label
| src_main_java_org_elasticsearch_common_io_stream_BytesStreamOutput.java |
2,486 | public static class MapParams implements Params {
private final Map<String, String> params;
public MapParams(Map<String, String> params) {
this.params = params;
}
@Override
public String param(String key) {
return params.get(key);
}
@Override
public String param(String key, String defaultValue) {
String value = params.get(key);
if (value == null) {
return defaultValue;
}
return value;
}
@Override
public boolean paramAsBoolean(String key, boolean defaultValue) {
return Booleans.parseBoolean(param(key), defaultValue);
}
@Override
public Boolean paramAsBoolean(String key, Boolean defaultValue) {
return Booleans.parseBoolean(param(key), defaultValue);
}
@Override @Deprecated
public Boolean paramAsBooleanOptional(String key, Boolean defaultValue) {
return paramAsBoolean(key, defaultValue);
}
} | 0true
| src_main_java_org_elasticsearch_common_xcontent_ToXContent.java |
792 | new Thread() {
public void run() {
long delta = (long) (Math.random() * 1000);
for (int j = 0; j < 10000; j++) {
atomicLong.addAndGet(delta);
}
for (int j = 0; j < 10000; j++) {
atomicLong.addAndGet(-1 * delta);
}
countDownLatch.countDown();
}
}.start(); | 0true
| hazelcast_src_test_java_com_hazelcast_concurrent_atomiclong_AtomicLongTest.java |
1,276 | public class OStorageVariableParser implements OVariableParserListener {
public static final String STORAGE_PATH = "STORAGE_PATH";
private String dbPath;
public static final String VAR_BEGIN = "${";
public static final String VAR_END = "}";
public static final String DB_PATH_VARIABLE = VAR_BEGIN + STORAGE_PATH + VAR_END;
public OStorageVariableParser(String dbPath) {
this.dbPath = dbPath;
}
public String resolveVariables(String iPath) {
return (String) OVariableParser.resolveVariables(iPath, VAR_BEGIN, VAR_END, this);
}
public String convertPathToRelative(String iPath) {
return iPath.replace(dbPath, VAR_BEGIN + STORAGE_PATH + VAR_END);
}
public String resolve(String variable) {
if (variable.equals(STORAGE_PATH))
return dbPath;
String resolved = System.getProperty(variable);
if (resolved == null)
// TRY TO FIND THE VARIABLE BETWEEN SYSTEM'S ENVIRONMENT PROPERTIES
resolved = System.getenv(variable);
return resolved;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_OStorageVariableParser.java |
745 | public class ExplainResponse extends ActionResponse {
private boolean exists;
private Explanation explanation;
private GetResult getResult;
ExplainResponse() {
}
public ExplainResponse(boolean exists) {
this.exists = exists;
}
public ExplainResponse(boolean exists, Explanation explanation) {
this.exists = exists;
this.explanation = explanation;
}
public ExplainResponse(boolean exists, Explanation explanation, GetResult getResult) {
this.exists = exists;
this.explanation = explanation;
this.getResult = getResult;
}
public Explanation getExplanation() {
return explanation;
}
public boolean isMatch() {
return explanation != null && explanation.isMatch();
}
public boolean hasExplanation() {
return explanation != null;
}
public boolean isExists() {
return exists;
}
public GetResult getGetResult() {
return getResult;
}
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
exists = in.readBoolean();
if (in.readBoolean()) {
explanation = readExplanation(in);
}
if (in.readBoolean()) {
getResult = GetResult.readGetResult(in);
}
}
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(exists);
if (explanation == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
writeExplanation(out, explanation);
}
if (getResult == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
getResult.writeTo(out);
}
}
} | 0true
| src_main_java_org_elasticsearch_action_explain_ExplainResponse.java |
1,579 | public class ODistributedException extends OException {
private static final long serialVersionUID = 1L;
public ODistributedException() {
}
public ODistributedException(String message, Throwable cause) {
super(message, cause);
}
public ODistributedException(String message) {
super(message);
}
public ODistributedException(Throwable cause) {
super(cause);
}
} | 0true
| server_src_main_java_com_orientechnologies_orient_server_distributed_ODistributedException.java |
6,018 | public final class Correction {
public static final Correction[] EMPTY = new Correction[0];
public double score;
public final Candidate[] candidates;
public Correction(double score, Candidate[] candidates) {
this.score = score;
this.candidates = candidates;
}
@Override
public String toString() {
return "Correction [score=" + score + ", candidates=" + Arrays.toString(candidates) + "]";
}
public BytesRef join(BytesRef separator) {
return join(separator, null, null);
}
public BytesRef join(BytesRef separator, BytesRef preTag, BytesRef postTag) {
return join(separator, new BytesRef(), preTag, postTag);
}
public BytesRef join(BytesRef separator, BytesRef result, BytesRef preTag, BytesRef postTag) {
BytesRef[] toJoin = new BytesRef[this.candidates.length];
int len = separator.length * this.candidates.length - 1;
for (int i = 0; i < toJoin.length; i++) {
Candidate candidate = candidates[i];
if (preTag == null || candidate.userInput) {
toJoin[i] = candidate.term;
} else {
final int maxLen = preTag.length + postTag.length + candidate.term.length;
final BytesRef highlighted = new BytesRef(maxLen);// just allocate once
if (i == 0 || candidates[i-1].userInput) {
highlighted.append(preTag);
}
highlighted.append(candidate.term);
if (toJoin.length == i + 1 || candidates[i+1].userInput) {
highlighted.append(postTag);
}
toJoin[i] = highlighted;
}
len += toJoin[i].length;
}
result.offset = 0;
result.grow(len);
return SuggestUtils.joinPreAllocated(separator, result, toJoin);
}
} | 1no label
| src_main_java_org_elasticsearch_search_suggest_phrase_Correction.java |
1,657 | public static enum Flag {
STRICT
} | 0true
| src_main_java_org_elasticsearch_common_ParseField.java |
313 | return new Predicate<Long>() {
@Override
public boolean apply(@Nullable Long num) {
return num!=null && num>0;
}
}; | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_ConfigOption.java |
1,812 | public abstract class AbstractMoneyFieldPersistenceProvider extends FieldPersistenceProviderAdapter {
@Override
public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException {
if (!canHandleExtraction(extractValueRequest, property)) {
return FieldProviderResponse.NOT_HANDLED;
}
if (extractValueRequest.getRequestedValue() == null) {
return FieldProviderResponse.NOT_HANDLED;
}
property.setValue(formatValue((BigDecimal)extractValueRequest.getRequestedValue(), extractValueRequest, property));
property.setDisplayValue(formatDisplayValue((BigDecimal)extractValueRequest.getRequestedValue(), extractValueRequest, property));
return FieldProviderResponse.HANDLED_BREAK;
}
protected String formatValue(BigDecimal value, ExtractValueRequest extractValueRequest, Property property) {
NumberFormat format = NumberFormat.getInstance();
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(2);
format.setGroupingUsed(false);
return format.format(value);
}
protected String formatDisplayValue(BigDecimal value, ExtractValueRequest extractValueRequest, Property property) {
Locale locale = getLocale(extractValueRequest, property);
Currency currency = getCurrency(extractValueRequest, property);
NumberFormat format = NumberFormat.getCurrencyInstance(locale);
format.setCurrency(currency);
return format.format(value);
}
protected abstract boolean canHandleExtraction(ExtractValueRequest extractValueRequest, Property property);
protected abstract Locale getLocale(ExtractValueRequest extractValueRequest, Property property);
protected abstract Currency getCurrency(ExtractValueRequest extractValueRequest, Property property);
} | 1no label
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_provider_AbstractMoneyFieldPersistenceProvider.java |
2,071 | public class MergeOperation extends BasePutOperation {
private MapMergePolicy mergePolicy;
private EntryView<Data, Data> mergingEntry;
private boolean merged = false;
public MergeOperation(String name, Data dataKey, EntryView<Data, Data> entryView, MapMergePolicy policy) {
super(name, dataKey, null);
mergingEntry = entryView;
mergePolicy = policy;
}
public MergeOperation() {
}
public void run() {
SimpleEntryView entryView = (SimpleEntryView) mergingEntry;
entryView.setKey(mapService.toObject(mergingEntry.getKey()));
entryView.setValue(mapService.toObject(mergingEntry.getValue()));
merged = recordStore.merge(dataKey, mergingEntry, mergePolicy);
if (merged) {
Record record = recordStore.getRecord(dataKey);
if (record != null)
dataValue = mapService.toData(record.getValue());
}
}
@Override
public Object getResponse() {
return merged;
}
public boolean shouldBackup() {
return merged;
}
public void afterRun() {
if (merged) {
invalidateNearCaches();
}
}
public Operation getBackupOperation() {
if (dataValue == null) {
return new RemoveBackupOperation(name, dataKey);
} else {
RecordInfo replicationInfo = mapService.createRecordInfo(recordStore.getRecord(dataKey));
return new PutBackupOperation(name, dataKey, dataValue, replicationInfo);
}
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeObject(mergingEntry);
out.writeObject(mergePolicy);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
mergingEntry = in.readObject();
mergePolicy = in.readObject();
}
@Override
public String toString() {
return "MergeOperation{" + name + "}";
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_map_operation_MergeOperation.java |
472 | public interface ClientInvocationService {
<T> ICompletableFuture<T> invokeOnRandomTarget(ClientRequest request) throws Exception;
<T> ICompletableFuture<T> invokeOnTarget(ClientRequest request, Address target) throws Exception;
<T> ICompletableFuture<T> invokeOnKeyOwner(ClientRequest request, Object key) throws Exception;
<T> ICompletableFuture<T> invokeOnRandomTarget(ClientRequest request, EventHandler handler) throws Exception;
<T> ICompletableFuture<T> invokeOnTarget(ClientRequest request, Address target, EventHandler handler) throws Exception;
<T> ICompletableFuture<T> invokeOnKeyOwner(ClientRequest request, Object key, EventHandler handler) throws Exception;
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_spi_ClientInvocationService.java |
1,416 | new OProfilerHookValue() {
public Object getValue() {
return metricTransmittedBytes;
}
}, dictProfilerMetric + ".transmittedBytes"); | 0true
| enterprise_src_main_java_com_orientechnologies_orient_enterprise_channel_OChannel.java |
571 | public class OpenIndexRequestBuilder extends AcknowledgedRequestBuilder<OpenIndexRequest, OpenIndexResponse, OpenIndexRequestBuilder> {
public OpenIndexRequestBuilder(IndicesAdminClient indicesClient) {
super((InternalIndicesAdminClient) indicesClient, new OpenIndexRequest());
}
public OpenIndexRequestBuilder(IndicesAdminClient indicesClient, String... indices) {
super((InternalIndicesAdminClient) indicesClient, new OpenIndexRequest(indices));
}
/**
* Sets the indices to be opened
* @param indices the indices to be opened
* @return the request itself
*/
public OpenIndexRequestBuilder setIndices(String... indices) {
request.indices(indices);
return this;
}
/**
* Specifies what type of requested indices to ignore and how to deal with wildcard indices expressions.
* For example indices that don't exist.
*
* @param indicesOptions the desired behaviour regarding indices to ignore and wildcard indices expressions
* @return the request itself
*/
public OpenIndexRequestBuilder setIndicesOptions(IndicesOptions indicesOptions) {
request.indicesOptions(indicesOptions);
return this;
}
@Override
protected void doExecute(ActionListener<OpenIndexResponse> listener) {
((IndicesAdminClient) client).open(request, listener);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_open_OpenIndexRequestBuilder.java |
394 | public class ClusterSearchShardsRequest extends MasterNodeReadOperationRequest<ClusterSearchShardsRequest> {
private String[] indices;
@Nullable
private String routing;
@Nullable
private String preference;
private String[] types = Strings.EMPTY_ARRAY;
private IndicesOptions indicesOptions = IndicesOptions.lenient();
public ClusterSearchShardsRequest() {
}
public ClusterSearchShardsRequest(String... indices) {
indices(indices);
}
@Override
public ActionRequestValidationException validate() {
return null;
}
/**
* Sets the indices the search will be executed on.
*/
public ClusterSearchShardsRequest indices(String... indices) {
if (indices == null) {
throw new ElasticsearchIllegalArgumentException("indices must not be null");
} else {
for (int i = 0; i < indices.length; i++) {
if (indices[i] == null) {
throw new ElasticsearchIllegalArgumentException("indices[" + i + "] must not be null");
}
}
}
this.indices = indices;
return this;
}
/**
* The indices
*/
public String[] indices() {
return indices;
}
public IndicesOptions indicesOptions() {
return indicesOptions;
}
public ClusterSearchShardsRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
/**
* The document types to execute the search against. Defaults to be executed against
* all types.
*/
public String[] types() {
return types;
}
/**
* The document types to execute the search against. Defaults to be executed against
* all types.
*/
public ClusterSearchShardsRequest types(String... types) {
this.types = types;
return this;
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public String routing() {
return this.routing;
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public ClusterSearchShardsRequest routing(String routing) {
this.routing = routing;
return this;
}
/**
* The routing values to control the shards that the search will be executed on.
*/
public ClusterSearchShardsRequest routing(String... routings) {
this.routing = Strings.arrayToCommaDelimitedString(routings);
return this;
}
/**
* Sets the preference to execute the search. Defaults to randomize across shards. Can be set to
* <tt>_local</tt> to prefer local shards, <tt>_primary</tt> to execute only on primary shards, or
* a custom value, which guarantees that the same order will be used across different requests.
*/
public ClusterSearchShardsRequest preference(String preference) {
this.preference = preference;
return this;
}
public String preference() {
return this.preference;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
indices = new String[in.readVInt()];
for (int i = 0; i < indices.length; i++) {
indices[i] = in.readString();
}
routing = in.readOptionalString();
preference = in.readOptionalString();
types = in.readStringArray();
indicesOptions = IndicesOptions.readIndicesOptions(in);
readLocal(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(indices.length);
for (String index : indices) {
out.writeString(index);
}
out.writeOptionalString(routing);
out.writeOptionalString(preference);
out.writeStringArray(types);
indicesOptions.writeIndicesOptions(out);
writeLocal(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_shards_ClusterSearchShardsRequest.java |
774 | mappingUpdatedAction.execute(mappingRequest, new ActionListener<MappingUpdatedAction.MappingUpdatedResponse>() {
@Override
public void onResponse(MappingUpdatedAction.MappingUpdatedResponse mappingUpdatedResponse) {
// all is well
latch.countDown();
}
@Override
public void onFailure(Throwable e) {
latch.countDown();
logger.warn("Failed to update master on updated mapping for {}", e, mappingRequest);
}
}); | 0true
| src_main_java_org_elasticsearch_action_index_TransportIndexAction.java |
914 | final Iterator<?> myIterator = makeDbCall(iMyDb, new ODbRelatedCall<Iterator<?>>() {
public Iterator<?> call() {
return myCollection.iterator();
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java |
698 | constructors[LIST_REMOVE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListRemoveRequest();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java |
1,123 | public class NativeScriptExamplesPlugin extends AbstractPlugin {
@Override
public String name() {
return "native-script-example";
}
@Override
public String description() {
return "Native script examples";
}
public void onModule(ScriptModule module) {
module.registerScript(NativeNaiveTFIDFScoreScript.NATIVE_NAIVE_TFIDF_SCRIPT_SCORE, NativeNaiveTFIDFScoreScript.Factory.class);
module.registerScript(NativeConstantForLoopScoreScript.NATIVE_CONSTANT_FOR_LOOP_SCRIPT_SCORE, NativeConstantForLoopScoreScript.Factory.class);
module.registerScript(NativeConstantScoreScript.NATIVE_CONSTANT_SCRIPT_SCORE, NativeConstantScoreScript.Factory.class);
module.registerScript(NativePayloadSumScoreScript.NATIVE_PAYLOAD_SUM_SCRIPT_SCORE, NativePayloadSumScoreScript.Factory.class);
module.registerScript(NativePayloadSumNoRecordScoreScript.NATIVE_PAYLOAD_SUM_NO_RECORD_SCRIPT_SCORE, NativePayloadSumNoRecordScoreScript.Factory.class);
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_scripts_score_plugin_NativeScriptExamplesPlugin.java |
1,973 | public class ProviderMethod<T> implements ProviderWithDependencies<T> {
private final Key<T> key;
private final Class<? extends Annotation> scopeAnnotation;
private final Object instance;
private final Method method;
private final ImmutableSet<Dependency<?>> dependencies;
private final List<Provider<?>> parameterProviders;
private final boolean exposed;
/**
* @param method the method to invoke. Its return type must be the same type as {@code key}.
*/
ProviderMethod(Key<T> key, Method method, Object instance,
ImmutableSet<Dependency<?>> dependencies, List<Provider<?>> parameterProviders,
Class<? extends Annotation> scopeAnnotation) {
this.key = key;
this.scopeAnnotation = scopeAnnotation;
this.instance = instance;
this.dependencies = dependencies;
this.method = method;
this.parameterProviders = parameterProviders;
this.exposed = method.getAnnotation(Exposed.class) != null;
method.setAccessible(true);
}
public Key<T> getKey() {
return key;
}
public Method getMethod() {
return method;
}
// exposed for GIN
public Object getInstance() {
return instance;
}
public void configure(Binder binder) {
binder = binder.withSource(method);
if (scopeAnnotation != null) {
binder.bind(key).toProvider(this).in(scopeAnnotation);
} else {
binder.bind(key).toProvider(this);
}
if (exposed) {
// the cast is safe 'cause the only binder we have implements PrivateBinder. If there's a
// misplaced @Exposed, calling this will add an error to the binder's error queue
((PrivateBinder) binder).expose(key);
}
}
public T get() {
Object[] parameters = new Object[parameterProviders.size()];
for (int i = 0; i < parameters.length; i++) {
parameters[i] = parameterProviders.get(i).get();
}
try {
// We know this cast is safe becase T is the method's return type.
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
T result = (T) method.invoke(instance, parameters);
return result;
} catch (IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public Set<Dependency<?>> getDependencies() {
return dependencies;
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_internal_ProviderMethod.java |
785 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class AtomicLongClientRequestTest extends ClientTestSupport {
static final String name = "test";
protected Config createConfig() {
return new Config();
}
private IAtomicLong getAtomicLong() {
return getInstance().getAtomicLong(name);
}
@Test
public void testAddAndGet() throws Exception {
final SimpleClient client = getClient();
client.send(new AddAndGetRequest(name, 3));
long result = (Long) client.receive();
assertEquals(3, result);
client.send(new AddAndGetRequest(name, 4));
result = (Long) client.receive();
assertEquals(7, result);
}
@Test
public void testCompareAndSet() throws Exception {
IAtomicLong atomicLong = getAtomicLong();
atomicLong.set(11);
final SimpleClient client = getClient();
client.send(new CompareAndSetRequest(name, 9, 5));
boolean result = (Boolean) client.receive();
assertFalse(result);
assertEquals(11, atomicLong.get());
client.send(new CompareAndSetRequest(name, 11, 5));
result = (Boolean) client.receive();
assertTrue(result);
assertEquals(5, atomicLong.get());
}
@Test
public void testGetAndAdd() throws IOException {
IAtomicLong atomicLong = getAtomicLong();
atomicLong.set(11);
final SimpleClient client = getClient();
client.send(new GetAndAddRequest(name, 4));
long result = (Long) client.receive();
assertEquals(11, result);
assertEquals(15, atomicLong.get());
}
@Test
public void testGetAndSet() throws IOException {
IAtomicLong atomicLong = getAtomicLong();
atomicLong.set(11);
final SimpleClient client = getClient();
client.send(new GetAndSetRequest(name, 9));
long result = (Long) client.receive();
assertEquals(11, result);
assertEquals(9, atomicLong.get());
}
@Test
public void testSet() throws IOException {
IAtomicLong atomicLong = getAtomicLong();
atomicLong.set(11);
final SimpleClient client = getClient();
client.send(new SetRequest(name, 7));
client.receive();
assertEquals(7, atomicLong.get());
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_concurrent_atomiclong_AtomicLongClientRequestTest.java |
1,046 | public class OrderItemTest extends TestCase {
private PromotableOrderItemPriceDetail priceDetail1;
private PromotableCandidateItemOffer candidateOffer;
private Offer offer;
@Override
protected void setUp() throws Exception {
PromotableOrder promotableOrder = new PromotableOrderImpl(new OrderImpl(), new PromotableItemFactoryImpl(), false);
DiscreteOrderItemImpl discreteOrderItem1 = new DiscreteOrderItemImpl();
discreteOrderItem1.setName("test1");
discreteOrderItem1.setOrderItemType(OrderItemType.DISCRETE);
discreteOrderItem1.setQuantity(2);
discreteOrderItem1.setRetailPrice(new Money(19.99D));
OrderItemPriceDetail pdetail = new OrderItemPriceDetailImpl();
pdetail.setOrderItem(discreteOrderItem1);
pdetail.setQuantity(2);
PromotableOrderItem orderItem1 = new PromotableOrderItemImpl(discreteOrderItem1, null,
new PromotableItemFactoryImpl(), false);
priceDetail1 = new PromotableOrderItemPriceDetailImpl(orderItem1, 2);
OfferDataItemProvider dataProvider = new OfferDataItemProvider();
offer = dataProvider.createItemBasedOfferWithItemCriteria(
"order.subTotal.getAmount()>20",
OfferDiscountType.PERCENT_OFF,
"([MVEL.eval(\"toUpperCase()\",\"test1\"), MVEL.eval(\"toUpperCase()\",\"test2\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.category.name))",
"([MVEL.eval(\"toUpperCase()\",\"test1\"), MVEL.eval(\"toUpperCase()\",\"test2\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.category.name))"
).get(0);
candidateOffer = new PromotableCandidateItemOfferImpl(promotableOrder, offer);
}
public void testGetQuantityAvailableToBeUsedAsQualifier() throws Exception {
int quantity = priceDetail1.getQuantityAvailableToBeUsedAsQualifier(candidateOffer);
//no previous qualifiers, so all quantity is available
assertTrue(quantity == 2);
PromotionDiscount discount = new PromotionDiscount();
discount.setPromotion(offer);
discount.setQuantity(1);
priceDetail1.getPromotionDiscounts().add(discount);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsQualifier(candidateOffer);
//items that have already received this promotion cannot get it again
assertTrue(quantity==1);
Offer testOffer = new OfferImpl();
testOffer.setOfferItemQualifierRuleType(OfferItemRestrictionRuleType.NONE);
testOffer.setOfferItemTargetRuleType(OfferItemRestrictionRuleType.NONE);
discount.setPromotion(testOffer);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsQualifier(candidateOffer);
//this item received a different promotion, but the restriction rule is NONE, so this item cannot be a qualifier for this promotion
assertTrue(quantity==1);
testOffer.setOfferItemTargetRuleType(OfferItemRestrictionRuleType.QUALIFIER);
candidateOffer.getOffer().setOfferItemQualifierRuleType(OfferItemRestrictionRuleType.TARGET);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsQualifier(candidateOffer);
//this item received a different promotion, but the restriction rule is QUALIFIER, so this item can be a qualifier
// for this promotion
assertTrue(quantity==2);
priceDetail1.getPromotionDiscounts().clear();
PromotionQualifier qualifier = new PromotionQualifier();
qualifier.setPromotion(offer);
qualifier.setQuantity(1);
priceDetail1.getPromotionQualifiers().add(qualifier);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsQualifier(candidateOffer);
//items that have already qualified for this promotion cannot qualify again
assertTrue(quantity==1);
qualifier.setPromotion(testOffer);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsQualifier(candidateOffer);
//this item qualified for a different promotion, but the restriction rule is NONE, so this item cannot be a qualifier for this promotion
assertTrue(quantity==1);
testOffer.setOfferItemQualifierRuleType(OfferItemRestrictionRuleType.QUALIFIER);
candidateOffer.getOffer().setOfferItemQualifierRuleType(OfferItemRestrictionRuleType.QUALIFIER);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsQualifier(candidateOffer);
// this item qualified for a different promotion, but the restriction rule is QUALIFIER,
// so this item can be a qualifier for this promotion
assertTrue(quantity==2);
}
public void testGetQuantityAvailableToBeUsedAsTarget() throws Exception {
int quantity = priceDetail1.getQuantityAvailableToBeUsedAsTarget(candidateOffer);
//no previous qualifiers, so all quantity is available
assertTrue(quantity == 2);
PromotionDiscount discount = new PromotionDiscount();
discount.setPromotion(offer);
discount.setQuantity(1);
priceDetail1.getPromotionDiscounts().add(discount);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsTarget(candidateOffer);
//items that have already received this promotion cannot get it again
assertTrue(quantity==1);
Offer tempOffer = new OfferImpl();
tempOffer.setCombinableWithOtherOffers(true);
tempOffer.setOfferItemQualifierRuleType(OfferItemRestrictionRuleType.NONE);
tempOffer.setOfferItemTargetRuleType(OfferItemRestrictionRuleType.NONE);
discount.setPromotion(tempOffer);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsTarget(candidateOffer);
//this item received a different promotion, but the restriction rule is NONE, so this item cannot be a qualifier
//for this promotion
assertTrue(quantity==1);
tempOffer.setOfferItemTargetRuleType(OfferItemRestrictionRuleType.TARGET);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsTarget(candidateOffer);
// this item received a different promotion, but the restriction rule is TARGET,
// so this item can be a target of this promotion but since the "candidateOffer"
// is set to NONE, the quantity can only be 1
assertTrue(quantity == 1);
// Now set the candidateOffer to be "TARGET" and we can use the quantity
// for both promotions.
candidateOffer.getOffer().setOfferItemTargetRuleType(OfferItemRestrictionRuleType.TARGET);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsTarget(candidateOffer);
// this item received a different promotion, but the restriction rule is TARGET,
// so this item can be a target of this promotion but since the "candidateOffer"
// is set to NONE, the quantity can only be 1
assertTrue(quantity == 2);
priceDetail1.getPromotionDiscounts().clear();
// rest candidate offer
candidateOffer.getOffer().setOfferItemTargetRuleType(OfferItemRestrictionRuleType.NONE);
PromotionQualifier qualifier = new PromotionQualifier();
qualifier.setPromotion(offer);
qualifier.setQuantity(1);
priceDetail1.getPromotionQualifiers().add(qualifier);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsTarget(candidateOffer);
//items that have already qualified for this promotion cannot qualify again
assertTrue(quantity==1);
qualifier.setPromotion(tempOffer);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsTarget(candidateOffer);
//this item qualified for a different promotion, but the restriction rule is NONE,
// so this item cannot be a qualifier for this promotion
assertTrue(quantity==1);
tempOffer.setOfferItemQualifierRuleType(OfferItemRestrictionRuleType.TARGET);
candidateOffer.getOffer().setOfferItemTargetRuleType(OfferItemRestrictionRuleType.QUALIFIER);
quantity = priceDetail1.getQuantityAvailableToBeUsedAsTarget(candidateOffer);
//this item qualified for a different promotion, but the restriction rule is QUALIFIER,
// so this item can be a qualifier for this promotion
assertTrue(quantity==2);
}
} | 0true
| core_broadleaf-framework_src_test_java_org_broadleafcommerce_core_order_domain_OrderItemTest.java |
1,016 | public class ReduceOperation extends SemaphoreBackupAwareOperation implements IdentifiedDataSerializable {
public ReduceOperation() {
}
public ReduceOperation(String name, int permitCount) {
super(name, permitCount);
}
@Override
public void run() throws Exception {
Permit permit = getPermit();
response = permit.reduce(permitCount);
}
@Override
public boolean shouldBackup() {
return Boolean.TRUE.equals(response);
}
@Override
public Operation getBackupOperation() {
return new ReduceBackupOperation(name, permitCount);
}
@Override
public int getFactoryId() {
return SemaphoreDataSerializerHook.F_ID;
}
@Override
public int getId() {
return SemaphoreDataSerializerHook.REDUCE_OPERATION;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_semaphore_operations_ReduceOperation.java |
566 | public class TransportPutMappingAction extends TransportMasterNodeOperationAction<PutMappingRequest, PutMappingResponse> {
private final MetaDataMappingService metaDataMappingService;
@Inject
public TransportPutMappingAction(Settings settings, TransportService transportService, ClusterService clusterService,
ThreadPool threadPool, MetaDataMappingService metaDataMappingService) {
super(settings, transportService, clusterService, threadPool);
this.metaDataMappingService = metaDataMappingService;
}
@Override
protected String executor() {
// we go async right away
return ThreadPool.Names.SAME;
}
@Override
protected String transportAction() {
return PutMappingAction.NAME;
}
@Override
protected PutMappingRequest newRequest() {
return new PutMappingRequest();
}
@Override
protected PutMappingResponse newResponse() {
return new PutMappingResponse();
}
@Override
protected void doExecute(PutMappingRequest request, ActionListener<PutMappingResponse> listener) {
request.indices(clusterService.state().metaData().concreteIndices(request.indices(), request.indicesOptions()));
super.doExecute(request, listener);
}
@Override
protected ClusterBlockException checkBlock(PutMappingRequest request, ClusterState state) {
return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA, request.indices());
}
@Override
protected void masterOperation(final PutMappingRequest request, final ClusterState state, final ActionListener<PutMappingResponse> listener) throws ElasticsearchException {
PutMappingClusterStateUpdateRequest updateRequest = new PutMappingClusterStateUpdateRequest()
.ackTimeout(request.timeout()).masterNodeTimeout(request.masterNodeTimeout())
.indices(request.indices()).type(request.type())
.source(request.source()).ignoreConflicts(request.ignoreConflicts());
metaDataMappingService.putMapping(updateRequest, new ClusterStateUpdateListener() {
@Override
public void onResponse(ClusterStateUpdateResponse response) {
listener.onResponse(new PutMappingResponse(response.isAcknowledged()));
}
@Override
public void onFailure(Throwable t) {
logger.debug("failed to put mappings on indices [{}], type [{}]", t, request.indices(), request.type());
listener.onFailure(t);
}
});
}
} | 1no label
| src_main_java_org_elasticsearch_action_admin_indices_mapping_put_TransportPutMappingAction.java |
303 | AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
try {
if (!InstrumentationRuntimeFactory.class.getClassLoader().equals(
ClassLoader.getSystemClassLoader())) {
return null;
}
} catch (Throwable t) {
return null;
}
File toolsJar = null;
// When running on IBM, the attach api classes are packaged in vm.jar which is a part
// of the default vm classpath.
if (! isIBM) {
// If we can't find the tools.jar and we're not on IBM we can't load the agent.
toolsJar = findToolsJar();
if (toolsJar == null) {
return null;
}
}
Class<?> vmClass = loadVMClass(toolsJar);
if (vmClass == null) {
return null;
}
String agentPath = getAgentJar();
if (agentPath == null) {
return null;
}
loadAgent(agentPath, vmClass);
return null;
}
}); | 0true
| common_src_main_java_org_broadleafcommerce_common_extensibility_InstrumentationRuntimeFactory.java |
6 | public class StateHandlingStatementOperations implements
KeyReadOperations,
KeyWriteOperations,
EntityOperations,
SchemaReadOperations,
SchemaWriteOperations
{
private final StoreReadLayer storeLayer;
private final LegacyPropertyTrackers legacyPropertyTrackers;
private final ConstraintIndexCreator constraintIndexCreator;
public StateHandlingStatementOperations(
StoreReadLayer storeLayer, LegacyPropertyTrackers propertyTrackers,
ConstraintIndexCreator constraintIndexCreator )
{
this.storeLayer = storeLayer;
this.legacyPropertyTrackers = propertyTrackers;
this.constraintIndexCreator = constraintIndexCreator;
}
@Override
public void nodeDelete( KernelStatement state, long nodeId )
{
legacyPropertyTrackers.nodeDelete( nodeId );
state.txState().nodeDoDelete( nodeId );
}
@Override
public void relationshipDelete( KernelStatement state, long relationshipId )
{
legacyPropertyTrackers.relationshipDelete( relationshipId );
state.txState().relationshipDoDelete( relationshipId );
}
@Override
public boolean nodeHasLabel( KernelStatement state, long nodeId, int labelId ) throws EntityNotFoundException
{
if ( state.hasTxStateWithChanges() )
{
if ( state.txState().nodeIsDeletedInThisTx( nodeId ) )
{
return false;
}
if ( state.txState().nodeIsAddedInThisTx( nodeId ) )
{
TxState.UpdateTriState labelState = state.txState().labelState( nodeId, labelId );
return labelState.isTouched() && labelState.isAdded();
}
TxState.UpdateTriState labelState = state.txState().labelState( nodeId, labelId );
if ( labelState.isTouched() )
{
return labelState.isAdded();
}
}
return storeLayer.nodeHasLabel( state, nodeId, labelId );
}
@Override
public PrimitiveIntIterator nodeGetLabels( KernelStatement state, long nodeId ) throws EntityNotFoundException
{
if ( state.hasTxStateWithChanges() )
{
if ( state.txState().nodeIsDeletedInThisTx( nodeId ) )
{
return IteratorUtil.emptyPrimitiveIntIterator();
}
if ( state.txState().nodeIsAddedInThisTx( nodeId ) )
{
return toPrimitiveIntIterator(
state.txState().nodeStateLabelDiffSets( nodeId ).getAdded().iterator() );
}
return state.txState().nodeStateLabelDiffSets( nodeId ).applyPrimitiveIntIterator(
storeLayer.nodeGetLabels( state, nodeId ) );
}
return storeLayer.nodeGetLabels( state, nodeId );
}
@Override
public boolean nodeAddLabel( KernelStatement state, long nodeId, int labelId ) throws EntityNotFoundException
{
if ( nodeHasLabel( state, nodeId, labelId ) )
{
// Label is already in state or in store, no-op
return false;
}
state.txState().nodeDoAddLabel( labelId, nodeId );
return true;
}
@Override
public boolean nodeRemoveLabel( KernelStatement state, long nodeId, int labelId ) throws EntityNotFoundException
{
if ( !nodeHasLabel( state, nodeId, labelId ) )
{
// Label does not exist in state nor in store, no-op
return false;
}
state.txState().nodeDoRemoveLabel( labelId, nodeId );
return true;
}
@Override
public PrimitiveLongIterator nodesGetForLabel( KernelStatement state, int labelId )
{
if ( state.hasTxStateWithChanges() )
{
PrimitiveLongIterator wLabelChanges =
state.txState().nodesWithLabelChanged( labelId ).applyPrimitiveLongIterator(
storeLayer.nodesGetForLabel( state, labelId ) );
return state.txState().nodesDeletedInTx().applyPrimitiveLongIterator( wLabelChanges );
}
return storeLayer.nodesGetForLabel( state, labelId );
}
@Override
public IndexDescriptor indexCreate( KernelStatement state, int labelId, int propertyKey )
{
IndexDescriptor rule = new IndexDescriptor( labelId, propertyKey );
state.txState().indexRuleDoAdd( rule );
return rule;
}
@Override
public void indexDrop( KernelStatement state, IndexDescriptor descriptor ) throws DropIndexFailureException
{
state.txState().indexDoDrop( descriptor );
}
@Override
public void uniqueIndexDrop( KernelStatement state, IndexDescriptor descriptor ) throws DropIndexFailureException
{
state.txState().constraintIndexDoDrop( descriptor );
}
@Override
public UniquenessConstraint uniquenessConstraintCreate( KernelStatement state, int labelId, int propertyKeyId )
throws CreateConstraintFailureException
{
UniquenessConstraint constraint = new UniquenessConstraint( labelId, propertyKeyId );
try
{
IndexDescriptor index = new IndexDescriptor( labelId, propertyKeyId );
if ( state.txState().constraintIndexDoUnRemove( index ) ) // ..., DROP, *CREATE*
{ // creation is undoing a drop
state.txState().constraintIndexDiffSetsByLabel( labelId ).unRemove( index );
if ( !state.txState().constraintDoUnRemove( constraint ) ) // CREATE, ..., DROP, *CREATE*
{ // ... the drop we are undoing did itself undo a prior create...
state.txState().constraintsChangesForLabel( labelId ).unRemove( constraint );
state.txState().constraintDoAdd(
constraint, state.txState().indexCreatedForConstraint( constraint ) );
}
}
else // *CREATE*
{ // create from scratch
for ( Iterator<UniquenessConstraint> it = storeLayer.constraintsGetForLabelAndPropertyKey(
state, labelId, propertyKeyId ); it.hasNext(); )
{
if ( it.next().equals( labelId, propertyKeyId ) )
{
return constraint;
}
}
long indexId = constraintIndexCreator.createUniquenessConstraintIndex(
state, this, labelId, propertyKeyId );
state.txState().constraintDoAdd( constraint, indexId );
}
return constraint;
}
catch ( TransactionalException | ConstraintVerificationFailedKernelException | DropIndexFailureException e )
{
throw new CreateConstraintFailureException( constraint, e );
}
}
@Override
public Iterator<UniquenessConstraint> constraintsGetForLabelAndPropertyKey( KernelStatement state,
int labelId, int propertyKeyId )
{
return applyConstraintsDiff( state, storeLayer.constraintsGetForLabelAndPropertyKey(
state, labelId, propertyKeyId ), labelId, propertyKeyId );
}
@Override
public Iterator<UniquenessConstraint> constraintsGetForLabel( KernelStatement state, int labelId )
{
return applyConstraintsDiff( state, storeLayer.constraintsGetForLabel( state, labelId ), labelId );
}
@Override
public Iterator<UniquenessConstraint> constraintsGetAll( KernelStatement state )
{
return applyConstraintsDiff( state, storeLayer.constraintsGetAll( state ) );
}
private Iterator<UniquenessConstraint> applyConstraintsDiff( KernelStatement state,
Iterator<UniquenessConstraint> constraints, int labelId, int propertyKeyId )
{
if ( state.hasTxStateWithChanges() )
{
DiffSets<UniquenessConstraint> diff =
state.txState().constraintsChangesForLabelAndProperty( labelId, propertyKeyId );
if ( diff != null )
{
return diff.apply( constraints );
}
}
return constraints;
}
private Iterator<UniquenessConstraint> applyConstraintsDiff( KernelStatement state,
Iterator<UniquenessConstraint> constraints, int labelId )
{
if ( state.hasTxStateWithChanges() )
{
DiffSets<UniquenessConstraint> diff = state.txState().constraintsChangesForLabel( labelId );
if ( diff != null )
{
return diff.apply( constraints );
}
}
return constraints;
}
private Iterator<UniquenessConstraint> applyConstraintsDiff( KernelStatement state,
Iterator<UniquenessConstraint> constraints )
{
if ( state.hasTxStateWithChanges() )
{
DiffSets<UniquenessConstraint> diff = state.txState().constraintsChanges();
if ( diff != null )
{
return diff.apply( constraints );
}
}
return constraints;
}
@Override
public void constraintDrop( KernelStatement state, UniquenessConstraint constraint )
{
state.txState().constraintDoDrop( constraint );
}
@Override
public IndexDescriptor indexesGetForLabelAndPropertyKey( KernelStatement state, int labelId, int propertyKey )
throws SchemaRuleNotFoundException
{
Iterable<IndexDescriptor> committedRules;
try
{
committedRules = option( storeLayer.indexesGetForLabelAndPropertyKey( state, labelId,
propertyKey ) );
}
catch ( SchemaRuleNotFoundException e )
{
committedRules = emptyList();
}
DiffSets<IndexDescriptor> ruleDiffSet = state.txState().indexDiffSetsByLabel( labelId );
Iterator<IndexDescriptor> rules =
state.hasTxStateWithChanges() ? ruleDiffSet.apply( committedRules.iterator() ) : committedRules
.iterator();
IndexDescriptor single = singleOrNull( rules );
if ( single == null )
{
throw new SchemaRuleNotFoundException( "Index rule for label:" + labelId + " and property:" +
propertyKey + " not found" );
}
return single;
}
@Override
public InternalIndexState indexGetState( KernelStatement state, IndexDescriptor descriptor )
throws IndexNotFoundKernelException
{
// If index is in our state, then return populating
if ( state.hasTxStateWithChanges() )
{
if ( checkIndexState( descriptor, state.txState().indexDiffSetsByLabel( descriptor.getLabelId() ) ) )
{
return InternalIndexState.POPULATING;
}
if ( checkIndexState( descriptor, state.txState().constraintIndexDiffSetsByLabel( descriptor.getLabelId()
) ) )
{
return InternalIndexState.POPULATING;
}
}
return storeLayer.indexGetState( state, descriptor );
}
private boolean checkIndexState( IndexDescriptor indexRule, DiffSets<IndexDescriptor> diffSet )
throws IndexNotFoundKernelException
{
if ( diffSet.isAdded( indexRule ) )
{
return true;
}
if ( diffSet.isRemoved( indexRule ) )
{
throw new IndexNotFoundKernelException( String.format( "Index for label id %d on property id %d has been " +
"dropped in this transaction.",
indexRule.getLabelId(),
indexRule.getPropertyKeyId() ) );
}
return false;
}
@Override
public Iterator<IndexDescriptor> indexesGetForLabel( KernelStatement state, int labelId )
{
if ( state.hasTxStateWithChanges() )
{
return state.txState().indexDiffSetsByLabel( labelId )
.apply( storeLayer.indexesGetForLabel( state, labelId ) );
}
return storeLayer.indexesGetForLabel( state, labelId );
}
@Override
public Iterator<IndexDescriptor> indexesGetAll( KernelStatement state )
{
if ( state.hasTxStateWithChanges() )
{
return state.txState().indexChanges().apply( storeLayer.indexesGetAll( state ) );
}
return storeLayer.indexesGetAll( state );
}
@Override
public Iterator<IndexDescriptor> uniqueIndexesGetForLabel( KernelStatement state, int labelId )
{
if ( state.hasTxStateWithChanges() )
{
return state.txState().constraintIndexDiffSetsByLabel( labelId )
.apply( storeLayer.uniqueIndexesGetForLabel( state, labelId ) );
}
return storeLayer.uniqueIndexesGetForLabel( state, labelId );
}
@Override
public Iterator<IndexDescriptor> uniqueIndexesGetAll( KernelStatement state )
{
if ( state.hasTxStateWithChanges() )
{
return state.txState().constraintIndexChanges()
.apply( storeLayer.uniqueIndexesGetAll( state ) );
}
return storeLayer.uniqueIndexesGetAll( state );
}
@Override
public long nodeGetUniqueFromIndexLookup(
KernelStatement state,
IndexDescriptor index,
Object value )
throws IndexNotFoundKernelException, IndexBrokenKernelException
{
PrimitiveLongIterator committed = storeLayer.nodeGetUniqueFromIndexLookup( state, index, value );
PrimitiveLongIterator exactMatches = filterExactIndexMatches( state, index, value, committed );
PrimitiveLongIterator changeFilteredMatches = filterIndexStateChanges( state, index, value, exactMatches );
return single( changeFilteredMatches, NO_SUCH_NODE );
}
@Override
public PrimitiveLongIterator nodesGetFromIndexLookup( KernelStatement state, IndexDescriptor index, final Object value )
throws IndexNotFoundKernelException
{
PrimitiveLongIterator committed = storeLayer.nodesGetFromIndexLookup( state, index, value );
PrimitiveLongIterator exactMatches = filterExactIndexMatches( state, index, value, committed );
PrimitiveLongIterator changeFilteredMatches = filterIndexStateChanges( state, index, value, exactMatches );
return changeFilteredMatches;
}
private PrimitiveLongIterator filterExactIndexMatches(
KernelStatement state,
IndexDescriptor index,
Object value,
PrimitiveLongIterator committed )
{
if ( isNumberOrArray( value ) )
{
return filter( exactMatch( state, index.getPropertyKeyId(), value ), committed );
}
return committed;
}
private boolean isNumberOrArray( Object value )
{
return value instanceof Number || value.getClass().isArray();
}
private PrimitiveLongPredicate exactMatch(
final KernelStatement state,
final int propertyKeyId,
final Object value )
{
return new PrimitiveLongPredicate()
{
@Override
public boolean accept( long nodeId )
{
try
{
return nodeGetProperty( state, nodeId, propertyKeyId ).valueEquals( value );
}
catch ( EntityNotFoundException e )
{
throw new ThisShouldNotHappenError( "Chris", "An index claims a node by id " + nodeId +
" has the value. However, it looks like that node does not exist.", e);
}
}
};
}
private PrimitiveLongIterator filterIndexStateChanges(
KernelStatement state,
IndexDescriptor index,
Object value,
PrimitiveLongIterator nodeIds )
{
if ( state.hasTxStateWithChanges() )
{
DiffSets<Long> labelPropertyChanges = nodesWithLabelAndPropertyDiffSet( state, index, value );
DiffSets<Long> deletionChanges = state.txState().nodesDeletedInTx();
// Apply to actual index lookup
return deletionChanges.applyPrimitiveLongIterator(
labelPropertyChanges.applyPrimitiveLongIterator( nodeIds ) );
}
return nodeIds;
}
@Override
public Property nodeSetProperty( KernelStatement state, long nodeId, DefinedProperty property )
throws EntityNotFoundException
{
Property existingProperty = nodeGetProperty( state, nodeId, property.propertyKeyId() );
if ( !existingProperty.isDefined() )
{
legacyPropertyTrackers.nodeAddStoreProperty( nodeId, property );
state.neoStoreTransaction.nodeAddProperty( nodeId, property.propertyKeyId(), property.value() );
}
else
{
legacyPropertyTrackers.nodeChangeStoreProperty( nodeId, (DefinedProperty) existingProperty, property );
state.neoStoreTransaction.nodeChangeProperty( nodeId, property.propertyKeyId(), property.value() );
}
state.txState().nodeDoReplaceProperty( nodeId, existingProperty, property );
return existingProperty;
}
@Override
public Property relationshipSetProperty( KernelStatement state, long relationshipId, DefinedProperty property )
throws EntityNotFoundException
{
Property existingProperty = relationshipGetProperty( state, relationshipId, property.propertyKeyId() );
if ( !existingProperty.isDefined() )
{
legacyPropertyTrackers.relationshipAddStoreProperty( relationshipId, property );
state.neoStoreTransaction.relAddProperty( relationshipId, property.propertyKeyId(), property.value() );
}
else
{
legacyPropertyTrackers.relationshipChangeStoreProperty( relationshipId, (DefinedProperty)
existingProperty, property );
state.neoStoreTransaction.relChangeProperty( relationshipId, property.propertyKeyId(), property.value() );
}
state.txState().relationshipDoReplaceProperty( relationshipId, existingProperty, property );
return existingProperty;
}
@Override
public Property graphSetProperty( KernelStatement state, DefinedProperty property )
{
Property existingProperty = graphGetProperty( state, property.propertyKeyId() );
if ( !existingProperty.isDefined() )
{
state.neoStoreTransaction.graphAddProperty( property.propertyKeyId(), property.value() );
}
else
{
state.neoStoreTransaction.graphChangeProperty( property.propertyKeyId(), property.value() );
}
state.txState().graphDoReplaceProperty( existingProperty, property );
return existingProperty;
}
@Override
public Property nodeRemoveProperty( KernelStatement state, long nodeId, int propertyKeyId )
throws EntityNotFoundException
{
Property existingProperty = nodeGetProperty( state, nodeId, propertyKeyId );
if ( existingProperty.isDefined() )
{
legacyPropertyTrackers.nodeRemoveStoreProperty( nodeId, (DefinedProperty) existingProperty );
state.neoStoreTransaction.nodeRemoveProperty( nodeId, propertyKeyId );
}
state.txState().nodeDoRemoveProperty( nodeId, existingProperty );
return existingProperty;
}
@Override
public Property relationshipRemoveProperty( KernelStatement state, long relationshipId, int propertyKeyId )
throws EntityNotFoundException
{
Property existingProperty = relationshipGetProperty( state, relationshipId, propertyKeyId );
if ( existingProperty.isDefined() )
{
legacyPropertyTrackers.relationshipRemoveStoreProperty( relationshipId, (DefinedProperty)
existingProperty );
state.neoStoreTransaction.relRemoveProperty( relationshipId, propertyKeyId );
}
state.txState().relationshipDoRemoveProperty( relationshipId, existingProperty );
return existingProperty;
}
@Override
public Property graphRemoveProperty( KernelStatement state, int propertyKeyId )
{
Property existingProperty = graphGetProperty( state, propertyKeyId );
if ( existingProperty.isDefined() )
{
state.neoStoreTransaction.graphRemoveProperty( propertyKeyId );
}
state.txState().graphDoRemoveProperty( existingProperty );
return existingProperty;
}
@Override
public PrimitiveLongIterator nodeGetPropertyKeys( KernelStatement state, long nodeId ) throws EntityNotFoundException
{
if ( state.hasTxStateWithChanges() )
{
return new PropertyKeyIdIterator( nodeGetAllProperties( state, nodeId ) );
}
return storeLayer.nodeGetPropertyKeys( state, nodeId );
}
@Override
public Property nodeGetProperty( KernelStatement state, long nodeId, int propertyKeyId )
throws EntityNotFoundException
{
if ( state.hasTxStateWithChanges() )
{
Iterator<DefinedProperty> properties = nodeGetAllProperties( state, nodeId );
while ( properties.hasNext() )
{
Property property = properties.next();
if ( property.propertyKeyId() == propertyKeyId )
{
return property;
}
}
return Property.noNodeProperty( nodeId, propertyKeyId );
}
return storeLayer.nodeGetProperty( state, nodeId, propertyKeyId );
}
@Override
public Iterator<DefinedProperty> nodeGetAllProperties( KernelStatement state, long nodeId )
throws EntityNotFoundException
{
if ( state.hasTxStateWithChanges() )
{
if ( state.txState().nodeIsAddedInThisTx( nodeId ) )
{
return state.txState().nodePropertyDiffSets( nodeId ).getAdded().iterator();
}
if ( state.txState().nodeIsDeletedInThisTx( nodeId ) )
{
// TODO Throw IllegalStateException to conform with beans API. We may want to introduce
// EntityDeletedException instead and use it instead of returning empty values in similar places
throw new IllegalStateException( "Node " + nodeId + " has been deleted" );
}
return state.txState().nodePropertyDiffSets( nodeId )
.apply( storeLayer.nodeGetAllProperties( state, nodeId ) );
}
return storeLayer.nodeGetAllProperties( state, nodeId );
}
@Override
public PrimitiveLongIterator relationshipGetPropertyKeys( KernelStatement state, long relationshipId )
throws EntityNotFoundException
{
if ( state.hasTxStateWithChanges() )
{
return new PropertyKeyIdIterator( relationshipGetAllProperties( state, relationshipId ) );
}
return storeLayer.relationshipGetPropertyKeys( state, relationshipId );
}
@Override
public Property relationshipGetProperty( KernelStatement state, long relationshipId, int propertyKeyId )
throws EntityNotFoundException
{
if ( state.hasTxStateWithChanges() )
{
Iterator<DefinedProperty> properties = relationshipGetAllProperties( state, relationshipId );
while ( properties.hasNext() )
{
Property property = properties.next();
if ( property.propertyKeyId() == propertyKeyId )
{
return property;
}
}
return Property.noRelationshipProperty( relationshipId, propertyKeyId );
}
return storeLayer.relationshipGetProperty( state, relationshipId, propertyKeyId );
}
@Override
public Iterator<DefinedProperty> relationshipGetAllProperties( KernelStatement state, long relationshipId )
throws EntityNotFoundException
{
if ( state.hasTxStateWithChanges() )
{
if ( state.txState().relationshipIsAddedInThisTx( relationshipId ) )
{
return state.txState().relationshipPropertyDiffSets( relationshipId ).getAdded().iterator();
}
if ( state.txState().relationshipIsDeletedInThisTx( relationshipId ) )
{
// TODO Throw IllegalStateException to conform with beans API. We may want to introduce
// EntityDeletedException instead and use it instead of returning empty values in similar places
throw new IllegalStateException( "Relationship " + relationshipId + " has been deleted" );
}
return state.txState().relationshipPropertyDiffSets( relationshipId )
.apply( storeLayer.relationshipGetAllProperties( state, relationshipId ) );
}
else
{
return storeLayer.relationshipGetAllProperties( state, relationshipId );
}
}
@Override
public PrimitiveLongIterator graphGetPropertyKeys( KernelStatement state )
{
if ( state.hasTxStateWithChanges() )
{
return new PropertyKeyIdIterator( graphGetAllProperties( state ) );
}
return storeLayer.graphGetPropertyKeys( state );
}
@Override
public Property graphGetProperty( KernelStatement state, int propertyKeyId )
{
Iterator<DefinedProperty> properties = graphGetAllProperties( state );
while ( properties.hasNext() )
{
Property property = properties.next();
if ( property.propertyKeyId() == propertyKeyId )
{
return property;
}
}
return Property.noGraphProperty( propertyKeyId );
}
@Override
public Iterator<DefinedProperty> graphGetAllProperties( KernelStatement state )
{
if ( state.hasTxStateWithChanges() )
{
return state.txState().graphPropertyDiffSets().apply( storeLayer.graphGetAllProperties( state ) );
}
return storeLayer.graphGetAllProperties( state );
}
private DiffSets<Long> nodesWithLabelAndPropertyDiffSet( KernelStatement state, IndexDescriptor index, Object value )
{
TxState txState = state.txState();
int labelId = index.getLabelId();
int propertyKeyId = index.getPropertyKeyId();
// Start with nodes where the given property has changed
DiffSets<Long> diff = txState.nodesWithChangedProperty( propertyKeyId, value );
// Ensure remaining nodes have the correct label
HasLabelFilter hasLabel = new HasLabelFilter( state, labelId );
diff = diff.filter( hasLabel );
// Include newly labeled nodes that already had the correct property
HasPropertyFilter hasPropertyFilter = new HasPropertyFilter( state, propertyKeyId, value );
Iterator<Long> addedNodesWithLabel = txState.nodesWithLabelAdded( labelId ).iterator();
diff.addAll( filter( hasPropertyFilter, addedNodesWithLabel ) );
// Remove de-labeled nodes that had the correct value before
Set<Long> removedNodesWithLabel = txState.nodesWithLabelChanged( index.getLabelId() ).getRemoved();
diff.removeAll( filter( hasPropertyFilter, removedNodesWithLabel.iterator() ) );
return diff;
}
private long nodeIfNotDeleted( long nodeId, TxState txState )
{
return txState.nodeIsDeletedInThisTx( nodeId ) ? NO_SUCH_NODE : nodeId;
}
private class HasPropertyFilter implements Predicate<Long>
{
private final Object value;
private final int propertyKeyId;
private final KernelStatement state;
public HasPropertyFilter( KernelStatement state, int propertyKeyId, Object value )
{
this.state = state;
this.value = value;
this.propertyKeyId = propertyKeyId;
}
@Override
public boolean accept( Long nodeId )
{
try
{
if ( state.hasTxStateWithChanges() && state.txState().nodeIsDeletedInThisTx( nodeId ) )
{
return false;
}
Property property = nodeGetProperty( state, nodeId, propertyKeyId );
return property.isDefined() && property.valueEquals( value );
}
catch ( EntityNotFoundException e )
{
return false;
}
}
}
private class HasLabelFilter implements Predicate<Long>
{
private final int labelId;
private final KernelStatement state;
public HasLabelFilter( KernelStatement state, int labelId )
{
this.state = state;
this.labelId = labelId;
}
@Override
public boolean accept( Long nodeId )
{
try
{
return nodeHasLabel( state, nodeId, labelId );
}
catch ( EntityNotFoundException e )
{
return false;
}
}
}
//
// Methods that delegate directly to storage
//
@Override
public Long indexGetOwningUniquenessConstraintId( KernelStatement state, IndexDescriptor index )
throws SchemaRuleNotFoundException
{
return storeLayer.indexGetOwningUniquenessConstraintId( state, index );
}
@Override
public long indexGetCommittedId( KernelStatement state, IndexDescriptor index, SchemaStorage.IndexRuleKind kind )
throws SchemaRuleNotFoundException
{
return storeLayer.indexGetCommittedId( state, index, kind );
}
@Override
public String indexGetFailure( Statement state, IndexDescriptor descriptor )
throws IndexNotFoundKernelException
{
return storeLayer.indexGetFailure( state, descriptor );
}
@Override
public int labelGetForName( Statement state, String labelName )
{
return storeLayer.labelGetForName( labelName );
}
@Override
public String labelGetName( Statement state, int labelId ) throws LabelNotFoundKernelException
{
return storeLayer.labelGetName( labelId );
}
@Override
public int propertyKeyGetForName( Statement state, String propertyKeyName )
{
return storeLayer.propertyKeyGetForName( propertyKeyName );
}
@Override
public String propertyKeyGetName( Statement state, int propertyKeyId ) throws PropertyKeyIdNotFoundKernelException
{
return storeLayer.propertyKeyGetName( propertyKeyId );
}
@Override
public Iterator<Token> propertyKeyGetAllTokens( Statement state )
{
return storeLayer.propertyKeyGetAllTokens();
}
@Override
public Iterator<Token> labelsGetAllTokens( Statement state )
{
return storeLayer.labelsGetAllTokens();
}
@Override
public int relationshipTypeGetForName( Statement state, String relationshipTypeName )
{
return storeLayer.relationshipTypeGetForName( relationshipTypeName );
}
@Override
public String relationshipTypeGetName( Statement state, int relationshipTypeId ) throws
RelationshipTypeIdNotFoundKernelException
{
return storeLayer.relationshipTypeGetName( relationshipTypeId );
}
@Override
public int labelGetOrCreateForName( Statement state, String labelName ) throws IllegalTokenNameException,
TooManyLabelsException
{
return storeLayer.labelGetOrCreateForName( labelName );
}
@Override
public int propertyKeyGetOrCreateForName( Statement state, String propertyKeyName ) throws IllegalTokenNameException
{
return storeLayer.propertyKeyGetOrCreateForName( propertyKeyName );
}
@Override
public int relationshipTypeGetOrCreateForName( Statement state, String relationshipTypeName ) throws IllegalTokenNameException
{
return storeLayer.relationshipTypeGetOrCreateForName( relationshipTypeName );
}
} | 1no label
| community_kernel_src_main_java_org_neo4j_kernel_impl_api_StateHandlingStatementOperations.java |
2,828 | private static class ReplicaSyncEntryProcessor implements ScheduledEntryProcessor<Integer, ReplicaSyncInfo> {
private InternalPartitionServiceImpl partitionService;
public ReplicaSyncEntryProcessor(InternalPartitionServiceImpl partitionService) {
this.partitionService = partitionService;
}
@Override
public void process(EntryTaskScheduler<Integer, ReplicaSyncInfo> scheduler,
Collection<ScheduledEntry<Integer, ReplicaSyncInfo>> entries) {
for (ScheduledEntry<Integer, ReplicaSyncInfo> entry : entries) {
ReplicaSyncInfo syncInfo = entry.getValue();
if (partitionService.replicaSyncRequests.compareAndSet(entry.getKey(), syncInfo, null)) {
logRendingSyncReplicaRequest(syncInfo);
partitionService.triggerPartitionReplicaSync(syncInfo.partitionId, syncInfo.replicaIndex);
}
}
}
private void logRendingSyncReplicaRequest(ReplicaSyncInfo syncInfo) {
ILogger logger = partitionService.logger;
if (logger.isFinestEnabled()) {
logger.finest("Re-sending sync replica request for partition: " + syncInfo.partitionId + ", replica: "
+ syncInfo.replicaIndex);
}
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_partition_impl_InternalPartitionServiceImpl.java |
3,327 | public abstract class FloatArrayAtomicFieldData extends AbstractAtomicNumericFieldData {
public static FloatArrayAtomicFieldData empty(int numDocs) {
return new Empty(numDocs);
}
private final int numDocs;
protected long size = -1;
public FloatArrayAtomicFieldData(int numDocs) {
super(true);
this.numDocs = numDocs;
}
@Override
public void close() {
}
@Override
public int getNumDocs() {
return numDocs;
}
static class Empty extends FloatArrayAtomicFieldData {
Empty(int numDocs) {
super(numDocs);
}
@Override
public LongValues getLongValues() {
return LongValues.EMPTY;
}
@Override
public DoubleValues getDoubleValues() {
return DoubleValues.EMPTY;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public long getNumberUniqueValues() {
return 0;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getMemorySizeInBytes() {
return 0;
}
@Override
public BytesValues getBytesValues(boolean needsHashes) {
return BytesValues.EMPTY;
}
@Override
public ScriptDocValues getScriptValues() {
return ScriptDocValues.EMPTY;
}
}
public static class WithOrdinals extends FloatArrayAtomicFieldData {
private final Ordinals ordinals;
private final BigFloatArrayList values;
public WithOrdinals(BigFloatArrayList values, int numDocs, Ordinals ordinals) {
super(numDocs);
this.values = values;
this.ordinals = ordinals;
}
@Override
public boolean isMultiValued() {
return ordinals.isMultiValued();
}
@Override
public boolean isValuesOrdered() {
return true;
}
@Override
public long getNumberUniqueValues() {
return ordinals.getNumOrds();
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_INT/*size*/ + RamUsageEstimator.NUM_BYTES_INT/*numDocs*/ + values.sizeInBytes() + ordinals.getMemorySizeInBytes();
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values, ordinals.ordinals());
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values, ordinals.ordinals());
}
static class LongValues extends org.elasticsearch.index.fielddata.LongValues.WithOrdinals {
private final BigFloatArrayList values;
LongValues(BigFloatArrayList values, Ordinals.Docs ordinals) {
super(ordinals);
this.values = values;
}
@Override
public long getValueByOrd(long ord) {
assert ord != Ordinals.MISSING_ORDINAL;
return (long) values.get(ord);
}
}
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues.WithOrdinals {
private final BigFloatArrayList values;
DoubleValues(BigFloatArrayList values, Ordinals.Docs ordinals) {
super(ordinals);
this.values = values;
}
@Override
public double getValueByOrd(long ord) {
return values.get(ord);
}
}
}
/**
* A single valued case, where not all values are "set", so we have a FixedBitSet that
* indicates which values have an actual value.
*/
public static class SingleFixedSet extends FloatArrayAtomicFieldData {
private final BigFloatArrayList values;
private final FixedBitSet set;
private final long numOrd;
public SingleFixedSet(BigFloatArrayList values, int numDocs, FixedBitSet set, long numOrd) {
super(numDocs);
this.values = values;
this.set = set;
this.numOrd = numOrd;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getNumberUniqueValues() {
return numOrd;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.sizeInBytes() + RamUsageEstimator.sizeOf(set.getBits());
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values, set);
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values, set);
}
static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final BigFloatArrayList values;
private final FixedBitSet set;
LongValues(BigFloatArrayList values, FixedBitSet set) {
super(false);
this.values = values;
this.set = set;
}
@Override
public int setDocument(int docId) {
this.docId = docId;
return set.get(docId) ? 1 : 0;
}
@Override
public long nextValue() {
return (long) values.get(docId);
}
}
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues {
private final BigFloatArrayList values;
private final FixedBitSet set;
DoubleValues(BigFloatArrayList values, FixedBitSet set) {
super(false);
this.values = values;
this.set = set;
}
@Override
public int setDocument(int docId) {
this.docId = docId;
return set.get(docId) ? 1 : 0;
}
@Override
public double nextValue() {
return values.get(docId);
}
}
}
/**
* Assumes all the values are "set", and docId is used as the index to the value array.
*/
public static class Single extends FloatArrayAtomicFieldData {
private final BigFloatArrayList values;
private final long numOrd;
/**
* Note, here, we assume that there is no offset by 1 from docId, so position 0
* is the value for docId 0.
*/
public Single(BigFloatArrayList values, int numDocs, long numOrd) {
super(numDocs);
this.values = values;
this.numOrd = numOrd;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getNumberUniqueValues() {
return numOrd;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.sizeInBytes();
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values);
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values);
}
static class LongValues extends DenseLongValues {
private final BigFloatArrayList values;
LongValues(BigFloatArrayList values) {
super(false);
this.values = values;
}
@Override
public long nextValue() {
return (long) values.get(docId);
}
}
static class DoubleValues extends DenseDoubleValues {
private final BigFloatArrayList values;
DoubleValues(BigFloatArrayList values) {
super(false);
this.values = values;
}
@Override
public double nextValue() {
return values.get(docId);
}
}
}
} | 1no label
| src_main_java_org_elasticsearch_index_fielddata_plain_FloatArrayAtomicFieldData.java |
1,356 | public class JDTAnnotation implements AnnotationMirror {
private Map<String, Object> values;
public JDTAnnotation(AnnotationBinding annotation) {
values = new HashMap<String, Object>();
ElementValuePair[] annotationVaues = annotation.getElementValuePairs();
for (ElementValuePair annotationValue : annotationVaues) {
String name = new String(annotationValue.getName());
MethodBinding elementMethod = annotationValue.getMethodBinding();
Object value = null;
if (elementMethod != null) {
value = convertValue(annotationValue.getMethodBinding().returnType, annotationValue.getValue());
} else {
value = JDTType.UNKNOWN_TYPE;
}
values.put(name, value);
}
}
@Override
public Object getValue(String fieldName) {
return values.get(fieldName);
}
private Object convertValue(TypeBinding returnType, Object value) {
if(value.getClass().isArray()){
Object[] array = (Object[])value;
List<Object> values = new ArrayList<Object>(array.length);
TypeBinding elementType = ((ArrayBinding)returnType).elementsType();
for(Object val : array)
values.add(convertValue(elementType, val));
return values;
}
if(returnType.isArrayType()){
// got a single value but expecting array
List<Object> values = new ArrayList<Object>(1);
TypeBinding elementType = ((ArrayBinding)returnType).elementsType();
values.add(convertValue(elementType, value));
return values;
}
if(value instanceof AnnotationBinding){
return new JDTAnnotation((AnnotationBinding) value);
}
if(value instanceof TypeBinding){
return new JDTType((TypeBinding) value);
}
if(value instanceof FieldBinding){
return new String(((FieldBinding) value).name);
}
if(value instanceof Constant){
Constant constant = (Constant) value;
return JDTUtils.fromConstant(constant);
}
return value;
}
@Override
public Object getValue() {
return getValue("value");
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_mirror_JDTAnnotation.java |
1,319 | public class OPaginatedCluster extends ODurableComponent implements OCluster {
public static final String DEF_EXTENSION = ".pcl";
private static final int DISK_PAGE_SIZE = DISK_CACHE_PAGE_SIZE.getValueAsInteger();
private static final int LOWEST_FREELIST_BOUNDARY = PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY
.getValueAsInteger();
private final static int FREE_LIST_SIZE = DISK_PAGE_SIZE - LOWEST_FREELIST_BOUNDARY;
private OCompression compression;
public static final String TYPE = "PHYSICAL";
private static final int PAGE_INDEX_OFFSET = 16;
private static final int RECORD_POSITION_MASK = 0xFFFF;
private static final int ONE_KB = 1024;
private ODiskCache diskCache;
private OClusterPositionMap clusterPositionMap;
private String name;
private OLocalPaginatedStorage storageLocal;
private volatile int id;
private long fileId;
private OStoragePaginatedClusterConfiguration config;
private final OModificationLock externalModificationLock = new OModificationLock();
private OCacheEntry pinnedStateEntry;
public OPaginatedCluster() {
super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean());
}
@Override
public void configure(OStorage storage, int id, String clusterName, String location, int dataSegmentId, Object... parameters)
throws IOException {
externalModificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
config = new OStoragePaginatedClusterConfiguration(storage.getConfiguration(), id, clusterName, null, true,
OStoragePaginatedClusterConfiguration.DEFAULT_GROW_FACTOR, OStoragePaginatedClusterConfiguration.DEFAULT_GROW_FACTOR,
OGlobalConfiguration.STORAGE_COMPRESSION_METHOD.getValueAsString());
config.name = clusterName;
init((OLocalPaginatedStorage) storage, config);
} finally {
releaseExclusiveLock();
}
} finally {
externalModificationLock.releaseModificationLock();
}
}
@Override
public void configure(OStorage storage, OStorageClusterConfiguration config) throws IOException {
externalModificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
init((OLocalPaginatedStorage) storage, config);
} finally {
releaseExclusiveLock();
}
} finally {
externalModificationLock.releaseModificationLock();
}
}
private void init(OLocalPaginatedStorage storage, OStorageClusterConfiguration config) throws IOException {
OFileUtils.checkValidName(config.getName());
this.config = (OStoragePaginatedClusterConfiguration) config;
this.compression = OCompressionFactory.INSTANCE.getCompression(this.config.compression);
storageLocal = storage;
init(storage.getWALInstance());
diskCache = storageLocal.getDiskCache();
name = config.getName();
this.id = config.getId();
clusterPositionMap = new OClusterPositionMap(diskCache, name, storage.getWALInstance());
}
public boolean exists() {
return diskCache.exists(name + DEF_EXTENSION);
}
@Override
public void create(int startSize) throws IOException {
externalModificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
fileId = diskCache.openFile(name + DEF_EXTENSION);
startDurableOperation(null);
initCusterState();
endDurableOperation(null, false);
if (config.root.clusters.size() <= config.id)
config.root.clusters.add(config);
else
config.root.clusters.set(config.id, config);
clusterPositionMap.create();
} finally {
releaseExclusiveLock();
}
} finally {
externalModificationLock.releaseModificationLock();
}
}
@Override
public void open() throws IOException {
externalModificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
fileId = diskCache.openFile(name + DEF_EXTENSION);
pinnedStateEntry = diskCache.load(fileId, 0, false);
try {
diskCache.pinPage(pinnedStateEntry);
} finally {
diskCache.release(pinnedStateEntry);
}
clusterPositionMap.open();
} finally {
releaseExclusiveLock();
}
} finally {
externalModificationLock.releaseModificationLock();
}
}
@Override
public void close() throws IOException {
close(true);
}
public void close(boolean flush) throws IOException {
externalModificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
if (flush)
synch();
diskCache.closeFile(fileId, flush);
clusterPositionMap.close();
} finally {
releaseExclusiveLock();
}
} finally {
externalModificationLock.releaseModificationLock();
}
}
@Override
public void delete() throws IOException {
externalModificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
diskCache.deleteFile(fileId);
clusterPositionMap.delete();
} finally {
releaseExclusiveLock();
}
} finally {
externalModificationLock.releaseModificationLock();
}
}
@Override
public void set(OCluster.ATTRIBUTES attribute, Object value) throws IOException {
if (attribute == null)
throw new IllegalArgumentException("attribute is null");
final String stringValue = value != null ? value.toString() : null;
externalModificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
switch (attribute) {
case NAME:
setNameInternal(stringValue);
break;
case USE_WAL:
setUseWalInternal(stringValue);
break;
case RECORD_GROW_FACTOR:
setRecordGrowFactorInternal(stringValue);
break;
case RECORD_OVERFLOW_GROW_FACTOR:
setRecordOverflowGrowFactorInternal(stringValue);
break;
case COMPRESSION:
setCompressionInternal(stringValue);
break;
}
} finally {
releaseExclusiveLock();
}
} finally {
externalModificationLock.releaseModificationLock();
}
}
private void setCompressionInternal(String stringValue) {
try {
compression = OCompressionFactory.INSTANCE.getCompression(stringValue);
config.compression = stringValue;
storageLocal.getConfiguration().update();
} catch (IllegalArgumentException e) {
throw new OStorageException("Invalid value for " + OCluster.ATTRIBUTES.COMPRESSION + " attribute. ", e);
}
}
private void setRecordOverflowGrowFactorInternal(String stringValue) {
try {
float growFactor = Float.parseFloat(stringValue);
if (growFactor < 1)
throw new OStorageException(OCluster.ATTRIBUTES.RECORD_OVERFLOW_GROW_FACTOR + " can not be less than 1");
config.recordOverflowGrowFactor = growFactor;
storageLocal.getConfiguration().update();
} catch (NumberFormatException nfe) {
throw new OStorageException("Invalid value for cluster attribute " + OCluster.ATTRIBUTES.RECORD_OVERFLOW_GROW_FACTOR
+ " was passed [" + stringValue + "].", nfe);
}
}
private void setRecordGrowFactorInternal(String stringValue) {
try {
float growFactor = Float.parseFloat(stringValue);
if (growFactor < 1)
throw new OStorageException(OCluster.ATTRIBUTES.RECORD_GROW_FACTOR + " can not be less than 1");
config.recordGrowFactor = growFactor;
storageLocal.getConfiguration().update();
} catch (NumberFormatException nfe) {
throw new OStorageException("Invalid value for cluster attribute " + OCluster.ATTRIBUTES.RECORD_GROW_FACTOR + " was passed ["
+ stringValue + "].", nfe);
}
}
private void setUseWalInternal(String stringValue) {
if (!(stringValue.equals("true") || stringValue.equals("false")))
throw new OStorageException("Invalid value for cluster attribute " + OCluster.ATTRIBUTES.USE_WAL + " was passed ["
+ stringValue + "].");
config.useWal = Boolean.valueOf(stringValue);
storageLocal.getConfiguration().update();
}
private void setNameInternal(String newName) throws IOException {
diskCache.renameFile(fileId, this.name, newName);
clusterPositionMap.rename(newName);
config.name = newName;
storageLocal.renameCluster(name, newName);
name = newName;
storageLocal.getConfiguration().update();
}
@Override
public boolean useWal() {
acquireSharedLock();
try {
return config.useWal;
} finally {
releaseSharedLock();
}
}
@Override
public float recordGrowFactor() {
acquireSharedLock();
try {
return config.recordGrowFactor;
} finally {
releaseSharedLock();
}
}
@Override
public float recordOverflowGrowFactor() {
acquireSharedLock();
try {
return config.recordOverflowGrowFactor;
} finally {
releaseSharedLock();
}
}
@Override
public String compression() {
acquireSharedLock();
try {
return config.compression;
} finally {
releaseSharedLock();
}
}
@Override
public void convertToTombstone(OClusterPosition iPosition) throws IOException {
throw new UnsupportedOperationException("convertToTombstone");
}
public OPhysicalPosition createRecord(byte[] content, final ORecordVersion recordVersion, final byte recordType)
throws IOException {
externalModificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
final OStorageTransaction transaction = storageLocal.getStorageTransaction();
content = compression.compress(content);
int grownContentSize = (int) (config.recordGrowFactor * content.length);
int entryContentLength = grownContentSize + 2 * OByteSerializer.BYTE_SIZE + OIntegerSerializer.INT_SIZE
+ OLongSerializer.LONG_SIZE;
if (entryContentLength < OClusterPage.MAX_RECORD_SIZE) {
startDurableOperation(transaction);
byte[] entryContent = new byte[entryContentLength];
int entryPosition = 0;
entryContent[entryPosition] = recordType;
entryPosition++;
OIntegerSerializer.INSTANCE.serializeNative(content.length, entryContent, entryPosition);
entryPosition += OIntegerSerializer.INT_SIZE;
System.arraycopy(content, 0, entryContent, entryPosition, content.length);
entryPosition += grownContentSize;
entryContent[entryPosition] = 1;
entryPosition++;
OLongSerializer.INSTANCE.serializeNative(-1L, entryContent, entryPosition);
ODurablePage.TrackMode trackMode = getTrackMode();
final AddEntryResult addEntryResult = addEntry(recordVersion, entryContent, trackMode);
updateClusterState(trackMode, 1, addEntryResult.recordsSizeDiff);
final OClusterPosition clusterPosition = clusterPositionMap.add(addEntryResult.pageIndex, addEntryResult.pagePosition,
getCurrentOperationUnitId(), getStartLSN(), trackMode);
endDurableOperation(transaction, false);
return createPhysicalPosition(recordType, clusterPosition, addEntryResult.recordVersion);
} else {
startDurableOperation(transaction);
final OClusterPage.TrackMode trackMode = getTrackMode();
int entrySize = grownContentSize + OIntegerSerializer.INT_SIZE + OByteSerializer.BYTE_SIZE;
int fullEntryPosition = 0;
byte[] fullEntry = new byte[entrySize];
fullEntry[fullEntryPosition] = recordType;
fullEntryPosition++;
OIntegerSerializer.INSTANCE.serializeNative(content.length, fullEntry, fullEntryPosition);
fullEntryPosition += OIntegerSerializer.INT_SIZE;
System.arraycopy(content, 0, fullEntry, fullEntryPosition, content.length);
long prevPageRecordPointer = -1;
long firstPageIndex = -1;
int firstPagePosition = -1;
ORecordVersion version = null;
int from = 0;
int to = from + (OClusterPage.MAX_RECORD_SIZE - OByteSerializer.BYTE_SIZE - OLongSerializer.LONG_SIZE);
int recordsSizeDiff = 0;
do {
byte[] entryContent = new byte[to - from + OByteSerializer.BYTE_SIZE + OLongSerializer.LONG_SIZE];
System.arraycopy(fullEntry, from, entryContent, 0, to - from);
if (from > 0)
entryContent[entryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 0;
else
entryContent[entryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 1;
OLongSerializer.INSTANCE.serializeNative(-1L, entryContent, entryContent.length - OLongSerializer.LONG_SIZE);
final AddEntryResult addEntryResult = addEntry(recordVersion, entryContent, trackMode);
recordsSizeDiff += addEntryResult.recordsSizeDiff;
if (firstPageIndex == -1) {
firstPageIndex = addEntryResult.pageIndex;
firstPagePosition = addEntryResult.pagePosition;
version = addEntryResult.recordVersion;
}
long addedPagePointer = createPagePointer(addEntryResult.pageIndex, addEntryResult.pagePosition);
if (prevPageRecordPointer >= 0) {
long prevPageIndex = prevPageRecordPointer >>> PAGE_INDEX_OFFSET;
int prevPageRecordPosition = (int) (prevPageRecordPointer & RECORD_POSITION_MASK);
final OCacheEntry prevPageCacheEntry = diskCache.load(fileId, prevPageIndex, false);
final OCachePointer prevPageMemoryPointer = prevPageCacheEntry.getCachePointer();
prevPageMemoryPointer.acquireExclusiveLock();
try {
final OClusterPage prevPage = new OClusterPage(prevPageMemoryPointer.getDataPointer(), false,
ODurablePage.TrackMode.FULL);
int prevRecordPageOffset = prevPage.getRecordPageOffset(prevPageRecordPosition);
int prevPageRecordSize = prevPage.getRecordSize(prevPageRecordPosition);
prevPage.setLongValue(prevRecordPageOffset + prevPageRecordSize - OLongSerializer.LONG_SIZE, addedPagePointer);
logPageChanges(prevPage, fileId, prevPageIndex, false);
prevPageCacheEntry.markDirty();
} finally {
prevPageMemoryPointer.releaseExclusiveLock();
diskCache.release(prevPageCacheEntry);
}
}
prevPageRecordPointer = addedPagePointer;
from = to;
to = to + (OClusterPage.MAX_RECORD_SIZE - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE);
if (to > fullEntry.length)
to = fullEntry.length;
} while (from < to);
updateClusterState(trackMode, 1, recordsSizeDiff);
OClusterPosition clusterPosition = clusterPositionMap.add(firstPageIndex, firstPagePosition, getCurrentOperationUnitId(),
getStartLSN(), trackMode);
endDurableOperation(transaction, false);
return createPhysicalPosition(recordType, clusterPosition, version);
}
} finally {
releaseExclusiveLock();
}
} finally {
externalModificationLock.releaseModificationLock();
}
}
private long createPagePointer(long pageIndex, int pagePosition) {
return pageIndex << PAGE_INDEX_OFFSET | pagePosition;
}
private void updateClusterState(ODurablePage.TrackMode trackMode, long sizeDiff, long recordsSizeDiff) throws IOException {
diskCache.loadPinnedPage(pinnedStateEntry);
OCachePointer statePointer = pinnedStateEntry.getCachePointer();
statePointer.acquireExclusiveLock();
try {
OPaginatedClusterState paginatedClusterState = new OPaginatedClusterState(statePointer.getDataPointer(), trackMode);
paginatedClusterState.setSize(paginatedClusterState.getSize() + sizeDiff);
paginatedClusterState.setRecordsSize(paginatedClusterState.getRecordsSize() + recordsSizeDiff);
logPageChanges(paginatedClusterState, fileId, pinnedStateEntry.getPageIndex(), false);
pinnedStateEntry.markDirty();
} finally {
statePointer.releaseExclusiveLock();
diskCache.release(pinnedStateEntry);
}
}
private OPhysicalPosition createPhysicalPosition(byte recordType, OClusterPosition clusterPosition, ORecordVersion version) {
final OPhysicalPosition physicalPosition = new OPhysicalPosition();
physicalPosition.recordType = recordType;
physicalPosition.recordSize = -1;
physicalPosition.dataSegmentId = -1;
physicalPosition.dataSegmentPos = -1;
physicalPosition.clusterPosition = clusterPosition;
physicalPosition.recordVersion = version;
return physicalPosition;
}
public ORawBuffer readRecord(OClusterPosition clusterPosition) throws IOException {
acquireSharedLock();
try {
OClusterPositionMapBucket.PositionEntry positionEntry = clusterPositionMap.get(clusterPosition);
if (positionEntry == null)
return null;
int recordPosition = positionEntry.getRecordPosition();
long pageIndex = positionEntry.getPageIndex();
if (diskCache.getFilledUpTo(fileId) <= pageIndex)
return null;
ORecordVersion recordVersion = null;
OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
OCachePointer pointer = cacheEntry.getCachePointer();
try {
final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, ODurablePage.TrackMode.NONE);
int recordPageOffset = localPage.getRecordPageOffset(recordPosition);
if (recordPageOffset < 0)
return null;
recordVersion = localPage.getRecordVersion(recordPosition);
} finally {
diskCache.release(cacheEntry);
}
byte[] fullContent = readFullEntry(clusterPosition, pageIndex, recordPosition);
if (fullContent == null)
return null;
int fullContentPosition = 0;
byte recordType = fullContent[fullContentPosition];
fullContentPosition++;
int readContentSize = OIntegerSerializer.INSTANCE.deserializeNative(fullContent, fullContentPosition);
fullContentPosition += OIntegerSerializer.INT_SIZE;
byte[] recordContent = new byte[readContentSize];
System.arraycopy(fullContent, fullContentPosition, recordContent, 0, recordContent.length);
recordContent = compression.uncompress(recordContent);
return new ORawBuffer(recordContent, recordVersion, recordType);
} finally {
releaseSharedLock();
}
}
private byte[] readFullEntry(OClusterPosition clusterPosition, long pageIndex, int recordPosition) throws IOException {
if (diskCache.getFilledUpTo(fileId) <= pageIndex)
return null;
final List<byte[]> recordChunks = new ArrayList<byte[]>();
int contentSize = 0;
long nextPagePointer = -1;
boolean firstEntry = true;
do {
OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
OCachePointer pointer = cacheEntry.getCachePointer();
try {
final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, ODurablePage.TrackMode.NONE);
int recordPageOffset = localPage.getRecordPageOffset(recordPosition);
if (recordPageOffset < 0) {
if (recordChunks.isEmpty())
return null;
else
throw new OStorageException("Content of record " + new ORecordId(id, clusterPosition) + " was broken.");
}
byte[] content = localPage.getBinaryValue(recordPageOffset, localPage.getRecordSize(recordPosition));
if (firstEntry && content[content.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] == 0)
return null;
recordChunks.add(content);
nextPagePointer = OLongSerializer.INSTANCE.deserializeNative(content, content.length - OLongSerializer.LONG_SIZE);
contentSize += content.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE;
firstEntry = false;
} finally {
diskCache.release(cacheEntry);
}
pageIndex = nextPagePointer >>> PAGE_INDEX_OFFSET;
recordPosition = (int) (nextPagePointer & RECORD_POSITION_MASK);
} while (nextPagePointer >= 0);
byte[] fullContent;
if (recordChunks.size() == 1)
fullContent = recordChunks.get(0);
else {
fullContent = new byte[contentSize + OLongSerializer.LONG_SIZE + OByteSerializer.BYTE_SIZE];
int fullContentPosition = 0;
for (byte[] recordChuck : recordChunks) {
System.arraycopy(recordChuck, 0, fullContent, fullContentPosition, recordChuck.length - OLongSerializer.LONG_SIZE
- OByteSerializer.BYTE_SIZE);
fullContentPosition += recordChuck.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE;
}
}
return fullContent;
}
public boolean deleteRecord(OClusterPosition clusterPosition) throws IOException {
externalModificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
final OStorageTransaction transaction = storageLocal.getStorageTransaction();
OClusterPositionMapBucket.PositionEntry positionEntry = clusterPositionMap.get(clusterPosition);
if (positionEntry == null)
return false;
long pageIndex = positionEntry.getPageIndex();
int recordPosition = positionEntry.getRecordPosition();
if (diskCache.getFilledUpTo(fileId) <= pageIndex)
return false;
final OClusterPage.TrackMode trackMode = getTrackMode();
long nextPagePointer = -1;
int removedContentSize = 0;
do {
final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
final OCachePointer pointer = cacheEntry.getCachePointer();
pointer.acquireExclusiveLock();
int initialFreePageIndex;
try {
final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, trackMode);
initialFreePageIndex = calculateFreePageIndex(localPage);
int recordPageOffset = localPage.getRecordPageOffset(recordPosition);
if (recordPageOffset < 0) {
if (removedContentSize == 0)
return false;
else
throw new OStorageException("Content of record " + new ORecordId(id, clusterPosition) + " was broken.");
} else if (removedContentSize == 0) {
startDurableOperation(transaction);
}
byte[] content = localPage.getBinaryValue(recordPageOffset, localPage.getRecordSize(recordPosition));
int initialFreeSpace = localPage.getFreeSpace();
localPage.deleteRecord(recordPosition);
removedContentSize += localPage.getFreeSpace() - initialFreeSpace;
nextPagePointer = OLongSerializer.INSTANCE.deserializeNative(content, content.length - OLongSerializer.LONG_SIZE);
logPageChanges(localPage, fileId, pageIndex, false);
cacheEntry.markDirty();
} finally {
pointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
updateFreePagesIndex(initialFreePageIndex, pageIndex, trackMode);
pageIndex = nextPagePointer >>> PAGE_INDEX_OFFSET;
recordPosition = (int) (nextPagePointer & RECORD_POSITION_MASK);
} while (nextPagePointer >= 0);
updateClusterState(trackMode, -1, -removedContentSize);
clusterPositionMap.remove(clusterPosition, getCurrentOperationUnitId(), getStartLSN(), trackMode);
endDurableOperation(transaction, false);
return true;
} finally {
releaseExclusiveLock();
}
} finally {
externalModificationLock.releaseModificationLock();
}
}
public void updateRecord(OClusterPosition clusterPosition, byte[] content, final ORecordVersion recordVersion,
final byte recordType) throws IOException {
externalModificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
final OStorageTransaction transaction = storageLocal.getStorageTransaction();
OClusterPositionMapBucket.PositionEntry positionEntry = clusterPositionMap.get(clusterPosition);
int recordPosition = positionEntry.getRecordPosition();
long pageIndex = positionEntry.getPageIndex();
long pagePointer = createPagePointer(pageIndex, recordPosition);
byte[] fullEntryContent = readFullEntry(clusterPosition, pageIndex, recordPosition);
if (fullEntryContent == null)
return;
content = compression.compress(content);
int updatedContentLength = content.length + 2 * OByteSerializer.BYTE_SIZE + OIntegerSerializer.INT_SIZE
+ OLongSerializer.LONG_SIZE;
byte[] recordEntry;
if (updatedContentLength <= fullEntryContent.length)
recordEntry = new byte[fullEntryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE];
else {
int grownContent = (int) (content.length * config.recordOverflowGrowFactor);
recordEntry = new byte[grownContent + OByteSerializer.BYTE_SIZE + OIntegerSerializer.INT_SIZE];
}
final OClusterPage.TrackMode trackMode = getTrackMode();
startDurableOperation(transaction);
int entryPosition = 0;
recordEntry[entryPosition] = recordType;
entryPosition++;
OIntegerSerializer.INSTANCE.serializeNative(content.length, recordEntry, entryPosition);
entryPosition += OIntegerSerializer.INT_SIZE;
System.arraycopy(content, 0, recordEntry, entryPosition, content.length);
int recordsSizeDiff = 0;
long prevPageRecordPointer = -1;
int currentPos = 0;
while (pagePointer >= 0 && currentPos < recordEntry.length) {
recordPosition = (int) (pagePointer & RECORD_POSITION_MASK);
pageIndex = pagePointer >>> PAGE_INDEX_OFFSET;
int freePageIndex;
final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
final OCachePointer dataPointer = cacheEntry.getCachePointer();
dataPointer.acquireExclusiveLock();
try {
final OClusterPage localPage = new OClusterPage(dataPointer.getDataPointer(), false, trackMode);
int freeSpace = localPage.getFreeSpace();
freePageIndex = calculateFreePageIndex(localPage);
int recordPageOffset = localPage.getRecordPageOffset(recordPosition);
int chunkSize = localPage.getRecordSize(recordPosition);
long nextPagePointer = localPage.getLongValue(recordPageOffset + +chunkSize - OLongSerializer.LONG_SIZE);
int newChunkLen = Math.min(recordEntry.length - currentPos + OLongSerializer.LONG_SIZE + OByteSerializer.BYTE_SIZE,
chunkSize);
int dataLen = newChunkLen - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE;
byte[] newRecordChunk = new byte[newChunkLen];
System.arraycopy(recordEntry, currentPos, newRecordChunk, 0, dataLen);
if (currentPos > 0)
newRecordChunk[newRecordChunk.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 0;
else
newRecordChunk[newRecordChunk.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 1;
OLongSerializer.INSTANCE.serializeNative(-1L, newRecordChunk, newRecordChunk.length - OLongSerializer.LONG_SIZE);
if (prevPageRecordPointer >= 0) {
long prevPageIndex = prevPageRecordPointer >>> PAGE_INDEX_OFFSET;
int prevPageRecordPosition = (int) (prevPageRecordPointer & RECORD_POSITION_MASK);
final OCacheEntry prevPageCacheEntry = diskCache.load(fileId, prevPageIndex, false);
final OCachePointer prevPageMemoryPointer = prevPageCacheEntry.getCachePointer();
prevPageMemoryPointer.acquireExclusiveLock();
try {
final OClusterPage prevPage = new OClusterPage(prevPageMemoryPointer.getDataPointer(), false, trackMode);
int prevRecordPageOffset = prevPage.getRecordPageOffset(prevPageRecordPosition);
int prevPageRecordSize = prevPage.getRecordSize(prevPageRecordPosition);
prevPage.setLongValue(prevRecordPageOffset + prevPageRecordSize - OLongSerializer.LONG_SIZE, pagePointer);
logPageChanges(prevPage, fileId, prevPageIndex, false);
prevPageCacheEntry.markDirty();
} finally {
prevPageMemoryPointer.releaseExclusiveLock();
diskCache.release(prevPageCacheEntry);
}
}
localPage.replaceRecord(recordPosition, newRecordChunk, recordVersion.getCounter() != -2 ? recordVersion : null);
currentPos += dataLen;
recordsSizeDiff += freeSpace - localPage.getFreeSpace();
prevPageRecordPointer = pagePointer;
pagePointer = nextPagePointer;
logPageChanges(localPage, fileId, pageIndex, false);
cacheEntry.markDirty();
} finally {
dataPointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
updateFreePagesIndex(freePageIndex, pageIndex, trackMode);
}
int from = currentPos;
int to = from + (OClusterPage.MAX_RECORD_SIZE - OByteSerializer.BYTE_SIZE - OLongSerializer.LONG_SIZE);
if (to > recordEntry.length)
to = recordEntry.length;
while (from < to) {
byte[] entryContent = new byte[to - from + OByteSerializer.BYTE_SIZE + OLongSerializer.LONG_SIZE];
System.arraycopy(recordEntry, from, entryContent, 0, to - from);
if (from > 0)
entryContent[entryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 0;
else
entryContent[entryContent.length - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE] = 1;
OLongSerializer.INSTANCE.serializeNative(-1L, entryContent, entryContent.length - OLongSerializer.LONG_SIZE);
final AddEntryResult addEntryResult = addEntry(recordVersion, entryContent, trackMode);
recordsSizeDiff += addEntryResult.recordsSizeDiff;
long addedPagePointer = createPagePointer(addEntryResult.pageIndex, addEntryResult.pagePosition);
if (prevPageRecordPointer >= 0) {
long prevPageIndex = prevPageRecordPointer >>> PAGE_INDEX_OFFSET;
int prevPageRecordPosition = (int) (prevPageRecordPointer & RECORD_POSITION_MASK);
final OCacheEntry prevPageCacheEntry = diskCache.load(fileId, prevPageIndex, false);
final OCachePointer prevPageMemoryPointer = prevPageCacheEntry.getCachePointer();
prevPageMemoryPointer.acquireExclusiveLock();
try {
final OClusterPage prevPage = new OClusterPage(prevPageMemoryPointer.getDataPointer(), false, trackMode);
int recordPageOffset = prevPage.getRecordPageOffset(prevPageRecordPosition);
int prevPageRecordSize = prevPage.getRecordSize(prevPageRecordPosition);
prevPage.setLongValue(recordPageOffset + prevPageRecordSize - OLongSerializer.LONG_SIZE, addedPagePointer);
logPageChanges(prevPage, fileId, prevPageIndex, false);
prevPageCacheEntry.markDirty();
} finally {
prevPageMemoryPointer.releaseExclusiveLock();
diskCache.release(prevPageCacheEntry);
}
}
prevPageRecordPointer = addedPagePointer;
from = to;
to = to + (OClusterPage.MAX_RECORD_SIZE - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE);
if (to > recordEntry.length)
to = recordEntry.length;
}
updateClusterState(trackMode, 0, recordsSizeDiff);
endDurableOperation(transaction, false);
} finally {
releaseExclusiveLock();
}
} finally {
externalModificationLock.releaseModificationLock();
}
}
private AddEntryResult addEntry(ORecordVersion recordVersion, byte[] entryContent, OClusterPage.TrackMode trackMode)
throws IOException {
final FindFreePageResult findFreePageResult = findFreePage(entryContent.length, trackMode);
int freePageIndex = findFreePageResult.freePageIndex;
long pageIndex = findFreePageResult.pageIndex;
boolean newRecord = freePageIndex >= FREE_LIST_SIZE;
final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
final OCachePointer pagePointer = cacheEntry.getCachePointer();
pagePointer.acquireExclusiveLock();
int recordSizesDiff;
int position;
final ORecordVersion finalVersion;
try {
final OClusterPage localPage = new OClusterPage(pagePointer.getDataPointer(), newRecord, trackMode);
assert newRecord || freePageIndex == calculateFreePageIndex(localPage);
int initialFreeSpace = localPage.getFreeSpace();
position = localPage.appendRecord(recordVersion, entryContent, false);
assert position >= 0;
finalVersion = localPage.getRecordVersion(position);
int freeSpace = localPage.getFreeSpace();
recordSizesDiff = initialFreeSpace - freeSpace;
logPageChanges(localPage, fileId, pageIndex, newRecord);
cacheEntry.markDirty();
} finally {
pagePointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
updateFreePagesIndex(freePageIndex, pageIndex, trackMode);
return new AddEntryResult(pageIndex, position, finalVersion, recordSizesDiff);
}
private FindFreePageResult findFreePage(int contentSize, OClusterPage.TrackMode trackMode) throws IOException {
diskCache.loadPinnedPage(pinnedStateEntry);
OCachePointer pinnedPagePointer = pinnedStateEntry.getCachePointer();
try {
while (true) {
int freePageIndex = contentSize / ONE_KB;
freePageIndex -= PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getValueAsInteger();
if (freePageIndex < 0)
freePageIndex = 0;
OPaginatedClusterState freePageLists = new OPaginatedClusterState(pinnedPagePointer.getDataPointer(),
ODurablePage.TrackMode.NONE);
long pageIndex;
do {
pageIndex = freePageLists.getFreeListPage(freePageIndex);
freePageIndex++;
} while (pageIndex < 0 && freePageIndex < FREE_LIST_SIZE);
if (pageIndex < 0)
pageIndex = diskCache.getFilledUpTo(fileId);
else
freePageIndex--;
if (freePageIndex < FREE_LIST_SIZE) {
OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
OCachePointer pointer = cacheEntry.getCachePointer();
int realFreePageIndex;
try {
OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, ODurablePage.TrackMode.NONE);
realFreePageIndex = calculateFreePageIndex(localPage);
} finally {
diskCache.release(cacheEntry);
}
if (realFreePageIndex != freePageIndex) {
OLogManager.instance().warn(this,
"Page in file %s with index %d was placed in wrong free list, this error will be fixed automatically.",
name + DEF_EXTENSION, pageIndex);
updateFreePagesIndex(freePageIndex, pageIndex, trackMode);
continue;
}
}
return new FindFreePageResult(pageIndex, freePageIndex);
}
} finally {
diskCache.release(pinnedStateEntry);
}
}
private void updateFreePagesIndex(int prevFreePageIndex, long pageIndex, OClusterPage.TrackMode trackMode) throws IOException {
final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
final OCachePointer pointer = cacheEntry.getCachePointer();
pointer.acquireExclusiveLock();
try {
final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, trackMode);
int newFreePageIndex = calculateFreePageIndex(localPage);
if (prevFreePageIndex == newFreePageIndex)
return;
long nextPageIndex = localPage.getNextPage();
long prevPageIndex = localPage.getPrevPage();
if (prevPageIndex >= 0) {
final OCacheEntry prevPageCacheEntry = diskCache.load(fileId, prevPageIndex, false);
final OCachePointer prevPagePointer = prevPageCacheEntry.getCachePointer();
prevPagePointer.acquireExclusiveLock();
try {
final OClusterPage prevPage = new OClusterPage(prevPagePointer.getDataPointer(), false, trackMode);
assert calculateFreePageIndex(prevPage) == prevFreePageIndex;
prevPage.setNextPage(nextPageIndex);
logPageChanges(prevPage, fileId, prevPageIndex, false);
prevPageCacheEntry.markDirty();
} finally {
prevPagePointer.releaseExclusiveLock();
diskCache.release(prevPageCacheEntry);
}
}
if (nextPageIndex >= 0) {
final OCacheEntry nextPageCacheEntry = diskCache.load(fileId, nextPageIndex, false);
final OCachePointer nextPagePointer = nextPageCacheEntry.getCachePointer();
nextPagePointer.acquireExclusiveLock();
try {
final OClusterPage nextPage = new OClusterPage(nextPagePointer.getDataPointer(), false, trackMode);
if (calculateFreePageIndex(nextPage) != prevFreePageIndex)
calculateFreePageIndex(nextPage);
assert calculateFreePageIndex(nextPage) == prevFreePageIndex;
nextPage.setPrevPage(prevPageIndex);
logPageChanges(nextPage, fileId, nextPageIndex, false);
nextPageCacheEntry.markDirty();
} finally {
nextPagePointer.releaseExclusiveLock();
diskCache.release(nextPageCacheEntry);
}
}
localPage.setNextPage(-1);
localPage.setPrevPage(-1);
if (prevFreePageIndex < 0 && newFreePageIndex < 0)
return;
if (prevFreePageIndex >= 0 && prevFreePageIndex < FREE_LIST_SIZE) {
if (prevPageIndex < 0)
updateFreePagesList(prevFreePageIndex, nextPageIndex);
}
if (newFreePageIndex >= 0) {
long oldFreePage;
diskCache.loadPinnedPage(pinnedStateEntry);
OCachePointer freeListPointer = pinnedStateEntry.getCachePointer();
try {
OPaginatedClusterState clusterFreeList = new OPaginatedClusterState(freeListPointer.getDataPointer(),
ODurablePage.TrackMode.NONE);
oldFreePage = clusterFreeList.getFreeListPage(newFreePageIndex);
} finally {
diskCache.release(pinnedStateEntry);
}
if (oldFreePage >= 0) {
final OCacheEntry oldFreePageCacheEntry = diskCache.load(fileId, oldFreePage, false);
final OCachePointer oldFreePagePointer = oldFreePageCacheEntry.getCachePointer();
oldFreePagePointer.acquireExclusiveLock();
try {
final OClusterPage oldFreeLocalPage = new OClusterPage(oldFreePagePointer.getDataPointer(), false, trackMode);
assert calculateFreePageIndex(oldFreeLocalPage) == newFreePageIndex;
oldFreeLocalPage.setPrevPage(pageIndex);
logPageChanges(oldFreeLocalPage, fileId, oldFreePage, false);
oldFreePageCacheEntry.markDirty();
} finally {
oldFreePagePointer.releaseExclusiveLock();
diskCache.release(oldFreePageCacheEntry);
}
localPage.setNextPage(oldFreePage);
localPage.setPrevPage(-1);
}
updateFreePagesList(newFreePageIndex, pageIndex);
}
logPageChanges(localPage, fileId, pageIndex, false);
cacheEntry.markDirty();
} finally {
pointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
}
private void updateFreePagesList(int freeListIndex, long pageIndex) throws IOException {
ODurablePage.TrackMode trackMode = getTrackMode();
diskCache.loadPinnedPage(pinnedStateEntry);
OCachePointer statePointer = pinnedStateEntry.getCachePointer();
statePointer.acquireExclusiveLock();
try {
OPaginatedClusterState paginatedClusterState = new OPaginatedClusterState(statePointer.getDataPointer(), trackMode);
paginatedClusterState.setFreeListPage(freeListIndex, pageIndex);
logPageChanges(paginatedClusterState, fileId, pinnedStateEntry.getPageIndex(), false);
pinnedStateEntry.markDirty();
} finally {
statePointer.releaseExclusiveLock();
diskCache.release(pinnedStateEntry);
}
}
private int calculateFreePageIndex(OClusterPage localPage) {
int newFreePageIndex;
if (localPage.isEmpty())
newFreePageIndex = FREE_LIST_SIZE - 1;
else {
newFreePageIndex = (localPage.getMaxRecordSize() - (ONE_KB - 1)) / ONE_KB;
newFreePageIndex -= LOWEST_FREELIST_BOUNDARY;
}
return newFreePageIndex;
}
@Override
public long getTombstonesCount() {
return 0;
}
@Override
public boolean hasTombstonesSupport() {
return false;
}
@Override
public void truncate() throws IOException {
storageLocal.checkForClusterPermissions(getName());
externalModificationLock.requestModificationLock();
try {
acquireExclusiveLock();
try {
if (config.useWal)
startDurableOperation(null);
diskCache.truncateFile(fileId);
clusterPositionMap.truncate();
initCusterState();
if (config.useWal)
endDurableOperation(null, false);
} finally {
releaseExclusiveLock();
}
} finally {
externalModificationLock.releaseModificationLock();
}
storageLocal.scheduleFullCheckpoint();
}
private void initCusterState() throws IOException {
ODurablePage.TrackMode trackMode = getTrackMode();
pinnedStateEntry = diskCache.allocateNewPage(fileId);
OCachePointer statePointer = pinnedStateEntry.getCachePointer();
statePointer.acquireExclusiveLock();
try {
OPaginatedClusterState paginatedClusterState = new OPaginatedClusterState(statePointer.getDataPointer(), trackMode);
diskCache.pinPage(pinnedStateEntry);
paginatedClusterState.setSize(0);
paginatedClusterState.setRecordsSize(0);
for (int i = 0; i < FREE_LIST_SIZE; i++)
paginatedClusterState.setFreeListPage(i, -1);
logPageChanges(paginatedClusterState, fileId, pinnedStateEntry.getPageIndex(), true);
pinnedStateEntry.markDirty();
} finally {
statePointer.releaseExclusiveLock();
diskCache.release(pinnedStateEntry);
}
}
@Override
public String getType() {
return TYPE;
}
@Override
public int getDataSegmentId() {
return -1;
}
@Override
public boolean addPhysicalPosition(OPhysicalPosition iPPosition) throws IOException {
throw new UnsupportedOperationException("addPhysicalPosition");
}
@Override
public OPhysicalPosition getPhysicalPosition(OPhysicalPosition position) throws IOException {
acquireSharedLock();
try {
OClusterPosition clusterPosition = position.clusterPosition;
OClusterPositionMapBucket.PositionEntry positionEntry = clusterPositionMap.get(clusterPosition);
if (positionEntry == null)
return null;
long pageIndex = positionEntry.getPageIndex();
int recordPosition = positionEntry.getRecordPosition();
long pagesCount = diskCache.getFilledUpTo(fileId);
if (pageIndex >= pagesCount)
return null;
OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
OCachePointer pointer = cacheEntry.getCachePointer();
try {
final OClusterPage localPage = new OClusterPage(pointer.getDataPointer(), false, ODurablePage.TrackMode.NONE);
int recordPageOffset = localPage.getRecordPageOffset(recordPosition);
if (recordPageOffset < 0)
return null;
int recordSize = localPage.getRecordSize(recordPosition);
if (localPage.getByteValue(recordPageOffset + recordSize - OLongSerializer.LONG_SIZE - OByteSerializer.BYTE_SIZE) == 0)
return null;
final OPhysicalPosition physicalPosition = new OPhysicalPosition();
physicalPosition.dataSegmentId = -1;
physicalPosition.dataSegmentPos = -1;
physicalPosition.recordSize = -1;
physicalPosition.recordType = localPage.getByteValue(recordPageOffset);
physicalPosition.recordVersion = localPage.getRecordVersion(recordPosition);
physicalPosition.clusterPosition = position.clusterPosition;
return physicalPosition;
} finally {
diskCache.release(cacheEntry);
}
} finally {
releaseSharedLock();
}
}
@Override
public void updateDataSegmentPosition(OClusterPosition iPosition, int iDataSegmentId, long iDataPosition) throws IOException {
throw new UnsupportedOperationException("updateDataSegmentPosition");
}
@Override
public void removePhysicalPosition(OClusterPosition iPosition) throws IOException {
throw new UnsupportedOperationException("updateDataSegmentPosition");
}
@Override
public void updateRecordType(OClusterPosition iPosition, byte iRecordType) throws IOException {
throw new UnsupportedOperationException("updateRecordType");
}
@Override
public void updateVersion(OClusterPosition iPosition, ORecordVersion iVersion) throws IOException {
throw new UnsupportedOperationException("updateVersion");
}
@Override
public long getEntries() {
acquireSharedLock();
try {
diskCache.loadPinnedPage(pinnedStateEntry);
OCachePointer statePointer = pinnedStateEntry.getCachePointer();
try {
return new OPaginatedClusterState(statePointer.getDataPointer(), ODurablePage.TrackMode.NONE).getSize();
} finally {
diskCache.release(pinnedStateEntry);
}
} catch (IOException ioe) {
throw new OStorageException("Error during retrieval of size of " + name + " cluster.");
} finally {
releaseSharedLock();
}
}
@Override
public OClusterPosition getFirstPosition() throws IOException {
acquireSharedLock();
try {
return clusterPositionMap.getFirstPosition();
} finally {
releaseSharedLock();
}
}
@Override
public OClusterPosition getLastPosition() throws IOException {
acquireSharedLock();
try {
return clusterPositionMap.getLastPosition();
} finally {
releaseSharedLock();
}
}
@Override
public void lock() {
throw new UnsupportedOperationException("lock");
}
@Override
public void unlock() {
throw new UnsupportedOperationException("unlock");
}
@Override
public int getId() {
return id;
}
@Override
public void synch() throws IOException {
acquireSharedLock();
try {
diskCache.flushFile(fileId);
clusterPositionMap.flush();
} finally {
releaseSharedLock();
}
}
@Override
public void setSoftlyClosed(boolean softlyClosed) throws IOException {
acquireExclusiveLock();
try {
diskCache.setSoftlyClosed(fileId, softlyClosed);
} finally {
releaseExclusiveLock();
}
}
@Override
public boolean wasSoftlyClosed() throws IOException {
acquireSharedLock();
try {
return diskCache.wasSoftlyClosed(fileId) || clusterPositionMap.wasSoftlyClosed();
} finally {
releaseSharedLock();
}
}
@Override
public String getName() {
acquireSharedLock();
try {
return name;
} finally {
releaseSharedLock();
}
}
@Override
public long getRecordsSize() throws IOException {
acquireSharedLock();
try {
diskCache.loadPinnedPage(pinnedStateEntry);
OCachePointer statePointer = pinnedStateEntry.getCachePointer();
try {
return new OPaginatedClusterState(statePointer.getDataPointer(), ODurablePage.TrackMode.NONE).getRecordsSize();
} finally {
diskCache.release(pinnedStateEntry);
}
} finally {
releaseSharedLock();
}
}
@Override
public boolean isHashBased() {
return false;
}
@Override
public OClusterEntryIterator absoluteIterator() {
acquireSharedLock();
try {
return new OClusterEntryIterator(this);
} finally {
releaseSharedLock();
}
}
@Override
public OPhysicalPosition[] higherPositions(OPhysicalPosition position) throws IOException {
acquireSharedLock();
try {
final OClusterPosition[] clusterPositions = clusterPositionMap.higherPositions(position.clusterPosition);
return convertToPhysicalPositions(clusterPositions);
} finally {
releaseSharedLock();
}
}
private OPhysicalPosition[] convertToPhysicalPositions(OClusterPosition[] clusterPositions) {
OPhysicalPosition[] positions = new OPhysicalPosition[clusterPositions.length];
for (int i = 0; i < positions.length; i++) {
OPhysicalPosition physicalPosition = new OPhysicalPosition();
physicalPosition.clusterPosition = clusterPositions[i];
positions[i] = physicalPosition;
}
return positions;
}
@Override
public OPhysicalPosition[] ceilingPositions(OPhysicalPosition position) throws IOException {
acquireSharedLock();
try {
final OClusterPosition[] clusterPositions = clusterPositionMap.ceilingPositions(position.clusterPosition);
return convertToPhysicalPositions(clusterPositions);
} finally {
releaseSharedLock();
}
}
@Override
public OPhysicalPosition[] lowerPositions(OPhysicalPosition position) throws IOException {
acquireSharedLock();
try {
final OClusterPosition[] clusterPositions = clusterPositionMap.lowerPositions(position.clusterPosition);
return convertToPhysicalPositions(clusterPositions);
} finally {
releaseSharedLock();
}
}
@Override
public OPhysicalPosition[] floorPositions(OPhysicalPosition position) throws IOException {
acquireSharedLock();
try {
final OClusterPosition[] clusterPositions = clusterPositionMap.floorPositions(position.clusterPosition);
return convertToPhysicalPositions(clusterPositions);
} finally {
releaseSharedLock();
}
}
@Override
protected void endDurableOperation(OStorageTransaction transaction, boolean rollback) throws IOException {
if (!config.useWal)
return;
super.endDurableOperation(transaction, rollback);
}
@Override
protected void startDurableOperation(OStorageTransaction transaction) throws IOException {
if (!config.useWal)
return;
super.startDurableOperation(transaction);
}
@Override
protected void logPageChanges(ODurablePage localPage, long fileId, long pageIndex, boolean isNewPage) throws IOException {
if (!config.useWal)
return;
super.logPageChanges(localPage, fileId, pageIndex, isNewPage);
}
@Override
protected ODurablePage.TrackMode getTrackMode() {
if (!config.useWal)
return ODurablePage.TrackMode.NONE;
return super.getTrackMode();
}
public OModificationLock getExternalModificationLock() {
return externalModificationLock;
}
private static final class AddEntryResult {
private final long pageIndex;
private final int pagePosition;
private final ORecordVersion recordVersion;
private final int recordsSizeDiff;
public AddEntryResult(long pageIndex, int pagePosition, ORecordVersion recordVersion, int recordsSizeDiff) {
this.pageIndex = pageIndex;
this.pagePosition = pagePosition;
this.recordVersion = recordVersion;
this.recordsSizeDiff = recordsSizeDiff;
}
}
private static final class FindFreePageResult {
private final long pageIndex;
private final int freePageIndex;
private FindFreePageResult(long pageIndex, int freePageIndex) {
this.pageIndex = pageIndex;
this.freePageIndex = freePageIndex;
}
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_OPaginatedCluster.java |
1,473 | public class BroadleafUpdateAccountController extends BroadleafAbstractController {
@Resource(name = "blCustomerService")
protected CustomerService customerService;
@Resource(name = "blUpdateAccountValidator")
protected UpdateAccountValidator updateAccountValidator;
protected String accountUpdatedMessage = "Account successfully updated";
protected static String updateAccountView = "account/updateAccount";
protected static String accountRedirectView = "redirect:/account";
public String viewUpdateAccount(HttpServletRequest request, Model model, UpdateAccountForm form) {
Customer customer = CustomerState.getCustomer();
form.setEmailAddress(customer.getEmailAddress());
form.setFirstName(customer.getFirstName());
form.setLastName(customer.getLastName());
return getUpdateAccountView();
}
public String processUpdateAccount(HttpServletRequest request, Model model, UpdateAccountForm form, BindingResult result, RedirectAttributes redirectAttributes) throws ServiceException {
updateAccountValidator.validate(form, result);
if (result.hasErrors()) {
return getUpdateAccountView();
}
Customer customer = CustomerState.getCustomer();
customer.setEmailAddress(form.getEmailAddress());
customer.setFirstName(form.getFirstName());
customer.setLastName(form.getLastName());
customerService.saveCustomer(customer);
redirectAttributes.addFlashAttribute("successMessage", getAccountUpdatedMessage());
return getAccountRedirectView();
}
public String getUpdateAccountView() {
return updateAccountView;
}
public String getAccountRedirectView() {
return accountRedirectView;
}
public String getAccountUpdatedMessage() {
return accountUpdatedMessage;
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_account_BroadleafUpdateAccountController.java |
1,357 | clusterService.submitStateUpdateTask("shard-failed (" + shardRoutingEntry.shardRouting + "), reason [" + shardRoutingEntry.reason + "]", Priority.HIGH, new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
List<ShardRoutingEntry> shardRoutingEntries = new ArrayList<ShardRoutingEntry>();
failedShardQueue.drainTo(shardRoutingEntries);
// nothing to process (a previous event has processed it already)
if (shardRoutingEntries.isEmpty()) {
return currentState;
}
MetaData metaData = currentState.getMetaData();
List<ShardRouting> shardRoutingsToBeApplied = new ArrayList<ShardRouting>(shardRoutingEntries.size());
for (int i = 0; i < shardRoutingEntries.size(); i++) {
ShardRoutingEntry shardRoutingEntry = shardRoutingEntries.get(i);
ShardRouting shardRouting = shardRoutingEntry.shardRouting;
IndexMetaData indexMetaData = metaData.index(shardRouting.index());
// if there is no metadata or the current index is not of the right uuid, the index has been deleted while it was being allocated
// which is fine, we should just ignore this
if (indexMetaData == null) {
continue;
}
if (!indexMetaData.isSameUUID(shardRoutingEntry.indexUUID)) {
logger.debug("{} ignoring shard failed, different index uuid, current {}, got {}", shardRouting.shardId(), indexMetaData.getUUID(), shardRoutingEntry);
continue;
}
logger.debug("{} will apply shard failed {}", shardRouting.shardId(), shardRoutingEntry);
shardRoutingsToBeApplied.add(shardRouting);
}
RoutingAllocation.Result routingResult = allocationService.applyFailedShards(currentState, shardRoutingsToBeApplied);
if (!routingResult.changed()) {
return currentState;
}
return ClusterState.builder(currentState).routingResult(routingResult).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
}
}); | 0true
| src_main_java_org_elasticsearch_cluster_action_shard_ShardStateAction.java |
542 | public class DeleteMappingResponse extends AcknowledgedResponse {
DeleteMappingResponse() {
}
DeleteMappingResponse(boolean acknowledged) {
super(acknowledged);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
readAcknowledged(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
writeAcknowledged(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_mapping_delete_DeleteMappingResponse.java |
642 | public class CollectionAddOperation extends CollectionBackupAwareOperation {
protected Data value;
protected long itemId = -1;
public CollectionAddOperation() {
}
public CollectionAddOperation(String name, Data value) {
super(name);
this.value = value;
}
@Override
public boolean shouldBackup() {
return itemId != -1;
}
@Override
public Operation getBackupOperation() {
return new CollectionAddBackupOperation(name, itemId, value);
}
@Override
public int getId() {
return CollectionDataSerializerHook.COLLECTION_ADD;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
if (hasEnoughCapacity(1)) {
itemId = getOrCreateContainer().add(value);
}
response = itemId != -1;
}
@Override
public void afterRun() throws Exception {
if (itemId != -1) {
publishEvent(ItemEventType.ADDED, value);
}
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
value.writeData(out);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
value = new Data();
value.readData(in);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionAddOperation.java |
2,072 | public class MergeRemoveOperation extends BaseRemoveOperation {
private long removeTime;
private boolean merged = false;
public MergeRemoveOperation(String name, Data dataKey, long removeTime) {
super(name, dataKey);
this.removeTime = removeTime;
}
public MergeRemoveOperation() {
}
public void run() {
Record record = recordStore.getRecord(dataKey);
// todo what if statistics is disabled. currently it accepts the remove
// check if there is newer update or insert. If so then cancel the remove
if (record.getStatistics() != null
&& (record.getStatistics().getCreationTime() > removeTime
|| record.getLastUpdateTime() > removeTime)) {
return;
}
recordStore.deleteRecord(dataKey);
merged = true;
}
@Override
public Object getResponse() {
return merged;
}
public void afterRun() {
if (merged) {
invalidateNearCaches();
}
}
public boolean shouldBackup() {
return merged;
}
@Override
public void onWaitExpire() {
getResponseHandler().sendResponse(false);
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeLong(removeTime);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
removeTime = in.readLong();
}
@Override
public String toString() {
return "MergeRemoveOperation{" + name + "}";
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_operation_MergeRemoveOperation.java |
1,575 | public class AdornedTargetList implements PersistencePerspectiveItem {
private static final long serialVersionUID = 1L;
private String collectionFieldName;
private String linkedObjectPath;
private String targetObjectPath;
private String adornedTargetEntityClassname;
private String adornedTargetEntityPolymorphicType;
private String sortField;
private Boolean sortAscending;
private String linkedIdProperty;
private String targetIdProperty;
private Boolean inverse = Boolean.FALSE;
private String joinEntityClass;
private Boolean mutable = true;
public AdornedTargetList() {
//do nothing
}
public AdornedTargetList(String collectionFieldName, String linkedObjectPath, String linkedIdProperty, String targetObjectPath, String targetIdProperty, String adornedTargetEntityClassname) {
this(collectionFieldName, linkedObjectPath, linkedIdProperty, targetObjectPath, targetIdProperty, adornedTargetEntityClassname, null, null);
}
public AdornedTargetList(String collectionFieldName, String linkedObjectPath, String linkedIdProperty, String targetObjectPath, String targetIdProperty, String adornedTargetEntityClassname, String adornedTargetEntityPolymorphicType) {
this(collectionFieldName, linkedObjectPath, linkedIdProperty, targetObjectPath, targetIdProperty, adornedTargetEntityClassname, adornedTargetEntityPolymorphicType, null, null);
}
public AdornedTargetList(String collectionFieldName, String linkedObjectPath, String linkedIdProperty, String targetObjectPath, String targetIdProperty, String adornedTargetEntityClassname, String sortField, Boolean sortAscending) {
this(collectionFieldName, linkedObjectPath, linkedIdProperty, targetObjectPath, targetIdProperty, adornedTargetEntityClassname, null, sortField, sortAscending);
}
public AdornedTargetList(String collectionFieldName, String linkedObjectPath, String linkedIdProperty, String targetObjectPath, String targetIdProperty, String adornedTargetEntityClassname, String adornedTargetEntityPolymorphicType, String sortField, Boolean sortAscending) {
this.collectionFieldName = collectionFieldName;
this.linkedObjectPath = linkedObjectPath;
this.targetObjectPath = targetObjectPath;
this.adornedTargetEntityClassname = adornedTargetEntityClassname;
this.adornedTargetEntityPolymorphicType = adornedTargetEntityPolymorphicType;
this.sortField = sortField;
this.sortAscending = sortAscending;
this.linkedIdProperty = linkedIdProperty;
this.targetIdProperty = targetIdProperty;
}
public String getCollectionFieldName() {
return collectionFieldName;
}
public void setCollectionFieldName(String manyToField) {
this.collectionFieldName = manyToField;
}
public String getLinkedObjectPath() {
return linkedObjectPath;
}
public void setLinkedObjectPath(String linkedPropertyPath) {
this.linkedObjectPath = linkedPropertyPath;
}
public String getTargetObjectPath() {
return targetObjectPath;
}
public void setTargetObjectPath(String targetObjectPath) {
this.targetObjectPath = targetObjectPath;
}
public String getAdornedTargetEntityClassname() {
return adornedTargetEntityClassname;
}
public void setAdornedTargetEntityClassname(String adornedTargetEntityClassname) {
this.adornedTargetEntityClassname = adornedTargetEntityClassname;
}
public String getSortField() {
return sortField;
}
public void setSortField(String sortField) {
this.sortField = sortField;
}
public Boolean getSortAscending() {
return sortAscending;
}
public void setSortAscending(Boolean sortAscending) {
this.sortAscending = sortAscending;
}
public String getLinkedIdProperty() {
return linkedIdProperty;
}
public void setLinkedIdProperty(String linkedIdProperty) {
this.linkedIdProperty = linkedIdProperty;
}
public String getTargetIdProperty() {
return targetIdProperty;
}
public void setTargetIdProperty(String targetIdProperty) {
this.targetIdProperty = targetIdProperty;
}
public Boolean getInverse() {
return inverse;
}
public void setInverse(Boolean inverse) {
this.inverse = inverse;
}
public void accept(PersistencePerspectiveItemVisitor visitor) {
visitor.visit(this);
}
public String getAdornedTargetEntityPolymorphicType() {
return adornedTargetEntityPolymorphicType;
}
public void setAdornedTargetEntityPolymorphicType(String adornedTargetEntityPolymorphicType) {
this.adornedTargetEntityPolymorphicType = adornedTargetEntityPolymorphicType;
}
public String getJoinEntityClass() {
return joinEntityClass;
}
public void setJoinEntityClass(String joinEntityClass) {
this.joinEntityClass = joinEntityClass;
}
public Boolean getMutable() {
return mutable;
}
public void setMutable(Boolean mutable) {
this.mutable = mutable;
}
@Override
public PersistencePerspectiveItem clonePersistencePerspectiveItem() {
AdornedTargetList adornedTargetList = new AdornedTargetList();
adornedTargetList.collectionFieldName = collectionFieldName;
adornedTargetList.linkedObjectPath = linkedObjectPath;
adornedTargetList.targetObjectPath = targetObjectPath;
adornedTargetList.adornedTargetEntityClassname = adornedTargetEntityClassname;
adornedTargetList.adornedTargetEntityPolymorphicType = adornedTargetEntityPolymorphicType;
adornedTargetList.sortField = sortField;
adornedTargetList.sortAscending = sortAscending;
adornedTargetList.linkedIdProperty = linkedIdProperty;
adornedTargetList.targetIdProperty = targetIdProperty;
adornedTargetList.inverse = inverse;
adornedTargetList.joinEntityClass = joinEntityClass;
adornedTargetList.mutable = mutable;
return adornedTargetList;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof AdornedTargetList)) return false;
AdornedTargetList that = (AdornedTargetList) o;
if (adornedTargetEntityClassname != null ? !adornedTargetEntityClassname.equals(that.adornedTargetEntityClassname) : that.adornedTargetEntityClassname != null)
return false;
if (adornedTargetEntityPolymorphicType != null ? !adornedTargetEntityPolymorphicType.equals(that.adornedTargetEntityPolymorphicType) : that.adornedTargetEntityPolymorphicType != null)
return false;
if (collectionFieldName != null ? !collectionFieldName.equals(that.collectionFieldName) : that.collectionFieldName != null)
return false;
if (inverse != null ? !inverse.equals(that.inverse) : that.inverse != null) return false;
if (linkedIdProperty != null ? !linkedIdProperty.equals(that.linkedIdProperty) : that.linkedIdProperty != null)
return false;
if (linkedObjectPath != null ? !linkedObjectPath.equals(that.linkedObjectPath) : that.linkedObjectPath != null)
return false;
if (sortAscending != null ? !sortAscending.equals(that.sortAscending) : that.sortAscending != null)
return false;
if (sortField != null ? !sortField.equals(that.sortField) : that.sortField != null) return false;
if (targetIdProperty != null ? !targetIdProperty.equals(that.targetIdProperty) : that.targetIdProperty != null)
return false;
if (targetObjectPath != null ? !targetObjectPath.equals(that.targetObjectPath) : that.targetObjectPath != null)
return false;
if (joinEntityClass != null ? !joinEntityClass.equals(that.joinEntityClass) : that.joinEntityClass != null)
return false;
if (mutable != null ? !mutable.equals(that.mutable) : that.mutable != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = collectionFieldName != null ? collectionFieldName.hashCode() : 0;
result = 31 * result + (linkedObjectPath != null ? linkedObjectPath.hashCode() : 0);
result = 31 * result + (targetObjectPath != null ? targetObjectPath.hashCode() : 0);
result = 31 * result + (adornedTargetEntityClassname != null ? adornedTargetEntityClassname.hashCode() : 0);
result = 31 * result + (adornedTargetEntityPolymorphicType != null ? adornedTargetEntityPolymorphicType.hashCode() : 0);
result = 31 * result + (sortField != null ? sortField.hashCode() : 0);
result = 31 * result + (sortAscending != null ? sortAscending.hashCode() : 0);
result = 31 * result + (linkedIdProperty != null ? linkedIdProperty.hashCode() : 0);
result = 31 * result + (targetIdProperty != null ? targetIdProperty.hashCode() : 0);
result = 31 * result + (inverse != null ? inverse.hashCode() : 0);
result = 31 * result + (joinEntityClass != null ? joinEntityClass.hashCode() : 0);
result = 31 * result + (mutable != null ? mutable.hashCode() : 0);
return result;
}
} | 1no label
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_AdornedTargetList.java |
95 | static final class ReservationNode<K,V> extends Node<K,V> {
ReservationNode() {
super(RESERVED, null, null, null);
}
Node<K,V> find(int h, Object k) {
return null;
}
} | 0true
| src_main_java_jsr166e_ConcurrentHashMapV8.java |
3,317 | static class LongValues extends org.elasticsearch.index.fielddata.LongValues.WithOrdinals {
private final BigDoubleArrayList values;
LongValues(BigDoubleArrayList values, Ordinals.Docs ordinals) {
super(ordinals);
this.values = values;
}
@Override
public final long getValueByOrd(long ord) {
assert ord != Ordinals.MISSING_ORDINAL;
return (long) values.get(ord);
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_DoubleArrayAtomicFieldData.java |
1,366 | public enum TXSTATUS {
INVALID, BEGUN, COMMITTING, ROLLBACKING
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_tx_OTransaction.java |
248 | public static class ResourceHolder
{
private final TxEventSyncHookFactory syncHookFactory;
private final Transaction tx;
private final XaConnection connection;
private final NeoStoreTransaction resource;
private boolean enlisted;
ResourceHolder( TxEventSyncHookFactory syncHookFactory,
Transaction tx, XaConnection connection, NeoStoreTransaction resource )
{
this.syncHookFactory = syncHookFactory;
this.tx = tx;
this.connection = connection;
this.resource = resource;
}
public NeoStoreTransaction forReading()
{
return resource;
}
public NeoStoreTransaction forWriting()
{
if ( !enlisted )
{
enlist();
enlisted = true;
}
return resource;
}
private void enlist()
{
try
{
XAResource xaResource = connection.getXaResource();
if ( !tx.enlistResource( xaResource ) )
{
throw new ResourceAcquisitionFailedException( xaResource );
}
TransactionEventsSyncHook hook = syncHookFactory.create();
if ( hook != null )
{
tx.registerSynchronization( hook );
}
}
catch ( RollbackException re )
{
throw new ResourceAcquisitionFailedException( re );
}
catch ( SystemException se )
{
throw new ResourceAcquisitionFailedException( se );
}
}
public void delist()
{
if ( enlisted )
{
try
{
connection.delistResource( tx, XAResource.TMSUCCESS );
}
catch ( SystemException e )
{
throw new TransactionFailureException(
"Failed to delist resource '" + resource + "' from current transaction.", e );
}
}
}
void destroy()
{
connection.destroy();
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_persistence_PersistenceManager.java |