Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
547 |
public class TransactionUtils {
/**
* Intended for use in all @Transactional definitions. For instance:
* <pre>@Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER)</pre>
*/
public static final String DEFAULT_TRANSACTION_MANAGER = "blTransactionManager";
private static final Log LOG = LogFactory.getLog(TransactionUtils.class);
public static TransactionStatus createTransaction(String name, int propagationBehavior, PlatformTransactionManager transactionManager) {
return createTransaction(name, propagationBehavior, transactionManager, false);
}
public static TransactionStatus createTransaction(String name, int propagationBehavior, PlatformTransactionManager transactionManager, boolean isReadOnly) {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName(name);
def.setReadOnly(isReadOnly);
def.setPropagationBehavior(propagationBehavior);
return transactionManager.getTransaction(def);
}
public static TransactionStatus createTransaction(int propagationBehavior, PlatformTransactionManager transactionManager, boolean isReadOnly) {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setReadOnly(isReadOnly);
def.setPropagationBehavior(propagationBehavior);
return transactionManager.getTransaction(def);
}
public static void finalizeTransaction(TransactionStatus status, PlatformTransactionManager transactionManager, boolean isError) {
boolean isActive = false;
try {
if (!status.isRollbackOnly()) {
isActive = true;
}
} catch (Exception e) {
//do nothing
}
if (isError || !isActive) {
try {
transactionManager.rollback(status);
} catch (Exception e) {
LOG.error("Rolling back caused exception. Logging and continuing.", e);
}
} else {
transactionManager.commit(status);
}
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_util_TransactionUtils.java
|
291 |
public interface DataDrivenEnumerationValue extends Serializable {
public String getDisplay();
public void setDisplay(String display);
public Boolean getHidden();
public void setHidden(Boolean hidden);
public Long getId();
public void setId(Long id);
public String getKey();
public void setKey(String key);
public DataDrivenEnumeration getType();
public void setType(DataDrivenEnumeration type);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_enumeration_domain_DataDrivenEnumerationValue.java
|
6,132 |
public class MockRepository extends FsRepository {
private final AtomicLong failureCounter = new AtomicLong();
public void resetFailureCount() {
failureCounter.set(0);
}
public long getFailureCount() {
return failureCounter.get();
}
private final double randomControlIOExceptionRate;
private final double randomDataFileIOExceptionRate;
private final long waitAfterUnblock;
private final MockBlobStore mockBlobStore;
private final String randomPrefix;
private volatile boolean blockOnControlFiles;
private volatile boolean blockOnDataFiles;
private volatile boolean blocked = false;
@Inject
public MockRepository(RepositoryName name, RepositorySettings repositorySettings, IndexShardRepository indexShardRepository) throws IOException {
super(name, repositorySettings, indexShardRepository);
randomControlIOExceptionRate = repositorySettings.settings().getAsDouble("random_control_io_exception_rate", 0.0);
randomDataFileIOExceptionRate = repositorySettings.settings().getAsDouble("random_data_file_io_exception_rate", 0.0);
blockOnControlFiles = repositorySettings.settings().getAsBoolean("block_on_control", false);
blockOnDataFiles = repositorySettings.settings().getAsBoolean("block_on_data", false);
randomPrefix = repositorySettings.settings().get("random");
waitAfterUnblock = repositorySettings.settings().getAsLong("wait_after_unblock", 0L);
logger.info("starting mock repository with random prefix " + randomPrefix);
mockBlobStore = new MockBlobStore(super.blobStore());
}
private void addFailure() {
failureCounter.incrementAndGet();
}
@Override
protected void doStop() throws ElasticsearchException {
unblock();
super.doStop();
}
@Override
protected BlobStore blobStore() {
return mockBlobStore;
}
public boolean blocked() {
return mockBlobStore.blocked();
}
public void unblock() {
mockBlobStore.unblockExecution();
}
public void blockOnDataFiles(boolean blocked) {
blockOnDataFiles = blocked;
}
public void blockOnControlFiles(boolean blocked) {
blockOnControlFiles = blocked;
}
public class MockBlobStore extends BlobStoreWrapper {
ConcurrentMap<String, AtomicLong> accessCounts = new ConcurrentHashMap<String, AtomicLong>();
private long incrementAndGet(String path) {
AtomicLong value = accessCounts.get(path);
if (value == null) {
value = accessCounts.putIfAbsent(path, new AtomicLong(1));
}
if (value != null) {
return value.incrementAndGet();
}
return 1;
}
public MockBlobStore(BlobStore delegate) {
super(delegate);
}
@Override
public ImmutableBlobContainer immutableBlobContainer(BlobPath path) {
return new MockImmutableBlobContainer(super.immutableBlobContainer(path));
}
public synchronized void unblockExecution() {
if (blocked) {
blocked = false;
// Clean blocking flags, so we wouldn't try to block again
blockOnDataFiles = false;
blockOnControlFiles = false;
this.notifyAll();
}
}
public boolean blocked() {
return blocked;
}
private synchronized boolean blockExecution() {
boolean wasBlocked = false;
try {
while (blockOnDataFiles || blockOnControlFiles) {
blocked = true;
this.wait();
wasBlocked = true;
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
return wasBlocked;
}
private class MockImmutableBlobContainer extends ImmutableBlobContainerWrapper {
private MessageDigest digest;
private boolean shouldFail(String blobName, double probability) {
if (probability > 0.0) {
String path = path().add(blobName).buildAsString("/") + "/" + randomPrefix;
path += "/" + incrementAndGet(path);
logger.info("checking [{}] [{}]", path, Math.abs(hashCode(path)) < Integer.MAX_VALUE * probability);
return Math.abs(hashCode(path)) < Integer.MAX_VALUE * probability;
} else {
return false;
}
}
private int hashCode(String path) {
try {
digest = MessageDigest.getInstance("MD5");
byte[] bytes = digest.digest(path.getBytes("UTF-8"));
int i = 0;
return ((bytes[i++] & 0xFF) << 24) | ((bytes[i++] & 0xFF) << 16)
| ((bytes[i++] & 0xFF) << 8) | (bytes[i++] & 0xFF);
} catch (NoSuchAlgorithmException ex) {
throw new ElasticsearchException("cannot calculate hashcode", ex);
} catch (UnsupportedEncodingException ex) {
throw new ElasticsearchException("cannot calculate hashcode", ex);
}
}
private void maybeIOExceptionOrBlock(String blobName) throws IOException {
if (blobName.startsWith("__")) {
if (shouldFail(blobName, randomDataFileIOExceptionRate)) {
logger.info("throwing random IOException for file [{}] at path [{}]", blobName, path());
addFailure();
throw new IOException("Random IOException");
} else if (blockOnDataFiles) {
logger.info("blocking I/O operation for file [{}] at path [{}]", blobName, path());
if (blockExecution() && waitAfterUnblock > 0) {
try {
// Delay operation after unblocking
// So, we can start node shutdown while this operation is still running.
Thread.sleep(waitAfterUnblock);
} catch (InterruptedException ex) {
//
}
}
}
} else {
if (shouldFail(blobName, randomControlIOExceptionRate)) {
logger.info("throwing random IOException for file [{}] at path [{}]", blobName, path());
addFailure();
throw new IOException("Random IOException");
} else if (blockOnControlFiles) {
logger.info("blocking I/O operation for file [{}] at path [{}]", blobName, path());
if (blockExecution() && waitAfterUnblock > 0) {
try {
// Delay operation after unblocking
// So, we can start node shutdown while this operation is still running.
Thread.sleep(waitAfterUnblock);
} catch (InterruptedException ex) {
//
}
}
}
}
}
private void maybeIOExceptionOrBlock(String blobName, ImmutableBlobContainer.WriterListener listener) {
try {
maybeIOExceptionOrBlock(blobName);
} catch (IOException ex) {
listener.onFailure(ex);
}
}
private void maybeIOExceptionOrBlock(String blobName, ImmutableBlobContainer.ReadBlobListener listener) {
try {
maybeIOExceptionOrBlock(blobName);
} catch (IOException ex) {
listener.onFailure(ex);
}
}
public MockImmutableBlobContainer(ImmutableBlobContainer delegate) {
super(delegate);
}
@Override
public void writeBlob(String blobName, InputStream is, long sizeInBytes, WriterListener listener) {
maybeIOExceptionOrBlock(blobName, listener);
super.writeBlob(blobName, is, sizeInBytes, listener);
}
@Override
public void writeBlob(String blobName, InputStream is, long sizeInBytes) throws IOException {
maybeIOExceptionOrBlock(blobName);
super.writeBlob(blobName, is, sizeInBytes);
}
@Override
public boolean blobExists(String blobName) {
return super.blobExists(blobName);
}
@Override
public void readBlob(String blobName, ReadBlobListener listener) {
maybeIOExceptionOrBlock(blobName, listener);
super.readBlob(blobName, listener);
}
@Override
public byte[] readBlobFully(String blobName) throws IOException {
maybeIOExceptionOrBlock(blobName);
return super.readBlobFully(blobName);
}
@Override
public boolean deleteBlob(String blobName) throws IOException {
maybeIOExceptionOrBlock(blobName);
return super.deleteBlob(blobName);
}
@Override
public void deleteBlobsByPrefix(String blobNamePrefix) throws IOException {
maybeIOExceptionOrBlock(blobNamePrefix);
super.deleteBlobsByPrefix(blobNamePrefix);
}
@Override
public void deleteBlobsByFilter(BlobNameFilter filter) throws IOException {
maybeIOExceptionOrBlock("");
super.deleteBlobsByFilter(filter);
}
@Override
public ImmutableMap<String, BlobMetaData> listBlobs() throws IOException {
maybeIOExceptionOrBlock("");
return super.listBlobs();
}
@Override
public ImmutableMap<String, BlobMetaData> listBlobsByPrefix(String blobNamePrefix) throws IOException {
maybeIOExceptionOrBlock(blobNamePrefix);
return super.listBlobsByPrefix(blobNamePrefix);
}
}
}
}
| 1no label
|
src_test_java_org_elasticsearch_snapshots_mockstore_MockRepository.java
|
502 |
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientMapStandaloneTest {
private static final ClassLoader FILTERING_CLASS_LOADER;
static HazelcastInstance client;
static {
List<String> excludes = Arrays.asList(new String[]{"com.hazelcast.client.standalone.model"});
FILTERING_CLASS_LOADER = new FilteringClassLoader(excludes, "com.hazelcast");
}
@BeforeClass
public static void init()
throws Exception {
Thread thread = Thread.currentThread();
ClassLoader tccl = thread.getContextClassLoader();
thread.setContextClassLoader(FILTERING_CLASS_LOADER);
try {
Class<?> configClazz = FILTERING_CLASS_LOADER.loadClass("com.hazelcast.config.Config");
Object config = configClazz.newInstance();
Method setClassLoader = configClazz.getDeclaredMethod("setClassLoader", ClassLoader.class);
setClassLoader.invoke(config, FILTERING_CLASS_LOADER);
Class<?> hazelcastClazz = FILTERING_CLASS_LOADER.loadClass("com.hazelcast.core.Hazelcast");
Method newHazelcastInstance = hazelcastClazz.getDeclaredMethod("newHazelcastInstance", configClazz);
newHazelcastInstance.invoke(hazelcastClazz, config);
} finally {
thread.setContextClassLoader(tccl);
}
client = HazelcastClient.newHazelcastClient(null);
}
public IMap createMap() {
return client.getMap(randomString());
}
@AfterClass
public static void destroy()
throws Exception {
client.shutdown();
Class<?> hazelcastClazz = FILTERING_CLASS_LOADER.loadClass("com.hazelcast.core.Hazelcast");
Method shutdownAll = hazelcastClazz.getDeclaredMethod("shutdownAll");
shutdownAll.invoke(hazelcastClazz);
}
@Test
public void testPut()
throws Exception {
MyKey key = new MyKey();
MyElement element = new MyElement(randomString());
Thread thread = Thread.currentThread();
ClassLoader tccl = thread.getContextClassLoader();
thread.setContextClassLoader(FILTERING_CLASS_LOADER);
try {
IMap<MyKey, MyElement> map = createMap();
map.put(key, element);
} finally {
thread.setContextClassLoader(tccl);
}
}
@Test
public void testGet()
throws Exception {
IMap<MyKey, MyElement> map = createMap();
MyKey key = new MyKey();
MyElement element = new MyElement(randomString());
Thread thread = Thread.currentThread();
ClassLoader tccl = thread.getContextClassLoader();
thread.setContextClassLoader(FILTERING_CLASS_LOADER);
try {
map.put(key, element);
MyElement result = map.get(key);
assertEquals(element, result);
} finally {
thread.setContextClassLoader(tccl);
}
}
@Test
public void testRemove()
throws Exception {
IMap<MyKey, MyElement> map = createMap();
MyKey key = new MyKey();
MyElement element = new MyElement(randomString());
Thread thread = Thread.currentThread();
ClassLoader tccl = thread.getContextClassLoader();
thread.setContextClassLoader(FILTERING_CLASS_LOADER);
try {
map.put(key, element);
MyElement result = map.remove(key);
assertEquals(element, result);
} finally {
thread.setContextClassLoader(tccl);
}
}
@Test
public void testClear()
throws Exception {
IMap<MyKey, MyElement> map = createMap();
Thread thread = Thread.currentThread();
ClassLoader tccl = thread.getContextClassLoader();
thread.setContextClassLoader(FILTERING_CLASS_LOADER);
try {
MyKey key = new MyKey();
MyElement element = new MyElement(randomString());
map.put(key, element);
map.clear();
} finally {
thread.setContextClassLoader(tccl);
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_standalone_ClientMapStandaloneTest.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
|
1,482 |
public abstract class OSQLFunctionPathFinder<T extends Comparable<T>> extends OSQLFunctionMathAbstract {
protected OrientBaseGraph db;
protected Set<Vertex> settledNodes;
protected Set<Vertex> unSettledNodes;
protected Map<Vertex, Vertex> predecessors;
protected Map<Vertex, T> distance;
protected Vertex paramSourceVertex;
protected Vertex paramDestinationVertex;
protected Direction paramDirection = Direction.OUT;
public OSQLFunctionPathFinder(final String iName, final int iMinParams, final int iMaxParams) {
super(iName, iMinParams, iMaxParams);
}
protected abstract T getDistance(Vertex node, Vertex target);
protected abstract T getShortestDistance(Vertex destination);
protected abstract T getMinimumDistance();
protected abstract T sumDistances(T iDistance1, T iDistance2);
public Object execute(final Object[] iParameters, final OCommandContext iContext) {
settledNodes = new HashSet<Vertex>();
unSettledNodes = new HashSet<Vertex>();
distance = new HashMap<Vertex, T>();
predecessors = new HashMap<Vertex, Vertex>();
distance.put(paramSourceVertex, getMinimumDistance());
unSettledNodes.add(paramSourceVertex);
while (continueTraversing()) {
final Vertex node = getMinimum(unSettledNodes);
settledNodes.add(node);
unSettledNodes.remove(node);
findMinimalDistances(node);
}
return getPath();
}
/*
* This method returns the path from the source to the selected target and NULL if no path exists
*/
public LinkedList<Vertex> getPath() {
final LinkedList<Vertex> path = new LinkedList<Vertex>();
Vertex step = paramDestinationVertex;
// Check if a path exists
if (predecessors.get(step) == null)
return null;
path.add(step);
while (predecessors.get(step) != null) {
step = predecessors.get(step);
path.add(step);
}
// Put it into the correct order
Collections.reverse(path);
return path;
}
public boolean aggregateResults() {
return false;
}
@Override
public Object getResult() {
return getPath();
}
protected void findMinimalDistances(final Vertex node) {
final List<Vertex> adjacentNodes = getNeighbors(node);
for (Vertex target : adjacentNodes) {
final T d = sumDistances(getShortestDistance(node), getDistance(node, target));
if (getShortestDistance(target).compareTo(d) > 0) {
distance.put(target, d);
predecessors.put(target, node);
unSettledNodes.add(target);
}
}
}
protected List<Vertex> getNeighbors(final Vertex node) {
final List<Vertex> neighbors = new ArrayList<Vertex>();
if (node != null) {
for (Vertex v : node.getVertices(paramDirection))
if (v != null && !isSettled(v))
neighbors.add(v);
}
return neighbors;
}
protected Vertex getMinimum(final Set<Vertex> vertexes) {
Vertex minimum = null;
for (Vertex vertex : vertexes) {
if (minimum == null || getShortestDistance(vertex).compareTo(getShortestDistance(minimum)) < 0)
minimum = vertex;
}
return minimum;
}
protected boolean isSettled(final Vertex vertex) {
return settledNodes.contains(vertex.getId());
}
protected boolean continueTraversing() {
return unSettledNodes.size() > 0;
}
}
| 1no label
|
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_functions_OSQLFunctionPathFinder.java
|
42 |
Arrays.sort(properties, new Comparator<Property>() {
@Override
public int compare(Property o1, Property o2) {
/*
* First, compare properties based on order fields
*/
if (o1.getMetadata().getOrder() != null && o2.getMetadata().getOrder() != null) {
return o1.getMetadata().getOrder().compareTo(o2.getMetadata().getOrder());
} else if (o1.getMetadata().getOrder() != null && o2.getMetadata().getOrder() == null) {
/*
* Always favor fields that have an order identified
*/
return -1;
} else if (o1.getMetadata().getOrder() == null && o2.getMetadata().getOrder() != null) {
/*
* Always favor fields that have an order identified
*/
return 1;
} else if (o1.getMetadata().getFriendlyName() != null && o2.getMetadata().getFriendlyName() != null) {
return o1.getMetadata().getFriendlyName().compareTo(o2.getMetadata().getFriendlyName());
} else {
return o1.getName().compareTo(o2.getName());
}
}
});
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_admin_server_handler_DynamicFieldPersistenceHandlerHelper.java
|
422 |
static final class Fields {
static final XContentBuilderString SNAPSHOT = new XContentBuilderString("snapshot");
static final XContentBuilderString ACCEPTED = new XContentBuilderString("accepted");
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_restore_RestoreSnapshotResponse.java
|
269 |
public interface OCommandOutputListener {
public void onMessage(String iText);
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_command_OCommandOutputListener.java
|
263 |
public interface OCommandDistributedReplicateRequest {
public boolean isReplicated();
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_command_OCommandDistributedReplicateRequest.java
|
174 |
public interface EntryList extends List<Entry> {
/**
* Returns the same iterator as {@link #iterator()} with the only difference
* that it reuses {@link Entry} objects when calling {@link java.util.Iterator#next()}.
* Hence, this method should only be used if references to {@link Entry} objects are only
* kept and accesed until the next {@link java.util.Iterator#next()} call.
*
* @return
*/
public Iterator<Entry> reuseIterator();
/**
* Returns the total amount of bytes this entry consumes on the heap - including all object headers.
*
* @return
*/
public int getByteSize();
public static final EmptyList EMPTY_LIST = new EmptyList();
static class EmptyList extends AbstractList<Entry> implements EntryList {
@Override
public Entry get(int index) {
throw new ArrayIndexOutOfBoundsException();
}
@Override
public int size() {
return 0;
}
@Override
public Iterator<Entry> reuseIterator() {
return iterator();
}
@Override
public int getByteSize() {
return 0;
}
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_EntryList.java
|
92 |
class ConvertToBlockProposal extends CorrectionProposal {
ConvertToBlockProposal(String desc, int offset, TextChange change) {
super(desc, change, new Region(offset, 0));
}
static void addConvertToBlockProposal(IDocument doc,
Collection<ICompletionProposal> proposals, IFile file,
Node decNode) {
TextChange change = new TextFileChange("Convert to Block", file);
change.setEdit(new MultiTextEdit());
int offset;
int len;
String semi;
boolean isVoid;
String addedKeyword = null;
String desc = "Convert => to block";
if (decNode instanceof Tree.MethodDeclaration) {
Tree.MethodDeclaration md = (Tree.MethodDeclaration) decNode;
Method dm = md.getDeclarationModel();
if (dm==null || dm.isParameter()) return;
isVoid = dm.isDeclaredVoid();
List<Tree.ParameterList> pls = md.getParameterLists();
if (pls.isEmpty()) return;
offset = pls.get(pls.size()-1).getStopIndex()+1;
len = md.getSpecifierExpression().getExpression().getStartIndex() - offset;
semi = "";
}
else if (decNode instanceof Tree.AttributeDeclaration) {
Tree.AttributeDeclaration ad = (Tree.AttributeDeclaration) decNode;
Value dm = ad.getDeclarationModel();
if (dm==null || dm.isParameter()) return;
isVoid = false;
offset = ad.getIdentifier().getStopIndex()+1;
len = ad.getSpecifierOrInitializerExpression().getExpression().getStartIndex() - offset;
semi = "";
}
else if (decNode instanceof Tree.AttributeSetterDefinition) {
Tree.AttributeSetterDefinition asd = (Tree.AttributeSetterDefinition) decNode;
isVoid = true;
offset = asd.getIdentifier().getStopIndex()+1;
len = asd.getSpecifierExpression().getExpression().getStartIndex() - offset;
semi = "";
}
else if (decNode instanceof Tree.MethodArgument) {
Tree.MethodArgument ma = (Tree.MethodArgument) decNode;
Method dm = ma.getDeclarationModel();
if (dm==null) return;
isVoid = dm.isDeclaredVoid();
if (ma.getType().getToken()==null) {
addedKeyword = "function ";
}
List<Tree.ParameterList> pls = ma.getParameterLists();
if (pls.isEmpty()) return;
offset = pls.get(pls.size()-1).getStopIndex()+1;
len = ma.getSpecifierExpression().getExpression().getStartIndex() - offset;
semi = "";
}
else if (decNode instanceof Tree.AttributeArgument) {
Tree.AttributeArgument aa = (Tree.AttributeArgument) decNode;
isVoid = false;
if (aa.getType().getToken()==null) {
addedKeyword = "value ";
}
offset = aa.getIdentifier().getStopIndex()+1;
len = aa.getSpecifierExpression().getExpression().getStartIndex() - offset;
semi = "";
}
else if (decNode instanceof Tree.FunctionArgument) {
Tree.FunctionArgument fun = (Tree.FunctionArgument) decNode;
Method dm = fun.getDeclarationModel();
if (dm==null) return;
isVoid = dm.isDeclaredVoid();
List<Tree.ParameterList> pls = fun.getParameterLists();
if (pls.isEmpty()) return;
offset = pls.get(pls.size()-1).getStopIndex()+1;
len = fun.getExpression().getStartIndex() - offset;
semi = ";";
desc = "Convert anonymous function => to block";
}
else {
return;
}
if (addedKeyword!=null) {
change.addEdit(new InsertEdit(decNode.getStartIndex(), addedKeyword));
}
change.addEdit(new ReplaceEdit(offset, len, " {" + (isVoid?"":" return") + " "));
change.addEdit(new InsertEdit(decNode.getStopIndex()+1, semi + " }"));
proposals.add(new ConvertToBlockProposal(desc, offset + 3, change));
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToBlockProposal.java
|
644 |
public class DeleteIndexTemplateRequest extends MasterNodeOperationRequest<DeleteIndexTemplateRequest> {
private String name;
DeleteIndexTemplateRequest() {
}
/**
* Constructs a new delete index request for the specified name.
*/
public DeleteIndexTemplateRequest(String name) {
this.name = name;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (name == null) {
validationException = addValidationError("name is missing", validationException);
}
return validationException;
}
/**
* The index template name to delete.
*/
String name() {
return name;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
name = in.readString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(name);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_template_delete_DeleteIndexTemplateRequest.java
|
476 |
makeDbCall(databaseDocumentTxOne, new ODocumentHelper.ODbRelatedCall<java.lang.Object>() {
public Object call() {
convertSchemaDoc(doc1);
return null;
}
});
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java
|
289 |
public class OJSScriptFormatter implements OScriptFormatter {
public String getFunctionDefinition(final OFunction f) {
final StringBuilder fCode = new StringBuilder();
fCode.append("function ");
fCode.append(f.getName());
fCode.append('(');
int i = 0;
if (f.getParameters() != null)
for (String p : f.getParameters()) {
if (i++ > 0)
fCode.append(',');
fCode.append(p);
}
fCode.append(") {\n");
fCode.append(f.getCode());
fCode.append("\n}\n");
return fCode.toString();
}
@Override
public String getFunctionInvoke(final OFunction iFunction, final Object[] iArgs) {
final StringBuilder code = new StringBuilder();
code.append(iFunction.getName());
code.append('(');
if (iArgs != null) {
int i = 0;
for (Object a : iArgs) {
if (i++ > 0)
code.append(',');
code.append(a);
}
}
code.append(");");
return code.toString();
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_command_script_formatter_OJSScriptFormatter.java
|
582 |
executionService.scheduleWithFixedDelay(executorName, new Runnable() {
public void run() {
sendMemberListToOthers();
}
}, memberListPublishInterval, memberListPublishInterval, TimeUnit.SECONDS);
| 1no label
|
hazelcast_src_main_java_com_hazelcast_cluster_ClusterServiceImpl.java
|
3,933 |
public class RangeQueryParser implements QueryParser {
public static final String NAME = "range";
@Inject
public RangeQueryParser() {
}
@Override
public String[] names() {
return new String[]{NAME};
}
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new QueryParsingException(parseContext.index(), "[range] query malformed, no field to indicate field name");
}
String fieldName = parser.currentName();
token = parser.nextToken();
if (token != XContentParser.Token.START_OBJECT) {
throw new QueryParsingException(parseContext.index(), "[range] query malformed, after field missing start object");
}
Object from = null;
Object to = null;
boolean includeLower = true;
boolean includeUpper = true;
float boost = 1.0f;
String queryName = null;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
if ("from".equals(currentFieldName)) {
from = parser.objectBytes();
} else if ("to".equals(currentFieldName)) {
to = parser.objectBytes();
} else if ("include_lower".equals(currentFieldName) || "includeLower".equals(currentFieldName)) {
includeLower = parser.booleanValue();
} else if ("include_upper".equals(currentFieldName) || "includeUpper".equals(currentFieldName)) {
includeUpper = parser.booleanValue();
} else if ("boost".equals(currentFieldName)) {
boost = parser.floatValue();
} else if ("gt".equals(currentFieldName)) {
from = parser.objectBytes();
includeLower = false;
} else if ("gte".equals(currentFieldName) || "ge".equals(currentFieldName)) {
from = parser.objectBytes();
includeLower = true;
} else if ("lt".equals(currentFieldName)) {
to = parser.objectBytes();
includeUpper = false;
} else if ("lte".equals(currentFieldName) || "le".equals(currentFieldName)) {
to = parser.objectBytes();
includeUpper = true;
} else if ("_name".equals(currentFieldName)) {
queryName = parser.text();
} else {
throw new QueryParsingException(parseContext.index(), "[range] query does not support [" + currentFieldName + "]");
}
}
}
// move to the next end object, to close the field name
token = parser.nextToken();
if (token != XContentParser.Token.END_OBJECT) {
throw new QueryParsingException(parseContext.index(), "[range] query malformed, does not end with an object");
}
Query query = null;
MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName);
if (smartNameFieldMappers != null) {
if (smartNameFieldMappers.hasMapper()) {
//LUCENE 4 UPGRADE Mapper#rangeQuery should use bytesref as well?
query = smartNameFieldMappers.mapper().rangeQuery(from, to, includeLower, includeUpper, parseContext);
}
}
if (query == null) {
query = new TermRangeQuery(fieldName, BytesRefs.toBytesRef(from), BytesRefs.toBytesRef(to), includeLower, includeUpper);
}
query.setBoost(boost);
query = wrapSmartNameQuery(query, smartNameFieldMappers, parseContext);
if (queryName != null) {
parseContext.addNamedQuery(queryName, query);
}
return query;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_query_RangeQueryParser.java
|
103 |
static final class TreeBin<K,V> extends Node<K,V> {
TreeNode<K,V> root;
volatile TreeNode<K,V> first;
volatile Thread waiter;
volatile int lockState;
// values for lockState
static final int WRITER = 1; // set while holding write lock
static final int WAITER = 2; // set when waiting for write lock
static final int READER = 4; // increment value for setting read lock
/**
* Tie-breaking utility for ordering insertions when equal
* hashCodes and non-comparable. We don't require a total
* order, just a consistent insertion rule to maintain
* equivalence across rebalancings. Tie-breaking further than
* necessary simplifies testing a bit.
*/
static int tieBreakOrder(Object a, Object b) {
int d;
if (a == null || b == null ||
(d = a.getClass().getName().
compareTo(b.getClass().getName())) == 0)
d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
-1 : 1);
return d;
}
/**
* Creates bin with initial set of nodes headed by b.
*/
TreeBin(TreeNode<K,V> b) {
super(TREEBIN, null, null, null);
this.first = b;
TreeNode<K,V> r = null;
for (TreeNode<K,V> x = b, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
if (r == null) {
x.parent = null;
x.red = false;
r = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = r;;) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
r = balanceInsertion(r, x);
break;
}
}
}
}
this.root = r;
assert checkInvariants(root);
}
/**
* Acquires write lock for tree restructuring.
*/
private final void lockRoot() {
if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
contendedLock(); // offload to separate method
}
/**
* Releases write lock for tree restructuring.
*/
private final void unlockRoot() {
lockState = 0;
}
/**
* Possibly blocks awaiting root lock.
*/
private final void contendedLock() {
boolean waiting = false;
for (int s;;) {
if (((s = lockState) & ~WAITER) == 0) {
if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
if (waiting)
waiter = null;
return;
}
}
else if ((s & WAITER) == 0) {
if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
waiting = true;
waiter = Thread.currentThread();
}
}
else if (waiting)
LockSupport.park(this);
}
}
/**
* Returns matching node or null if none. Tries to search
* using tree comparisons from root, but continues linear
* search when lock not available.
*/
final Node<K,V> find(int h, Object k) {
if (k != null) {
for (Node<K,V> e = first; e != null; ) {
int s; K ek;
if (((s = lockState) & (WAITER|WRITER)) != 0) {
if (e.hash == h &&
((ek = e.key) == k || (ek != null && k.equals(ek))))
return e;
e = e.next;
}
else if (U.compareAndSwapInt(this, LOCKSTATE, s,
s + READER)) {
TreeNode<K,V> r, p;
try {
p = ((r = root) == null ? null :
r.findTreeNode(h, k, null));
} finally {
Thread w;
int ls;
do {} while (!U.compareAndSwapInt
(this, LOCKSTATE,
ls = lockState, ls - READER));
if (ls == (READER|WAITER) && (w = waiter) != null)
LockSupport.unpark(w);
}
return p;
}
}
}
return null;
}
/**
* Finds or adds a node.
* @return null if added
*/
final TreeNode<K,V> putTreeVal(int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if (p == null) {
first = root = new TreeNode<K,V>(h, k, v, null, null);
break;
}
else if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.findTreeNode(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.findTreeNode(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
TreeNode<K,V> x, f = first;
first = x = new TreeNode<K,V>(h, k, v, f, xp);
if (f != null)
f.prev = x;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
if (!xp.red)
x.red = true;
else {
lockRoot();
try {
root = balanceInsertion(root, x);
} finally {
unlockRoot();
}
}
break;
}
}
assert checkInvariants(root);
return null;
}
/**
* Removes the given node, that must be present before this
* call. This is messier than typical red-black deletion code
* because we cannot swap the contents of an interior node
* with a leaf successor that is pinned by "next" pointers
* that are accessible independently of lock. So instead we
* swap the tree linkages.
*
* @return true if now too small, so should be untreeified
*/
final boolean removeTreeNode(TreeNode<K,V> p) {
TreeNode<K,V> next = (TreeNode<K,V>)p.next;
TreeNode<K,V> pred = p.prev; // unlink traversal pointers
TreeNode<K,V> r, rl;
if (pred == null)
first = next;
else
pred.next = next;
if (next != null)
next.prev = pred;
if (first == null) {
root = null;
return true;
}
if ((r = root) == null || r.right == null || // too small
(rl = r.left) == null || rl.left == null)
return true;
lockRoot();
try {
TreeNode<K,V> replacement;
TreeNode<K,V> pl = p.left;
TreeNode<K,V> pr = p.right;
if (pl != null && pr != null) {
TreeNode<K,V> s = pr, sl;
while ((sl = s.left) != null) // find successor
s = sl;
boolean c = s.red; s.red = p.red; p.red = c; // swap colors
TreeNode<K,V> sr = s.right;
TreeNode<K,V> pp = p.parent;
if (s == pr) { // p was s's direct parent
p.parent = s;
s.right = p;
}
else {
TreeNode<K,V> sp = s.parent;
if ((p.parent = sp) != null) {
if (s == sp.left)
sp.left = p;
else
sp.right = p;
}
if ((s.right = pr) != null)
pr.parent = s;
}
p.left = null;
if ((p.right = sr) != null)
sr.parent = p;
if ((s.left = pl) != null)
pl.parent = s;
if ((s.parent = pp) == null)
r = s;
else if (p == pp.left)
pp.left = s;
else
pp.right = s;
if (sr != null)
replacement = sr;
else
replacement = p;
}
else if (pl != null)
replacement = pl;
else if (pr != null)
replacement = pr;
else
replacement = p;
if (replacement != p) {
TreeNode<K,V> pp = replacement.parent = p.parent;
if (pp == null)
r = replacement;
else if (p == pp.left)
pp.left = replacement;
else
pp.right = replacement;
p.left = p.right = p.parent = null;
}
root = (p.red) ? r : balanceDeletion(r, replacement);
if (p == replacement) { // detach pointers
TreeNode<K,V> pp;
if ((pp = p.parent) != null) {
if (p == pp.left)
pp.left = null;
else if (p == pp.right)
pp.right = null;
p.parent = null;
}
}
} finally {
unlockRoot();
}
assert checkInvariants(root);
return false;
}
/* ------------------------------------------------------------ */
// Red-black tree methods, all adapted from CLR
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> r, pp, rl;
if (p != null && (r = p.right) != null) {
if ((rl = p.right = r.left) != null)
rl.parent = p;
if ((pp = r.parent = p.parent) == null)
(root = r).red = false;
else if (pp.left == p)
pp.left = r;
else
pp.right = r;
r.left = p;
p.parent = r;
}
return root;
}
static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> l, pp, lr;
if (p != null && (l = p.left) != null) {
if ((lr = p.left = l.right) != null)
lr.parent = p;
if ((pp = l.parent = p.parent) == null)
(root = l).red = false;
else if (pp.right == p)
pp.right = l;
else
pp.left = l;
l.right = p;
p.parent = l;
}
return root;
}
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {
x.red = true;
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (!xp.red || (xpp = xp.parent) == null)
return root;
if (xp == (xppl = xpp.left)) {
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.right) {
root = rotateLeft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateRight(root, xpp);
}
}
}
}
else {
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.left) {
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}
static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
TreeNode<K,V> x) {
for (TreeNode<K,V> xp, xpl, xpr;;) {
if (x == null || x == root)
return root;
else if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (x.red) {
x.red = false;
return root;
}
else if ((xpl = xp.left) == x) {
if ((xpr = xp.right) != null && xpr.red) {
xpr.red = false;
xp.red = true;
root = rotateLeft(root, xp);
xpr = (xp = x.parent) == null ? null : xp.right;
}
if (xpr == null)
x = xp;
else {
TreeNode<K,V> sl = xpr.left, sr = xpr.right;
if ((sr == null || !sr.red) &&
(sl == null || !sl.red)) {
xpr.red = true;
x = xp;
}
else {
if (sr == null || !sr.red) {
if (sl != null)
sl.red = false;
xpr.red = true;
root = rotateRight(root, xpr);
xpr = (xp = x.parent) == null ?
null : xp.right;
}
if (xpr != null) {
xpr.red = (xp == null) ? false : xp.red;
if ((sr = xpr.right) != null)
sr.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateLeft(root, xp);
}
x = root;
}
}
}
else { // symmetric
if (xpl != null && xpl.red) {
xpl.red = false;
xp.red = true;
root = rotateRight(root, xp);
xpl = (xp = x.parent) == null ? null : xp.left;
}
if (xpl == null)
x = xp;
else {
TreeNode<K,V> sl = xpl.left, sr = xpl.right;
if ((sl == null || !sl.red) &&
(sr == null || !sr.red)) {
xpl.red = true;
x = xp;
}
else {
if (sl == null || !sl.red) {
if (sr != null)
sr.red = false;
xpl.red = true;
root = rotateLeft(root, xpl);
xpl = (xp = x.parent) == null ?
null : xp.left;
}
if (xpl != null) {
xpl.red = (xp == null) ? false : xp.red;
if ((sl = xpl.left) != null)
sl.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateRight(root, xp);
}
x = root;
}
}
}
}
}
/**
* Recursive invariant check
*/
static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
tb = t.prev, tn = (TreeNode<K,V>)t.next;
if (tb != null && tb.next != t)
return false;
if (tn != null && tn.prev != t)
return false;
if (tp != null && t != tp.left && t != tp.right)
return false;
if (tl != null && (tl.parent != t || tl.hash > t.hash))
return false;
if (tr != null && (tr.parent != t || tr.hash < t.hash))
return false;
if (t.red && tl != null && tl.red && tr != null && tr.red)
return false;
if (tl != null && !checkInvariants(tl))
return false;
if (tr != null && !checkInvariants(tr))
return false;
return true;
}
private static final sun.misc.Unsafe U;
private static final long LOCKSTATE;
static {
try {
U = getUnsafe();
Class<?> k = TreeBin.class;
LOCKSTATE = U.objectFieldOffset
(k.getDeclaredField("lockState"));
} catch (Exception e) {
throw new Error(e);
}
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
3,710 |
public final class SingleExecutorThreadFactory extends AbstractExecutorThreadFactory {
private final String threadName;
public SingleExecutorThreadFactory(ThreadGroup threadGroup, ClassLoader classLoader, String threadName) {
super(threadGroup, classLoader);
this.threadName = threadName;
}
@Override
protected Thread createThread(Runnable r) {
return new ManagedThread(r);
}
private class ManagedThread extends Thread {
public ManagedThread(Runnable target) {
super(threadGroup, target, threadName);
}
@Override
public void run() {
try {
super.run();
} catch (OutOfMemoryError e) {
OutOfMemoryErrorDispatcher.onOutOfMemory(e);
}
}
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_util_executor_SingleExecutorThreadFactory.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
|
1,608 |
updateTasksExecutor.execute(new PrioritizedRunnable(Priority.HIGH) {
@Override
public void run() {
NotifyTimeout notifyTimeout = new NotifyTimeout(listener, timeout);
notifyTimeout.future = threadPool.schedule(timeout, ThreadPool.Names.GENERIC, notifyTimeout);
onGoingTimeouts.add(notifyTimeout);
clusterStateListeners.add(listener);
listener.postAdded();
}
});
| 1no label
|
src_main_java_org_elasticsearch_cluster_service_InternalClusterService.java
|
2,638 |
public class ClassDefinitionImpl extends BinaryClassDefinition implements ClassDefinition {
private final List<FieldDefinition> fieldDefinitions = new ArrayList<FieldDefinition>();
private final Map<String, FieldDefinition> fieldDefinitionsMap = new HashMap<String,
FieldDefinition>();
private final Set<ClassDefinition> nestedClassDefinitions = new HashSet<ClassDefinition>();
public ClassDefinitionImpl() {
}
public ClassDefinitionImpl(int factoryId, int classId) {
this.factoryId = factoryId;
this.classId = classId;
}
public void addFieldDef(FieldDefinition fd) {
fieldDefinitions.add(fd);
fieldDefinitionsMap.put(fd.getName(), fd);
}
public void addClassDef(ClassDefinition cd) {
nestedClassDefinitions.add(cd);
}
public FieldDefinition get(String name) {
return fieldDefinitionsMap.get(name);
}
public FieldDefinition get(int fieldIndex) {
return fieldDefinitions.get(fieldIndex);
}
public Set<ClassDefinition> getNestedClassDefinitions() {
return nestedClassDefinitions;
}
public boolean hasField(String fieldName) {
return fieldDefinitionsMap.containsKey(fieldName);
}
public Set<String> getFieldNames() {
return new HashSet<String>(fieldDefinitionsMap.keySet());
}
public FieldType getFieldType(String fieldName) {
final FieldDefinition fd = get(fieldName);
if (fd != null) {
return fd.getType();
}
throw new IllegalArgumentException();
}
public int getFieldClassId(String fieldName) {
final FieldDefinition fd = get(fieldName);
if (fd != null) {
return fd.getClassId();
}
throw new IllegalArgumentException();
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(factoryId);
out.writeInt(classId);
out.writeInt(version);
out.writeInt(fieldDefinitions.size());
for (FieldDefinition fieldDefinition : fieldDefinitions) {
fieldDefinition.writeData(out);
}
out.writeInt(nestedClassDefinitions.size());
for (ClassDefinition classDefinition : nestedClassDefinitions) {
classDefinition.writeData(out);
}
}
public void readData(ObjectDataInput in) throws IOException {
factoryId = in.readInt();
classId = in.readInt();
version = in.readInt();
int size = in.readInt();
for (int i = 0; i < size; i++) {
FieldDefinitionImpl fieldDefinition = new FieldDefinitionImpl();
fieldDefinition.readData(in);
addFieldDef(fieldDefinition);
}
size = in.readInt();
for (int i = 0; i < size; i++) {
ClassDefinitionImpl classDefinition = new ClassDefinitionImpl();
classDefinition.readData(in);
addClassDef(classDefinition);
}
}
public int getFieldCount() {
return fieldDefinitions.size();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClassDefinitionImpl that = (ClassDefinitionImpl) o;
if (classId != that.classId) {
return false;
}
if (version != that.version) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = classId;
result = 31 * result + version;
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("ClassDefinition");
sb.append("{factoryId=").append(factoryId);
sb.append(", classId=").append(classId);
sb.append(", version=").append(version);
sb.append(", fieldDefinitions=").append(fieldDefinitions);
sb.append('}');
return sb.toString();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_serialization_ClassDefinitionImpl.java
|
3,822 |
public class ExistsFilterParser implements FilterParser {
public static final String NAME = "exists";
@Inject
public ExistsFilterParser() {
}
@Override
public String[] names() {
return new String[]{NAME};
}
@Override
public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
String fieldPattern = null;
String filterName = null;
XContentParser.Token token;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if ("field".equals(currentFieldName)) {
fieldPattern = parser.text();
} else if ("_name".equals(currentFieldName)) {
filterName = parser.text();
} else {
throw new QueryParsingException(parseContext.index(), "[exists] filter does not support [" + currentFieldName + "]");
}
}
}
if (fieldPattern == null) {
throw new QueryParsingException(parseContext.index(), "exists must be provided with a [field]");
}
MapperService.SmartNameObjectMapper smartNameObjectMapper = parseContext.smartObjectMapper(fieldPattern);
if (smartNameObjectMapper != null && smartNameObjectMapper.hasMapper()) {
// automatic make the object mapper pattern
fieldPattern = fieldPattern + ".*";
}
Set<String> fields = parseContext.simpleMatchToIndexNames(fieldPattern);
if (fields.isEmpty()) {
// no fields exists, so we should not match anything
return Queries.MATCH_NO_FILTER;
}
MapperService.SmartNameFieldMappers nonNullFieldMappers = null;
XBooleanFilter boolFilter = new XBooleanFilter();
for (String field : fields) {
MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(field);
if (smartNameFieldMappers != null) {
nonNullFieldMappers = smartNameFieldMappers;
}
Filter filter = null;
if (smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) {
filter = smartNameFieldMappers.mapper().rangeFilter(null, null, true, true, parseContext);
}
if (filter == null) {
filter = new TermRangeFilter(field, null, null, true, true);
}
boolFilter.add(filter, BooleanClause.Occur.SHOULD);
}
// we always cache this one, really does not change... (exists)
// its ok to cache under the fieldName cacheKey, since its per segment and the mapping applies to this data on this segment...
Filter filter = parseContext.cacheFilter(boolFilter, new CacheKeyFilter.Key("$exists$" + fieldPattern));
filter = wrapSmartNameFilter(filter, nonNullFieldMappers, parseContext);
if (filterName != null) {
parseContext.addNamedFilter(filterName, filter);
}
return filter;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_query_ExistsFilterParser.java
|
2,112 |
future.andThen(new ExecutionCallback<Data>() {
@Override
public void onResponse(Data response) {
if (nearCacheEnabled) {
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
if (!nodeEngine.getPartitionService().getPartitionOwner(partitionId)
.equals(nodeEngine.getClusterService().getThisAddress()) || mapConfig.getNearCacheConfig().isCacheLocalEntries()) {
mapService.putNearCache(name, key, response);
}
}
}
@Override
public void onFailure(Throwable t) {
}
});
| 1no label
|
hazelcast_src_main_java_com_hazelcast_map_proxy_MapProxySupport.java
|
862 |
searchService.sendExecuteFetch(node, querySearchRequest, new SearchServiceListener<QueryFetchSearchResult>() {
@Override
public void onResult(QueryFetchSearchResult result) {
result.shardTarget(dfsResult.shardTarget());
queryFetchResults.set(shardIndex, result);
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
@Override
public void onFailure(Throwable t) {
onSecondPhaseFailure(t, querySearchRequest, shardIndex, dfsResult, counter);
}
});
| 0true
|
src_main_java_org_elasticsearch_action_search_type_TransportSearchDfsQueryAndFetchAction.java
|
2,854 |
final class PromoteFromBackupOperation extends AbstractOperation
implements PartitionAwareOperation, MigrationCycleOperation {
@Override
public void run() throws Exception {
logPromotingPartition();
PartitionMigrationEvent event = createPartitionMigrationEvent();
sendToAllMigrationAwareServices(event);
}
private void sendToAllMigrationAwareServices(PartitionMigrationEvent event) {
NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine();
for (MigrationAwareService service : nodeEngine.getServices(MigrationAwareService.class)) {
try {
service.beforeMigration(event);
service.commitMigration(event);
} catch (Throwable e) {
logMigrationError(e);
}
}
}
private PartitionMigrationEvent createPartitionMigrationEvent() {
int partitionId = getPartitionId();
return new PartitionMigrationEvent(MigrationEndpoint.DESTINATION, partitionId);
}
private void logMigrationError(Throwable e) {
ILogger logger = getLogger();
logger.warning("While promoting partition " + getPartitionId(), e);
}
private void logPromotingPartition() {
ILogger logger = getLogger();
if (logger.isFinestEnabled()) {
logger.finest("Promoting partition " + getPartitionId());
}
}
@Override
public boolean returnsResponse() {
return false;
}
@Override
public boolean validatesTarget() {
return false;
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
throw new UnsupportedOperationException();
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
throw new UnsupportedOperationException();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_partition_impl_PromoteFromBackupOperation.java
|
968 |
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
try {
onOperation(idx, nodeOperation(newNodeRequest(clusterState.nodes().localNodeId(), request)));
} catch (Throwable e) {
onFailure(idx, clusterState.nodes().localNodeId(), e);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_support_nodes_TransportNodesOperationAction.java
|
1,144 |
static class SearchThread implements Runnable {
private final Client client;
private final int numValues;
private volatile boolean run = true;
SearchThread(Client client) {
this.client = client;
this.numValues = NUM_CHILDREN_PER_PARENT / NUM_CHILDREN_PER_PARENT;
}
@Override
public void run() {
while (run) {
try {
long totalQueryTime = 0;
for (int j = 0; j < QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName)
.setQuery(
filteredQuery(
matchAllQuery(),
hasChildFilter("child", termQuery("field2", "value" + random.nextInt(numValues)))
)
)
.execute().actionGet();
if (searchResponse.getFailedShards() > 0) {
System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> has_child filter with term filter Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
totalQueryTime = 0;
for (int j = 1; j <= QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName)
.setQuery(
filteredQuery(
matchAllQuery(),
hasChildFilter("child", matchAllQuery())
)
)
.execute().actionGet();
if (searchResponse.getFailedShards() > 0) {
System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> has_child filter with match_all child query, Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
NodesStatsResponse statsResponse = client.admin().cluster().prepareNodesStats()
.setJvm(true).execute().actionGet();
System.out.println("--> Committed heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapCommitted());
System.out.println("--> Used heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapUsed());
Thread.sleep(1000);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public void stop() {
run = false;
}
}
| 0true
|
src_test_java_org_elasticsearch_benchmark_search_child_ChildSearchAndIndexingBenchmark.java
|
132 |
public abstract class RecursiveAction extends ForkJoinTask<Void> {
private static final long serialVersionUID = 5232453952276485070L;
/**
* The main computation performed by this task.
*/
protected abstract void compute();
/**
* Always returns {@code null}.
*
* @return {@code null} always
*/
public final Void getRawResult() { return null; }
/**
* Requires null completion value.
*/
protected final void setRawResult(Void mustBeNull) { }
/**
* Implements execution conventions for RecursiveActions.
*/
protected final boolean exec() {
compute();
return true;
}
}
| 0true
|
src_main_java_jsr166e_RecursiveAction.java
|
2,007 |
@Service("blCustomerAddressService")
public class CustomerAddressServiceImpl implements CustomerAddressService {
@Resource(name="blCustomerAddressDao")
protected CustomerAddressDao customerAddressDao;
public CustomerAddress saveCustomerAddress(CustomerAddress customerAddress) {
// if parameter address is set as default, unset all other default addresses
List<CustomerAddress> activeCustomerAddresses = readActiveCustomerAddressesByCustomerId(customerAddress.getCustomer().getId());
if (activeCustomerAddresses != null && activeCustomerAddresses.isEmpty()) {
customerAddress.getAddress().setDefault(true);
} else {
if (customerAddress.getAddress().isDefault()) {
for (CustomerAddress activeCustomerAddress : activeCustomerAddresses) {
if (activeCustomerAddress.getId() != customerAddress.getId() && activeCustomerAddress.getAddress().isDefault()) {
activeCustomerAddress.getAddress().setDefault(false);
customerAddressDao.save(activeCustomerAddress);
}
}
}
}
return customerAddressDao.save(customerAddress);
}
public List<CustomerAddress> readActiveCustomerAddressesByCustomerId(Long customerId) {
return customerAddressDao.readActiveCustomerAddressesByCustomerId(customerId);
}
public CustomerAddress readCustomerAddressById(Long customerAddressId) {
return customerAddressDao.readCustomerAddressById(customerAddressId);
}
public void makeCustomerAddressDefault(Long customerAddressId, Long customerId) {
customerAddressDao.makeCustomerAddressDefault(customerAddressId, customerId);
}
public void deleteCustomerAddressById(Long customerAddressId){
customerAddressDao.deleteCustomerAddressById(customerAddressId);
}
public CustomerAddress findDefaultCustomerAddress(Long customerId) {
return customerAddressDao.findDefaultCustomerAddress(customerId);
}
public CustomerAddress create() {
return customerAddressDao.create();
}
}
| 1no label
|
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_service_CustomerAddressServiceImpl.java
|
1,377 |
public abstract class CartEndpoint extends BaseEndpoint {
@Resource(name="blOrderService")
protected OrderService orderService;
@Resource(name="blOfferService")
protected OfferService offerService;
@Resource(name="blCustomerService")
protected CustomerService customerService;
/**
* Search for {@code Order} by {@code Customer}
*
* @return the cart for the customer
*/
public OrderWrapper findCartForCustomer(HttpServletRequest request) {
Order cart = CartState.getCart();
if (cart != null) {
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(cart, request);
return wrapper;
}
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
/**
* Create a new {@code Order} for {@code Customer}
*
* @return the cart for the customer
*/
public OrderWrapper createNewCartForCustomer(HttpServletRequest request) {
Customer customer = CustomerState.getCustomer(request);
if (customer == null) {
customer = customerService.createCustomerFromId(null);
}
Order cart = orderService.findCartForCustomer(customer);
if (cart == null) {
cart = orderService.createNewCartForCustomer(customer);
CartState.setCart(cart);
}
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(cart, request);
return wrapper;
}
/**
* This method takes in a categoryId and productId as path parameters. In addition, query parameters can be supplied including:
*
* <li>skuId</li>
* <li>quantity</li>
* <li>priceOrder</li>
*
* You must provide a ProductId OR ProductId with product options. Product options can be posted as form or querystring parameters.
* You must pass in the ProductOption attributeName as the key and the
* ProductOptionValue attributeValue as the value. See {@link CatalogEndpoint}.
*
* @param request
* @param uriInfo
* @param categoryId
* @param productId
* @param quantity
* @param priceOrder
* @return OrderWrapper
*/
public OrderWrapper addProductToOrder(HttpServletRequest request,
UriInfo uriInfo,
Long productId,
Long categoryId,
int quantity,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart != null) {
try {
//We allow product options to be submitted via form post or via query params. We need to take
//the product options and build a map with them...
MultivaluedMap<String, String> multiValuedMap = uriInfo.getQueryParameters();
HashMap<String, String> productOptions = new HashMap<String, String>();
//Fill up a map of key values that will represent product options
Set<String> keySet = multiValuedMap.keySet();
for (String key : keySet) {
if (multiValuedMap.getFirst(key) != null) {
//Product options should be returned with "productOption." as a prefix. We'll look for those, and
//remove the prefix.
if (key.startsWith("productOption.")) {
productOptions.put(StringUtils.removeStart(key, "productOption."), multiValuedMap.getFirst(key));
}
}
}
OrderItemRequestDTO orderItemRequestDTO = new OrderItemRequestDTO();
orderItemRequestDTO.setProductId(productId);
orderItemRequestDTO.setCategoryId(categoryId);
orderItemRequestDTO.setQuantity(quantity);
//If we have product options set them on the DTO
if (productOptions.size() > 0) {
orderItemRequestDTO.setItemAttributes(productOptions);
}
Order order = orderService.addItem(cart.getId(), orderItemRequestDTO, priceOrder);
order = orderService.save(order, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(order, request);
return wrapper;
} catch (PricingException e) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the order.").build());
} catch (AddToCartException e) {
if (e.getCause() != null) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("" + e.getCause()).build());
}
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured adding the item to the cart." + e.getCause()).build());
}
}
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
public OrderWrapper removeItemFromOrder(HttpServletRequest request,
Long itemId,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart != null) {
try {
Order order = orderService.removeItem(cart.getId(), itemId, priceOrder);
order = orderService.save(order, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(order, request);
return wrapper;
} catch (PricingException e) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the cart.").build());
} catch (RemoveFromCartException e) {
if (e.getCause() instanceof ItemNotFoundException) {
throw new WebApplicationException(e, Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Could not find order item id " + itemId).build());
} else {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured removing the item to the cart.").build());
}
}
}
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
public OrderWrapper updateItemQuantity(HttpServletRequest request,
Long itemId,
Integer quantity,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart != null) {
try {
OrderItemRequestDTO orderItemRequestDTO = new OrderItemRequestDTO();
orderItemRequestDTO.setOrderItemId(itemId);
orderItemRequestDTO.setQuantity(quantity);
Order order = orderService.updateItemQuantity(cart.getId(), orderItemRequestDTO, priceOrder);
order = orderService.save(order, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(order, request);
return wrapper;
} catch (UpdateCartException e) {
if (e.getCause() instanceof ItemNotFoundException) {
throw new WebApplicationException(e, Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Could not find order item id " + itemId).build());
} else {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured removing the item to the cart.").build());
}
} catch (RemoveFromCartException e) {
if (e.getCause() instanceof ItemNotFoundException) {
throw new WebApplicationException(e, Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Could not find order item id " + itemId).build());
} else {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured removing the item to the cart.").build());
}
} catch (PricingException pe) {
throw new WebApplicationException(pe, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the cart.").build());
}
}
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
public OrderWrapper addOfferCode(HttpServletRequest request,
String promoCode,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
OfferCode offerCode = offerService.lookupOfferCodeByCode(promoCode);
if (offerCode == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Offer Code could not be found").build());
}
try {
cart = orderService.addOfferCode(cart, offerCode, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(cart, request);
return wrapper;
} catch (PricingException e) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the cart.").build());
} catch (OfferMaxUseExceededException e) {
throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST)
.type(MediaType.TEXT_PLAIN).entity("The offer (promo) code provided has exceeded its max usages: " + promoCode).build());
}
}
public OrderWrapper removeOfferCode(HttpServletRequest request,
String promoCode,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
OfferCode offerCode = offerService.lookupOfferCodeByCode(promoCode);
if (offerCode == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Offer code was invalid or could not be found.").build());
}
try {
cart = orderService.removeOfferCode(cart, offerCode, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(cart, request);
return wrapper;
} catch (PricingException e) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the cart.").build());
}
}
public OrderWrapper removeAllOfferCodes(HttpServletRequest request,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
try {
cart = orderService.removeAllOfferCodes(cart, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(cart, request);
return wrapper;
} catch (PricingException e) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the cart.").build());
}
}
}
| 1no label
|
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_endpoint_order_CartEndpoint.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
|
137 |
@Test
public class ByteSerializerTest {
private static final int FIELD_SIZE = 1;
private static final Byte OBJECT = 1;
private OByteSerializer byteSerializer;
byte[] stream = new byte[FIELD_SIZE];
@BeforeClass
public void beforeClass() {
byteSerializer = new OByteSerializer();
}
public void testFieldSize() {
Assert.assertEquals(byteSerializer.getObjectSize(null), FIELD_SIZE);
}
public void testSerialize() {
byteSerializer.serialize(OBJECT, stream, 0);
Assert.assertEquals(byteSerializer.deserialize(stream, 0), OBJECT);
}
public void testSerializeNative() {
byteSerializer.serializeNative(OBJECT, stream, 0);
Assert.assertEquals(byteSerializer.deserializeNative(stream, 0), OBJECT);
}
public void testNativeDirectMemoryCompatibility() {
byteSerializer.serializeNative(OBJECT, stream, 0);
ODirectMemoryPointer pointer = new ODirectMemoryPointer(stream);
try {
Assert.assertEquals(byteSerializer.deserializeFromDirectMemory(pointer, 0), OBJECT);
} finally {
pointer.free();
}
}
}
| 0true
|
commons_src_test_java_com_orientechnologies_common_serialization_types_ByteSerializerTest.java
|
1,003 |
public abstract class SingleCustomOperationRequestBuilder<Request extends SingleCustomOperationRequest<Request>, Response extends ActionResponse, RequestBuilder extends SingleCustomOperationRequestBuilder<Request, Response, RequestBuilder>>
extends ActionRequestBuilder<Request, Response, RequestBuilder> {
protected SingleCustomOperationRequestBuilder(InternalGenericClient client, Request request) {
super(client, request);
}
/**
* Controls if the operation will be executed on a separate thread when executed locally.
*/
@SuppressWarnings("unchecked")
public final RequestBuilder setOperationThreaded(boolean threadedOperation) {
request.operationThreaded(threadedOperation);
return (RequestBuilder) this;
}
/**
* if this operation hits a node with a local relevant shard, should it be preferred
* to be executed on, or just do plain round robin. Defaults to <tt>true</tt>
*/
@SuppressWarnings("unchecked")
public final RequestBuilder setPreferLocal(boolean preferLocal) {
request.preferLocal(preferLocal);
return (RequestBuilder) this;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_single_custom_SingleCustomOperationRequestBuilder.java
|
782 |
docMapper.parse(SourceToParse.source(getResponse.getSourceAsBytesRef()).type(request.type()).id(request.id()), new DocumentMapper.ParseListenerAdapter() {
@Override
public boolean beforeFieldAdded(FieldMapper fieldMapper, Field field, Object parseContext) {
if (!field.fieldType().indexed()) {
return false;
}
if (fieldMapper instanceof InternalMapper) {
return true;
}
String value = fieldMapper.value(convertField(field)).toString();
if (value == null) {
return false;
}
if (fields.isEmpty() || fields.contains(field.name())) {
addMoreLikeThis(request, boolBuilder, fieldMapper, field, !fields.isEmpty());
}
return false;
}
});
| 0true
|
src_main_java_org_elasticsearch_action_mlt_TransportMoreLikeThisAction.java
|
610 |
public class UpdateSettingsRequestBuilder extends AcknowledgedRequestBuilder<UpdateSettingsRequest, UpdateSettingsResponse, UpdateSettingsRequestBuilder> {
public UpdateSettingsRequestBuilder(IndicesAdminClient indicesClient, String... indices) {
super((InternalIndicesAdminClient) indicesClient, new UpdateSettingsRequest(indices));
}
/**
* Sets the indices the update settings will execute on
*/
public UpdateSettingsRequestBuilder setIndices(String... indices) {
request.indices(indices);
return this;
}
/**
* Specifies what type of requested indices to ignore and wildcard indices expressions.
*
* For example indices that don't exist.
*/
public UpdateSettingsRequestBuilder setIndicesOptions(IndicesOptions options) {
request.indicesOptions(options);
return this;
}
/**
* Sets the settings to be updated
*/
public UpdateSettingsRequestBuilder setSettings(Settings settings) {
request.settings(settings);
return this;
}
/**
* Sets the settings to be updated
*/
public UpdateSettingsRequestBuilder setSettings(Settings.Builder settings) {
request.settings(settings);
return this;
}
/**
* Sets the settings to be updated (either json/yaml/properties format)
*/
public UpdateSettingsRequestBuilder setSettings(String source) {
request.settings(source);
return this;
}
/**
* Sets the settings to be updated (either json/yaml/properties format)
*/
public UpdateSettingsRequestBuilder setSettings(Map<String, Object> source) {
request.settings(source);
return this;
}
@Override
protected void doExecute(ActionListener<UpdateSettingsResponse> listener) {
((IndicesAdminClient) client).updateSettings(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_settings_put_UpdateSettingsRequestBuilder.java
|
988 |
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response result) {
try {
channel.sendResponse(result);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send error response for action [" + transportAction + "] and request [" + request + "]", e1);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_support_replication_TransportIndicesReplicationOperationAction.java
|
536 |
class ShardGatewaySnapshotResponse extends BroadcastShardOperationResponse {
ShardGatewaySnapshotResponse() {
}
public ShardGatewaySnapshotResponse(String index, int shardId) {
super(index, shardId);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_gateway_snapshot_ShardGatewaySnapshotResponse.java
|
275 |
public interface OCommandRequestInternal extends OCommandRequest, OSerializableStream {
public Map<Object, Object> getParameters();
public OCommandResultListener getResultListener();
public void setResultListener(OCommandResultListener iListener);
public OProgressListener getProgressListener();
public OCommandRequestInternal setProgressListener(OProgressListener iProgressListener);
public void reset();
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_command_OCommandRequestInternal.java
|
527 |
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ClientTxnMultiMapTest {
private static final String multiMapBackedByList = "BackedByList*";
static HazelcastInstance client;
static HazelcastInstance server;
@BeforeClass
public static void init() {
Config config = new Config();
MultiMapConfig multiMapConfig = config.getMultiMapConfig(multiMapBackedByList);
multiMapConfig.setValueCollectionType(MultiMapConfig.ValueCollectionType.LIST);
server = Hazelcast.newHazelcastInstance(config);
client = HazelcastClient.newHazelcastClient();
}
@AfterClass
public static void destroy() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testRemove() throws Exception {
final String mapName = randomString();
final String key = "key";
final String val = "value";
MultiMap multiMap = client.getMultiMap(mapName);
multiMap.put(key, val);
TransactionContext tx = client.newTransactionContext();
tx.beginTransaction();
TransactionalMultiMap txnMultiMap = tx.getMultiMap(mapName);
txnMultiMap.remove(key, val);
tx.commitTransaction();
assertEquals(Collections.EMPTY_LIST, client.getMultiMap(mapName).get(key));
}
@Test
public void testRemoveAll() throws Exception {
final String mapName = randomString();
final String key = "key";
MultiMap multiMap = client.getMultiMap(mapName);
for (int i = 0; i < 10; i++) {
multiMap.put(key, i);
}
TransactionContext tx = client.newTransactionContext();
tx.beginTransaction();
TransactionalMultiMap txnMultiMap = tx.getMultiMap(mapName);
txnMultiMap.remove(key);
tx.commitTransaction();
assertEquals(Collections.EMPTY_LIST, multiMap.get(key));
}
@Test
public void testConcrruentTxnPut() throws Exception {
final String mapName = randomString();
final MultiMap multiMap = client.getMultiMap(mapName);
final int threads = 10;
final ExecutorService ex = Executors.newFixedThreadPool(threads);
final CountDownLatch latch = new CountDownLatch(threads);
final AtomicReference<Throwable> error = new AtomicReference<Throwable>(null);
for (int i = 0; i < threads; i++) {
final int key = i;
ex.execute(new Runnable() {
public void run() {
multiMap.put(key, "value");
final TransactionContext context = client.newTransactionContext();
try {
context.beginTransaction();
final TransactionalMultiMap txnMultiMap = context.getMultiMap(mapName);
txnMultiMap.put(key, "value");
txnMultiMap.put(key, "value1");
txnMultiMap.put(key, "value2");
assertEquals(3, txnMultiMap.get(key).size());
context.commitTransaction();
assertEquals(3, multiMap.get(key).size());
} catch (Exception e) {
error.compareAndSet(null, e);
} finally {
latch.countDown();
}
}
});
}
try {
latch.await(1, TimeUnit.MINUTES);
assertNull(error.get());
} finally {
ex.shutdownNow();
}
}
@Test
public void testPutAndRoleBack() throws Exception {
final String mapName = randomString();
final String key = "key";
final String value = "value";
final MultiMap multiMap = client.getMultiMap(mapName);
TransactionContext tx = client.newTransactionContext();
tx.beginTransaction();
TransactionalMultiMap mulitMapTxn = tx.getMultiMap(mapName);
mulitMapTxn.put(key, value);
mulitMapTxn.put(key, value);
tx.rollbackTransaction();
assertEquals(Collections.EMPTY_LIST, multiMap.get(key));
}
@Test
public void testSize() throws Exception {
final String mapName = randomString();
final String key = "key";
final String value = "value";
final MultiMap multiMap = client.getMultiMap(mapName);
multiMap.put(key, value);
TransactionContext tx = client.newTransactionContext();
tx.beginTransaction();
TransactionalMultiMap mulitMapTxn = tx.getMultiMap(mapName);
mulitMapTxn.put(key, "newValue");
mulitMapTxn.put("newKey", value);
assertEquals(3, mulitMapTxn.size());
tx.commitTransaction();
}
@Test
public void testCount() throws Exception {
final String mapName = randomString();
final String key = "key";
final String value = "value";
final MultiMap multiMap = client.getMultiMap(mapName);
multiMap.put(key, value);
TransactionContext tx = client.newTransactionContext();
tx.beginTransaction();
TransactionalMultiMap mulitMapTxn = tx.getMultiMap(mapName);
mulitMapTxn.put(key, "newValue");
assertEquals(2, mulitMapTxn.valueCount(key));
tx.commitTransaction();
}
@Test
public void testGet_whenBackedWithList() throws Exception {
final String mapName = multiMapBackedByList+randomString();
final String key = "key";
final String value = "value";
final MultiMap multiMap = server.getMultiMap(mapName);
multiMap.put(key, value);
TransactionContext tx = client.newTransactionContext();
tx.beginTransaction();
TransactionalMultiMap mulitMapTxn = tx.getMultiMap(mapName);
Collection c = mulitMapTxn.get(key);
assertFalse(c.isEmpty());
tx.commitTransaction();
}
@Test
public void testRemove_whenBackedWithList() throws Exception {
final String mapName = multiMapBackedByList+randomString();
final String key = "key";
final String value = "value";
final MultiMap multiMap = server.getMultiMap(mapName);
multiMap.put(key, value);
TransactionContext tx = client.newTransactionContext();
tx.beginTransaction();
TransactionalMultiMap mulitMapTxn = tx.getMultiMap(mapName);
Collection c = mulitMapTxn.remove(key);
assertFalse(c.isEmpty());
tx.commitTransaction();
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientTxnMultiMapTest.java
|
433 |
public class ClientSemaphoreProxy extends ClientProxy implements ISemaphore {
private final String name;
private volatile Data key;
public ClientSemaphoreProxy(String instanceName, String serviceName, String objectId) {
super(instanceName, serviceName, objectId);
this.name = objectId;
}
public boolean init(int permits) {
checkNegative(permits);
InitRequest request = new InitRequest(name, permits);
Boolean result = invoke(request);
return result;
}
public void acquire() throws InterruptedException {
acquire(1);
}
public void acquire(int permits) throws InterruptedException {
checkNegative(permits);
AcquireRequest request = new AcquireRequest(name, permits, -1);
invoke(request);
}
public int availablePermits() {
AvailableRequest request = new AvailableRequest(name);
Integer result = invoke(request);
return result;
}
public int drainPermits() {
DrainRequest request = new DrainRequest(name);
Integer result = invoke(request);
return result;
}
public void reducePermits(int reduction) {
checkNegative(reduction);
ReduceRequest request = new ReduceRequest(name, reduction);
invoke(request);
}
public void release() {
release(1);
}
public void release(int permits) {
checkNegative(permits);
ReleaseRequest request = new ReleaseRequest(name, permits);
invoke(request);
}
public boolean tryAcquire() {
return tryAcquire(1);
}
public boolean tryAcquire(int permits) {
checkNegative(permits);
try {
return tryAcquire(permits, 0, TimeUnit.SECONDS);
} catch (InterruptedException e) {
return false;
}
}
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException {
return tryAcquire(1, timeout, unit);
}
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException {
checkNegative(permits);
AcquireRequest request = new AcquireRequest(name, permits, unit.toMillis(timeout));
Boolean result = invoke(request);
return result;
}
protected void onDestroy() {
}
protected <T> T invoke(ClientRequest req) {
return super.invoke(req, getKey());
}
public Data getKey() {
if (key == null) {
key = getContext().getSerializationService().toData(name);
}
return key;
}
private void checkNegative(int permits) {
if (permits < 0) {
throw new IllegalArgumentException("Permits cannot be negative!");
}
}
@Override
public String toString() {
return "ISemaphore{" + "name='" + getName() + '\'' + '}';
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientSemaphoreProxy.java
|
632 |
public class NullBroadleafVariableExpression implements BroadleafVariableExpression {
@Override
public String getName() {
return null;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_web_expression_NullBroadleafVariableExpression.java
|
2,824 |
private static class LocalPartitionListener implements PartitionListener {
final Address thisAddress;
private InternalPartitionServiceImpl partitionService;
private LocalPartitionListener(InternalPartitionServiceImpl partitionService, Address thisAddress) {
this.thisAddress = thisAddress;
this.partitionService = partitionService;
}
@Override
public void replicaChanged(PartitionReplicaChangeEvent event) {
int replicaIndex = event.getReplicaIndex();
Address newAddress = event.getNewAddress();
if (replicaIndex > 0) {
// backup replica owner changed!
int partitionId = event.getPartitionId();
if (thisAddress.equals(event.getOldAddress())) {
InternalPartitionImpl partition = partitionService.partitions[partitionId];
if (!partition.isOwnerOrBackup(thisAddress)) {
partitionService.clearPartitionReplica(partitionId, replicaIndex);
}
} else if (thisAddress.equals(newAddress)) {
partitionService.clearPartitionReplica(partitionId, replicaIndex);
partitionService.forcePartitionReplicaSync(partitionId, replicaIndex);
}
}
Node node = partitionService.node;
if (replicaIndex == 0 && newAddress == null && node.isActive() && node.joined()) {
logOwnerOfPartitionIsRemoved(event);
}
if (partitionService.node.isMaster()) {
partitionService.stateVersion.incrementAndGet();
}
}
private void logOwnerOfPartitionIsRemoved(PartitionReplicaChangeEvent event) {
String warning = "Owner of partition is being removed! "
+ "Possible data loss for partition[" + event.getPartitionId() + "]. " + event;
partitionService.logger.warning(warning);
partitionService.systemLogService.logWarningPartition(warning);
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_partition_impl_InternalPartitionServiceImpl.java
|
1,314 |
transportNodesStatsAction.execute(nodesStatsRequest, new ActionListener<NodesStatsResponse>() {
@Override
public void onResponse(NodesStatsResponse nodeStatses) {
Map<String, DiskUsage> newUsages = new HashMap<String, DiskUsage>();
for (NodeStats nodeStats : nodeStatses.getNodes()) {
if (nodeStats.getFs() == null) {
logger.warn("Unable to retrieve node FS stats for {}", nodeStats.getNode().name());
} else {
long available = 0;
long total = 0;
for (FsStats.Info info : nodeStats.getFs()) {
available += info.getAvailable().bytes();
total += info.getTotal().bytes();
}
String nodeId = nodeStats.getNode().id();
if (logger.isTraceEnabled()) {
logger.trace("node: [{}], total disk: {}, available disk: {}", nodeId, total, available);
}
newUsages.put(nodeId, new DiskUsage(nodeId, total, available));
}
}
usages = ImmutableMap.copyOf(newUsages);
}
@Override
public void onFailure(Throwable e) {
logger.error("Failed to execute NodeStatsAction for ClusterInfoUpdateJob", e);
}
});
| 0true
|
src_main_java_org_elasticsearch_cluster_InternalClusterInfoService.java
|
338 |
public class MetadataOverrideNodeReplaceInsert extends NodeReplaceInsert {
protected boolean checkNode(List<Node> usedNodes, Node[] primaryNodes, Node node) {
//find matching nodes based on id
if (replaceNode(primaryNodes, node, "configurationKey", usedNodes)) {
return true;
}
//find matching nodes based on name
if (replaceNode(primaryNodes, node, "ceilingEntity", usedNodes)) {
return true;
}
//check if this same node already exists
if (exactNodeExists(primaryNodes, node, usedNodes)) {
return true;
}
return false;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_MetadataOverrideNodeReplaceInsert.java
|
482 |
public interface ResponseHandler {
void handle(ResponseStream stream) throws Exception;
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_spi_ResponseHandler.java
|
2,237 |
public abstract class ScoreFunction {
private final CombineFunction scoreCombiner;
public abstract void setNextReader(AtomicReaderContext context);
public abstract double score(int docId, float subQueryScore);
public abstract Explanation explainScore(int docId, Explanation subQueryExpl);
public CombineFunction getDefaultScoreCombiner() {
return scoreCombiner;
}
protected ScoreFunction(CombineFunction scoreCombiner) {
this.scoreCombiner = scoreCombiner;
}
}
| 1no label
|
src_main_java_org_elasticsearch_common_lucene_search_function_ScoreFunction.java
|
500 |
private static class SetRewriter implements FieldRewriter<Set<?>> {
@Override
public Set<?> rewriteValue(Set<?> setValue) {
boolean wasRewritten = false;
Set<Object> result = new HashSet<Object>();
for (Object item : setValue) {
FieldRewriter<Object> fieldRewriter = RewritersFactory.INSTANCE.findRewriter(null, null, item);
Object newItem = fieldRewriter.rewriteValue(item);
if (newItem != null) {
wasRewritten = true;
result.add(newItem);
} else
result.add(item);
}
if (wasRewritten)
return result;
return null;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseImport.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
|
491 |
database.getMetadata().getIndexManager().getIndex(indexName).rebuild(new OProgressListener() {
@Override
public void onBegin(Object iTask, long iTotal) {
listener.onMessage("\nCluster content was truncated and index " + indexName + " will be rebuilt");
}
@Override
public boolean onProgress(Object iTask, long iCounter, float iPercent) {
listener.onMessage(String.format("\nIndex %s is rebuilt on %f percent", indexName, iPercent));
return true;
}
@Override
public void onCompletition(Object iTask, boolean iSucceed) {
listener.onMessage("\nIndex " + indexName + " was successfully rebuilt.");
}
});
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseImport.java
|
4,663 |
private final PercolatorType queryCountPercolator = new PercolatorType() {
@Override
public byte id() {
return 0x02;
}
@Override
public ReduceResult reduce(List<PercolateShardResponse> shardResults) {
return countPercolator.reduce(shardResults);
}
@Override
public PercolateShardResponse doPercolate(PercolateShardRequest request, PercolateContext context) {
long count = 0;
Engine.Searcher percolatorSearcher = context.indexShard().acquireSearcher("percolate");
try {
Count countCollector = count(logger, context);
queryBasedPercolating(percolatorSearcher, context, countCollector);
count = countCollector.counter();
} catch (Throwable e) {
logger.warn("failed to execute", e);
} finally {
percolatorSearcher.release();
}
return new PercolateShardResponse(count, context, request.index(), request.shardId());
}
};
| 1no label
|
src_main_java_org_elasticsearch_percolator_PercolatorService.java
|
140 |
public static class Name {
public static final String Description = "StructuredContentImpl_Description";
public static final String Internal = "StructuredContentImpl_Internal";
public static final String Rules = "StructuredContentImpl_Rules";
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentImpl.java
|
3,123 |
Arrays.sort(segmentsArr, new Comparator<Segment>() {
@Override
public int compare(Segment o1, Segment o2) {
return (int) (o1.getGeneration() - o2.getGeneration());
}
});
| 1no label
|
src_main_java_org_elasticsearch_index_engine_internal_InternalEngine.java
|
131 |
public static class CriteriaStructuredContentXrefPK implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
@ManyToOne(targetEntity = StructuredContentImpl.class, optional=false)
@JoinColumn(name = "SC_ID")
protected StructuredContent structuredContent = new StructuredContentImpl();
@ManyToOne(targetEntity = StructuredContentItemCriteriaImpl.class, optional=false)
@JoinColumn(name = "SC_ITEM_CRITERIA_ID")
protected StructuredContentItemCriteria structuredContentItemCriteria = new StructuredContentItemCriteriaImpl();
public StructuredContent getStructuredContent() {
return structuredContent;
}
public void setStructuredContent(StructuredContent structuredContent) {
this.structuredContent = structuredContent;
}
public StructuredContentItemCriteria getStructuredContentItemCriteria() {
return structuredContentItemCriteria;
}
public void setStructuredContentItemCriteria(StructuredContentItemCriteria structuredContentItemCriteria) {
this.structuredContentItemCriteria = structuredContentItemCriteria;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((structuredContent == null) ? 0 : structuredContent.hashCode());
result = prime * result + ((structuredContentItemCriteria == null) ? 0 : structuredContentItemCriteria.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CriteriaStructuredContentXrefPK other = (CriteriaStructuredContentXrefPK) obj;
if (structuredContent == null) {
if (other.structuredContent != null)
return false;
} else if (!structuredContent.equals(other.structuredContent))
return false;
if (structuredContentItemCriteria == null) {
if (other.structuredContentItemCriteria != null)
return false;
} else if (!structuredContentItemCriteria.equals(other.structuredContentItemCriteria))
return false;
return true;
}
}
| 1no label
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_CriteriaStructuredContentXref.java
|
760 |
public class MultiGetShardResponse extends ActionResponse {
IntArrayList locations;
List<GetResponse> responses;
List<MultiGetResponse.Failure> failures;
MultiGetShardResponse() {
locations = new IntArrayList();
responses = new ArrayList<GetResponse>();
failures = new ArrayList<MultiGetResponse.Failure>();
}
public void add(int location, GetResponse response) {
locations.add(location);
responses.add(response);
failures.add(null);
}
public void add(int location, MultiGetResponse.Failure failure) {
locations.add(location);
responses.add(null);
failures.add(failure);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
int size = in.readVInt();
locations = new IntArrayList(size);
responses = new ArrayList<GetResponse>(size);
failures = new ArrayList<MultiGetResponse.Failure>(size);
for (int i = 0; i < size; i++) {
locations.add(in.readVInt());
if (in.readBoolean()) {
GetResponse response = new GetResponse();
response.readFrom(in);
responses.add(response);
} else {
responses.add(null);
}
if (in.readBoolean()) {
failures.add(MultiGetResponse.Failure.readFailure(in));
} else {
failures.add(null);
}
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(locations.size());
for (int i = 0; i < locations.size(); i++) {
out.writeVInt(locations.get(i));
if (responses.get(i) == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
responses.get(i).writeTo(out);
}
if (failures.get(i) == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
failures.get(i).writeTo(out);
}
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_get_MultiGetShardResponse.java
|
703 |
createIndexAction.execute(new CreateIndexRequest(index).cause("auto(bulk api)"), new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse result) {
if (counter.decrementAndGet() == 0) {
executeBulk(bulkRequest, startTime, listener);
}
}
@Override
public void onFailure(Throwable e) {
if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) {
// we have the index, do it
if (counter.decrementAndGet() == 0) {
executeBulk(bulkRequest, startTime, listener);
}
} else if (failed.compareAndSet(false, true)) {
listener.onFailure(e);
}
}
});
| 1no label
|
src_main_java_org_elasticsearch_action_bulk_TransportBulkAction.java
|
278 |
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(COUNT, map.size());
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_io_ClientExecutionPoolSizeLowTest.java
|
798 |
public abstract class AbstractAlterRequest extends PartitionClientRequest implements Portable, SecureRequest {
protected String name;
protected Data function;
public AbstractAlterRequest() {
}
public AbstractAlterRequest(String name, Data function) {
this.name = name;
this.function = function;
}
@Override
protected int getPartition() {
ClientEngine clientEngine = getClientEngine();
Data key = clientEngine.getSerializationService().toData(name);
return getClientEngine().getPartitionService().getPartitionId(key);
}
@Override
public String getServiceName() {
return AtomicLongService.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return AtomicLongPortableHook.F_ID;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
ObjectDataOutput out = writer.getRawDataOutput();
writeNullableData(out, function);
}
@Override
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
ObjectDataInput in = reader.getRawDataInput();
function = readNullableData(in);
}
protected IFunction<Long, Long> getFunction() {
SerializationService serializationService = getClientEngine().getSerializationService();
//noinspection unchecked
return (IFunction<Long, Long>) serializationService.toObject(function);
}
@Override
public Permission getRequiredPermission() {
return new AtomicLongPermission(name, ActionConstants.ACTION_MODIFY);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_AbstractAlterRequest.java
|
125 |
public interface OProfilerMBean extends OService {
public enum METRIC_TYPE {
CHRONO, COUNTER, STAT, SIZE, ENABLED, TEXT
}
public void updateCounter(String iStatName, String iDescription, long iPlus);
public void updateCounter(String iStatName, String iDescription, long iPlus, String iDictionary);
public long getCounter(String iStatName);
public String dump();
public String dumpCounters();
public OProfilerEntry getChrono(String string);
public long startChrono();
public long stopChrono(String iName, String iDescription, long iStartTime);
public long stopChrono(String iName, String iDescription, long iStartTime, String iDictionary);
public String dumpChronos();
public String[] getCountersAsString();
public String[] getChronosAsString();
public Date getLastReset();
public boolean isRecording();
public boolean startRecording();
public boolean stopRecording();
public void unregisterHookValue(String string);
public void configure(String string);
public void setAutoDump(int iNewValue);
public String metadataToJSON();
public Map<String, OPair<String, METRIC_TYPE>> getMetadata();
public void registerHookValue(final String iName, final String iDescription, final METRIC_TYPE iType,
final OProfilerHookValue iHookValue);
public void registerHookValue(final String iName, final String iDescription, final METRIC_TYPE iType,
final OProfilerHookValue iHookValue, final String iMetadataName);
public String getSystemMetric(String iMetricName);
public String getProcessMetric(String iName);
public String getDatabaseMetric(String databaseName, String iName);
public String toJSON(String command, final String iPar1);
public void resetRealtime(final String iText);
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_profiler_OProfilerMBean.java
|
278 |
public abstract class Action<Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>>
extends GenericAction<Request, Response> {
protected Action(String name) {
super(name);
}
public abstract RequestBuilder newRequestBuilder(Client client);
}
| 0true
|
src_main_java_org_elasticsearch_action_Action.java
|
657 |
constructors[COLLECTION_ADD_ALL_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new CollectionAddAllBackupOperation();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
|
960 |
public abstract class NodeOperationRequest extends TransportRequest {
private String nodeId;
protected NodeOperationRequest() {
}
protected NodeOperationRequest(NodesOperationRequest request, String nodeId) {
super(request);
this.nodeId = nodeId;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
nodeId = in.readString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(nodeId);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_nodes_NodeOperationRequest.java
|
707 |
public class TransportShardBulkAction extends TransportShardReplicationOperationAction<BulkShardRequest, BulkShardRequest, BulkShardResponse> {
private final MappingUpdatedAction mappingUpdatedAction;
private final UpdateHelper updateHelper;
private final boolean allowIdGeneration;
@Inject
public TransportShardBulkAction(Settings settings, TransportService transportService, ClusterService clusterService,
IndicesService indicesService, ThreadPool threadPool, ShardStateAction shardStateAction,
MappingUpdatedAction mappingUpdatedAction, UpdateHelper updateHelper) {
super(settings, transportService, clusterService, indicesService, threadPool, shardStateAction);
this.mappingUpdatedAction = mappingUpdatedAction;
this.updateHelper = updateHelper;
this.allowIdGeneration = settings.getAsBoolean("action.allow_id_generation", true);
}
@Override
protected String executor() {
return ThreadPool.Names.BULK;
}
@Override
protected boolean checkWriteConsistency() {
return true;
}
@Override
protected TransportRequestOptions transportOptions() {
return BulkAction.INSTANCE.transportOptions(settings);
}
@Override
protected BulkShardRequest newRequestInstance() {
return new BulkShardRequest();
}
@Override
protected BulkShardRequest newReplicaRequestInstance() {
return new BulkShardRequest();
}
@Override
protected BulkShardResponse newResponseInstance() {
return new BulkShardResponse();
}
@Override
protected String transportAction() {
return BulkAction.NAME + "/shard";
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, BulkShardRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.WRITE);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, BulkShardRequest request) {
return state.blocks().indexBlockedException(ClusterBlockLevel.WRITE, request.index());
}
@Override
protected ShardIterator shards(ClusterState clusterState, BulkShardRequest request) {
return clusterState.routingTable().index(request.index()).shard(request.shardId()).shardsIt();
}
@Override
protected PrimaryResponse<BulkShardResponse, BulkShardRequest> shardOperationOnPrimary(ClusterState clusterState, PrimaryOperationRequest shardRequest) {
final BulkShardRequest request = shardRequest.request;
IndexShard indexShard = indicesService.indexServiceSafe(shardRequest.request.index()).shardSafe(shardRequest.shardId);
Engine.IndexingOperation[] ops = null;
Set<Tuple<String, String>> mappingsToUpdate = null;
BulkItemResponse[] responses = new BulkItemResponse[request.items().length];
long[] preVersions = new long[request.items().length];
for (int requestIndex = 0; requestIndex < request.items().length; requestIndex++) {
BulkItemRequest item = request.items()[requestIndex];
if (item.request() instanceof IndexRequest) {
IndexRequest indexRequest = (IndexRequest) item.request();
try {
WriteResult result = shardIndexOperation(request, indexRequest, clusterState, indexShard, true);
// add the response
IndexResponse indexResponse = result.response();
responses[requestIndex] = new BulkItemResponse(item.id(), indexRequest.opType().lowercase(), indexResponse);
preVersions[requestIndex] = result.preVersion;
if (result.mappingToUpdate != null) {
if (mappingsToUpdate == null) {
mappingsToUpdate = Sets.newHashSet();
}
mappingsToUpdate.add(result.mappingToUpdate);
}
if (result.op != null) {
if (ops == null) {
ops = new Engine.IndexingOperation[request.items().length];
}
ops[requestIndex] = result.op;
}
} catch (Throwable e) {
// rethrow the failure if we are going to retry on primary and let parent failure to handle it
if (retryPrimaryException(e)) {
// restore updated versions...
for (int j = 0; j < requestIndex; j++) {
applyVersion(request.items()[j], preVersions[j]);
}
throw (ElasticsearchException) e;
}
if (e instanceof ElasticsearchException && ((ElasticsearchException) e).status() == RestStatus.CONFLICT) {
logger.trace("[{}][{}] failed to execute bulk item (index) {}", e, shardRequest.request.index(), shardRequest.shardId, indexRequest);
} else {
logger.debug("[{}][{}] failed to execute bulk item (index) {}", e, shardRequest.request.index(), shardRequest.shardId, indexRequest);
}
responses[requestIndex] = new BulkItemResponse(item.id(), indexRequest.opType().lowercase(),
new BulkItemResponse.Failure(indexRequest.index(), indexRequest.type(), indexRequest.id(), e));
// nullify the request so it won't execute on the replicas
request.items()[requestIndex] = null;
}
} else if (item.request() instanceof DeleteRequest) {
DeleteRequest deleteRequest = (DeleteRequest) item.request();
try {
// add the response
DeleteResponse deleteResponse = shardDeleteOperation(deleteRequest, indexShard).response();
responses[requestIndex] = new BulkItemResponse(item.id(), "delete", deleteResponse);
} catch (Throwable e) {
// rethrow the failure if we are going to retry on primary and let parent failure to handle it
if (retryPrimaryException(e)) {
// restore updated versions...
for (int j = 0; j < requestIndex; j++) {
applyVersion(request.items()[j], preVersions[j]);
}
throw (ElasticsearchException) e;
}
if (e instanceof ElasticsearchException && ((ElasticsearchException) e).status() == RestStatus.CONFLICT) {
logger.trace("[{}][{}] failed to execute bulk item (delete) {}", e, shardRequest.request.index(), shardRequest.shardId, deleteRequest);
} else {
logger.debug("[{}][{}] failed to execute bulk item (delete) {}", e, shardRequest.request.index(), shardRequest.shardId, deleteRequest);
}
responses[requestIndex] = new BulkItemResponse(item.id(), "delete",
new BulkItemResponse.Failure(deleteRequest.index(), deleteRequest.type(), deleteRequest.id(), e));
// nullify the request so it won't execute on the replicas
request.items()[requestIndex] = null;
}
} else if (item.request() instanceof UpdateRequest) {
UpdateRequest updateRequest = (UpdateRequest) item.request();
// We need to do the requested retries plus the initial attempt. We don't do < 1+retry_on_conflict because retry_on_conflict may be Integer.MAX_VALUE
for (int updateAttemptsCount = 0; updateAttemptsCount <= updateRequest.retryOnConflict(); updateAttemptsCount++) {
UpdateResult updateResult;
try {
updateResult = shardUpdateOperation(clusterState, request, updateRequest, indexShard);
} catch (Throwable t) {
updateResult = new UpdateResult(null, null, false, t, null);
}
if (updateResult.success()) {
switch (updateResult.result.operation()) {
case UPSERT:
case INDEX:
WriteResult result = updateResult.writeResult;
IndexRequest indexRequest = updateResult.request();
BytesReference indexSourceAsBytes = indexRequest.source();
// add the response
IndexResponse indexResponse = result.response();
UpdateResponse updateResponse = new UpdateResponse(indexResponse.getIndex(), indexResponse.getType(), indexResponse.getId(), indexResponse.getVersion(), indexResponse.isCreated());
if (updateRequest.fields() != null && updateRequest.fields().length > 0) {
Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(indexSourceAsBytes, true);
updateResponse.setGetResult(updateHelper.extractGetResult(updateRequest, indexResponse.getVersion(), sourceAndContent.v2(), sourceAndContent.v1(), indexSourceAsBytes));
}
responses[requestIndex] = new BulkItemResponse(item.id(), "update", updateResponse);
preVersions[requestIndex] = result.preVersion;
if (result.mappingToUpdate != null) {
if (mappingsToUpdate == null) {
mappingsToUpdate = Sets.newHashSet();
}
mappingsToUpdate.add(result.mappingToUpdate);
}
if (result.op != null) {
if (ops == null) {
ops = new Engine.IndexingOperation[request.items().length];
}
ops[requestIndex] = result.op;
}
// Replace the update request to the translated index request to execute on the replica.
request.items()[requestIndex] = new BulkItemRequest(request.items()[requestIndex].id(), indexRequest);
break;
case DELETE:
DeleteResponse response = updateResult.writeResult.response();
DeleteRequest deleteRequest = updateResult.request();
updateResponse = new UpdateResponse(response.getIndex(), response.getType(), response.getId(), response.getVersion(), false);
updateResponse.setGetResult(updateHelper.extractGetResult(updateRequest, response.getVersion(), updateResult.result.updatedSourceAsMap(), updateResult.result.updateSourceContentType(), null));
responses[requestIndex] = new BulkItemResponse(item.id(), "update", updateResponse);
// Replace the update request to the translated delete request to execute on the replica.
request.items()[requestIndex] = new BulkItemRequest(request.items()[requestIndex].id(), deleteRequest);
break;
case NONE:
responses[requestIndex] = new BulkItemResponse(item.id(), "update", updateResult.noopResult);
request.items()[requestIndex] = null; // No need to go to the replica
break;
}
// NOTE: Breaking out of the retry_on_conflict loop!
break;
} else if (updateResult.failure()) {
Throwable t = updateResult.error;
if (updateResult.retry) {
// updateAttemptCount is 0 based and marks current attempt, if it's equal to retryOnConflict we are going out of the iteration
if (updateAttemptsCount >= updateRequest.retryOnConflict()) {
// we can't try any more
responses[requestIndex] = new BulkItemResponse(item.id(), "update",
new BulkItemResponse.Failure(updateRequest.index(), updateRequest.type(), updateRequest.id(), t));
;
request.items()[requestIndex] = null; // do not send to replicas
}
} else {
// rethrow the failure if we are going to retry on primary and let parent failure to handle it
if (retryPrimaryException(t)) {
// restore updated versions...
for (int j = 0; j < requestIndex; j++) {
applyVersion(request.items()[j], preVersions[j]);
}
throw (ElasticsearchException) t;
}
if (updateResult.result == null) {
responses[requestIndex] = new BulkItemResponse(item.id(), "update", new BulkItemResponse.Failure(updateRequest.index(), updateRequest.type(), updateRequest.id(), t));
} else {
switch (updateResult.result.operation()) {
case UPSERT:
case INDEX:
IndexRequest indexRequest = updateResult.request();
if (t instanceof ElasticsearchException && ((ElasticsearchException) t).status() == RestStatus.CONFLICT) {
logger.trace("[{}][{}] failed to execute bulk item (index) {}", t, shardRequest.request.index(), shardRequest.shardId, indexRequest);
} else {
logger.debug("[{}][{}] failed to execute bulk item (index) {}", t, shardRequest.request.index(), shardRequest.shardId, indexRequest);
}
responses[requestIndex] = new BulkItemResponse(item.id(), indexRequest.opType().lowercase(),
new BulkItemResponse.Failure(indexRequest.index(), indexRequest.type(), indexRequest.id(), t));
break;
case DELETE:
DeleteRequest deleteRequest = updateResult.request();
if (t instanceof ElasticsearchException && ((ElasticsearchException) t).status() == RestStatus.CONFLICT) {
logger.trace("[{}][{}] failed to execute bulk item (delete) {}", t, shardRequest.request.index(), shardRequest.shardId, deleteRequest);
} else {
logger.debug("[{}][{}] failed to execute bulk item (delete) {}", t, shardRequest.request.index(), shardRequest.shardId, deleteRequest);
}
responses[requestIndex] = new BulkItemResponse(item.id(), "delete",
new BulkItemResponse.Failure(deleteRequest.index(), deleteRequest.type(), deleteRequest.id(), t));
break;
}
}
// nullify the request so it won't execute on the replicas
request.items()[requestIndex] = null;
// NOTE: Breaking out of the retry_on_conflict loop!
break;
}
}
}
}
assert responses[requestIndex] != null; // we must have set a response somewhere.
}
if (mappingsToUpdate != null) {
for (Tuple<String, String> mappingToUpdate : mappingsToUpdate) {
updateMappingOnMaster(mappingToUpdate.v1(), mappingToUpdate.v2());
}
}
if (request.refresh()) {
try {
indexShard.refresh(new Engine.Refresh("refresh_flag_bulk").force(false));
} catch (Throwable e) {
// ignore
}
}
BulkShardResponse response = new BulkShardResponse(new ShardId(request.index(), request.shardId()), responses);
return new PrimaryResponse<BulkShardResponse, BulkShardRequest>(shardRequest.request, response, ops);
}
static class WriteResult {
final Object response;
final long preVersion;
final Tuple<String, String> mappingToUpdate;
final Engine.IndexingOperation op;
WriteResult(Object response, long preVersion, Tuple<String, String> mappingToUpdate, Engine.IndexingOperation op) {
this.response = response;
this.preVersion = preVersion;
this.mappingToUpdate = mappingToUpdate;
this.op = op;
}
@SuppressWarnings("unchecked")
<T> T response() {
return (T) response;
}
}
private WriteResult shardIndexOperation(BulkShardRequest request, IndexRequest indexRequest, ClusterState clusterState,
IndexShard indexShard, boolean processed) {
// validate, if routing is required, that we got routing
MappingMetaData mappingMd = clusterState.metaData().index(request.index()).mappingOrDefault(indexRequest.type());
if (mappingMd != null && mappingMd.routing().required()) {
if (indexRequest.routing() == null) {
throw new RoutingMissingException(indexRequest.index(), indexRequest.type(), indexRequest.id());
}
}
if (!processed) {
indexRequest.process(clusterState.metaData(), indexRequest.index(), mappingMd, allowIdGeneration);
}
SourceToParse sourceToParse = SourceToParse.source(SourceToParse.Origin.PRIMARY, indexRequest.source()).type(indexRequest.type()).id(indexRequest.id())
.routing(indexRequest.routing()).parent(indexRequest.parent()).timestamp(indexRequest.timestamp()).ttl(indexRequest.ttl());
long version;
boolean created;
Engine.IndexingOperation op;
if (indexRequest.opType() == IndexRequest.OpType.INDEX) {
Engine.Index index = indexShard.prepareIndex(sourceToParse).version(indexRequest.version()).versionType(indexRequest.versionType()).origin(Engine.Operation.Origin.PRIMARY);
indexShard.index(index);
version = index.version();
op = index;
created = index.created();
} else {
Engine.Create create = indexShard.prepareCreate(sourceToParse).version(indexRequest.version()).versionType(indexRequest.versionType()).origin(Engine.Operation.Origin.PRIMARY);
indexShard.create(create);
version = create.version();
op = create;
created = true;
}
long preVersion = indexRequest.version();
// update the version on request so it will happen on the replicas
indexRequest.version(version);
// update mapping on master if needed, we won't update changes to the same type, since once its changed, it won't have mappers added
Tuple<String, String> mappingsToUpdate = null;
if (op.parsedDoc().mappingsModified()) {
mappingsToUpdate = Tuple.tuple(indexRequest.index(), indexRequest.type());
}
IndexResponse indexResponse = new IndexResponse(indexRequest.index(), indexRequest.type(), indexRequest.id(), version, created);
return new WriteResult(indexResponse, preVersion, mappingsToUpdate, op);
}
private WriteResult shardDeleteOperation(DeleteRequest deleteRequest, IndexShard indexShard) {
Engine.Delete delete = indexShard.prepareDelete(deleteRequest.type(), deleteRequest.id(), deleteRequest.version()).versionType(deleteRequest.versionType()).origin(Engine.Operation.Origin.PRIMARY);
indexShard.delete(delete);
// update the request with the version so it will go to the replicas
deleteRequest.version(delete.version());
DeleteResponse deleteResponse = new DeleteResponse(deleteRequest.index(), deleteRequest.type(), deleteRequest.id(), delete.version(), delete.found());
return new WriteResult(deleteResponse, deleteRequest.version(), null, null);
}
static class UpdateResult {
final UpdateHelper.Result result;
final ActionRequest actionRequest;
final boolean retry;
final Throwable error;
final WriteResult writeResult;
final UpdateResponse noopResult;
UpdateResult(UpdateHelper.Result result, ActionRequest actionRequest, boolean retry, Throwable error, WriteResult writeResult) {
this.result = result;
this.actionRequest = actionRequest;
this.retry = retry;
this.error = error;
this.writeResult = writeResult;
this.noopResult = null;
}
UpdateResult(UpdateHelper.Result result, ActionRequest actionRequest, WriteResult writeResult) {
this.result = result;
this.actionRequest = actionRequest;
this.writeResult = writeResult;
this.retry = false;
this.error = null;
this.noopResult = null;
}
public UpdateResult(UpdateHelper.Result result, UpdateResponse updateResponse) {
this.result = result;
this.noopResult = updateResponse;
this.actionRequest = null;
this.writeResult = null;
this.retry = false;
this.error = null;
}
boolean failure() {
return error != null;
}
boolean success() {
return noopResult != null || writeResult != null;
}
@SuppressWarnings("unchecked")
<T extends ActionRequest> T request() {
return (T) actionRequest;
}
}
private UpdateResult shardUpdateOperation(ClusterState clusterState, BulkShardRequest bulkShardRequest, UpdateRequest updateRequest, IndexShard indexShard) {
UpdateHelper.Result translate = updateHelper.prepare(updateRequest, indexShard);
switch (translate.operation()) {
case UPSERT:
case INDEX:
IndexRequest indexRequest = translate.action();
try {
WriteResult result = shardIndexOperation(bulkShardRequest, indexRequest, clusterState, indexShard, false);
return new UpdateResult(translate, indexRequest, result);
} catch (Throwable t) {
t = ExceptionsHelper.unwrapCause(t);
boolean retry = false;
if (t instanceof VersionConflictEngineException || (t instanceof DocumentAlreadyExistsException && translate.operation() == UpdateHelper.Operation.UPSERT)) {
retry = true;
}
return new UpdateResult(translate, indexRequest, retry, t, null);
}
case DELETE:
DeleteRequest deleteRequest = translate.action();
try {
WriteResult result = shardDeleteOperation(deleteRequest, indexShard);
return new UpdateResult(translate, deleteRequest, result);
} catch (Throwable t) {
t = ExceptionsHelper.unwrapCause(t);
boolean retry = false;
if (t instanceof VersionConflictEngineException) {
retry = true;
}
return new UpdateResult(translate, deleteRequest, retry, t, null);
}
case NONE:
UpdateResponse updateResponse = translate.action();
return new UpdateResult(translate, updateResponse);
default:
throw new ElasticsearchIllegalStateException("Illegal update operation " + translate.operation());
}
}
protected void shardOperationOnReplica(ReplicaOperationRequest shardRequest) {
IndexShard indexShard = indicesService.indexServiceSafe(shardRequest.request.index()).shardSafe(shardRequest.shardId);
final BulkShardRequest request = shardRequest.request;
for (int i = 0; i < request.items().length; i++) {
BulkItemRequest item = request.items()[i];
if (item == null) {
continue;
}
if (item.request() instanceof IndexRequest) {
IndexRequest indexRequest = (IndexRequest) item.request();
try {
SourceToParse sourceToParse = SourceToParse.source(SourceToParse.Origin.REPLICA, indexRequest.source()).type(indexRequest.type()).id(indexRequest.id())
.routing(indexRequest.routing()).parent(indexRequest.parent()).timestamp(indexRequest.timestamp()).ttl(indexRequest.ttl());
if (indexRequest.opType() == IndexRequest.OpType.INDEX) {
Engine.Index index = indexShard.prepareIndex(sourceToParse).version(indexRequest.version()).origin(Engine.Operation.Origin.REPLICA);
indexShard.index(index);
} else {
Engine.Create create = indexShard.prepareCreate(sourceToParse).version(indexRequest.version()).origin(Engine.Operation.Origin.REPLICA);
indexShard.create(create);
}
} catch (Throwable e) {
// ignore, we are on backup
}
} else if (item.request() instanceof DeleteRequest) {
DeleteRequest deleteRequest = (DeleteRequest) item.request();
try {
Engine.Delete delete = indexShard.prepareDelete(deleteRequest.type(), deleteRequest.id(), deleteRequest.version()).origin(Engine.Operation.Origin.REPLICA);
indexShard.delete(delete);
} catch (Throwable e) {
// ignore, we are on backup
}
}
}
if (request.refresh()) {
try {
indexShard.refresh(new Engine.Refresh("refresh_flag_bulk").force(false));
} catch (Throwable e) {
// ignore
}
}
}
private void updateMappingOnMaster(final String index, final String type) {
try {
MapperService mapperService = indicesService.indexServiceSafe(index).mapperService();
final DocumentMapper documentMapper = mapperService.documentMapper(type);
if (documentMapper == null) { // should not happen
return;
}
IndexMetaData metaData = clusterService.state().metaData().index(index);
if (metaData == null) {
return;
}
// we generate the order id before we get the mapping to send and refresh the source, so
// if 2 happen concurrently, we know that the later order will include the previous one
long orderId = mappingUpdatedAction.generateNextMappingUpdateOrder();
documentMapper.refreshSource();
DiscoveryNode node = clusterService.localNode();
final MappingUpdatedAction.MappingUpdatedRequest request = new MappingUpdatedAction.MappingUpdatedRequest(index, metaData.uuid(), type, documentMapper.mappingSource(), orderId, node != null ? node.id() : null);
mappingUpdatedAction.execute(request, new ActionListener<MappingUpdatedAction.MappingUpdatedResponse>() {
@Override
public void onResponse(MappingUpdatedAction.MappingUpdatedResponse mappingUpdatedResponse) {
// all is well
}
@Override
public void onFailure(Throwable e) {
logger.warn("failed to update master on updated mapping for {}", e, request);
}
});
} catch (Throwable e) {
logger.warn("failed to update master on updated mapping for index [{}], type [{}]", e, index, type);
}
}
private void applyVersion(BulkItemRequest item, long version) {
if (item.request() instanceof IndexRequest) {
((IndexRequest) item.request()).version(version);
} else if (item.request() instanceof DeleteRequest) {
((DeleteRequest) item.request()).version(version);
} else {
// log?
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_bulk_TransportShardBulkAction.java
|
385 |
public class ClusterUpdateSettingsAction extends ClusterAction<ClusterUpdateSettingsRequest, ClusterUpdateSettingsResponse, ClusterUpdateSettingsRequestBuilder> {
public static final ClusterUpdateSettingsAction INSTANCE = new ClusterUpdateSettingsAction();
public static final String NAME = "cluster/settings/update";
private ClusterUpdateSettingsAction() {
super(NAME);
}
@Override
public ClusterUpdateSettingsResponse newResponse() {
return new ClusterUpdateSettingsResponse();
}
@Override
public ClusterUpdateSettingsRequestBuilder newRequestBuilder(ClusterAdminClient client) {
return new ClusterUpdateSettingsRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_settings_ClusterUpdateSettingsAction.java
|
132 |
public class ReadPastEndException extends Exception
{
public ReadPastEndException()
{
super();
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_ReadPastEndException.java
|
252 |
public interface EmailReportingDao {
public Long createTracking(String emailAddress, String type, String extraValue) ;
public void recordOpen(Long emailId, String userAgent);
public void recordClick(Long emailId, String customerId, String destinationUri, String queryString);
public EmailTracking retrieveTracking(Long emailId);
public EmailTarget createTarget();
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_email_dao_EmailReportingDao.java
|
3,477 |
public class DocumentMapper implements ToXContent {
/**
* A result of a merge.
*/
public static class MergeResult {
private final String[] conflicts;
public MergeResult(String[] conflicts) {
this.conflicts = conflicts;
}
/**
* Does the merge have conflicts or not?
*/
public boolean hasConflicts() {
return conflicts.length > 0;
}
/**
* The merge conflicts.
*/
public String[] conflicts() {
return this.conflicts;
}
}
public static class MergeFlags {
public static MergeFlags mergeFlags() {
return new MergeFlags();
}
private boolean simulate = true;
public MergeFlags() {
}
/**
* A simulation run, don't perform actual modifications to the mapping.
*/
public boolean simulate() {
return simulate;
}
public MergeFlags simulate(boolean simulate) {
this.simulate = simulate;
return this;
}
}
/**
* A listener to be called during the parse process.
*/
public static interface ParseListener<ParseContext> {
public static final ParseListener EMPTY = new ParseListenerAdapter();
/**
* Called before a field is added to the document. Return <tt>true</tt> to include
* it in the document.
*/
boolean beforeFieldAdded(FieldMapper fieldMapper, Field fieldable, ParseContext parseContent);
}
public static class ParseListenerAdapter implements ParseListener {
@Override
public boolean beforeFieldAdded(FieldMapper fieldMapper, Field fieldable, Object parseContext) {
return true;
}
}
public static class Builder {
private Map<Class<? extends RootMapper>, RootMapper> rootMappers = new LinkedHashMap<Class<? extends RootMapper>, RootMapper>();
private NamedAnalyzer indexAnalyzer;
private NamedAnalyzer searchAnalyzer;
private NamedAnalyzer searchQuoteAnalyzer;
private final String index;
@Nullable
private final Settings indexSettings;
private final RootObjectMapper rootObjectMapper;
private ImmutableMap<String, Object> meta = ImmutableMap.of();
private final Mapper.BuilderContext builderContext;
public Builder(String index, @Nullable Settings indexSettings, RootObjectMapper.Builder builder) {
this.index = index;
this.indexSettings = indexSettings;
this.builderContext = new Mapper.BuilderContext(indexSettings, new ContentPath(1));
this.rootObjectMapper = builder.build(builderContext);
IdFieldMapper idFieldMapper = new IdFieldMapper();
if (indexSettings != null) {
String idIndexed = indexSettings.get("index.mapping._id.indexed");
if (idIndexed != null && Booleans.parseBoolean(idIndexed, false)) {
FieldType fieldType = new FieldType(IdFieldMapper.Defaults.FIELD_TYPE);
fieldType.setTokenized(false);
idFieldMapper = new IdFieldMapper(fieldType);
}
}
// UID first so it will be the first stored field to load (so will benefit from "fields: []" early termination
this.rootMappers.put(UidFieldMapper.class, new UidFieldMapper());
this.rootMappers.put(IdFieldMapper.class, idFieldMapper);
this.rootMappers.put(RoutingFieldMapper.class, new RoutingFieldMapper());
// add default mappers, order is important (for example analyzer should come before the rest to set context.analyzer)
this.rootMappers.put(SizeFieldMapper.class, new SizeFieldMapper());
this.rootMappers.put(IndexFieldMapper.class, new IndexFieldMapper());
this.rootMappers.put(SourceFieldMapper.class, new SourceFieldMapper());
this.rootMappers.put(TypeFieldMapper.class, new TypeFieldMapper());
this.rootMappers.put(AnalyzerMapper.class, new AnalyzerMapper());
this.rootMappers.put(AllFieldMapper.class, new AllFieldMapper());
this.rootMappers.put(BoostFieldMapper.class, new BoostFieldMapper());
this.rootMappers.put(TimestampFieldMapper.class, new TimestampFieldMapper());
this.rootMappers.put(TTLFieldMapper.class, new TTLFieldMapper());
this.rootMappers.put(VersionFieldMapper.class, new VersionFieldMapper());
this.rootMappers.put(ParentFieldMapper.class, new ParentFieldMapper());
}
public Builder meta(ImmutableMap<String, Object> meta) {
this.meta = meta;
return this;
}
public Builder put(RootMapper.Builder mapper) {
RootMapper rootMapper = (RootMapper) mapper.build(builderContext);
rootMappers.put(rootMapper.getClass(), rootMapper);
return this;
}
public Builder indexAnalyzer(NamedAnalyzer indexAnalyzer) {
this.indexAnalyzer = indexAnalyzer;
return this;
}
public boolean hasIndexAnalyzer() {
return indexAnalyzer != null;
}
public Builder searchAnalyzer(NamedAnalyzer searchAnalyzer) {
this.searchAnalyzer = searchAnalyzer;
if (this.searchQuoteAnalyzer == null) {
this.searchQuoteAnalyzer = searchAnalyzer;
}
return this;
}
public Builder searchQuoteAnalyzer(NamedAnalyzer searchQuoteAnalyzer) {
this.searchQuoteAnalyzer = searchQuoteAnalyzer;
return this;
}
public boolean hasSearchAnalyzer() {
return searchAnalyzer != null;
}
public boolean hasSearchQuoteAnalyzer() {
return searchQuoteAnalyzer != null;
}
public DocumentMapper build(DocumentMapperParser docMapperParser) {
Preconditions.checkNotNull(rootObjectMapper, "Mapper builder must have the root object mapper set");
return new DocumentMapper(index, indexSettings, docMapperParser, rootObjectMapper, meta,
indexAnalyzer, searchAnalyzer, searchQuoteAnalyzer,
rootMappers);
}
}
private CloseableThreadLocal<ParseContext> cache = new CloseableThreadLocal<ParseContext>() {
@Override
protected ParseContext initialValue() {
return new ParseContext(index, indexSettings, docMapperParser, DocumentMapper.this, new ContentPath(0));
}
};
public static final String ALLOW_TYPE_WRAPPER = "index.mapping.allow_type_wrapper";
private final String index;
private final Settings indexSettings;
private final String type;
private final StringAndBytesText typeText;
private final DocumentMapperParser docMapperParser;
private volatile ImmutableMap<String, Object> meta;
private volatile CompressedString mappingSource;
private final RootObjectMapper rootObjectMapper;
private final ImmutableMap<Class<? extends RootMapper>, RootMapper> rootMappers;
private final RootMapper[] rootMappersOrdered;
private final RootMapper[] rootMappersNotIncludedInObject;
private final NamedAnalyzer indexAnalyzer;
private final NamedAnalyzer searchAnalyzer;
private final NamedAnalyzer searchQuoteAnalyzer;
private final DocumentFieldMappers fieldMappers;
private volatile ImmutableMap<String, ObjectMapper> objectMappers = ImmutableMap.of();
private final List<FieldMapperListener> fieldMapperListeners = new CopyOnWriteArrayList<FieldMapperListener>();
private final List<ObjectMapperListener> objectMapperListeners = new CopyOnWriteArrayList<ObjectMapperListener>();
private boolean hasNestedObjects = false;
private final Filter typeFilter;
private final Object mappersMutex = new Object();
private boolean initMappersAdded = true;
public DocumentMapper(String index, @Nullable Settings indexSettings, DocumentMapperParser docMapperParser,
RootObjectMapper rootObjectMapper,
ImmutableMap<String, Object> meta,
NamedAnalyzer indexAnalyzer, NamedAnalyzer searchAnalyzer, NamedAnalyzer searchQuoteAnalyzer,
Map<Class<? extends RootMapper>, RootMapper> rootMappers) {
this.index = index;
this.indexSettings = indexSettings;
this.type = rootObjectMapper.name();
this.typeText = new StringAndBytesText(this.type);
this.docMapperParser = docMapperParser;
this.meta = meta;
this.rootObjectMapper = rootObjectMapper;
this.rootMappers = ImmutableMap.copyOf(rootMappers);
this.rootMappersOrdered = rootMappers.values().toArray(new RootMapper[rootMappers.values().size()]);
List<RootMapper> rootMappersNotIncludedInObjectLst = newArrayList();
for (RootMapper rootMapper : rootMappersOrdered) {
if (!rootMapper.includeInObject()) {
rootMappersNotIncludedInObjectLst.add(rootMapper);
}
}
this.rootMappersNotIncludedInObject = rootMappersNotIncludedInObjectLst.toArray(new RootMapper[rootMappersNotIncludedInObjectLst.size()]);
this.indexAnalyzer = indexAnalyzer;
this.searchAnalyzer = searchAnalyzer;
this.searchQuoteAnalyzer = searchQuoteAnalyzer != null ? searchQuoteAnalyzer : searchAnalyzer;
this.typeFilter = typeMapper().termFilter(type, null);
if (rootMapper(ParentFieldMapper.class).active()) {
// mark the routing field mapper as required
rootMapper(RoutingFieldMapper.class).markAsRequired();
}
FieldMapperListener.Aggregator fieldMappersAgg = new FieldMapperListener.Aggregator();
for (RootMapper rootMapper : rootMappersOrdered) {
if (rootMapper.includeInObject()) {
rootObjectMapper.putMapper(rootMapper);
} else {
if (rootMapper instanceof FieldMapper) {
fieldMappersAgg.mappers.add((FieldMapper) rootMapper);
}
}
}
// now traverse and get all the statically defined ones
rootObjectMapper.traverse(fieldMappersAgg);
this.fieldMappers = new DocumentFieldMappers(this);
this.fieldMappers.addNewMappers(fieldMappersAgg.mappers);
final Map<String, ObjectMapper> objectMappers = Maps.newHashMap();
rootObjectMapper.traverse(new ObjectMapperListener() {
@Override
public void objectMapper(ObjectMapper objectMapper) {
objectMappers.put(objectMapper.fullPath(), objectMapper);
}
});
this.objectMappers = ImmutableMap.copyOf(objectMappers);
for (ObjectMapper objectMapper : objectMappers.values()) {
if (objectMapper.nested().isNested()) {
hasNestedObjects = true;
}
}
refreshSource();
}
public String type() {
return this.type;
}
public Text typeText() {
return this.typeText;
}
public ImmutableMap<String, Object> meta() {
return this.meta;
}
public CompressedString mappingSource() {
return this.mappingSource;
}
public RootObjectMapper root() {
return this.rootObjectMapper;
}
public UidFieldMapper uidMapper() {
return rootMapper(UidFieldMapper.class);
}
@SuppressWarnings({"unchecked"})
public <T extends RootMapper> T rootMapper(Class<T> type) {
return (T) rootMappers.get(type);
}
public TypeFieldMapper typeMapper() {
return rootMapper(TypeFieldMapper.class);
}
public SourceFieldMapper sourceMapper() {
return rootMapper(SourceFieldMapper.class);
}
public AllFieldMapper allFieldMapper() {
return rootMapper(AllFieldMapper.class);
}
public IdFieldMapper idFieldMapper() {
return rootMapper(IdFieldMapper.class);
}
public RoutingFieldMapper routingFieldMapper() {
return rootMapper(RoutingFieldMapper.class);
}
public ParentFieldMapper parentFieldMapper() {
return rootMapper(ParentFieldMapper.class);
}
public TimestampFieldMapper timestampFieldMapper() {
return rootMapper(TimestampFieldMapper.class);
}
public TTLFieldMapper TTLFieldMapper() {
return rootMapper(TTLFieldMapper.class);
}
public IndexFieldMapper IndexFieldMapper() {
return rootMapper(IndexFieldMapper.class);
}
public SizeFieldMapper SizeFieldMapper() {
return rootMapper(SizeFieldMapper.class);
}
public BoostFieldMapper boostFieldMapper() {
return rootMapper(BoostFieldMapper.class);
}
public Analyzer indexAnalyzer() {
return this.indexAnalyzer;
}
public Analyzer searchAnalyzer() {
return this.searchAnalyzer;
}
public Analyzer searchQuotedAnalyzer() {
return this.searchQuoteAnalyzer;
}
public Filter typeFilter() {
return this.typeFilter;
}
public boolean hasNestedObjects() {
return hasNestedObjects;
}
public DocumentFieldMappers mappers() {
return this.fieldMappers;
}
public ImmutableMap<String, ObjectMapper> objectMappers() {
return this.objectMappers;
}
public ParsedDocument parse(BytesReference source) throws MapperParsingException {
return parse(SourceToParse.source(source));
}
public ParsedDocument parse(String type, String id, BytesReference source) throws MapperParsingException {
return parse(SourceToParse.source(source).type(type).id(id));
}
public ParsedDocument parse(SourceToParse source) throws MapperParsingException {
return parse(source, null);
}
public ParsedDocument parse(SourceToParse source, @Nullable ParseListener listener) throws MapperParsingException {
ParseContext context = cache.get();
if (source.type() != null && !source.type().equals(this.type)) {
throw new MapperParsingException("Type mismatch, provide type [" + source.type() + "] but mapper is of type [" + this.type + "]");
}
source.type(this.type);
XContentParser parser = source.parser();
try {
if (parser == null) {
parser = XContentHelper.createParser(source.source());
}
context.reset(parser, new ParseContext.Document(), source, listener);
// on a newly created instance of document mapper, we always consider it as new mappers that have been added
if (initMappersAdded) {
context.setMappingsModified();
initMappersAdded = false;
}
// will result in START_OBJECT
int countDownTokens = 0;
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.START_OBJECT) {
throw new MapperParsingException("Malformed content, must start with an object");
}
boolean emptyDoc = false;
token = parser.nextToken();
if (token == XContentParser.Token.END_OBJECT) {
// empty doc, we can handle it...
emptyDoc = true;
} else if (token != XContentParser.Token.FIELD_NAME) {
throw new MapperParsingException("Malformed content, after first object, either the type field or the actual properties should exist");
}
// first field is the same as the type, this might be because the
// type is provided, and the object exists within it or because
// there is a valid field that by chance is named as the type.
// Because of this, by default wrapping a document in a type is
// disabled, but can be enabled by setting
// index.mapping.allow_type_wrapper to true
if (type.equals(parser.currentName()) && indexSettings.getAsBoolean(ALLOW_TYPE_WRAPPER, false)) {
parser.nextToken();
countDownTokens++;
}
for (RootMapper rootMapper : rootMappersOrdered) {
rootMapper.preParse(context);
}
if (!emptyDoc) {
rootObjectMapper.parse(context);
}
for (int i = 0; i < countDownTokens; i++) {
parser.nextToken();
}
for (RootMapper rootMapper : rootMappersOrdered) {
rootMapper.postParse(context);
}
for (RootMapper rootMapper : rootMappersOrdered) {
rootMapper.validate(context);
}
} catch (Throwable e) {
// if its already a mapper parsing exception, no need to wrap it...
if (e instanceof MapperParsingException) {
throw (MapperParsingException) e;
}
// Throw a more meaningful message if the document is empty.
if (source.source() != null && source.source().length() == 0) {
throw new MapperParsingException("failed to parse, document is empty");
}
throw new MapperParsingException("failed to parse", e);
} finally {
// only close the parser when its not provided externally
if (source.parser() == null && parser != null) {
parser.close();
}
}
// reverse the order of docs for nested docs support, parent should be last
if (context.docs().size() > 1) {
Collections.reverse(context.docs());
}
// apply doc boost
if (context.docBoost() != 1.0f) {
Set<String> encounteredFields = Sets.newHashSet();
for (ParseContext.Document doc : context.docs()) {
encounteredFields.clear();
for (IndexableField field : doc) {
if (field.fieldType().indexed() && !field.fieldType().omitNorms()) {
if (!encounteredFields.contains(field.name())) {
((Field) field).setBoost(context.docBoost() * field.boost());
encounteredFields.add(field.name());
}
}
}
}
}
ParsedDocument doc = new ParsedDocument(context.uid(), context.version(), context.id(), context.type(), source.routing(), source.timestamp(), source.ttl(), context.docs(), context.analyzer(),
context.source(), context.mappingsModified()).parent(source.parent());
// reset the context to free up memory
context.reset(null, null, null, null);
return doc;
}
public void addFieldMappers(Iterable<FieldMapper> fieldMappers) {
synchronized (mappersMutex) {
this.fieldMappers.addNewMappers(fieldMappers);
}
for (FieldMapperListener listener : fieldMapperListeners) {
listener.fieldMappers(fieldMappers);
}
}
public void addFieldMapperListener(FieldMapperListener fieldMapperListener, boolean includeExisting) {
fieldMapperListeners.add(fieldMapperListener);
if (includeExisting) {
traverse(fieldMapperListener);
}
}
public void traverse(FieldMapperListener listener) {
for (RootMapper rootMapper : rootMappersOrdered) {
if (!rootMapper.includeInObject() && rootMapper instanceof FieldMapper) {
listener.fieldMapper((FieldMapper) rootMapper);
}
}
rootObjectMapper.traverse(listener);
}
public void addObjectMappers(Collection<ObjectMapper> objectMappers) {
addObjectMappers(objectMappers.toArray(new ObjectMapper[objectMappers.size()]));
}
private void addObjectMappers(ObjectMapper... objectMappers) {
synchronized (mappersMutex) {
MapBuilder<String, ObjectMapper> builder = MapBuilder.newMapBuilder(this.objectMappers);
for (ObjectMapper objectMapper : objectMappers) {
builder.put(objectMapper.fullPath(), objectMapper);
if (objectMapper.nested().isNested()) {
hasNestedObjects = true;
}
}
this.objectMappers = builder.immutableMap();
}
for (ObjectMapperListener objectMapperListener : objectMapperListeners) {
objectMapperListener.objectMappers(objectMappers);
}
}
public void addObjectMapperListener(ObjectMapperListener objectMapperListener, boolean includeExisting) {
objectMapperListeners.add(objectMapperListener);
if (includeExisting) {
traverse(objectMapperListener);
}
}
public void traverse(ObjectMapperListener listener) {
rootObjectMapper.traverse(listener);
}
public synchronized MergeResult merge(DocumentMapper mergeWith, MergeFlags mergeFlags) {
MergeContext mergeContext = new MergeContext(this, mergeFlags);
assert rootMappers.size() == mergeWith.rootMappers.size();
rootObjectMapper.merge(mergeWith.rootObjectMapper, mergeContext);
for (Map.Entry<Class<? extends RootMapper>, RootMapper> entry : rootMappers.entrySet()) {
// root mappers included in root object will get merge in the rootObjectMapper
if (entry.getValue().includeInObject()) {
continue;
}
RootMapper mergeWithRootMapper = mergeWith.rootMappers.get(entry.getKey());
if (mergeWithRootMapper != null) {
entry.getValue().merge(mergeWithRootMapper, mergeContext);
}
}
if (!mergeFlags.simulate()) {
// let the merge with attributes to override the attributes
meta = mergeWith.meta();
// update the source of the merged one
refreshSource();
}
return new MergeResult(mergeContext.buildConflicts());
}
public CompressedString refreshSource() throws ElasticsearchGenerationException {
try {
BytesStreamOutput bStream = new BytesStreamOutput();
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON, CompressorFactory.defaultCompressor().streamOutput(bStream));
builder.startObject();
toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
builder.close();
return mappingSource = new CompressedString(bStream.bytes());
} catch (Exception e) {
throw new ElasticsearchGenerationException("failed to serialize source for type [" + type + "]", e);
}
}
public void close() {
cache.close();
rootObjectMapper.close();
for (RootMapper rootMapper : rootMappersOrdered) {
rootMapper.close();
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
rootObjectMapper.toXContent(builder, params, new ToXContent() {
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (indexAnalyzer != null && searchAnalyzer != null && indexAnalyzer.name().equals(searchAnalyzer.name()) && !indexAnalyzer.name().startsWith("_")) {
if (!indexAnalyzer.name().equals("default")) {
// same analyzers, output it once
builder.field("analyzer", indexAnalyzer.name());
}
} else {
if (indexAnalyzer != null && !indexAnalyzer.name().startsWith("_")) {
if (!indexAnalyzer.name().equals("default")) {
builder.field("index_analyzer", indexAnalyzer.name());
}
}
if (searchAnalyzer != null && !searchAnalyzer.name().startsWith("_")) {
if (!searchAnalyzer.name().equals("default")) {
builder.field("search_analyzer", searchAnalyzer.name());
}
}
}
if (meta != null && !meta.isEmpty()) {
builder.field("_meta", meta());
}
return builder;
}
// no need to pass here id and boost, since they are added to the root object mapper
// in the constructor
}, rootMappersNotIncludedInObject);
return builder;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_mapper_DocumentMapper.java
|
298 |
public class OTraverseMultiValueBreadthFirstProcess extends OTraverseAbstractProcess<Iterator<Object>> {
protected Object value;
protected int index = -1;
protected List<Object> sub = new ArrayList<Object>();
protected boolean shallow = true;
public OTraverseMultiValueBreadthFirstProcess(final OTraverse iCommand, final Iterator<Object> iTarget) {
super(iCommand, iTarget);
command.getContext().incrementDepth();
}
public OIdentifiable process() {
if (shallow) {
// RETURNS THE SHALLOW LEVEL FIRST
while (target.hasNext()) {
value = target.next();
index++;
if (value instanceof OIdentifiable) {
final ORecord<?> rec = ((OIdentifiable) value).getRecord();
if (rec instanceof ODocument) {
if (command.getPredicate() != null) {
final Object conditionResult = command.getPredicate().evaluate(rec, null, command.getContext());
if (conditionResult != Boolean.TRUE)
continue;
}
sub.add(rec);
return rec;
}
}
}
target = sub.iterator();
index = -1;
shallow = false;
}
// SHALLOW DONE, GO IN DEEP
while (target.hasNext()) {
value = target.next();
index++;
final OTraverseRecordProcess subProcess = new OTraverseRecordProcess(command, (ODocument) value, true);
final OIdentifiable subValue = subProcess.process();
if (subValue != null)
return subValue;
}
sub = null;
return drop();
}
@Override
public OIdentifiable drop() {
command.getContext().decrementDepth();
return super.drop();
}
@Override
public String getStatus() {
return toString();
}
@Override
public String toString() {
return "[" + index + "]";
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_command_traverse_OTraverseMultiValueBreadthFirstProcess.java
|
673 |
clusterService.submitStateUpdateTask("delete_warmer [" + Arrays.toString(request.names()) + "]", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return true;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
listener.onResponse(new DeleteWarmerResponse(true));
}
@Override
public void onAckTimeout() {
listener.onResponse(new DeleteWarmerResponse(false));
}
@Override
public TimeValue ackTimeout() {
return request.timeout();
}
@Override
public TimeValue timeout() {
return request.masterNodeTimeout();
}
@Override
public void onFailure(String source, Throwable t) {
logger.debug("failed to delete warmer [{}] on indices [{}]", t, Arrays.toString(request.names()), request.indices());
listener.onFailure(t);
}
@Override
public ClusterState execute(ClusterState currentState) {
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
boolean globalFoundAtLeastOne = false;
for (String index : request.indices()) {
IndexMetaData indexMetaData = currentState.metaData().index(index);
if (indexMetaData == null) {
throw new IndexMissingException(new Index(index));
}
IndexWarmersMetaData warmers = indexMetaData.custom(IndexWarmersMetaData.TYPE);
if (warmers != null) {
List<IndexWarmersMetaData.Entry> entries = Lists.newArrayList();
for (IndexWarmersMetaData.Entry entry : warmers.entries()) {
boolean keepWarmer = true;
for (String warmer : request.names()) {
if (Regex.simpleMatch(warmer, entry.name()) || warmer.equals("_all")) {
globalFoundAtLeastOne = true;
keepWarmer = false;
// don't add it...
break;
}
}
if (keepWarmer) {
entries.add(entry);
}
}
// a change, update it...
if (entries.size() != warmers.entries().size()) {
warmers = new IndexWarmersMetaData(entries.toArray(new IndexWarmersMetaData.Entry[entries.size()]));
IndexMetaData.Builder indexBuilder = IndexMetaData.builder(indexMetaData).putCustom(IndexWarmersMetaData.TYPE, warmers);
mdBuilder.put(indexBuilder);
}
}
}
if (!globalFoundAtLeastOne) {
throw new IndexWarmerMissingException(request.names());
}
if (logger.isInfoEnabled()) {
for (String index : request.indices()) {
IndexMetaData indexMetaData = currentState.metaData().index(index);
if (indexMetaData == null) {
throw new IndexMissingException(new Index(index));
}
IndexWarmersMetaData warmers = indexMetaData.custom(IndexWarmersMetaData.TYPE);
if (warmers != null) {
for (IndexWarmersMetaData.Entry entry : warmers.entries()) {
for (String warmer : request.names()) {
if (Regex.simpleMatch(warmer, entry.name()) || warmer.equals("_all")) {
logger.info("[{}] delete warmer [{}]", index, entry.name());
}
}
}
}
}
}
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
});
| 1no label
|
src_main_java_org_elasticsearch_action_admin_indices_warmer_delete_TransportDeleteWarmerAction.java
|
1,819 |
@Component("blMapFieldPersistenceProvider")
@Scope("prototype")
public class MapFieldPersistenceProvider extends BasicFieldPersistenceProvider {
@Override
protected boolean canHandlePersistence(PopulateValueRequest populateValueRequest, Serializable instance) {
return populateValueRequest.getProperty().getName().contains(FieldManager.MAPFIELDSEPARATOR);
}
@Override
protected boolean canHandleExtraction(ExtractValueRequest extractValueRequest, Property property) {
return property.getName().contains(FieldManager.MAPFIELDSEPARATOR);
}
@Override
public FieldProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) {
try {
//handle some additional field settings (if applicable)
Class<?> valueType = null;
String valueClassName = populateValueRequest.getMetadata().getMapFieldValueClass();
if (valueClassName != null) {
valueType = Class.forName(valueClassName);
}
if (valueType == null) {
valueType = populateValueRequest.getReturnType();
}
if (valueType == null) {
throw new IllegalAccessException("Unable to determine the valueType for the rule field (" + populateValueRequest.getProperty().getName() + ")");
}
if (ValueAssignable.class.isAssignableFrom(valueType)) {
ValueAssignable assignableValue;
try {
assignableValue = (ValueAssignable) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
} catch (FieldNotAvailableException e) {
throw new IllegalArgumentException(e);
}
String key = populateValueRequest.getProperty().getName().substring(populateValueRequest.getProperty().getName().indexOf(FieldManager.MAPFIELDSEPARATOR) + FieldManager.MAPFIELDSEPARATOR.length(), populateValueRequest.getProperty().getName().length());
boolean persistValue = false;
if (assignableValue == null) {
assignableValue = (ValueAssignable) valueType.newInstance();
persistValue = true;
}
assignableValue.setName(key);
assignableValue.setValue(populateValueRequest.getProperty().getValue());
String fieldName = populateValueRequest.getProperty().getName().substring(0, populateValueRequest.getProperty().getName().indexOf(FieldManager.MAPFIELDSEPARATOR));
Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), fieldName);
FieldInfo fieldInfo = buildFieldInfo(field);
String manyToField = null;
if (populateValueRequest.getMetadata().getManyToField() != null) {
manyToField = populateValueRequest.getMetadata().getManyToField();
}
if (manyToField == null) {
manyToField = fieldInfo.getManyToManyMappedBy();
}
if (manyToField == null) {
manyToField = fieldInfo.getOneToManyMappedBy();
}
if (manyToField != null) {
String propertyName = populateValueRequest.getProperty().getName();
Object middleInstance = instance;
if (propertyName.contains(".")) {
propertyName = propertyName.substring(0, propertyName.lastIndexOf("."));
middleInstance = populateValueRequest.getFieldManager().getFieldValue(instance, propertyName);
}
populateValueRequest.getFieldManager().setFieldValue(assignableValue, manyToField, middleInstance);
}
if (Searchable.class.isAssignableFrom(valueType)) {
((Searchable) assignableValue).setSearchable(populateValueRequest.getMetadata().getSearchable());
}
if (persistValue) {
populateValueRequest.getPersistenceManager().getDynamicEntityDao().persist(assignableValue);
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), assignableValue);
}
} else {
//handle the map value set itself
if (FieldProviderResponse.NOT_HANDLED==super.populateValue(populateValueRequest, instance)) {
return FieldProviderResponse.NOT_HANDLED;
}
}
} catch (Exception e) {
throw new PersistenceException(e);
}
return FieldProviderResponse.HANDLED;
}
@Override
public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException {
if (extractValueRequest.getRequestedValue() != null && extractValueRequest.getRequestedValue() instanceof ValueAssignable) {
ValueAssignable assignableValue = (ValueAssignable) extractValueRequest.getRequestedValue();
String val = (String) assignableValue.getValue();
property.setValue(val);
property.setDisplayValue(extractValueRequest.getDisplayVal());
} else {
if (FieldProviderResponse.NOT_HANDLED==super.extractValue(extractValueRequest, property)) {
return FieldProviderResponse.NOT_HANDLED;
}
}
return FieldProviderResponse.HANDLED;
}
@Override
public FieldProviderResponse addSearchMapping(AddSearchMappingRequest addSearchMappingRequest, List<FilterMapping> filterMappings) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public int getOrder() {
return FieldPersistenceProvider.MAP_FIELD;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_provider_MapFieldPersistenceProvider.java
|
1,125 |
public class XmlConfigBuilder extends AbstractXmlConfigHelper implements ConfigBuilder {
private final static ILogger logger = Logger.getLogger(XmlConfigBuilder.class);
private Config config;
private InputStream in;
private File configurationFile;
private URL configurationUrl;
private Properties properties = System.getProperties();
boolean usingSystemConfig = false;
/**
* Constructs a XmlConfigBuilder that reads from the provided file.
*
* @param xmlFileName the name of the XML file
* @throws FileNotFoundException if the file can't be found.
*/
public XmlConfigBuilder(String xmlFileName) throws FileNotFoundException {
this(new FileInputStream(xmlFileName));
}
/**
* Constructs a XmlConfigBuilder that reads from the given InputStream.
*
* @param inputStream the InputStream containing the XML configuration.
* @throws IllegalArgumentException if inputStream is null.
*/
public XmlConfigBuilder(InputStream inputStream) {
if (inputStream == null) {
throw new IllegalArgumentException("inputStream can't be null");
}
this.in = inputStream;
}
/**
* Constructs a XmlConfigBuilder that tries to find a usable XML configuration file.
*/
public XmlConfigBuilder() {
String configFile = System.getProperty("hazelcast.config");
try {
if (configFile != null) {
configurationFile = new File(configFile);
logger.info("Using configuration file at " + configurationFile.getAbsolutePath());
if (!configurationFile.exists()) {
String msg = "Config file at '" + configurationFile.getAbsolutePath() + "' doesn't exist.";
msg += "\nHazelcast will try to use the hazelcast.xml config file in the working directory.";
logger.warning(msg);
configurationFile = null;
}
}
if (configurationFile == null) {
configFile = "hazelcast.xml";
configurationFile = new File("hazelcast.xml");
if (!configurationFile.exists()) {
configurationFile = null;
}
}
if (configurationFile != null) {
logger.info("Using configuration file at " + configurationFile.getAbsolutePath());
try {
in = new FileInputStream(configurationFile);
configurationUrl = configurationFile.toURI().toURL();
usingSystemConfig = true;
} catch (final Exception e) {
String msg = "Having problem reading config file at '" + configFile + "'.";
msg += "\nException message: " + e.getMessage();
msg += "\nHazelcast will try to use the hazelcast.xml config file in classpath.";
logger.warning(msg);
in = null;
}
}
if (in == null) {
logger.info("Looking for hazelcast.xml config file in classpath.");
configurationUrl = Config.class.getClassLoader().getResource("hazelcast.xml");
if (configurationUrl == null) {
configurationUrl = Config.class.getClassLoader().getResource("hazelcast-default.xml");
logger.warning(
"Could not find hazelcast.xml in classpath.\nHazelcast will use hazelcast-default.xml config file in jar.");
if (configurationUrl == null) {
logger.warning("Could not find hazelcast-default.xml in the classpath!"
+ "\nThis may be due to a wrong-packaged or corrupted jar file.");
return;
}
}
logger.info("Using configuration file " + configurationUrl.getFile() + " in the classpath.");
in = configurationUrl.openStream();
if (in == null) {
String msg = "Having problem reading config file hazelcast-default.xml in the classpath.";
msg += "\nHazelcast will start with default configuration.";
logger.warning(msg);
}
}
} catch (final Throwable e) {
logger.severe("Error while creating configuration:" + e.getMessage(), e);
}
}
/**
* Gets the current used properties. Can be null if no properties are set.
*
* @return the used properties.
* @see #setProperties(java.util.Properties)
*/
public Properties getProperties() {
return properties;
}
/**
* Sets the used properties. Can be null if no properties should be used.
* <p/>
* Properties are used to resolve ${variable} occurrences in the XML file.
*
* @param properties the new properties.
* @return the XmlConfigBuilder
*/
public XmlConfigBuilder setProperties(Properties properties) {
this.properties = properties;
return this;
}
public Config build() {
Config config = new Config();
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
return build(config);
}
Config build(Config config) {
try {
parse(config);
} catch (Exception e) {
throw new HazelcastException(e);
}
config.setConfigurationFile(configurationFile);
config.setConfigurationUrl(configurationUrl);
return config;
}
private void parse(final Config config) throws Exception {
this.config = config;
final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc;
try {
doc = builder.parse(in);
} catch (final Exception e) {
String msgPart = "config file '" + config.getConfigurationFile() + "' set as a system property.";
if (!usingSystemConfig) {
msgPart = "hazelcast-default.xml config file in the classpath.";
}
String msg = "Having problem parsing the " + msgPart;
msg += "\nException: " + e.getMessage();
msg += "\nHazelcast startup interrupted.";
logger.severe(msg);
throw e;
} finally {
IOUtil.closeResource(in);
}
Element element = doc.getDocumentElement();
try {
element.getTextContent();
} catch (final Throwable e) {
domLevel3 = false;
}
preprocess(element);
handleConfig(element);
}
private void preprocess(Node root) {
NamedNodeMap attributes = root.getAttributes();
if (attributes != null) {
for (int k = 0; k < attributes.getLength(); k++) {
Node attribute = attributes.item(k);
replaceVariables(attribute);
}
}
if (root.getNodeValue() != null) {
replaceVariables(root);
}
final NodeList childNodes = root.getChildNodes();
for (int k = 0; k < childNodes.getLength(); k++) {
Node child = childNodes.item(k);
preprocess(child);
}
}
private void replaceVariables(Node node) {
String value = node.getNodeValue();
StringBuilder sb = new StringBuilder();
int endIndex = -1;
int startIndex = value.indexOf("${");
while (startIndex > -1) {
endIndex = value.indexOf('}', startIndex);
if (endIndex == -1) {
logger.warning("Bad variable syntax. Could not find a closing curly bracket '}' on node: " + node.getLocalName());
break;
}
String variable = value.substring(startIndex + 2, endIndex);
String variableReplacement = properties.getProperty(variable);
if (variableReplacement != null) {
sb.append(variableReplacement);
} else {
sb.append(value.substring(startIndex, endIndex + 1));
logger.warning("Could not find a value for property '" + variable + "' on node: " + node.getLocalName());
}
startIndex = value.indexOf("${", endIndex);
}
sb.append(value.substring(endIndex + 1));
node.setNodeValue(sb.toString());
}
private void handleConfig(final Element docElement) throws Exception {
for (org.w3c.dom.Node node : new IterableNodeList(docElement.getChildNodes())) {
final String nodeName = cleanNodeName(node.getNodeName());
if ("network".equals(nodeName)) {
handleNetwork(node);
} else if ("group".equals(nodeName)) {
handleGroup(node);
} else if ("properties".equals(nodeName)) {
fillProperties(node, config.getProperties());
} else if ("wan-replication".equals(nodeName)) {
handleWanReplication(node);
} else if ("executor-service".equals(nodeName)) {
handleExecutor(node);
} else if ("services".equals(nodeName)) {
handleServices(node);
} else if ("queue".equals(nodeName)) {
handleQueue(node);
} else if ("map".equals(nodeName)) {
handleMap(node);
} else if ("multimap".equals(nodeName)) {
handleMultiMap(node);
} else if ("replicatedmap".equals(nodeName)) {
handleReplicatedMap(node);
} else if ("list".equals(nodeName)) {
handleList(node);
} else if ("set".equals(nodeName)) {
handleSet(node);
} else if ("topic".equals(nodeName)) {
handleTopic(node);
} else if ("jobtracker".equals(nodeName)) {
handleJobTracker(node);
} else if ("semaphore".equals(nodeName)) {
handleSemaphore(node);
} else if ("listeners".equals(nodeName)) {
handleListeners(node);
} else if ("partition-group".equals(nodeName)) {
handlePartitionGroup(node);
} else if ("serialization".equals(nodeName)) {
handleSerialization(node);
} else if ("security".equals(nodeName)) {
handleSecurity(node);
} else if ("license-key".equals(nodeName)) {
config.setLicenseKey(getTextContent(node));
} else if ("management-center".equals(nodeName)) {
handleManagementCenterConfig(node);
}
}
}
private void handleServices(final Node node) {
final Node attDefaults = node.getAttributes().getNamedItem("enable-defaults");
final boolean enableDefaults = attDefaults == null || checkTrue(getTextContent(attDefaults));
ServicesConfig servicesConfig = config.getServicesConfig();
servicesConfig.setEnableDefaults(enableDefaults);
for (Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("service".equals(nodeName)) {
ServiceConfig serviceConfig = new ServiceConfig();
String enabledValue = getAttribute(child, "enabled");
boolean enabled = checkTrue(enabledValue);
serviceConfig.setEnabled(enabled);
for (org.w3c.dom.Node n : new IterableNodeList(child.getChildNodes())) {
final String value = cleanNodeName(n.getNodeName());
if ("name".equals(value)) {
String name = getTextContent(n);
serviceConfig.setName(name);
} else if ("class-name".equals(value)) {
String className = getTextContent(n);
serviceConfig.setClassName(className);
} else if ("properties".equals(value)) {
fillProperties(n, serviceConfig.getProperties());
} else if ("configuration".equals(value)) {
Node parserNode = n.getAttributes().getNamedItem("parser");
String parserClass;
if (parserNode == null || (parserClass = getTextContent(parserNode)) == null) {
throw new IllegalArgumentException("Parser is required!");
}
try {
ServiceConfigurationParser parser = ClassLoaderUtil.newInstance(config.getClassLoader(), parserClass);
Object obj = parser.parse((Element) n);
serviceConfig.setConfigObject(obj);
} catch (Exception e) {
ExceptionUtil.sneakyThrow(e);
}
}
}
servicesConfig.addServiceConfig(serviceConfig);
}
}
}
private void handleWanReplication(final Node node) throws Exception {
final Node attName = node.getAttributes().getNamedItem("name");
final String name = getTextContent(attName);
final WanReplicationConfig wanReplicationConfig = new WanReplicationConfig();
wanReplicationConfig.setName(name);
for (org.w3c.dom.Node nodeTarget : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(nodeTarget.getNodeName());
if ("target-cluster".equals(nodeName)) {
WanTargetClusterConfig wanTarget = new WanTargetClusterConfig();
String groupName = getAttribute(nodeTarget, "group-name");
String groupPassword = getAttribute(nodeTarget, "group-password");
if (groupName != null) {
wanTarget.setGroupName(groupName);
}
if (groupPassword != null) {
wanTarget.setGroupPassword(groupPassword);
}
for (org.w3c.dom.Node targetChild : new IterableNodeList(nodeTarget.getChildNodes())) {
final String targetChildName = cleanNodeName(targetChild.getNodeName());
if ("replication-impl".equals(targetChildName)) {
wanTarget.setReplicationImpl(getTextContent(targetChild));
} else if ("end-points".equals(targetChildName)) {
for (org.w3c.dom.Node address : new IterableNodeList(targetChild.getChildNodes())) {
final String addressNodeName = cleanNodeName(address.getNodeName());
if ("address".equals(addressNodeName)) {
String addressStr = getTextContent(address);
wanTarget.addEndpoint(addressStr);
}
}
}
}
wanReplicationConfig.addTargetClusterConfig(wanTarget);
}
}
config.addWanReplicationConfig(wanReplicationConfig);
}
private void handleNetwork(final org.w3c.dom.Node node) throws Exception {
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("port".equals(nodeName)) {
handlePort(child);
} else if ("outbound-ports".equals(nodeName)) {
handleOutboundPorts(child);
} else if ("public-address".equals(nodeName)) {
final String address = getTextContent(child);
config.getNetworkConfig().setPublicAddress(address);
} else if ("join".equals(nodeName)) {
handleJoin(child);
} else if ("interfaces".equals(nodeName)) {
handleInterfaces(child);
} else if ("symmetric-encryption".equals(nodeName)) {
handleViaReflection(child, config.getNetworkConfig(), new SymmetricEncryptionConfig());
} else if ("ssl".equals(nodeName)) {
handleSSLConfig(child);
} else if ("socket-interceptor".equals(nodeName)) {
handleSocketInterceptorConfig(child);
}
}
}
private void handleExecutor(final org.w3c.dom.Node node) throws Exception {
final ExecutorConfig executorConfig = new ExecutorConfig();
handleViaReflection(node, config, executorConfig);
}
private void handleGroup(final org.w3c.dom.Node node) {
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String value = getTextContent(n).trim();
final String nodeName = cleanNodeName(n.getNodeName());
if ("name".equals(nodeName)) {
config.getGroupConfig().setName(value);
} else if ("password".equals(nodeName)) {
config.getGroupConfig().setPassword(value);
}
}
}
private void handleInterfaces(final org.w3c.dom.Node node) {
final NamedNodeMap atts = node.getAttributes();
final InterfacesConfig interfaces = config.getNetworkConfig().getInterfaces();
for (int a = 0; a < atts.getLength(); a++) {
final org.w3c.dom.Node att = atts.item(a);
if ("enabled".equals(att.getNodeName())) {
final String value = att.getNodeValue();
interfaces.setEnabled(checkTrue(value));
}
}
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
if ("interface".equalsIgnoreCase(cleanNodeName(n.getNodeName()))) {
final String value = getTextContent(n).trim();
interfaces.addInterface(value);
}
}
}
private void handleViaReflection(final org.w3c.dom.Node node, Object parent, Object target) throws Exception {
final NamedNodeMap atts = node.getAttributes();
if (atts != null) {
for (int a = 0; a < atts.getLength(); a++) {
final org.w3c.dom.Node att = atts.item(a);
String methodName = "set" + getMethodName(att.getNodeName());
Method method = getMethod(target, methodName);
final String value = att.getNodeValue();
invoke(target, method, value);
}
}
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String value = getTextContent(n).trim();
String methodName = "set" + getMethodName(cleanNodeName(n.getNodeName()));
Method method = getMethod(target, methodName);
invoke(target, method, value);
}
String mName = "set" + target.getClass().getSimpleName();
Method method = getMethod(parent, mName);
if (method == null) {
mName = "add" + target.getClass().getSimpleName();
method = getMethod(parent, mName);
}
method.invoke(parent, target);
}
private void invoke(Object target, Method method, String value) {
if (method == null)
return;
Class<?>[] args = method.getParameterTypes();
if (args == null || args.length == 0)
return;
Class<?> arg = method.getParameterTypes()[0];
try {
if (arg == String.class) {
method.invoke(target, value);
} else if (arg == int.class) {
method.invoke(target, Integer.parseInt(value));
} else if (arg == long.class) {
method.invoke(target, Long.parseLong(value));
} else if (arg == boolean.class) {
method.invoke(target, Boolean.parseBoolean(value));
}
} catch (Exception e) {
logger.warning(e);
}
}
private Method getMethod(Object target, String methodName) {
Method[] methods = target.getClass().getMethods();
for (Method method : methods) {
if (method.getName().equalsIgnoreCase(methodName)) {
return method;
}
}
return null;
}
private String getMethodName(String element) {
StringBuilder sb = new StringBuilder();
char[] chars = element.toCharArray();
boolean upper = true;
for (char c : chars) {
if (c == '_' || c == '-' || c == '.') {
upper = true;
} else {
if (upper) {
sb.append(Character.toUpperCase(c));
upper = false;
} else {
sb.append(c);
}
}
}
return sb.toString();
}
private void handleJoin(final org.w3c.dom.Node node) {
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
final String name = cleanNodeName(child.getNodeName());
if ("multicast".equals(name)) {
handleMulticast(child);
} else if ("tcp-ip".equals(name)) {
handleTcpIp(child);
} else if ("aws".equals(name)) {
handleAWS(child);
}
}
}
private void handleAWS(Node node) {
final JoinConfig join = config.getNetworkConfig().getJoin();
final NamedNodeMap atts = node.getAttributes();
final AwsConfig awsConfig = join.getAwsConfig();
for (int a = 0; a < atts.getLength(); a++) {
final Node att = atts.item(a);
final String value = getTextContent(att).trim();
if ("enabled".equalsIgnoreCase(att.getNodeName())) {
awsConfig.setEnabled(checkTrue(value));
} else if (att.getNodeName().equals("connection-timeout-seconds")) {
awsConfig.setConnectionTimeoutSeconds(getIntegerValue("connection-timeout-seconds", value, 5));
}
}
for (Node n : new IterableNodeList(node.getChildNodes())) {
final String value = getTextContent(n).trim();
if ("secret-key".equals(cleanNodeName(n.getNodeName()))) {
awsConfig.setSecretKey(value);
} else if ("access-key".equals(cleanNodeName(n.getNodeName()))) {
awsConfig.setAccessKey(value);
} else if ("region".equals(cleanNodeName(n.getNodeName()))) {
awsConfig.setRegion(value);
} else if ("host-header".equals(cleanNodeName(n.getNodeName()))) {
awsConfig.setHostHeader(value);
} else if ("security-group-name".equals(cleanNodeName(n.getNodeName()))) {
awsConfig.setSecurityGroupName(value);
} else if ("tag-key".equals(cleanNodeName(n.getNodeName()))) {
awsConfig.setTagKey(value);
} else if ("tag-value".equals(cleanNodeName(n.getNodeName()))) {
awsConfig.setTagValue(value);
}
}
}
private void handleMulticast(final org.w3c.dom.Node node) {
final JoinConfig join = config.getNetworkConfig().getJoin();
final NamedNodeMap atts = node.getAttributes();
final MulticastConfig multicastConfig = join.getMulticastConfig();
for (int a = 0; a < atts.getLength(); a++) {
final org.w3c.dom.Node att = atts.item(a);
final String value = getTextContent(att).trim();
if ("enabled".equalsIgnoreCase(att.getNodeName())) {
multicastConfig.setEnabled(checkTrue(value));
}
}
for (Node n : new IterableNodeList(node.getChildNodes())) {
final String value = getTextContent(n).trim();
if ("multicast-group".equals(cleanNodeName(n.getNodeName()))) {
multicastConfig.setMulticastGroup(value);
} else if ("multicast-port".equals(cleanNodeName(n.getNodeName()))) {
multicastConfig.setMulticastPort(Integer.parseInt(value));
} else if ("multicast-timeout-seconds".equals(cleanNodeName(n.getNodeName()))) {
multicastConfig.setMulticastTimeoutSeconds(Integer.parseInt(value));
} else if ("multicast-time-to-live-seconds".equals(cleanNodeName(n.getNodeName()))) {
//we need this line for the time being to prevent not reading the multicast-time-to-live-seconds property
//for more info see: https://github.com/hazelcast/hazelcast/issues/752
multicastConfig.setMulticastTimeToLive(Integer.parseInt(value));
} else if ("multicast-time-to-live".equals(cleanNodeName(n.getNodeName()))) {
multicastConfig.setMulticastTimeToLive(Integer.parseInt(value));
} else if ("trusted-interfaces".equals(cleanNodeName(n.getNodeName()))) {
for (org.w3c.dom.Node child : new IterableNodeList(n.getChildNodes())) {
if ("interface".equalsIgnoreCase(cleanNodeName(child.getNodeName()))) {
multicastConfig.addTrustedInterface(getTextContent(child).trim());
}
}
}
}
}
private void handleTcpIp(final org.w3c.dom.Node node) {
final NamedNodeMap atts = node.getAttributes();
final JoinConfig join = config.getNetworkConfig().getJoin();
final TcpIpConfig tcpIpConfig = join.getTcpIpConfig();
for (int a = 0; a < atts.getLength(); a++) {
final org.w3c.dom.Node att = atts.item(a);
final String value = getTextContent(att).trim();
if (att.getNodeName().equals("enabled")) {
tcpIpConfig.setEnabled(checkTrue(value));
} else if (att.getNodeName().equals("connection-timeout-seconds")) {
tcpIpConfig.setConnectionTimeoutSeconds(getIntegerValue("connection-timeout-seconds", value, 5));
}
}
final NodeList nodelist = node.getChildNodes();
final Set<String> memberTags = new HashSet<String>(Arrays.asList("interface", "member", "members"));
for (int i = 0; i < nodelist.getLength(); i++) {
final org.w3c.dom.Node n = nodelist.item(i);
final String value = getTextContent(n).trim();
if (cleanNodeName(n.getNodeName()).equals("required-member")) {
tcpIpConfig.setRequiredMember(value);
} else if (memberTags.contains(cleanNodeName(n.getNodeName()))) {
tcpIpConfig.addMember(value);
}
}
}
private void handlePort(final Node node) {
final String portStr = getTextContent(node).trim();
final NetworkConfig networkConfig = config.getNetworkConfig();
if (portStr != null && portStr.length() > 0) {
networkConfig.setPort(Integer.parseInt(portStr));
}
final NamedNodeMap atts = node.getAttributes();
for (int a = 0; a < atts.getLength(); a++) {
final org.w3c.dom.Node att = atts.item(a);
final String value = getTextContent(att).trim();
if ("auto-increment".equals(att.getNodeName())) {
networkConfig.setPortAutoIncrement(checkTrue(value));
} else if ("port-count".equals(att.getNodeName())) {
int portCount = Integer.parseInt(value);
networkConfig.setPortCount(portCount);
}
}
}
private void handleOutboundPorts(final Node child) {
final NetworkConfig networkConfig = config.getNetworkConfig();
for (Node n : new IterableNodeList(child.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
if ("ports".equals(nodeName)) {
final String value = getTextContent(n);
networkConfig.addOutboundPortDefinition(value);
}
}
}
private void handleQueue(final org.w3c.dom.Node node) {
final Node attName = node.getAttributes().getNamedItem("name");
final String name = getTextContent(attName);
final QueueConfig qConfig = new QueueConfig();
qConfig.setName(name);
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
final String value = getTextContent(n).trim();
if ("max-size".equals(nodeName)) {
qConfig.setMaxSize(getIntegerValue("max-size", value, QueueConfig.DEFAULT_MAX_SIZE));
} else if ("backup-count".equals(nodeName)) {
qConfig.setBackupCount(getIntegerValue("backup-count", value, QueueConfig.DEFAULT_SYNC_BACKUP_COUNT));
} else if ("async-backup-count".equals(nodeName)) {
qConfig.setAsyncBackupCount(getIntegerValue("async-backup-count", value, QueueConfig.DEFAULT_ASYNC_BACKUP_COUNT));
} else if ("item-listeners".equals(nodeName)) {
for (org.w3c.dom.Node listenerNode : new IterableNodeList(n.getChildNodes())) {
if ("item-listener".equals(cleanNodeName(listenerNode))) {
final NamedNodeMap attrs = listenerNode.getAttributes();
boolean incValue = checkTrue(getTextContent(attrs.getNamedItem("include-value")));
String listenerClass = getTextContent(listenerNode);
qConfig.addItemListenerConfig(new ItemListenerConfig(listenerClass, incValue));
}
}
} else if ("statistics-enabled".equals(nodeName)) {
qConfig.setStatisticsEnabled(checkTrue(value));
} else if ("queue-store".equals(nodeName)) {
final QueueStoreConfig queueStoreConfig = createQueueStoreConfig(n);
qConfig.setQueueStoreConfig(queueStoreConfig);
} else if ("empty-queue-ttl".equals(nodeName)) {
qConfig.setEmptyQueueTtl(getIntegerValue("empty-queue-ttl", value, QueueConfig.DEFAULT_EMPTY_QUEUE_TTL));
}
}
this.config.addQueueConfig(qConfig);
}
private void handleList(final org.w3c.dom.Node node) {
final Node attName = node.getAttributes().getNamedItem("name");
final String name = getTextContent(attName);
final ListConfig lConfig = new ListConfig();
lConfig.setName(name);
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
final String value = getTextContent(n).trim();
if ("max-size".equals(nodeName)) {
lConfig.setMaxSize(getIntegerValue("max-size", value, ListConfig.DEFAULT_MAX_SIZE));
} else if ("backup-count".equals(nodeName)) {
lConfig.setBackupCount(getIntegerValue("backup-count", value, ListConfig.DEFAULT_SYNC_BACKUP_COUNT));
} else if ("async-backup-count".equals(nodeName)) {
lConfig.setAsyncBackupCount(getIntegerValue("async-backup-count", value, ListConfig.DEFAULT_ASYNC_BACKUP_COUNT));
} else if ("item-listeners".equals(nodeName)) {
for (org.w3c.dom.Node listenerNode : new IterableNodeList(n.getChildNodes())) {
if ("item-listener".equals(cleanNodeName(listenerNode))) {
final NamedNodeMap attrs = listenerNode.getAttributes();
boolean incValue = checkTrue(getTextContent(attrs.getNamedItem("include-value")));
String listenerClass = getTextContent(listenerNode);
lConfig.addItemListenerConfig(new ItemListenerConfig(listenerClass, incValue));
}
}
} else if ("statistics-enabled".equals(nodeName)) {
lConfig.setStatisticsEnabled(checkTrue(value));
}
}
this.config.addListConfig(lConfig);
}
private void handleSet(final org.w3c.dom.Node node) {
final Node attName = node.getAttributes().getNamedItem("name");
final String name = getTextContent(attName);
final SetConfig sConfig = new SetConfig();
sConfig.setName(name);
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
final String value = getTextContent(n).trim();
if ("max-size".equals(nodeName)) {
sConfig.setMaxSize(getIntegerValue("max-size", value, SetConfig.DEFAULT_MAX_SIZE));
} else if ("backup-count".equals(nodeName)) {
sConfig.setBackupCount(getIntegerValue("backup-count", value, SetConfig.DEFAULT_SYNC_BACKUP_COUNT));
} else if ("async-backup-count".equals(nodeName)) {
sConfig.setAsyncBackupCount(getIntegerValue("async-backup-count", value, SetConfig.DEFAULT_ASYNC_BACKUP_COUNT));
} else if ("item-listeners".equals(nodeName)) {
for (org.w3c.dom.Node listenerNode : new IterableNodeList(n.getChildNodes())) {
if ("item-listener".equals(cleanNodeName(listenerNode))) {
final NamedNodeMap attrs = listenerNode.getAttributes();
boolean incValue = checkTrue(getTextContent(attrs.getNamedItem("include-value")));
String listenerClass = getTextContent(listenerNode);
sConfig.addItemListenerConfig(new ItemListenerConfig(listenerClass, incValue));
}
}
} else if ("statistics-enabled".equals(nodeName)) {
sConfig.setStatisticsEnabled(checkTrue(value));
}
}
this.config.addSetConfig(sConfig);
}
private void handleMultiMap(final org.w3c.dom.Node node) {
final Node attName = node.getAttributes().getNamedItem("name");
final String name = getTextContent(attName);
final MultiMapConfig multiMapConfig = new MultiMapConfig();
multiMapConfig.setName(name);
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
final String value = getTextContent(n).trim();
if ("value-collection-type".equals(nodeName)) {
multiMapConfig.setValueCollectionType(value);
} else if ("backup-count".equals(nodeName)) {
multiMapConfig.setBackupCount(getIntegerValue("backup-count", value, MultiMapConfig.DEFAULT_SYNC_BACKUP_COUNT));
} else if ("async-backup-count".equals(nodeName)) {
multiMapConfig.setAsyncBackupCount(getIntegerValue("async-backup-count", value, MultiMapConfig.DEFAULT_ASYNC_BACKUP_COUNT));
} else if ("entry-listeners".equals(nodeName)) {
for (org.w3c.dom.Node listenerNode : new IterableNodeList(n.getChildNodes())) {
if ("entry-listener".equals(cleanNodeName(listenerNode))) {
final NamedNodeMap attrs = listenerNode.getAttributes();
boolean incValue = checkTrue(getTextContent(attrs.getNamedItem("include-value")));
boolean local = checkTrue(getTextContent(attrs.getNamedItem("local")));
String listenerClass = getTextContent(listenerNode);
multiMapConfig.addEntryListenerConfig(new EntryListenerConfig(listenerClass, local, incValue));
}
}
} else if ("statistics-enabled".equals(nodeName)) {
multiMapConfig.setStatisticsEnabled(checkTrue(value));
// } else if ("partition-strategy".equals(nodeName)) {
// multiMapConfig.setPartitioningStrategyConfig(new PartitioningStrategyConfig(value));
}
}
this.config.addMultiMapConfig(multiMapConfig);
}
private void handleReplicatedMap(final org.w3c.dom.Node node) {
final Node attName = node.getAttributes().getNamedItem("name");
final String name = getTextContent(attName);
final ReplicatedMapConfig replicatedMapConfig = new ReplicatedMapConfig();
replicatedMapConfig.setName(name);
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
final String value = getTextContent(n).trim();
if ("concurrency-level".equals(nodeName)) {
replicatedMapConfig.setConcurrencyLevel(getIntegerValue("concurrency-level", value, ReplicatedMapConfig.DEFAULT_CONCURRENCY_LEVEL));
} else if ("in-memory-format".equals(nodeName)) {
replicatedMapConfig.setInMemoryFormat(InMemoryFormat.valueOf(upperCaseInternal(value)));
} else if ("replication-delay-millis".equals(nodeName)) {
replicatedMapConfig.setReplicationDelayMillis(getIntegerValue("replication-delay-millis", value, ReplicatedMapConfig.DEFAULT_REPLICATION_DELAY_MILLIS));
} else if ("async-fillup".equals(nodeName)) {
replicatedMapConfig.setAsyncFillup(checkTrue(value));
} else if ("statistics-enabled".equals(nodeName)) {
replicatedMapConfig.setStatisticsEnabled(checkTrue(value));
} else if ("entry-listeners".equals(nodeName)) {
for (org.w3c.dom.Node listenerNode : new IterableNodeList(n.getChildNodes())) {
if ("entry-listener".equals(cleanNodeName(listenerNode))) {
final NamedNodeMap attrs = listenerNode.getAttributes();
boolean incValue = checkTrue(getTextContent(attrs.getNamedItem("include-value")));
boolean local = checkTrue(getTextContent(attrs.getNamedItem("local")));
String listenerClass = getTextContent(listenerNode);
replicatedMapConfig.addEntryListenerConfig(new EntryListenerConfig(listenerClass, local, incValue));
}
}
}
}
this.config.addReplicatedMapConfig(replicatedMapConfig);
}
private void handleMap(final org.w3c.dom.Node node) throws Exception {
final String name = getAttribute(node, "name");
final MapConfig mapConfig = new MapConfig();
mapConfig.setName(name);
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
final String value = getTextContent(n).trim();
if ("backup-count".equals(nodeName)) {
mapConfig.setBackupCount(getIntegerValue("backup-count", value, MapConfig.DEFAULT_BACKUP_COUNT));
} else if ("in-memory-format".equals(nodeName)) {
mapConfig.setInMemoryFormat(InMemoryFormat.valueOf(upperCaseInternal(value)));
} else if ("async-backup-count".equals(nodeName)) {
mapConfig.setAsyncBackupCount(getIntegerValue("async-backup-count", value, MapConfig.MIN_BACKUP_COUNT));
} else if ("eviction-policy".equals(nodeName)) {
mapConfig.setEvictionPolicy(MapConfig.EvictionPolicy.valueOf(upperCaseInternal(value)));
} else if ("max-size".equals(nodeName)) {
final MaxSizeConfig msc = mapConfig.getMaxSizeConfig();
final Node maxSizePolicy = n.getAttributes().getNamedItem("policy");
if (maxSizePolicy != null) {
msc.setMaxSizePolicy(MaxSizeConfig.MaxSizePolicy.valueOf(upperCaseInternal(getTextContent(maxSizePolicy))));
}
int size;
if (value.length() < 2) {
size = Integer.parseInt(value);
} else {
char last = value.charAt(value.length() - 1);
int type = 0;
if (last == 'g' || last == 'G') {
type = 1;
} else if (last == 'm' || last == 'M') {
type = 2;
}
if (type == 0) {
size = Integer.parseInt(value);
} else if (type == 1) {
size = Integer.parseInt(value.substring(0, value.length() - 1)) * 1000;
} else {
size = Integer.parseInt(value.substring(0, value.length() - 1));
}
}
msc.setSize(size);
} else if ("eviction-percentage".equals(nodeName)) {
mapConfig.setEvictionPercentage(getIntegerValue("eviction-percentage", value,
MapConfig.DEFAULT_EVICTION_PERCENTAGE));
} else if ("time-to-live-seconds".equals(nodeName)) {
mapConfig.setTimeToLiveSeconds(getIntegerValue("time-to-live-seconds", value,
MapConfig.DEFAULT_TTL_SECONDS));
} else if ("max-idle-seconds".equals(nodeName)) {
mapConfig.setMaxIdleSeconds(getIntegerValue("max-idle-seconds", value,
MapConfig.DEFAULT_MAX_IDLE_SECONDS));
} else if ("map-store".equals(nodeName)) {
MapStoreConfig mapStoreConfig = createMapStoreConfig(n);
mapConfig.setMapStoreConfig(mapStoreConfig);
} else if ("near-cache".equals(nodeName)) {
handleViaReflection(n, mapConfig, new NearCacheConfig());
} else if ("merge-policy".equals(nodeName)) {
mapConfig.setMergePolicy(value);
} else if ("read-backup-data".equals(nodeName)) {
mapConfig.setReadBackupData(checkTrue(value));
} else if ("statistics-enabled".equals(nodeName)) {
mapConfig.setStatisticsEnabled(checkTrue(value));
} else if ("wan-replication-ref".equals(nodeName)) {
WanReplicationRef wanReplicationRef = new WanReplicationRef();
final String wanName = getAttribute(n, "name");
wanReplicationRef.setName(wanName);
for (org.w3c.dom.Node wanChild : new IterableNodeList(n.getChildNodes())) {
final String wanChildName = cleanNodeName(wanChild.getNodeName());
final String wanChildValue = getTextContent(n);
if ("merge-policy".equals(wanChildName)) {
wanReplicationRef.setMergePolicy(wanChildValue);
}
}
mapConfig.setWanReplicationRef(wanReplicationRef);
} else if ("indexes".equals(nodeName)) {
for (org.w3c.dom.Node indexNode : new IterableNodeList(n.getChildNodes())) {
if ("index".equals(cleanNodeName(indexNode))) {
final NamedNodeMap attrs = indexNode.getAttributes();
boolean ordered = checkTrue(getTextContent(attrs.getNamedItem("ordered")));
String attribute = getTextContent(indexNode);
mapConfig.addMapIndexConfig(new MapIndexConfig(attribute, ordered));
}
}
} else if ("entry-listeners".equals(nodeName)) {
for (org.w3c.dom.Node listenerNode : new IterableNodeList(n.getChildNodes())) {
if ("entry-listener".equals(cleanNodeName(listenerNode))) {
final NamedNodeMap attrs = listenerNode.getAttributes();
boolean incValue = checkTrue(getTextContent(attrs.getNamedItem("include-value")));
boolean local = checkTrue(getTextContent(attrs.getNamedItem("local")));
String listenerClass = getTextContent(listenerNode);
mapConfig.addEntryListenerConfig(new EntryListenerConfig(listenerClass, local, incValue));
}
}
} else if ("partition-strategy".equals(nodeName)) {
mapConfig.setPartitioningStrategyConfig(new PartitioningStrategyConfig(value));
}
}
this.config.addMapConfig(mapConfig);
}
private MapStoreConfig createMapStoreConfig(final org.w3c.dom.Node node) {
MapStoreConfig mapStoreConfig = new MapStoreConfig();
final NamedNodeMap atts = node.getAttributes();
for (int a = 0; a < atts.getLength(); a++) {
final org.w3c.dom.Node att = atts.item(a);
final String value = getTextContent(att).trim();
if ("enabled".equals(att.getNodeName())) {
mapStoreConfig.setEnabled(checkTrue(value));
} else if ("initial-mode".equals(att.getNodeName())) {
final InitialLoadMode mode = InitialLoadMode.valueOf(upperCaseInternal(getTextContent(att)));
mapStoreConfig.setInitialLoadMode(mode);
}
}
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
if ("class-name".equals(nodeName)) {
mapStoreConfig.setClassName(getTextContent(n).trim());
} else if ("factory-class-name".equals(nodeName)) {
mapStoreConfig.setFactoryClassName(getTextContent(n).trim());
} else if ("write-delay-seconds".equals(nodeName)) {
mapStoreConfig.setWriteDelaySeconds(getIntegerValue("write-delay-seconds", getTextContent(n).trim(),
MapStoreConfig.DEFAULT_WRITE_DELAY_SECONDS));
} else if ("properties".equals(nodeName)) {
fillProperties(n, mapStoreConfig.getProperties());
}
}
return mapStoreConfig;
}
private QueueStoreConfig createQueueStoreConfig(final org.w3c.dom.Node node) {
QueueStoreConfig queueStoreConfig = new QueueStoreConfig();
final NamedNodeMap atts = node.getAttributes();
for (int a = 0; a < atts.getLength(); a++) {
final org.w3c.dom.Node att = atts.item(a);
final String value = getTextContent(att).trim();
if (att.getNodeName().equals("enabled")) {
queueStoreConfig.setEnabled(checkTrue(value));
}
}
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
if ("class-name".equals(nodeName)) {
queueStoreConfig.setClassName(getTextContent(n).trim());
} else if ("factory-class-name".equals(nodeName)) {
queueStoreConfig.setFactoryClassName(getTextContent(n).trim());
} else if ("properties".equals(nodeName)) {
fillProperties(n, queueStoreConfig.getProperties());
}
}
return queueStoreConfig;
}
private void handleSSLConfig(final org.w3c.dom.Node node) {
SSLConfig sslConfig = new SSLConfig();
final NamedNodeMap atts = node.getAttributes();
final Node enabledNode = atts.getNamedItem("enabled");
final boolean enabled = enabledNode != null && checkTrue(getTextContent(enabledNode).trim());
sslConfig.setEnabled(enabled);
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
if ("factory-class-name".equals(nodeName)) {
sslConfig.setFactoryClassName(getTextContent(n).trim());
} else if ("properties".equals(nodeName)) {
fillProperties(n, sslConfig.getProperties());
}
}
config.getNetworkConfig().setSSLConfig(sslConfig);
}
private void handleSocketInterceptorConfig(final org.w3c.dom.Node node) {
SocketInterceptorConfig socketInterceptorConfig = parseSocketInterceptorConfig(node);
config.getNetworkConfig().setSocketInterceptorConfig(socketInterceptorConfig);
}
private void handleTopic(final org.w3c.dom.Node node) {
final Node attName = node.getAttributes().getNamedItem("name");
final String name = getTextContent(attName);
final TopicConfig tConfig = new TopicConfig();
tConfig.setName(name);
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
if (nodeName.equals("global-ordering-enabled")) {
tConfig.setGlobalOrderingEnabled(checkTrue(getTextContent(n)));
} else if ("message-listeners".equals(nodeName)) {
for (org.w3c.dom.Node listenerNode : new IterableNodeList(n.getChildNodes())) {
if ("message-listener".equals(cleanNodeName(listenerNode))) {
tConfig.addMessageListenerConfig(new ListenerConfig(getTextContent(listenerNode)));
}
}
} else if ("statistics-enabled".equals(nodeName)) {
tConfig.setStatisticsEnabled(checkTrue(getTextContent(n)));
}
}
config.addTopicConfig(tConfig);
}
private void handleJobTracker(final Node node) {
final Node attName = node.getAttributes().getNamedItem("name");
final String name = getTextContent(attName);
final JobTrackerConfig jConfig = new JobTrackerConfig();
jConfig.setName(name);
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
final String value = getTextContent(n).trim();
if ("max-thread-size".equals(nodeName)) {
jConfig.setMaxThreadSize(getIntegerValue("max-thread-size", value, JobTrackerConfig.DEFAULT_MAX_THREAD_SIZE));
} else if ("queue-size".equals(nodeName)) {
jConfig.setQueueSize(getIntegerValue("queue-size", value, JobTrackerConfig.DEFAULT_QUEUE_SIZE));
} else if ("retry-count".equals(nodeName)) {
jConfig.setRetryCount(getIntegerValue("retry-count", value, JobTrackerConfig.DEFAULT_RETRY_COUNT));
} else if ("chunk-size".equals(nodeName)) {
jConfig.setChunkSize(getIntegerValue("chunk-size", value, JobTrackerConfig.DEFAULT_CHUNK_SIZE));
} else if ("communicate-stats".equals(nodeName)) {
jConfig.setCommunicateStats(value == null || value.length() == 0 ?
JobTrackerConfig.DEFAULT_COMMUNICATE_STATS : Boolean.parseBoolean(value));
} else if ("topology-changed-stategy".equals(nodeName)) {
TopologyChangedStrategy topologyChangedStrategy = JobTrackerConfig.DEFAULT_TOPOLOGY_CHANGED_STRATEGY;
for (TopologyChangedStrategy temp : TopologyChangedStrategy.values()) {
if (temp.name().equals(value)) {
topologyChangedStrategy = temp;
}
}
jConfig.setTopologyChangedStrategy(topologyChangedStrategy);
}
}
config.addJobTrackerConfig(jConfig);
}
private void handleSemaphore(final org.w3c.dom.Node node) {
final Node attName = node.getAttributes().getNamedItem("name");
final String name = getTextContent(attName);
final SemaphoreConfig sConfig = new SemaphoreConfig();
sConfig.setName(name);
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
final String value = getTextContent(n).trim();
if ("initial-permits".equals(nodeName)) {
sConfig.setInitialPermits(getIntegerValue("initial-permits", value, 0));
} else if ("backup-count".equals(nodeName)) {
sConfig.setBackupCount(getIntegerValue("backup-count", value, SemaphoreConfig.DEFAULT_SYNC_BACKUP_COUNT));
} else if ("async-backup-count".equals(nodeName)) {
sConfig.setAsyncBackupCount(getIntegerValue("async-backup-count", value, SemaphoreConfig.DEFAULT_ASYNC_BACKUP_COUNT));
}
}
config.addSemaphoreConfig(sConfig);
}
private void handleListeners(final org.w3c.dom.Node node) throws Exception {
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
if ("listener".equals(cleanNodeName(child))) {
String listenerClass = getTextContent(child);
config.addListenerConfig(new ListenerConfig(listenerClass));
}
}
}
private void handlePartitionGroup(Node node) {
final NamedNodeMap atts = node.getAttributes();
final Node enabledNode = atts.getNamedItem("enabled");
final boolean enabled = enabledNode != null ? checkTrue(getTextContent(enabledNode)) : false;
config.getPartitionGroupConfig().setEnabled(enabled);
final Node groupTypeNode = atts.getNamedItem("group-type");
final MemberGroupType groupType = groupTypeNode != null
? MemberGroupType.valueOf(upperCaseInternal(getTextContent(groupTypeNode)))
: MemberGroupType.PER_MEMBER;
config.getPartitionGroupConfig().setGroupType(groupType);
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
if ("member-group".equals(cleanNodeName(child))) {
handleMemberGroup(child);
}
}
}
private void handleMemberGroup(Node node) {
MemberGroupConfig memberGroupConfig = new MemberGroupConfig();
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
if ("interface".equals(cleanNodeName(child))) {
String value = getTextContent(child);
memberGroupConfig.addInterface(value);
}
}
config.getPartitionGroupConfig().addMemberGroupConfig(memberGroupConfig);
}
private void handleSerialization(final Node node) {
SerializationConfig serializationConfig = parseSerialization(node);
config.setSerializationConfig(serializationConfig);
}
private void handleManagementCenterConfig(final Node node) {
NamedNodeMap attrs = node.getAttributes();
final Node enabledNode = attrs.getNamedItem("enabled");
boolean enabled = enabledNode != null && checkTrue(getTextContent(enabledNode));
final Node intervalNode = attrs.getNamedItem("update-interval");
final int interval = intervalNode != null ? getIntegerValue("update-interval",
getTextContent(intervalNode), 5) : 5;
final Node securityTokenNode = attrs.getNamedItem("security-token");
final String securityToken = getTextContent(securityTokenNode);
if ((securityToken != null && !"".equals(securityToken)) && enabledNode == null) {
enabled = true;
}
final Node clusterIdNode = attrs.getNamedItem("cluster-id");
final String clusterId = getTextContent(clusterIdNode);
final String url = getTextContent(node);
ManagementCenterConfig managementCenterConfig = config.getManagementCenterConfig();
managementCenterConfig.setEnabled(enabled);
managementCenterConfig.setUpdateInterval(interval);
managementCenterConfig.setSecurityToken("".equals(securityToken) ? null : securityToken);
managementCenterConfig.setClusterId("".equals(clusterId) ? null : clusterId);
managementCenterConfig.setUrl("".equals(url) ? null : url);
}
private void handleSecurity(final org.w3c.dom.Node node) throws Exception {
final NamedNodeMap atts = node.getAttributes();
final Node enabledNode = atts.getNamedItem("enabled");
final boolean enabled = enabledNode != null && checkTrue(getTextContent(enabledNode));
config.getSecurityConfig().setEnabled(enabled);
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("member-credentials-factory".equals(nodeName)) {
handleCredentialsFactory(child);
} else if ("member-login-modules".equals(nodeName)) {
handleLoginModules(child, true);
} else if ("client-login-modules".equals(nodeName)) {
handleLoginModules(child, false);
} else if ("client-permission-policy".equals(nodeName)) {
handlePermissionPolicy(child);
} else if ("client-permissions".equals(nodeName)) { //listener-permission
handleSecurityPermissions(child);
}
}
}
private void handleCredentialsFactory(final org.w3c.dom.Node node) throws Exception {
final NamedNodeMap attrs = node.getAttributes();
Node classNameNode = attrs.getNamedItem("class-name");
String className = getTextContent(classNameNode);
final SecurityConfig cfg = config.getSecurityConfig();
final CredentialsFactoryConfig credentialsFactoryConfig = new CredentialsFactoryConfig(className);
cfg.setMemberCredentialsConfig(credentialsFactoryConfig);
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("properties".equals(nodeName)) {
fillProperties(child, credentialsFactoryConfig.getProperties());
break;
}
}
}
private void handleLoginModules(final org.w3c.dom.Node node, boolean member) throws Exception {
final SecurityConfig cfg = config.getSecurityConfig();
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("login-module".equals(nodeName)) {
LoginModuleConfig lm = handleLoginModule(child);
if (member) {
cfg.addMemberLoginModuleConfig(lm);
} else {
cfg.addClientLoginModuleConfig(lm);
}
}
}
}
private LoginModuleConfig handleLoginModule(final org.w3c.dom.Node node) throws Exception {
final NamedNodeMap attrs = node.getAttributes();
Node classNameNode = attrs.getNamedItem("class-name");
String className = getTextContent(classNameNode);
Node usageNode = attrs.getNamedItem("usage");
LoginModuleUsage usage = usageNode != null ? LoginModuleUsage.get(getTextContent(usageNode))
: LoginModuleUsage.REQUIRED;
final LoginModuleConfig moduleConfig = new LoginModuleConfig(className, usage);
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("properties".equals(nodeName)) {
fillProperties(child, moduleConfig.getProperties());
break;
}
}
return moduleConfig;
}
private void handlePermissionPolicy(final org.w3c.dom.Node node) throws Exception {
final NamedNodeMap attrs = node.getAttributes();
Node classNameNode = attrs.getNamedItem("class-name");
String className = getTextContent(classNameNode);
final SecurityConfig cfg = config.getSecurityConfig();
final PermissionPolicyConfig policyConfig = new PermissionPolicyConfig(className);
cfg.setClientPolicyConfig(policyConfig);
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("properties".equals(nodeName)) {
fillProperties(child, policyConfig.getProperties());
break;
}
}
}
private void handleSecurityPermissions(final org.w3c.dom.Node node) throws Exception {
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
PermissionType type;
if ("map-permission".equals(nodeName)) {
type = PermissionType.MAP;
} else if ("queue-permission".equals(nodeName)) {
type = PermissionType.QUEUE;
} else if ("multimap-permission".equals(nodeName)) {
type = PermissionType.MULTIMAP;
} else if ("topic-permission".equals(nodeName)) {
type = PermissionType.TOPIC;
} else if ("list-permission".equals(nodeName)) {
type = PermissionType.LIST;
} else if ("set-permission".equals(nodeName)) {
type = PermissionType.SET;
} else if ("lock-permission".equals(nodeName)) {
type = PermissionType.LOCK;
} else if ("atomic-long-permission".equals(nodeName)) {
type = PermissionType.ATOMIC_LONG;
} else if ("countdown-latch-permission".equals(nodeName)) {
type = PermissionType.COUNTDOWN_LATCH;
} else if ("semaphore-permission".equals(nodeName)) {
type = PermissionType.SEMAPHORE;
} else if ("id-generator-permission".equals(nodeName)) {
type = PermissionType.ID_GENERATOR;
} else if ("executor-service-permission".equals(nodeName)) {
type = PermissionType.EXECUTOR_SERVICE;
} else if ("transaction-permission".equals(nodeName)) {
type = PermissionType.TRANSACTION;
} else if ("all-permissions".equals(nodeName)) {
type = PermissionType.ALL;
} else {
continue;
}
handleSecurityPermission(child, type);
}
}
private void handleSecurityPermission(final org.w3c.dom.Node node, PermissionType type) throws Exception {
final SecurityConfig cfg = config.getSecurityConfig();
final NamedNodeMap attrs = node.getAttributes();
Node nameNode = attrs.getNamedItem("name");
String name = nameNode != null ? getTextContent(nameNode) : "*";
Node principalNode = attrs.getNamedItem("principal");
String principal = principalNode != null ? getTextContent(principalNode) : "*";
final PermissionConfig permConfig = new PermissionConfig(type, name, principal);
cfg.addClientPermissionConfig(permConfig);
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("endpoints".equals(nodeName)) {
handleSecurityPermissionEndpoints(child, permConfig);
} else if ("actions".equals(nodeName)) {
handleSecurityPermissionActions(child, permConfig);
}
}
}
private void handleSecurityPermissionEndpoints(final org.w3c.dom.Node node, PermissionConfig permConfig)
throws Exception {
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("endpoint".equals(nodeName)) {
permConfig.addEndpoint(getTextContent(child).trim());
}
}
}
private void handleSecurityPermissionActions(final org.w3c.dom.Node node, PermissionConfig permConfig)
throws Exception {
for (org.w3c.dom.Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("action".equals(nodeName)) {
permConfig.addAction(getTextContent(child).trim());
}
}
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_config_XmlConfigBuilder.java
|
62 |
public static class Record
{
private byte type = 0;
private byte globalId[] = null;
private byte branchId[] = null;
private int seqNr = -1;
Record( byte type, byte globalId[], byte branchId[], int seqNr )
{
if ( type < 1 || type > 4 )
{
throw new IllegalArgumentException( "Illegal type: " + type );
}
this.type = type;
this.globalId = globalId;
this.branchId = branchId;
this.seqNr = seqNr;
}
public byte getType()
{
return type;
}
public byte[] getGlobalId()
{
return globalId;
}
public byte[] getBranchId()
{
return branchId;
}
public int getSequenceNumber()
{
return seqNr;
}
@Override
public String toString()
{
XidImpl xid = new XidImpl( globalId, branchId == null ? new byte[0] : branchId );
int size = 1 + sizeOf( globalId ) + sizeOf( branchId );
return "TxLogRecord[" + typeName() + "," + xid + "," + seqNr + "," + size + "]";
}
private int sizeOf( byte[] id )
{
// If id is null it means this record type doesn't have it. TX_START/MARK_COMMIT/TX_DONE
// only has the global id, whereas BRANCH_ADD has got both the global and branch ids.
if ( id == null )
{
return 0;
}
// The length of the array (1 byte) + the actual array
return 1 + id.length;
}
String typeName()
{
switch ( type )
{
case TX_START:
return "TX_START";
case BRANCH_ADD:
return "BRANCH_ADD";
case MARK_COMMIT:
return "MARK_COMMIT";
case TX_DONE:
return "TX_DONE";
default:
return "<unknown type>";
}
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TxLog.java
|
379 |
assertTrueEventually(new AssertTask() {
public void run() throws Exception {
for(int i=0; i<putThreads.length; i++){
putThreads[i].assertResult(PutItemsThread.MAX_ITEMS * putThreads.length);
}
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_multimap_ClientMultiMapListenerStressTest.java
|
424 |
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java
|
188 |
public interface OService {
public String getName();
public void startup();
public void shutdown();
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_util_OService.java
|
12 |
.withPredicateProvider(new PredicateProvider() {
@Override
public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder,
From root, String ceilingEntity,
String fullPropertyName, Path explicitPath, List directValues) {
return explicitPath.as(String.class).in(directValues);
}
})
| 0true
|
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_server_service_handler_SkuCustomPersistenceHandler.java
|
83 |
GREATER_THAN {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp>0:false;
}
@Override
public String toString() {
return ">";
}
@Override
public TitanPredicate negate() {
return LESS_THAN_EQUAL;
}
},
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java
|
9 |
{
private Long highest;
@Override
public boolean reached( File file, long version, LogLoader source )
{
// Here we know that the log version exists (checked in AbstractPruneStrategy#prune)
long tx = source.getFirstCommittedTxId( version );
if ( highest == null )
{
highest = source.getLastCommittedTxId();
return false;
}
return highest-tx >= maxTransactionCount;
}
};
| 1no label
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
|
11 |
static final class AsyncApply<T,U> extends Async {
final T arg;
final Fun<? super T,? extends U> fn;
final CompletableFuture<U> dst;
AsyncApply(T arg, Fun<? super T,? extends U> fn,
CompletableFuture<U> dst) {
this.arg = arg; this.fn = fn; this.dst = dst;
}
public final boolean exec() {
CompletableFuture<U> d; U u; Throwable ex;
if ((d = this.dst) != null && d.result == null) {
try {
u = fn.apply(arg);
ex = null;
} catch (Throwable rex) {
ex = rex;
u = null;
}
d.internalComplete(u, ex);
}
return true;
}
private static final long serialVersionUID = 5232453952276885070L;
}
| 0true
|
src_main_java_jsr166e_CompletableFuture.java
|
1,169 |
public class PaymentInfoDetailType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, PaymentInfoDetailType> TYPES = new LinkedHashMap<String, PaymentInfoDetailType>();
public static final PaymentInfoDetailType CAPTURE = new PaymentInfoDetailType("CAPTURE", "Capture");
public static final PaymentInfoDetailType REFUND = new PaymentInfoDetailType("REFUND", "Refund");
public static final PaymentInfoDetailType REVERSE_AUTH = new PaymentInfoDetailType("REVERSE_AUTH", "Reverse Auth");
public static PaymentInfoDetailType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public PaymentInfoDetailType() {
// do nothing
}
public PaymentInfoDetailType(String type, String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)){
TYPES.put(type, this);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PaymentInfoDetailType other = (PaymentInfoDetailType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_domain_PaymentInfoDetailType.java
|
135 |
public static final class ClientTestResource extends ExternalResource {
private final Config config;
private HazelcastInstance instance;
private SimpleClient client;
public ClientTestResource(Config config) {
this.config = config;
}
protected void before() throws Throwable {
instance = new TestHazelcastInstanceFactory(1).newHazelcastInstance(config);
client = newClient(TestUtil.getNode(instance));
client.auth();
}
protected void after() {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
instance.shutdown();
}
}
| 0true
|
hazelcast_src_test_java_com_hazelcast_client_ClientTestSupport.java
|
474 |
private class MockResponse implements HttpServletResponse {
private Cookie tempCookie;
public void addCookie(Cookie arg0) {
this.tempCookie = arg0;
}
public Cookie getTempCookie() {
return tempCookie;
}
public void addDateHeader(String arg0, long arg1) {
//do nothing
}
public void addHeader(String arg0, String arg1) {
//do nothing
}
public void addIntHeader(String arg0, int arg1) {
//do nothing
}
public boolean containsHeader(String arg0) {
return false;
}
public String encodeRedirectUrl(String arg0) {
return null;
}
public String encodeRedirectURL(String arg0) {
return null;
}
public String encodeUrl(String arg0) {
return null;
}
public String encodeURL(String arg0) {
return null;
}
public void sendError(int arg0, String arg1) throws IOException {
//do nothing
}
public void sendError(int arg0) throws IOException {
//do nothing
}
public void sendRedirect(String arg0) throws IOException {
//do nothing
}
public void setDateHeader(String arg0, long arg1) {
//do nothing
}
public void setHeader(String arg0, String arg1) {
//do nothing
}
public void setIntHeader(String arg0, int arg1) {
//do nothing
}
public void setStatus(int arg0, String arg1) {
//do nothing
}
public void setStatus(int arg0) {
//do nothing
}
public void flushBuffer() throws IOException {
//do nothing
}
public int getBufferSize() {
return 0;
}
public String getCharacterEncoding() {
return null;
}
public String getContentType() {
return null;
}
public Locale getLocale() {
return null;
}
public ServletOutputStream getOutputStream() throws IOException {
return null;
}
public PrintWriter getWriter() throws IOException {
return null;
}
public boolean isCommitted() {
return false;
}
public void reset() {
//do nothing
}
public void resetBuffer() {
//do nothing
}
public void setBufferSize(int arg0) {
//do nothing
}
public void setCharacterEncoding(String arg0) {
//do nothing
}
public void setContentLength(int arg0) {
//do nothing
}
public void setContentType(String arg0) {
//do nothing
}
public void setLocale(Locale arg0) {
//do nothing
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_security_EnhancedTokenBasedRememberMeServices.java
|
1,162 |
public class OSQLMethodToUpperCase extends OAbstractSQLMethod {
public static final String NAME = "touppercase";
public OSQLMethodToUpperCase() {
super(NAME);
}
@Override
public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) {
ioResult = ioResult != null ? ioResult.toString().toUpperCase() : null;
return ioResult;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodToUpperCase.java
|
1,579 |
public class BatchPersistencePackage implements Serializable {
protected PersistencePackage[] persistencePackages;
public PersistencePackage[] getPersistencePackages() {
return persistencePackages;
}
public void setPersistencePackages(PersistencePackage[] persistencePackages) {
this.persistencePackages = persistencePackages;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BatchPersistencePackage)) return false;
BatchPersistencePackage that = (BatchPersistencePackage) o;
if (!Arrays.equals(persistencePackages, that.persistencePackages)) return false;
return true;
}
@Override
public int hashCode() {
return persistencePackages != null ? Arrays.hashCode(persistencePackages) : 0;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_BatchPersistencePackage.java
|
1,544 |
public class PropertyMap {
public static final String CLASS = Tokens.makeNamespace(PropertyMap.class) + ".class";
public static final String KEY = Tokens.makeNamespace(PropertyMap.class) + ".key";
public static final String TYPE = Tokens.makeNamespace(PropertyMap.class) + ".type";
public enum Counters {
VERTICES_PROCESSED,
OUT_EDGES_PROCESSED
}
public static Configuration createConfiguration(final Class<? extends Element> klass, final String key, final Class<? extends WritableComparable> type) {
final Configuration configuration = new EmptyConfiguration();
configuration.setClass(CLASS, klass, Element.class);
configuration.set(KEY, key);
configuration.setClass(TYPE, type, WritableComparable.class);
return configuration;
}
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, WritableComparable> {
private String key;
private boolean isVertex;
private WritableHandler handler;
private SafeMapperOutputs outputs;
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class);
this.key = context.getConfiguration().get(KEY);
this.handler = new WritableHandler(context.getConfiguration().getClass(TYPE, Text.class, WritableComparable.class));
this.outputs = new SafeMapperOutputs(context);
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, WritableComparable>.Context context) throws IOException, InterruptedException {
this.outputs.write(Tokens.GRAPH, NullWritable.get(), value);
if (this.isVertex) {
if (value.hasPaths()) {
WritableComparable writable = this.handler.set(ElementPicker.getProperty(value, this.key));
for (int i = 0; i < value.pathCount(); i++) {
this.outputs.write(Tokens.SIDEEFFECT, NullWritable.get(), writable);
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L);
}
} else {
long edgesProcessed = 0;
for (final Edge e : value.getEdges(Direction.OUT)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
WritableComparable writable = this.handler.set(ElementPicker.getProperty(edge, this.key));
for (int i = 0; i < edge.pathCount(); i++) {
this.outputs.write(Tokens.SIDEEFFECT, NullWritable.get(), writable);
}
edgesProcessed++;
}
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_PROCESSED, edgesProcessed);
}
}
@Override
public void cleanup(final Mapper<NullWritable, FaunusVertex, NullWritable, WritableComparable>.Context context) throws IOException, InterruptedException {
this.outputs.close();
}
}
}
| 1no label
|
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_transform_PropertyMap.java
|
438 |
map.addChangeListener(new OMultiValueChangeListener<Object, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) {
changed.value = true;
}
});
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedMapTest.java
|
1,373 |
public class OTransactionNoTx extends OTransactionAbstract {
public OTransactionNoTx(final ODatabaseRecordTx iDatabase) {
super(iDatabase);
}
public void begin() {
}
public void commit() {
}
public void rollback() {
}
public void close() {
}
public ORecordInternal<?> loadRecord(final ORID iRid, final ORecordInternal<?> iRecord, final String iFetchPlan,
boolean ignonreCache, boolean loadTombstone) {
if (iRid.isNew())
return null;
return database.executeReadRecord((ORecordId) iRid, iRecord, iFetchPlan, ignonreCache, loadTombstone);
}
/**
* Update the record.
*
* @param iForceCreate
* @param iRecordCreatedCallback
* @param iRecordUpdatedCallback
*/
public void saveRecord(final ORecordInternal<?> iRecord, final String iClusterName, final OPERATION_MODE iMode,
boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback,
ORecordCallback<ORecordVersion> iRecordUpdatedCallback) {
try {
database.executeSaveRecord(iRecord, iClusterName, iRecord.getRecordVersion(), iRecord.getRecordType(), true, iMode,
iForceCreate, iRecordCreatedCallback, null);
} catch (Exception e) {
// REMOVE IT FROM THE CACHE TO AVOID DIRTY RECORDS
final ORecordId rid = (ORecordId) iRecord.getIdentity();
if (rid.isValid())
database.getLevel1Cache().freeRecord(rid);
if (e instanceof RuntimeException)
throw (RuntimeException) e;
throw new OException(e);
}
}
@Override
public boolean updateReplica(ORecordInternal<?> iRecord) {
try {
return database.executeUpdateReplica(iRecord);
} catch (Exception e) {
// REMOVE IT FROM THE CACHE TO AVOID DIRTY RECORDS
final ORecordId rid = (ORecordId) iRecord.getIdentity();
database.getLevel1Cache().freeRecord(rid);
if (e instanceof RuntimeException)
throw (RuntimeException) e;
throw new OException(e);
}
}
/**
* Deletes the record.
*/
public void deleteRecord(final ORecordInternal<?> iRecord, final OPERATION_MODE iMode) {
if (!iRecord.getIdentity().isPersistent())
return;
try {
database.executeDeleteRecord(iRecord, iRecord.getRecordVersion(), true, true, iMode, false);
} catch (Exception e) {
// REMOVE IT FROM THE CACHE TO AVOID DIRTY RECORDS
final ORecordId rid = (ORecordId) iRecord.getIdentity();
if (rid.isValid())
database.getLevel1Cache().freeRecord(rid);
if (e instanceof RuntimeException)
throw (RuntimeException) e;
throw new OException(e);
}
}
public Collection<ORecordOperation> getCurrentRecordEntries() {
return null;
}
public Collection<ORecordOperation> getAllRecordEntries() {
return null;
}
public List<ORecordOperation> getRecordEntriesByClass(String iClassName) {
return null;
}
public List<ORecordOperation> getNewRecordEntriesByClusterIds(int[] iIds) {
return null;
}
public void clearRecordEntries() {
}
public int getRecordEntriesSize() {
return 0;
}
public ORecordInternal<?> getRecord(final ORID rid) {
return null;
}
public ORecordOperation getRecordEntry(final ORID rid) {
return null;
}
public boolean isUsingLog() {
return false;
}
public void setUsingLog(final boolean useLog) {
}
public ODocument getIndexChanges() {
return null;
}
public OTransactionIndexChangesPerKey getIndexEntry(final String iIndexName, final Object iKey) {
return null;
}
public void addIndexEntry(final OIndex<?> delegate, final String indexName, final OPERATION status, final Object key,
final OIdentifiable value) {
switch (status) {
case CLEAR:
delegate.clear();
break;
case PUT:
delegate.put(key, value);
break;
case REMOVE:
assert key != null;
delegate.remove(key, value);
break;
}
}
public void clearIndexEntries() {
}
public OTransactionIndexChanges getIndexChanges(final String iName) {
return null;
}
public int getId() {
return 0;
}
public List<String> getInvolvedIndexes() {
return null;
}
public void updateIdentityAfterCommit(ORID oldRid, ORID newRid) {
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_tx_OTransactionNoTx.java
|
1,640 |
@Component("blCollectionFieldMetadataProvider")
@Scope("prototype")
public class CollectionFieldMetadataProvider extends AdvancedCollectionFieldMetadataProvider {
private static final Log LOG = LogFactory.getLog(CollectionFieldMetadataProvider.class);
protected boolean canHandleFieldForConfiguredMetadata(AddMetadataRequest addMetadataRequest, Map<String, FieldMetadata> metadata) {
AdminPresentationCollection annot = addMetadataRequest.getRequestedField().getAnnotation(AdminPresentationCollection.class);
return annot != null;
}
protected boolean canHandleAnnotationOverride(OverrideViaAnnotationRequest overrideViaAnnotationRequest, Map<String, FieldMetadata> metadata) {
AdminPresentationOverrides myOverrides = overrideViaAnnotationRequest.getRequestedEntity().getAnnotation(AdminPresentationOverrides.class);
AdminPresentationMergeOverrides myMergeOverrides = overrideViaAnnotationRequest.getRequestedEntity().getAnnotation(AdminPresentationMergeOverrides.class);
return (myOverrides != null && !ArrayUtils.isEmpty(myOverrides.collections()) || myMergeOverrides != null);
}
@Override
public FieldProviderResponse addMetadata(AddMetadataRequest addMetadataRequest, Map<String, FieldMetadata> metadata) {
if (!canHandleFieldForConfiguredMetadata(addMetadataRequest, metadata)) {
return FieldProviderResponse.NOT_HANDLED;
}
AdminPresentationCollection annot = addMetadataRequest.getRequestedField().getAnnotation(AdminPresentationCollection
.class);
FieldInfo info = buildFieldInfo(addMetadataRequest.getRequestedField());
FieldMetadataOverride override = constructBasicCollectionMetadataOverride(annot);
buildCollectionMetadata(addMetadataRequest.getParentClass(), addMetadataRequest.getTargetClass(),
metadata, info, override);
setClassOwnership(addMetadataRequest.getParentClass(), addMetadataRequest.getTargetClass(), metadata, info);
return FieldProviderResponse.HANDLED;
}
@Override
public FieldProviderResponse overrideViaAnnotation(OverrideViaAnnotationRequest overrideViaAnnotationRequest, Map<String, FieldMetadata> metadata) {
if (!canHandleAnnotationOverride(overrideViaAnnotationRequest, metadata)) {
return FieldProviderResponse.NOT_HANDLED;
}
Map<String, AdminPresentationCollectionOverride> presentationCollectionOverrides = new HashMap<String, AdminPresentationCollectionOverride>();
AdminPresentationOverrides myOverrides = overrideViaAnnotationRequest.getRequestedEntity().getAnnotation(AdminPresentationOverrides.class);
if (myOverrides != null) {
for (AdminPresentationCollectionOverride myOverride : myOverrides.collections()) {
presentationCollectionOverrides.put(myOverride.name(), myOverride);
}
}
for (String propertyName : presentationCollectionOverrides.keySet()) {
for (String key : metadata.keySet()) {
if (key.startsWith(propertyName)) {
buildAdminPresentationCollectionOverride(overrideViaAnnotationRequest.getPrefix(), overrideViaAnnotationRequest.getParentExcluded(), metadata, presentationCollectionOverrides, propertyName, key, overrideViaAnnotationRequest.getDynamicEntityDao());
}
}
}
AdminPresentationMergeOverrides myMergeOverrides = overrideViaAnnotationRequest.getRequestedEntity().getAnnotation(AdminPresentationMergeOverrides.class);
if (myMergeOverrides != null) {
for (AdminPresentationMergeOverride override : myMergeOverrides.value()) {
String propertyName = override.name();
Map<String, FieldMetadata> loopMap = new HashMap<String, FieldMetadata>();
loopMap.putAll(metadata);
for (Map.Entry<String, FieldMetadata> entry : loopMap.entrySet()) {
if (entry.getKey().startsWith(propertyName) || StringUtils.isEmpty(propertyName)) {
FieldMetadata targetMetadata = entry.getValue();
if (targetMetadata instanceof BasicCollectionMetadata) {
BasicCollectionMetadata serverMetadata = (BasicCollectionMetadata) targetMetadata;
if (serverMetadata.getTargetClass() != null) {
try {
Class<?> targetClass = Class.forName(serverMetadata.getTargetClass());
Class<?> parentClass = null;
if (serverMetadata.getOwningClass() != null) {
parentClass = Class.forName(serverMetadata.getOwningClass());
}
String fieldName = serverMetadata.getFieldName();
Field field = overrideViaAnnotationRequest.getDynamicEntityDao().getFieldManager()
.getField(targetClass, fieldName);
Map<String, FieldMetadata> temp = new HashMap<String, FieldMetadata>(1);
temp.put(field.getName(), serverMetadata);
FieldInfo info = buildFieldInfo(field);
FieldMetadataOverride fieldMetadataOverride = overrideCollectionMergeMetadata(override);
if (serverMetadata.getExcluded() != null && serverMetadata.getExcluded() &&
(fieldMetadataOverride.getExcluded() == null || fieldMetadataOverride.getExcluded())) {
continue;
}
buildCollectionMetadata(parentClass, targetClass, temp, info, fieldMetadataOverride);
serverMetadata = (BasicCollectionMetadata) temp.get(field.getName());
metadata.put(entry.getKey(), serverMetadata);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
}
}
}
return FieldProviderResponse.HANDLED;
}
@Override
public FieldProviderResponse overrideViaXml(OverrideViaXmlRequest overrideViaXmlRequest, Map<String, FieldMetadata> metadata) {
Map<String, FieldMetadataOverride> overrides = getTargetedOverride(overrideViaXmlRequest.getDynamicEntityDao(), overrideViaXmlRequest.getRequestedConfigKey(), overrideViaXmlRequest.getRequestedCeilingEntity());
if (overrides != null) {
for (String propertyName : overrides.keySet()) {
final FieldMetadataOverride localMetadata = overrides.get(propertyName);
for (String key : metadata.keySet()) {
if (key.equals(propertyName)) {
try {
if (metadata.get(key) instanceof BasicCollectionMetadata) {
BasicCollectionMetadata serverMetadata = (BasicCollectionMetadata) metadata.get(key);
if (serverMetadata.getTargetClass() != null) {
Class<?> targetClass = Class.forName(serverMetadata.getTargetClass());
Class<?> parentClass = null;
if (serverMetadata.getOwningClass() != null) {
parentClass = Class.forName(serverMetadata.getOwningClass());
}
String fieldName = serverMetadata.getFieldName();
Field field = overrideViaXmlRequest.getDynamicEntityDao().getFieldManager().getField(targetClass, fieldName);
Map<String, FieldMetadata> temp = new HashMap<String, FieldMetadata>(1);
temp.put(field.getName(), serverMetadata);
FieldInfo info = buildFieldInfo(field);
buildCollectionMetadata(parentClass, targetClass, temp, info, localMetadata);
serverMetadata = (BasicCollectionMetadata) temp.get(field.getName());
metadata.put(key, serverMetadata);
if (overrideViaXmlRequest.getParentExcluded()) {
if (LOG.isDebugEnabled()) {
LOG.debug("applyCollectionMetadataOverrides:Excluding " + key + "because parent is marked as excluded.");
}
serverMetadata.setExcluded(true);
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
}
return FieldProviderResponse.HANDLED;
}
protected void buildAdminPresentationCollectionOverride(String prefix, Boolean isParentExcluded, Map<String, FieldMetadata> mergedProperties, Map<String, AdminPresentationCollectionOverride> presentationCollectionOverrides, String propertyName, String key, DynamicEntityDao dynamicEntityDao) {
AdminPresentationCollectionOverride override = presentationCollectionOverrides.get(propertyName);
if (override != null) {
AdminPresentationCollection annot = override.value();
if (annot != null) {
String testKey = prefix + key;
if ((testKey.startsWith(propertyName + ".") || testKey.equals(propertyName)) && annot.excluded()) {
FieldMetadata metadata = mergedProperties.get(key);
if (LOG.isDebugEnabled()) {
LOG.debug("buildAdminPresentationCollectionOverride:Excluding " + key + "because an override annotation declared " + testKey + "to be excluded");
}
metadata.setExcluded(true);
return;
}
if ((testKey.startsWith(propertyName + ".") || testKey.equals(propertyName)) && !annot.excluded()) {
FieldMetadata metadata = mergedProperties.get(key);
if (!isParentExcluded) {
if (LOG.isDebugEnabled()) {
LOG.debug("buildAdminPresentationCollectionOverride:Showing " + key + "because an override annotation declared " + testKey + " to not be excluded");
}
metadata.setExcluded(false);
}
}
if (!(mergedProperties.get(key) instanceof BasicCollectionMetadata)) {
return;
}
BasicCollectionMetadata serverMetadata = (BasicCollectionMetadata) mergedProperties.get(key);
if (serverMetadata.getTargetClass() != null) {
try {
Class<?> targetClass = Class.forName(serverMetadata.getTargetClass());
Class<?> parentClass = null;
if (serverMetadata.getOwningClass() != null) {
parentClass = Class.forName(serverMetadata.getOwningClass());
}
String fieldName = serverMetadata.getFieldName();
Field field = dynamicEntityDao.getFieldManager().getField(targetClass, fieldName);
FieldMetadataOverride localMetadata = constructBasicCollectionMetadataOverride(annot);
//do not include the previous metadata - we want to construct a fresh metadata from the override annotation
Map<String, FieldMetadata> temp = new HashMap<String, FieldMetadata>(1);
FieldInfo info = buildFieldInfo(field);
buildCollectionMetadata(parentClass, targetClass, temp, info, localMetadata);
BasicCollectionMetadata result = (BasicCollectionMetadata) temp.get(field.getName());
result.setInheritedFromType(serverMetadata.getInheritedFromType());
result.setAvailableToTypes(serverMetadata.getAvailableToTypes());
mergedProperties.put(key, result);
if (isParentExcluded) {
if (LOG.isDebugEnabled()) {
LOG.debug("buildAdminPresentationCollectionOverride:Excluding " + key + "because the parent was excluded");
}
serverMetadata.setExcluded(true);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
}
protected FieldMetadataOverride overrideCollectionMergeMetadata(AdminPresentationMergeOverride merge) {
FieldMetadataOverride fieldMetadataOverride = new FieldMetadataOverride();
Map<String, AdminPresentationMergeEntry> overrideValues = getAdminPresentationEntries(merge.mergeEntries());
for (Map.Entry<String, AdminPresentationMergeEntry> entry : overrideValues.entrySet()) {
String stringValue = entry.getValue().overrideValue();
if (entry.getKey().equals(PropertyType.AdminPresentationCollection.ADDTYPE)) {
fieldMetadataOverride.setAddType(OperationType.valueOf(stringValue));
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.CURRENCYCODEFIELD)) {
fieldMetadataOverride.setCurrencyCodeField(stringValue);
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.CUSTOMCRITERIA)) {
fieldMetadataOverride.setCustomCriteria(entry.getValue().stringArrayOverrideValue());
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.EXCLUDED)) {
fieldMetadataOverride.setExcluded(StringUtils.isEmpty(stringValue) ? entry.getValue()
.booleanOverrideValue() :
Boolean.parseBoolean(stringValue));
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.FRIENDLYNAME)) {
fieldMetadataOverride.setFriendlyName(stringValue);
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.MANYTOFIELD)) {
fieldMetadataOverride.setManyToField(stringValue);
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.OPERATIONTYPES)) {
AdminPresentationOperationTypes operationType = entry.getValue().operationTypes();
fieldMetadataOverride.setAddType(operationType.addType());
fieldMetadataOverride.setRemoveType(operationType.removeType());
fieldMetadataOverride.setUpdateType(operationType.updateType());
fieldMetadataOverride.setFetchType(operationType.fetchType());
fieldMetadataOverride.setInspectType(operationType.inspectType());
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.ORDER)) {
fieldMetadataOverride.setOrder(StringUtils.isEmpty(stringValue) ? entry.getValue().intOverrideValue() :
Integer.parseInt(stringValue));
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.MANYTOFIELD)) {
fieldMetadataOverride.setManyToField(stringValue);
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.READONLY)) {
fieldMetadataOverride.setReadOnly(StringUtils.isEmpty(stringValue) ? entry.getValue()
.booleanOverrideValue() :
Boolean.parseBoolean(stringValue));
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.SECURITYLEVEL)) {
fieldMetadataOverride.setSecurityLevel(stringValue);
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.SHOWIFPROPERTY)) {
fieldMetadataOverride.setShowIfProperty(stringValue);
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.TAB)) {
fieldMetadataOverride.setTab(stringValue);
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.TABORDER)) {
fieldMetadataOverride.setTabOrder(StringUtils.isEmpty(stringValue) ? entry.getValue()
.intOverrideValue() :
Integer.parseInt(stringValue));
} else if (entry.getKey().equals(PropertyType.AdminPresentationCollection.USESERVERSIDEINSPECTIONCACHE)) {
fieldMetadataOverride.setUseServerSideInspectionCache(StringUtils.isEmpty(stringValue) ? entry
.getValue().booleanOverrideValue() :
Boolean.parseBoolean(stringValue));
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Unrecognized type: " + entry.getKey() + ". Not setting on collection field.");
}
}
}
return fieldMetadataOverride;
}
protected FieldMetadataOverride constructBasicCollectionMetadataOverride(AdminPresentationCollection annotColl) {
if (annotColl != null) {
FieldMetadataOverride override = new FieldMetadataOverride();
override.setAddMethodType(annotColl.addType());
override.setManyToField(annotColl.manyToField());
override.setCustomCriteria(annotColl.customCriteria());
override.setUseServerSideInspectionCache(annotColl.useServerSideInspectionCache());
override.setExcluded(annotColl.excluded());
override.setFriendlyName(annotColl.friendlyName());
override.setReadOnly(annotColl.readOnly());
override.setOrder(annotColl.order());
override.setTab(annotColl.tab());
override.setTabOrder(annotColl.tabOrder());
override.setSecurityLevel(annotColl.securityLevel());
override.setAddType(annotColl.operationTypes().addType());
override.setFetchType(annotColl.operationTypes().fetchType());
override.setRemoveType(annotColl.operationTypes().removeType());
override.setUpdateType(annotColl.operationTypes().updateType());
override.setInspectType(annotColl.operationTypes().inspectType());
override.setShowIfProperty(annotColl.showIfProperty());
override.setCurrencyCodeField(annotColl.currencyCodeField());
return override;
}
throw new IllegalArgumentException("AdminPresentationCollection annotation not found on Field");
}
protected void buildCollectionMetadata(Class<?> parentClass, Class<?> targetClass, Map<String, FieldMetadata> attributes, FieldInfo field, FieldMetadataOverride collectionMetadata) {
BasicCollectionMetadata serverMetadata = (BasicCollectionMetadata) attributes.get(field.getName());
Class<?> resolvedClass = parentClass==null?targetClass:parentClass;
BasicCollectionMetadata metadata;
if (serverMetadata != null) {
metadata = serverMetadata;
} else {
metadata = new BasicCollectionMetadata();
}
metadata.setTargetClass(targetClass.getName());
metadata.setFieldName(field.getName());
if (collectionMetadata.getReadOnly() != null) {
metadata.setMutable(!collectionMetadata.getReadOnly());
}
if (collectionMetadata.getAddMethodType() != null) {
metadata.setAddMethodType(collectionMetadata.getAddMethodType());
}
if (collectionMetadata.getShowIfProperty()!=null) {
metadata.setShowIfProperty(collectionMetadata.getShowIfProperty());
}
org.broadleafcommerce.openadmin.dto.OperationTypes dtoOperationTypes = new org.broadleafcommerce.openadmin.dto.OperationTypes(OperationType.BASIC, OperationType.BASIC, OperationType.BASIC, OperationType.BASIC, OperationType.BASIC);
if (collectionMetadata.getAddType() != null) {
dtoOperationTypes.setAddType(collectionMetadata.getAddType());
}
if (collectionMetadata.getRemoveType() != null) {
dtoOperationTypes.setRemoveType(collectionMetadata.getRemoveType());
}
if (collectionMetadata.getFetchType() != null) {
dtoOperationTypes.setFetchType(collectionMetadata.getFetchType());
}
if (collectionMetadata.getInspectType() != null) {
dtoOperationTypes.setInspectType(collectionMetadata.getInspectType());
}
if (collectionMetadata.getUpdateType() != null) {
dtoOperationTypes.setUpdateType(collectionMetadata.getUpdateType());
}
if (AddMethodType.LOOKUP == metadata.getAddMethodType()) {
dtoOperationTypes.setRemoveType(OperationType.NONDESTRUCTIVEREMOVE);
}
//don't allow additional non-persistent properties or additional foreign keys for an advanced collection datasource - they don't make sense in this context
PersistencePerspective persistencePerspective;
if (serverMetadata != null) {
persistencePerspective = metadata.getPersistencePerspective();
persistencePerspective.setOperationTypes(dtoOperationTypes);
} else {
persistencePerspective = new PersistencePerspective(dtoOperationTypes, new String[]{}, new ForeignKey[]{});
metadata.setPersistencePerspective(persistencePerspective);
}
String foreignKeyName = null;
if (serverMetadata != null) {
foreignKeyName = ((ForeignKey) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems
().get(PersistencePerspectiveItemType.FOREIGNKEY)).getManyToField();
}
if (!StringUtils.isEmpty(collectionMetadata.getManyToField())) {
foreignKeyName = collectionMetadata.getManyToField();
}
if (foreignKeyName == null && !StringUtils.isEmpty(field.getOneToManyMappedBy())) {
foreignKeyName = field.getOneToManyMappedBy();
}
if (foreignKeyName == null && !StringUtils.isEmpty(field.getManyToManyMappedBy())) {
foreignKeyName = field.getManyToManyMappedBy();
}
if (StringUtils.isEmpty(foreignKeyName)) {
throw new IllegalArgumentException("Unable to infer a ManyToOne field name for the @AdminPresentationCollection annotated field("+field.getName()+"). If not using the mappedBy property of @OneToMany or @ManyToMany, please make sure to explicitly define the manyToField property");
}
if (serverMetadata != null) {
ForeignKey foreignKey = (ForeignKey) metadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
foreignKey.setManyToField(foreignKeyName);
foreignKey.setForeignKeyClass(resolvedClass.getName());
foreignKey.setMutable(metadata.isMutable());
foreignKey.setOriginatingField(field.getName());
} else {
ForeignKey foreignKey = new ForeignKey(foreignKeyName, resolvedClass.getName(), null, ForeignKeyRestrictionType.ID_EQ);
persistencePerspective.addPersistencePerspectiveItem(PersistencePerspectiveItemType.FOREIGNKEY, foreignKey);
foreignKey.setMutable(metadata.isMutable());
foreignKey.setOriginatingField(field.getName());
}
String ceiling = null;
checkCeiling: {
if (field.getGenericType() instanceof ParameterizedType) {
try {
ParameterizedType pt = (ParameterizedType) field.getGenericType();
java.lang.reflect.Type collectionType = pt.getActualTypeArguments()[0];
String ceilingEntityName = ((Class<?>) collectionType).getName();
ceiling = entityConfiguration.lookupEntityClass(ceilingEntityName).getName();
break checkCeiling;
} catch (NoSuchBeanDefinitionException e) {
// We weren't successful at looking at entity configuration to find the type of this collection.
// We will continue and attempt to find it via the Hibernate annotations
}
}
if (!StringUtils.isEmpty(field.getOneToManyTargetEntity()) && !void.class.getName().equals(field.getOneToManyTargetEntity())) {
ceiling = field.getOneToManyTargetEntity();
break checkCeiling;
}
if (!StringUtils.isEmpty(field.getManyToManyTargetEntity()) && !void.class.getName().equals(field.getManyToManyTargetEntity())) {
ceiling = field.getManyToManyTargetEntity();
break checkCeiling;
}
}
if (!StringUtils.isEmpty(ceiling)) {
metadata.setCollectionCeilingEntity(ceiling);
}
if (collectionMetadata.getExcluded() != null) {
if (LOG.isDebugEnabled()) {
if (collectionMetadata.getExcluded()) {
LOG.debug("buildCollectionMetadata:Excluding " + field.getName() + " because it was explicitly declared in config");
} else {
LOG.debug("buildCollectionMetadata:Showing " + field.getName() + " because it was explicitly declared in config");
}
}
metadata.setExcluded(collectionMetadata.getExcluded());
}
if (collectionMetadata.getFriendlyName() != null) {
metadata.setFriendlyName(collectionMetadata.getFriendlyName());
}
if (collectionMetadata.getSecurityLevel() != null) {
metadata.setSecurityLevel(collectionMetadata.getSecurityLevel());
}
if (collectionMetadata.getOrder() != null) {
metadata.setOrder(collectionMetadata.getOrder());
}
if (collectionMetadata.getTab() != null) {
metadata.setTab(collectionMetadata.getTab());
}
if (collectionMetadata.getTabOrder() != null) {
metadata.setTabOrder(collectionMetadata.getTabOrder());
}
if (collectionMetadata.getCustomCriteria() != null) {
metadata.setCustomCriteria(collectionMetadata.getCustomCriteria());
}
if (collectionMetadata.getUseServerSideInspectionCache() != null) {
persistencePerspective.setUseServerSideInspectionCache(collectionMetadata.getUseServerSideInspectionCache());
}
if (collectionMetadata.getCurrencyCodeField()!=null) {
metadata.setCurrencyCodeField(collectionMetadata.getCurrencyCodeField());
}
attributes.put(field.getName(), metadata);
}
@Override
public int getOrder() {
return FieldMetadataProvider.COLLECTION;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_dao_provider_metadata_CollectionFieldMetadataProvider.java
|
441 |
@Test
public class TrackedSetTest {
public void testAddOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD);
Assert.assertNull(event.getOldValue());
Assert.assertEquals(event.getKey(), "value1");
Assert.assertEquals(event.getValue(), "value1");
changed.value = true;
}
});
trackedSet.add("value1");
Assert.assertTrue(changed.value);
Assert.assertTrue(doc.isDirty());
}
public void testAddTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
trackedSet.add("value1");
Assert.assertTrue(doc.isDirty());
}
public void testAddThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedSet.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
changed.value = true;
}
});
trackedSet.add("value1");
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testAddFour() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
trackedSet.add("value1");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
changed.value = true;
}
});
trackedSet.add("value1");
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testRemoveNotificationOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
trackedSet.add("value1");
trackedSet.add("value2");
trackedSet.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.REMOVE);
Assert.assertEquals(event.getOldValue(), "value2");
Assert.assertEquals(event.getKey(), "value2");
Assert.assertNull(event.getValue());
changed.value = true;
}
});
trackedSet.remove("value2");
Assert.assertTrue(changed.value);
Assert.assertTrue(doc.isDirty());
}
public void testRemoveNotificationTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
trackedSet.add("value1");
trackedSet.add("value2");
trackedSet.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedSet.remove("value2");
Assert.assertTrue(doc.isDirty());
}
public void testRemoveNotificationThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
trackedSet.add("value1");
trackedSet.add("value2");
trackedSet.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedSet.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
changed.value = true;
}
});
trackedSet.remove("value2");
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testRemoveNotificationFour() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
trackedSet.add("value1");
trackedSet.add("value2");
trackedSet.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
changed.value = true;
}
});
trackedSet.remove("value5");
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testClearOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
trackedSet.add("value1");
trackedSet.add("value2");
trackedSet.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final Set<OMultiValueChangeEvent<String, String>> firedEvents = new HashSet<OMultiValueChangeEvent<String, String>>();
firedEvents
.add(new OMultiValueChangeEvent<String, String>(OMultiValueChangeEvent.OChangeType.REMOVE, "value1", null, "value1"));
firedEvents
.add(new OMultiValueChangeEvent<String, String>(OMultiValueChangeEvent.OChangeType.REMOVE, "value2", null, "value2"));
firedEvents
.add(new OMultiValueChangeEvent<String, String>(OMultiValueChangeEvent.OChangeType.REMOVE, "value3", null, "value3"));
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
if (!firedEvents.remove(event))
Assert.fail();
changed.value = true;
}
});
trackedSet.clear();
Assert.assertEquals(firedEvents.size(), 0);
Assert.assertTrue(changed.value);
Assert.assertTrue(doc.isDirty());
}
public void testClearTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
trackedSet.add("value1");
trackedSet.add("value2");
trackedSet.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedSet.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
changed.value = true;
}
});
trackedSet.clear();
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testClearThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
trackedSet.add("value1");
trackedSet.add("value2");
trackedSet.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedSet.clear();
Assert.assertTrue(doc.isDirty());
}
public void testReturnOriginalState() {
final ODocument doc = new ODocument();
final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
trackedSet.add("value1");
trackedSet.add("value2");
trackedSet.add("value3");
trackedSet.add("value4");
trackedSet.add("value5");
final Set<String> original = new HashSet<String>(trackedSet);
final List<OMultiValueChangeEvent<String, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<String, String>>();
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
firedEvents.add(event);
}
});
trackedSet.add("value6");
trackedSet.remove("value2");
trackedSet.remove("value5");
trackedSet.add("value7");
trackedSet.add("value8");
trackedSet.remove("value7");
trackedSet.add("value9");
trackedSet.add("value10");
Assert.assertEquals(original, trackedSet.returnOriginalState(firedEvents));
}
/**
* Test that {@link OTrackedSet} is serialised correctly.
*/
@Test
public void testSetSerialization() throws Exception {
class NotSerializableDocument extends ODocument {
private static final long serialVersionUID = 1L;
private void writeObject(ObjectOutputStream oos) throws IOException {
throw new NotSerializableException();
}
}
final OTrackedSet<String> beforeSerialization = new OTrackedSet<String>(new NotSerializableDocument());
beforeSerialization.add("firstVal");
beforeSerialization.add("secondVal");
final OMemoryStream memoryStream = new OMemoryStream();
ObjectOutputStream out = new ObjectOutputStream(memoryStream);
out.writeObject(beforeSerialization);
out.close();
final ObjectInputStream input = new ObjectInputStream(new OMemoryInputStream(memoryStream.copy()));
@SuppressWarnings("unchecked")
final Set<String> afterSerialization = (Set<String>) input.readObject();
Assert.assertEquals(afterSerialization.size(), beforeSerialization.size(), "Set size");
Assert.assertTrue(beforeSerialization.containsAll(afterSerialization));
}
}
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedSetTest.java
|
2,820 |
nodeEngine.getExecutionService().schedule(new Runnable() {
@Override
public void run() {
resumeMigration();
}
}, migrationActivationDelay, TimeUnit.MILLISECONDS);
| 1no label
|
hazelcast_src_main_java_com_hazelcast_partition_impl_InternalPartitionServiceImpl.java
|
304 |
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientMapIssueTest {
@After
public void reset(){
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testOperationNotBlockingAfterClusterShutdown() throws InterruptedException {
final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
final ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().setConnectionAttemptLimit(Integer.MAX_VALUE);
final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
final IMap<String, String> m = client.getMap("m");
m.put("elif", "Elif");
m.put("ali", "Ali");
m.put("alev", "Alev");
instance1.getLifecycleService().terminate();
instance2.getLifecycleService().terminate();
final CountDownLatch latch = new CountDownLatch(1);
new Thread(){
public void run() {
try {
m.get("ali");
} catch (Exception ignored) {
latch.countDown();
}
}
}.start();
assertTrue(latch.await(15, TimeUnit.SECONDS));
}
@Test
public void testMapPagingEntries() {
final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
final ClientConfig clientConfig = new ClientConfig();
final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
final IMap<Integer, Integer> map = client.getMap("map");
final int size = 50;
final int pageSize = 5;
for (int i = 0; i < size; i++) {
map.put(i, i);
}
final PagingPredicate predicate = new PagingPredicate(pageSize);
predicate.nextPage();
final Set<Map.Entry<Integer,Integer>> entries = map.entrySet(predicate);
assertEquals(pageSize, entries.size());
}
@Test
public void testMapPagingValues() {
final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
final ClientConfig clientConfig = new ClientConfig();
final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
final IMap<Integer, Integer> map = client.getMap("map");
final int size = 50;
final int pageSize = 5;
for (int i = 0; i < size; i++) {
map.put(i, i);
}
final PagingPredicate predicate = new PagingPredicate(pageSize);
predicate.nextPage();
final Collection<Integer> values = map.values(predicate);
assertEquals(pageSize, values.size());
}
@Test
public void testMapPagingKeySet() {
final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
final ClientConfig clientConfig = new ClientConfig();
final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
final IMap<Integer, Integer> map = client.getMap("map");
final int size = 50;
final int pageSize = 5;
for (int i = 0; i < size; i++) {
map.put(size - i, i);
}
final PagingPredicate predicate = new PagingPredicate(pageSize);
predicate.nextPage();
final Set<Integer> values = map.keySet(predicate);
assertEquals(pageSize, values.size());
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapIssueTest.java
|
1,428 |
static class MappingTask {
final String index;
final String indexUUID;
MappingTask(String index, final String indexUUID) {
this.index = index;
this.indexUUID = indexUUID;
}
}
| 0true
|
src_main_java_org_elasticsearch_cluster_metadata_MetaDataMappingService.java
|
350 |
@RunWith(HazelcastSerialClassRunner.class)
@Category(NightlyTest.class)
public class MapMemoryUsageStressTest extends HazelcastTestSupport {
private HazelcastInstance client;
@Before
public void launchHazelcastServer() {
Hazelcast.newHazelcastInstance();
ClientConfig config = new ClientConfig();
config.setGroupConfig(new GroupConfig("dev", "dev-pass"));
config.getNetworkConfig().addAddress("127.0.0.1");
client = HazelcastClient.newHazelcastClient(config);
}
@After
public void shutdownHazelcastServer() {
Hazelcast.shutdownAll();
}
@Test
public void voidCacher() throws Exception {
final AtomicInteger counter = new AtomicInteger(200000);
final AtomicInteger errors = new AtomicInteger();
Thread[] threads = new Thread[8];
for (int k = 0; k < threads.length; k++) {
StressThread stressThread = new StressThread(counter, errors);
threads[k] = stressThread;
stressThread.start();
}
assertJoinable(TimeUnit.MINUTES.toSeconds(10), threads);
assertEquals(0, errors.get());
assertTrue(counter.get() <= 0);
}
private class StressThread extends Thread {
private final AtomicInteger counter;
private final AtomicInteger errors;
public StressThread(AtomicInteger counter, AtomicInteger errors) {
this.counter = counter;
this.errors = errors;
}
public void run() {
try {
for(;;){
int index = counter.decrementAndGet();
if(index<=0){
return;
}
IMap<Object, Object> map = client.getMap("juka" + index);
map.set("aaaa", "bbbb");
map.clear();
map.destroy();
if(index % 1000 == 0){
System.out.println("At: "+index);
}
}
} catch (Throwable t) {
errors.incrementAndGet();
t.printStackTrace();
}
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_map_MapMemoryUsageStressTest.java
|
172 |
public abstract class DistributedStoreManagerTest<T extends DistributedStoreManager> {
protected T manager;
protected KeyColumnValueStore store;
@Test
@Category({ OrderedKeyStoreTests.class })
public void testGetDeployment() {
assertEquals(Deployment.LOCAL, manager.getDeployment());
}
@Test
@Category({ OrderedKeyStoreTests.class })
public void testGetLocalKeyPartition() throws BackendException {
List<KeyRange> local = manager.getLocalKeyPartition();
assertNotNull(local);
assertEquals(1, local.size());
assertNotNull(local.get(0).getStart());
assertNotNull(local.get(0).getEnd());
}
}
| 0true
|
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_DistributedStoreManagerTest.java
|
357 |
public class ODatabaseDocumentPool extends ODatabasePoolBase<ODatabaseDocumentTx> {
private static ODatabaseDocumentPool globalInstance = new ODatabaseDocumentPool();
public ODatabaseDocumentPool() {
super();
}
public ODatabaseDocumentPool(final String iURL, final String iUserName, final String iUserPassword) {
super(iURL, iUserName, iUserPassword);
}
public static ODatabaseDocumentPool global() {
globalInstance.setup();
return globalInstance;
}
public static ODatabaseDocumentPool global(final int iPoolMin, final int iPoolMax) {
globalInstance.setup(iPoolMin, iPoolMax);
return globalInstance;
}
@Override
protected ODatabaseDocumentTx createResource(Object owner, String iDatabaseName, Object... iAdditionalArgs) {
return new ODatabaseDocumentTxPooled((ODatabaseDocumentPool) owner, iDatabaseName, (String) iAdditionalArgs[0],
(String) iAdditionalArgs[1]);
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_document_ODatabaseDocumentPool.java
|
33 |
@Test
public class OMVRBTreeCompositeTest {
protected OMVRBTree<OCompositeKey, Double> tree;
@BeforeMethod
public void beforeMethod() throws Exception {
tree = new OMVRBTreeMemory<OCompositeKey, Double>(4, 0.5f, 2);
for (double i = 1; i < 4; i++) {
for (double j = 1; j < 10; j++) {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey(i);
compositeKey.addKey(j);
tree.put(compositeKey, i * 4 + j);
}
}
}
@Test
public void testGetEntrySameKeys() {
OMVRBTreeEntry<OCompositeKey, Double> result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(result.getKey(), compositeKey(1.0, 2.0));
result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(1.0, 2.0));
result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(1.0, 2.0));
}
@Test
public void testGetEntryPartialKeys() {
OMVRBTreeEntry<OCompositeKey, Double> result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(result.getKey().getKeys().get(0), 2.0);
result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(2.0, 1.0));
result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(2.0, 9.0));
}
@Test
public void testSubMapInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 9);
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testSubMapNonInclusiveDescending() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 0);
assertTrue(navigableMap.isEmpty());
navigableMap = tree.subMap(compositeKey(1.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testSubMapInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 9);
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testSubMapNonInclusive() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 0);
assertTrue(navigableMap.isEmpty());
navigableMap = tree.subMap(compositeKey(1.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testSubMapInclusivePartialKey() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusivePartialKey() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 6);
for (double j = 4; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusivePartialKey() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 14);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapNonInclusivePartial() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 5);
for (double i = 5; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testSubMapInclusivePartialKeyDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusivePartialKeyDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 6);
for (double j = 4; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusivePartialKeyDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 14);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapNonInclusivePartialDescending() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 5);
for (double i = 5; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testTailMapInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), true);
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), false);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testTailMapInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), true).descendingMap();
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), false).descendingMap();
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testTailMapInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), true);
assertEquals(navigableMap.size(), 16);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), false);
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), true).descendingMap();
assertEquals(navigableMap.size(), 16);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), false).descendingMap();
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), true);
assertEquals(navigableMap.size(), 27);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), false);
assertEquals(navigableMap.size(), 18);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), true).descendingMap();
assertEquals(navigableMap.size(), 27);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), false).descendingMap();
assertEquals(navigableMap.size(), 18);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), true);
assertEquals(navigableMap.size(), 20);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j > 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), false);
assertEquals(navigableMap.size(), 19);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j >= 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), true).descendingMap();
assertEquals(navigableMap.size(), 20);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j > 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), false).descendingMap();
assertEquals(navigableMap.size(), 19);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j >= 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testGetCeilingEntryKeyExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 3.0);
entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(3.0, 9.0));
entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(3.0, 1.0));
}
@Test
public void testGetCeilingEntryKeyNotExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 2.0);
entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 9.0));
entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 1.0));
}
@Test
public void testGetFloorEntryKeyExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 2.0);
entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 9.0));
entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 1.0));
}
@Test
public void testGetFloorEntryKeyNotExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 1.0);
entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(1.0, 9.0));
entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(1.0, 1.0));
}
@Test
public void testHigherEntryKeyExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(2.0));
assertEquals(entry.getKey(), compositeKey(3.0, 1.0));
}
@Test
public void testHigherEntryKeyNotExist() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(1.3));
assertEquals(entry.getKey(), compositeKey(2.0, 1.0));
}
@Test
public void testHigherEntryNullResult() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(12.0));
assertNull(entry);
}
@Test
public void testLowerEntryNullResult() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(0.0));
assertNull(entry);
}
@Test
public void testLowerEntryKeyExist() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(2.0));
assertEquals(entry.getKey(), compositeKey(1.0, 9.0));
}
@Test
public void testLowerEntryKeyNotExist() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(2.5));
assertEquals(entry.getKey(), compositeKey(2.0, 9.0));
}
private OCompositeKey compositeKey(Comparable<?>... params) {
return new OCompositeKey(Arrays.asList(params));
}
}
| 0true
|
core_src_test_java_com_orientechnologies_common_collection_OMVRBTreeCompositeTest.java
|
69 |
class AssignToIfExistsProposal extends LocalProposal {
protected DocumentChange createChange(IDocument document, Node expanse,
Integer stopIndex) {
DocumentChange change =
new DocumentChange("Assign to If Exists", document);
change.setEdit(new MultiTextEdit());
change.addEdit(new InsertEdit(offset, "if (exists " + initialName + " = "));
String terminal = expanse.getEndToken().getText();
if (!terminal.equals(";")) {
change.addEdit(new InsertEdit(stopIndex+1, ") {}"));
exitPos = stopIndex+9;
}
else {
change.addEdit(new ReplaceEdit(stopIndex, 1, ") {}"));
exitPos = stopIndex+8;
}
return change;
}
public AssignToIfExistsProposal(Tree.CompilationUnit cu,
Node node, int currentOffset) {
super(cu, node, currentOffset);
}
protected void addLinkedPositions(IDocument document, Unit unit)
throws BadLocationException {
// ProposalPosition typePosition =
// new ProposalPosition(document, offset, 5, 1,
// getSupertypeProposals(offset, unit,
// type, true, "value"));
ProposalPosition namePosition =
new ProposalPosition(document, offset+11, initialName.length(), 0,
getNameProposals(offset+11, 0, nameProposals));
// LinkedMode.addLinkedPosition(linkedModeModel, typePosition);
LinkedMode.addLinkedPosition(linkedModeModel, namePosition);
}
@Override
String[] computeNameProposals(Node expression) {
return super.computeNameProposals(expression);
}
@Override
public String getDisplayString() {
return "Assign expression to 'if (exists)' condition";
}
@Override
boolean isEnabled(ProducedType resultType) {
return resultType!=null &&
rootNode.getUnit().isOptionalType(resultType);
}
static void addAssignToIfExistsProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals,
Node node, int currentOffset) {
AssignToIfExistsProposal prop =
new AssignToIfExistsProposal(cu, node, currentOffset);
if (prop.isEnabled()) {
proposals.add(prop);
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AssignToIfExistsProposal.java
|
1,450 |
public static enum State {
INIT((byte) 0),
STARTED((byte) 1),
SUCCESS((byte) 2),
FAILED((byte) 3),
ABORTED((byte) 4),
MISSING((byte) 5);
private byte value;
State(byte value) {
this.value = value;
}
public byte value() {
return value;
}
public boolean completed() {
switch (this) {
case INIT:
return false;
case STARTED:
return false;
case SUCCESS:
return true;
case FAILED:
return true;
case ABORTED:
return false;
case MISSING:
return true;
default:
assert false;
return true;
}
}
public boolean failed() {
switch (this) {
case INIT:
return false;
case STARTED:
return false;
case SUCCESS:
return false;
case FAILED:
return true;
case ABORTED:
return true;
case MISSING:
return true;
default:
assert false;
return false;
}
}
public static State fromValue(byte value) {
switch (value) {
case 0:
return INIT;
case 1:
return STARTED;
case 2:
return SUCCESS;
case 3:
return FAILED;
case 4:
return ABORTED;
case 5:
return MISSING;
default:
throw new ElasticsearchIllegalArgumentException("No snapshot state for value [" + value + "]");
}
}
}
| 0true
|
src_main_java_org_elasticsearch_cluster_metadata_SnapshotMetaData.java
|
833 |
static final class Fields {
static final XContentBuilderString _SCROLL_ID = new XContentBuilderString("_scroll_id");
static final XContentBuilderString _SHARDS = new XContentBuilderString("_shards");
static final XContentBuilderString TOTAL = new XContentBuilderString("total");
static final XContentBuilderString SUCCESSFUL = new XContentBuilderString("successful");
static final XContentBuilderString FAILED = new XContentBuilderString("failed");
static final XContentBuilderString FAILURES = new XContentBuilderString("failures");
static final XContentBuilderString STATUS = new XContentBuilderString("status");
static final XContentBuilderString INDEX = new XContentBuilderString("index");
static final XContentBuilderString SHARD = new XContentBuilderString("shard");
static final XContentBuilderString REASON = new XContentBuilderString("reason");
static final XContentBuilderString TOOK = new XContentBuilderString("took");
static final XContentBuilderString TIMED_OUT = new XContentBuilderString("timed_out");
}
| 0true
|
src_main_java_org_elasticsearch_action_search_SearchResponse.java
|
4,490 |
class FileChunkTransportRequestHandler extends BaseTransportRequestHandler<RecoveryFileChunkRequest> {
@Override
public RecoveryFileChunkRequest newInstance() {
return new RecoveryFileChunkRequest();
}
@Override
public String executor() {
return ThreadPool.Names.GENERIC;
}
@Override
public void messageReceived(final RecoveryFileChunkRequest request, TransportChannel channel) throws Exception {
RecoveryStatus onGoingRecovery = onGoingRecoveries.get(request.recoveryId());
if (onGoingRecovery == null) {
// shard is getting closed on us
throw new IndexShardClosedException(request.shardId());
}
if (onGoingRecovery.isCanceled()) {
onGoingRecovery.sentCanceledToSource = true;
throw new IndexShardClosedException(request.shardId());
}
Store store = onGoingRecovery.indexShard.store();
IndexOutput indexOutput;
if (request.position() == 0) {
// first request
onGoingRecovery.checksums.remove(request.name());
indexOutput = onGoingRecovery.removeOpenIndexOutputs(request.name());
IOUtils.closeWhileHandlingException(indexOutput);
// we create an output with no checksum, this is because the pure binary data of the file is not
// the checksum (because of seek). We will create the checksum file once copying is done
// also, we check if the file already exists, if it does, we create a file name based
// on the current recovery "id" and later we make the switch, the reason for that is that
// we only want to overwrite the index files once we copied all over, and not create a
// case where the index is half moved
String fileName = request.name();
if (store.directory().fileExists(fileName)) {
fileName = "recovery." + onGoingRecovery.startTime + "." + fileName;
}
indexOutput = onGoingRecovery.openAndPutIndexOutput(request.name(), fileName, store);
} else {
indexOutput = onGoingRecovery.getOpenIndexOutput(request.name());
}
if (indexOutput == null) {
// shard is getting closed on us
throw new IndexShardClosedException(request.shardId());
}
boolean success = false;
synchronized (indexOutput) {
try {
if (recoverySettings.rateLimiter() != null) {
recoverySettings.rateLimiter().pause(request.content().length());
}
BytesReference content = request.content();
if (!content.hasArray()) {
content = content.toBytesArray();
}
indexOutput.writeBytes(content.array(), content.arrayOffset(), content.length());
onGoingRecovery.currentFilesSize.addAndGet(request.length());
if (indexOutput.getFilePointer() == request.length()) {
// we are done
indexOutput.close();
// write the checksum
if (request.checksum() != null) {
onGoingRecovery.checksums.put(request.name(), request.checksum());
}
store.directory().sync(Collections.singleton(request.name()));
IndexOutput remove = onGoingRecovery.removeOpenIndexOutputs(request.name());
assert remove == indexOutput;
}
success = true;
} finally {
if (!success || onGoingRecovery.isCanceled()) {
IndexOutput remove = onGoingRecovery.removeOpenIndexOutputs(request.name());
assert remove == indexOutput;
IOUtils.closeWhileHandlingException(indexOutput);
}
}
}
if (onGoingRecovery.isCanceled()) {
onGoingRecovery.sentCanceledToSource = true;
throw new IndexShardClosedException(request.shardId());
}
channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
}
| 1no label
|
src_main_java_org_elasticsearch_indices_recovery_RecoveryTarget.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.