Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
441 |
new Thread() {
public void run() {
while (true) {
int random = rnd.nextInt(100);
if (random > 54) {
q.poll();
totalPoll.incrementAndGet();
} else if (random > 4) {
q.offer(VALUE);
totalOffer.incrementAndGet();
} else {
q.peek();
totalPeek.incrementAndGet();
}
}
}
}.start();
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_queue_ClientQueuePerformanceTest.java
|
158 |
@Service("blContentDefaultRuleProcessor")
public class StructuredContentDefaultRuleProcessor extends AbstractStructuredContentRuleProcessor {
private static final Log LOG = LogFactory.getLog(StructuredContentDefaultRuleProcessor.class);
/**
* Returns true if all of the rules associated with the passed in <code>StructuredContent</code>
* item match based on the passed in vars.
*
* Also returns true if no rules are present for the passed in item.
*
* @param sc - a structured content item to test
* @param vars - a map of objects used by the rule MVEL expressions
* @return the result of the rule checks
*/
public boolean checkForMatch(StructuredContentDTO sc, Map<String, Object> vars) {
String ruleExpression = sc.getRuleExpression();
if (ruleExpression != null) {
if (LOG.isTraceEnabled()) {
LOG.trace("Processing content rule for StructuredContent with id " + sc.getId() +". Value = " + ruleExpression);
}
boolean result = executeExpression(ruleExpression, vars);
if (! result) {
if (LOG.isDebugEnabled()) {
LOG.debug("Content failed to pass rule and will not be included for StructuredContent with id " + sc.getId() +". Value = " + ruleExpression);
}
}
return result;
} else {
// If no rule found, then consider this a match.
return true;
}
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_service_StructuredContentDefaultRuleProcessor.java
|
311 |
public class MergeFileSystemXMLApplicationContext extends AbstractMergeXMLApplicationContext {
public MergeFileSystemXMLApplicationContext(ApplicationContext parent) {
super(parent);
}
/**
* Create a new MergeClassPathXMLApplicationContext, loading the definitions from the given files. Note,
* all sourceLocation files will be merged using standard Spring configuration override rules. However, the patch
* files are fully merged into the result of the sourceLocations simple merge. Patch merges are first executed according
* to beans with the same id. Subsequent merges within a bean are executed against tagnames - ignoring any
* further id attributes.
*
* @param sourceLocations array of absolute file system paths for the source application context files
* @param patchLocations array of absolute file system paths for the patch application context files
* @throws BeansException
*/
public MergeFileSystemXMLApplicationContext(String[] sourceLocations, String[] patchLocations) throws BeansException {
this(sourceLocations, patchLocations, null);
}
/**
* Create a new MergeClassPathXMLApplicationContext, loading the definitions from the given files. Note,
* all sourceLocation files will be merged using standard Spring configuration override rules. However, the patch
* files are fully merged into the result of the sourceLocations simple merge. Patch merges are first executed according
* to beans with the same id. Subsequent merges within a bean are executed against tagnames - ignoring any
* further id attributes.
*
* @param sourceLocations array of absolute file system paths for the source application context files
* @param patchLocations array of absolute file system paths for the patch application context files
* @param parent the parent context
* @throws BeansException
*/
public MergeFileSystemXMLApplicationContext(String[] sourceLocations, String[] patchLocations, ApplicationContext parent) throws BeansException {
this(parent);
ResourceInputStream[] sources;
ResourceInputStream[] patches;
try {
sources = new ResourceInputStream[sourceLocations.length];
for (int j=0;j<sourceLocations.length;j++){
File temp = new File(sourceLocations[j]);
sources[j] = new ResourceInputStream(new BufferedInputStream(new FileInputStream(temp)), sourceLocations[j]);
}
patches = new ResourceInputStream[patchLocations.length];
for (int j=0;j<patches.length;j++){
File temp = new File(patchLocations[j]);
sources[j] = new ResourceInputStream(new BufferedInputStream(new FileInputStream(temp)), patchLocations[j]);
}
} catch (FileNotFoundException e) {
throw new FatalBeanException("Unable to merge context files", e);
}
ImportProcessor importProcessor = new ImportProcessor(this);
try {
sources = importProcessor.extract(sources);
patches = importProcessor.extract(patches);
} catch (MergeException e) {
throw new FatalBeanException("Unable to merge source and patch locations", e);
}
this.configResources = new MergeApplicationContextXmlConfigResource().getConfigResources(sources, patches);
refresh();
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_MergeFileSystemXMLApplicationContext.java
|
1,119 |
public static class Results {
public static final String TIME_PER_DOCIN_MILLIS = "timePerDocinMillis";
public static final String NUM_TERMS = "numTerms";
public static final String NUM_DOCS = "numDocs";
public static final String TIME_PER_QUERY_IN_SEC = "timePerQueryInSec";
public static final String TOTAL_TIME_IN_SEC = "totalTimeInSec";
Double[] resultSeconds;
Double[] resultMSPerQuery;
Long[] numDocs;
Integer[] numTerms;
Double[] timePerDoc;
String label;
String description;
public String lineStyle;
public String color;
void init(int numVariations, String label, String description, String color, String lineStyle) {
resultSeconds = new Double[numVariations];
resultMSPerQuery = new Double[numVariations];
numDocs = new Long[numVariations];
numTerms = new Integer[numVariations];
timePerDoc = new Double[numVariations];
this.label = label;
this.description = description;
this.color = color;
this.lineStyle = lineStyle;
}
void set(SearchResponse searchResponse, StopWatch stopWatch, String message, int maxIter, int which, int numTerms) {
resultSeconds[which] = (double) ((double) stopWatch.lastTaskTime().getMillis() / (double) 1000);
resultMSPerQuery[which] = (double) ((double) stopWatch.lastTaskTime().secondsFrac() / (double) maxIter);
numDocs[which] = searchResponse.getHits().totalHits();
this.numTerms[which] = numTerms;
timePerDoc[which] = resultMSPerQuery[which] / numDocs[which];
}
public void printResults(BufferedWriter writer) throws IOException {
String comma = (writer == null) ? "" : ";";
String results = description + "\n" + Results.TOTAL_TIME_IN_SEC + " = " + getResultArray(resultSeconds) + comma + "\n"
+ Results.TIME_PER_QUERY_IN_SEC + " = " + getResultArray(resultMSPerQuery) + comma + "\n" + Results.NUM_DOCS + " = "
+ getResultArray(numDocs) + comma + "\n" + Results.NUM_TERMS + " = " + getResultArray(numTerms) + comma + "\n"
+ Results.TIME_PER_DOCIN_MILLIS + " = " + getResultArray(timePerDoc) + comma + "\n";
if (writer != null) {
writer.write(results);
} else {
System.out.println(results);
}
}
private String getResultArray(Object[] resultArray) {
String result = "[";
for (int i = 0; i < resultArray.length; i++) {
result += resultArray[i].toString();
if (i != resultArray.length - 1) {
result += ",";
}
}
result += "]";
return result;
}
}
| 0true
|
src_test_java_org_elasticsearch_benchmark_scripts_score_BasicScriptBenchmark.java
|
256 |
public interface EmailTracking extends Serializable {
public abstract Long getId();
public abstract void setId(Long id);
/**
* @return the emailAddress
*/
public abstract String getEmailAddress();
/**
* @param emailAddress the emailAddress to set
*/
public abstract void setEmailAddress(String emailAddress);
/**
* @return the dateSent
*/
public abstract Date getDateSent();
/**
* @param dateSent the dateSent to set
*/
public abstract void setDateSent(Date dateSent);
/**
* @return the type
*/
public abstract String getType();
/**
* @param type the type to set
*/
public abstract void setType(String type);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_email_domain_EmailTracking.java
|
129 |
class InferTypeVisitor extends Visitor {
Unit unit;
Declaration dec;
InferredType result;
InferTypeVisitor(Unit unit) {
this.unit = unit;
result = new InferredType(unit);
}
@Override public void visit(Tree.AttributeDeclaration that) {
super.visit(that);
//TODO: an assignment to something with an inferred
// type doesn't _directly_ constrain the type
// ... but _indirectly_ it can!
// if (!(that.getType() instanceof Tree.LocalModifier)) {
Term term = that.getSpecifierOrInitializerExpression()==null ?
null : that.getSpecifierOrInitializerExpression().getExpression().getTerm();
if (term instanceof Tree.BaseMemberExpression) {
Declaration d = ((Tree.BaseMemberExpression) term).getDeclaration();
if (d!=null && d.equals(dec)) {
result.intersect(that.getType().getTypeModel());
}
}
else if (term!=null) {
if (that.getDeclarationModel().equals(dec)) {
result.union(term.getTypeModel());
}
}
// }
}
@Override public void visit(Tree.MethodDeclaration that) {
super.visit(that);
//TODO: an assignment to something with an inferred
// type doesn't _directly_ constrain the type
// ... but _indirectly_ it can!
// if (!(that.getType() instanceof Tree.LocalModifier)) {
Term term = that.getSpecifierExpression()==null ?
null : that.getSpecifierExpression().getExpression().getTerm();
if (term instanceof Tree.BaseMemberExpression) {
Declaration d = ((Tree.BaseMemberExpression) term).getDeclaration();
if (d!=null && d.equals(dec)) {
result.intersect(that.getType().getTypeModel());
}
}
else if (term!=null) {
if (that.getDeclarationModel().equals(dec)) {
result.union(term.getTypeModel());
}
}
// }
}
@Override public void visit(Tree.SpecifierStatement that) {
super.visit(that);
Tree.Term bme = that.getBaseMemberExpression();
Term term = that.getSpecifierExpression()==null ?
null : that.getSpecifierExpression().getExpression().getTerm();
if (bme instanceof Tree.BaseMemberExpression) {
Declaration d = ((Tree.BaseMemberExpression) bme).getDeclaration();
if (d!=null && d.equals(dec)) {
if (term!=null)
result.union(term.getTypeModel());
}
}
if (term instanceof Tree.BaseMemberExpression) {
Declaration d = ((Tree.BaseMemberExpression) term).getDeclaration();
if (d!=null && d.equals(dec)) {
if (bme!=null)
result.intersect(bme.getTypeModel());
}
}
}
@Override public void visit(Tree.AssignmentOp that) {
super.visit(that);
Term rt = that.getRightTerm();
Term lt = that.getLeftTerm();
if (lt instanceof Tree.BaseMemberExpression) {
if (((Tree.BaseMemberExpression) lt).getDeclaration().equals(dec)) {
if (rt!=null)
result.union(rt.getTypeModel());
}
}
if (rt instanceof Tree.BaseMemberExpression) {
if (((Tree.BaseMemberExpression) rt).getDeclaration().equals(dec)) {
if (lt!=null)
result.intersect(lt.getTypeModel());
}
}
}
private ProducedReference pr;
@Override public void visit(Tree.InvocationExpression that) {
ProducedReference opr=null;
Tree.Primary primary = that.getPrimary();
if (primary!=null) {
if (primary instanceof Tree.MemberOrTypeExpression) {
pr = ((Tree.MemberOrTypeExpression) primary).getTarget();
}
}
super.visit(that);
pr = opr;
}
@Override public void visit(Tree.ListedArgument that) {
super.visit(that);
Tree.Term t = that.getExpression().getTerm();
if (t instanceof Tree.BaseMemberExpression) {
Tree.BaseMemberExpression bme = (Tree.BaseMemberExpression) t;
Declaration d = bme.getDeclaration();
if (d!=null && d.equals(dec)) {
Parameter p = that.getParameter();
if (p!=null && pr!=null) {
ProducedType ft = pr.getTypedParameter(p)
.getFullType();
if (p.isSequenced()) {
ft = unit.getIteratedType(ft);
}
result.intersect(ft);
}
}
}
}
@Override public void visit(Tree.SpreadArgument that) {
super.visit(that);
Tree.Term t = that.getExpression().getTerm();
if (t instanceof Tree.BaseMemberExpression) {
Tree.BaseMemberExpression bme = (Tree.BaseMemberExpression) t;
Declaration d = bme.getDeclaration();
if (d!=null && d.equals(dec)) {
Parameter p = that.getParameter();
if (p!=null && pr!=null) {
//TODO: is this correct?
ProducedType ft = pr.getTypedParameter(p)
.getFullType();
result.intersect(unit.getIterableType(unit.getIteratedType(ft)));
}
}
}
}
@Override public void visit(Tree.SpecifiedArgument that) {
super.visit(that);
Tree.Term t = that.getSpecifierExpression().getExpression().getTerm();
if (t instanceof Tree.BaseMemberExpression) {
Tree.BaseMemberExpression bme = (Tree.BaseMemberExpression) t;
Declaration d = bme.getDeclaration();
if (d!=null && d.equals(dec)) {
Parameter p = that.getParameter();
if (p!=null && pr!=null) {
ProducedType ft = pr.getTypedParameter(p)
.getFullType();
result.intersect(ft);
}
}
}
}
@Override public void visit(Tree.Return that) {
super.visit(that);
Tree.Term bme = that.getExpression().getTerm();
if (bme instanceof Tree.BaseMemberExpression) {
Declaration bmed = ((Tree.BaseMemberExpression) bme).getDeclaration();
if (bmed!=null && bmed.equals(dec)) {
Declaration d = that.getDeclaration();
if (d instanceof TypedDeclaration) {
result.intersect(((TypedDeclaration) d).getType());
}
}
}
else if (bme!=null) {
if (that.getDeclaration().equals(dec)) {
result.union(bme.getTypeModel());
}
}
}
@Override
public void visit(Tree.QualifiedMemberOrTypeExpression that) {
super.visit(that);
Tree.Primary primary = that.getPrimary();
if (primary instanceof Tree.BaseMemberExpression) {
Declaration bmed = ((Tree.BaseMemberExpression) primary).getDeclaration();
if (bmed!=null && bmed.equals(dec)) {
TypeDeclaration td = (TypeDeclaration) that.getDeclaration().getRefinedDeclaration().getContainer();
result.intersect(that.getTarget().getQualifyingType().getSupertype(td));
}
}
}
@Override
public void visit(Tree.KeyValueIterator that) {
super.visit(that);
Tree.Term primary = that.getSpecifierExpression().getExpression().getTerm();
if (primary instanceof Tree.BaseMemberExpression) {
Declaration bmed = ((Tree.BaseMemberExpression) primary).getDeclaration();
if (bmed!=null && bmed.equals(dec)) {
ProducedType kt = that.getKeyVariable().getType().getTypeModel();
ProducedType vt = that.getValueVariable().getType().getTypeModel();
result.intersect(that.getUnit().getIterableType(that.getUnit().getEntryType(kt, vt)));
}
}
}
@Override
public void visit(Tree.ValueIterator that) {
super.visit(that);
Tree.Term primary = that.getSpecifierExpression().getExpression().getTerm();
if (primary instanceof Tree.BaseMemberExpression) {
Declaration bmed = ((Tree.BaseMemberExpression) primary).getDeclaration();
if (bmed!=null && bmed.equals(dec)) {
ProducedType vt = that.getVariable().getType().getTypeModel();
result.intersect(that.getUnit().getIterableType(vt));
}
}
}
@Override
public void visit(Tree.BooleanCondition that) {
super.visit(that);
Tree.Term primary = that.getExpression().getTerm();
if (primary instanceof Tree.BaseMemberExpression) {
Declaration bmed = ((Tree.BaseMemberExpression) primary).getDeclaration();
if (bmed!=null && bmed.equals(dec)) {
result.intersect(that.getUnit().getBooleanDeclaration().getType());
}
}
}
@Override
public void visit(Tree.NonemptyCondition that) {
super.visit(that);
Tree.Term primary = that.getVariable().getSpecifierExpression().getExpression().getTerm();
if (primary instanceof Tree.BaseMemberExpression) {
Declaration bmed = ((Tree.BaseMemberExpression) primary).getDeclaration();
if (bmed!=null && bmed.equals(dec)) {
ProducedType et = that.getUnit().getSequentialElementType(that.getVariable().getType().getTypeModel());
result.intersect(that.getUnit().getSequentialType(et));
}
}
}
@Override
public void visit(Tree.ArithmeticOp that) {
super.visit(that);
Interface sd = getArithmeticDeclaration(that);
genericOperatorTerm(sd, that.getLeftTerm());
genericOperatorTerm(sd, that.getRightTerm());
}
@Override
public void visit(Tree.NegativeOp that) {
super.visit(that);
Interface sd = unit.getInvertableDeclaration();
genericOperatorTerm(sd, that.getTerm());
}
@Override
public void visit(Tree.PrefixOperatorExpression that) {
super.visit(that);
Interface sd = unit.getOrdinalDeclaration();
genericOperatorTerm(sd, that.getTerm());
}
@Override
public void visit(Tree.PostfixOperatorExpression that) {
super.visit(that);
Interface sd = unit.getOrdinalDeclaration();
genericOperatorTerm(sd, that.getTerm());
}
@Override
public void visit(Tree.BitwiseOp that) {
super.visit(that);
Interface sd = unit.getSetDeclaration();
genericOperatorTerm(sd, that.getLeftTerm());
genericOperatorTerm(sd, that.getRightTerm());
}
@Override
public void visit(Tree.ComparisonOp that) {
super.visit(that);
Interface sd = unit.getComparableDeclaration();
genericOperatorTerm(sd, that.getLeftTerm());
genericOperatorTerm(sd, that.getRightTerm());
}
@Override
public void visit(Tree.CompareOp that) {
super.visit(that);
Interface sd = unit.getComparableDeclaration();
genericOperatorTerm(sd, that.getLeftTerm());
genericOperatorTerm(sd, that.getRightTerm());
}
@Override
public void visit(Tree.LogicalOp that) {
super.visit(that);
TypeDeclaration sd = unit.getBooleanDeclaration();
operatorTerm(sd, that.getLeftTerm());
operatorTerm(sd, that.getRightTerm());
}
@Override
public void visit(Tree.NotOp that) {
super.visit(that);
TypeDeclaration sd = unit.getBooleanDeclaration();
operatorTerm(sd, that.getTerm());
}
@Override
public void visit(Tree.EntryOp that) {
super.visit(that);
TypeDeclaration sd = unit.getObjectDeclaration();
operatorTerm(sd, that.getLeftTerm());
operatorTerm(sd, that.getRightTerm());
}
private Interface getArithmeticDeclaration(Tree.ArithmeticOp that) {
if (that instanceof Tree.PowerOp) {
return unit.getExponentiableDeclaration();
}
else if (that instanceof Tree.SumOp) {
return unit.getSummableDeclaration();
}
else if (that instanceof Tree.DifferenceOp) {
return unit.getInvertableDeclaration();
}
else if (that instanceof Tree.RemainderOp) {
return unit.getIntegralDeclaration();
}
else {
return unit.getNumericDeclaration();
}
}
public void operatorTerm(TypeDeclaration sd, Tree.Term lhs) {
if (lhs instanceof Tree.BaseMemberExpression) {
Declaration bmed = ((Tree.BaseMemberExpression) lhs).getDeclaration();
if (bmed!=null && bmed.equals(dec)) {
result.intersect(sd.getType());
}
}
}
public void genericOperatorTerm(TypeDeclaration sd, Tree.Term lhs) {
if (lhs instanceof Tree.BaseMemberExpression) {
Declaration bmed = ((Tree.BaseMemberExpression) lhs).getDeclaration();
if (bmed!=null && bmed.equals(dec)) {
result.intersect(lhs.getTypeModel().getSupertype(sd).getTypeArguments().get(0));
}
}
}
//TODO: more operator expressions!
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_InferTypeVisitor.java
|
1,460 |
public static class Delta {
private final String localNodeId;
private final DiscoveryNode previousMasterNode;
private final DiscoveryNode newMasterNode;
private final ImmutableList<DiscoveryNode> removed;
private final ImmutableList<DiscoveryNode> added;
public Delta(String localNodeId, ImmutableList<DiscoveryNode> removed, ImmutableList<DiscoveryNode> added) {
this(null, null, localNodeId, removed, added);
}
public Delta(@Nullable DiscoveryNode previousMasterNode, @Nullable DiscoveryNode newMasterNode, String localNodeId, ImmutableList<DiscoveryNode> removed, ImmutableList<DiscoveryNode> added) {
this.previousMasterNode = previousMasterNode;
this.newMasterNode = newMasterNode;
this.localNodeId = localNodeId;
this.removed = removed;
this.added = added;
}
public boolean hasChanges() {
return masterNodeChanged() || !removed.isEmpty() || !added.isEmpty();
}
public boolean masterNodeChanged() {
return newMasterNode != null;
}
public DiscoveryNode previousMasterNode() {
return previousMasterNode;
}
public DiscoveryNode newMasterNode() {
return newMasterNode;
}
public boolean removed() {
return !removed.isEmpty();
}
public ImmutableList<DiscoveryNode> removedNodes() {
return removed;
}
public boolean added() {
return !added.isEmpty();
}
public ImmutableList<DiscoveryNode> addedNodes() {
return added;
}
public String shortSummary() {
StringBuilder sb = new StringBuilder();
if (!removed() && masterNodeChanged()) {
if (newMasterNode.id().equals(localNodeId)) {
// we are the master, no nodes we removed, we are actually the first master
sb.append("new_master ").append(newMasterNode());
} else {
// we are not the master, so we just got this event. No nodes were removed, so its not a *new* master
sb.append("detected_master ").append(newMasterNode());
}
} else {
if (masterNodeChanged()) {
sb.append("master {new ").append(newMasterNode());
if (previousMasterNode() != null) {
sb.append(", previous ").append(previousMasterNode());
}
sb.append("}");
}
if (removed()) {
if (masterNodeChanged()) {
sb.append(", ");
}
sb.append("removed {");
for (DiscoveryNode node : removedNodes()) {
sb.append(node).append(',');
}
sb.append("}");
}
}
if (added()) {
// don't print if there is one added, and it is us
if (!(addedNodes().size() == 1 && addedNodes().get(0).id().equals(localNodeId))) {
if (removed() || masterNodeChanged()) {
sb.append(", ");
}
sb.append("added {");
for (DiscoveryNode node : addedNodes()) {
if (!node.id().equals(localNodeId)) {
// don't print ourself
sb.append(node).append(',');
}
}
sb.append("}");
}
}
return sb.toString();
}
}
| 0true
|
src_main_java_org_elasticsearch_cluster_node_DiscoveryNodes.java
|
125 |
final EntryAdapter<String, String> listener = new EntryAdapter<String, String>() {
public void onEntryEvent(EntryEvent<String, String> event) {
latch.countDown();
}
};
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_ClientReconnectTest.java
|
357 |
public class NodesStatsRequest extends NodesOperationRequest<NodesStatsRequest> {
private CommonStatsFlags indices = new CommonStatsFlags();
private boolean os;
private boolean process;
private boolean jvm;
private boolean threadPool;
private boolean network;
private boolean fs;
private boolean transport;
private boolean http;
private boolean breaker;
protected NodesStatsRequest() {
}
/**
* Get stats from nodes based on the nodes ids specified. If none are passed, stats
* for all nodes will be returned.
*/
public NodesStatsRequest(String... nodesIds) {
super(nodesIds);
}
/**
* Sets all the request flags.
*/
public NodesStatsRequest all() {
this.indices.all();
this.os = true;
this.process = true;
this.jvm = true;
this.threadPool = true;
this.network = true;
this.fs = true;
this.transport = true;
this.http = true;
this.breaker = true;
return this;
}
/**
* Clears all the request flags.
*/
public NodesStatsRequest clear() {
this.indices.clear();
this.os = false;
this.process = false;
this.jvm = false;
this.threadPool = false;
this.network = false;
this.fs = false;
this.transport = false;
this.http = false;
this.breaker = false;
return this;
}
public CommonStatsFlags indices() {
return indices;
}
public NodesStatsRequest indices(CommonStatsFlags indices) {
this.indices = indices;
return this;
}
/**
* Should indices stats be returned.
*/
public NodesStatsRequest indices(boolean indices) {
if (indices) {
this.indices.all();
} else {
this.indices.clear();
}
return this;
}
/**
* Should the node OS be returned.
*/
public boolean os() {
return this.os;
}
/**
* Should the node OS be returned.
*/
public NodesStatsRequest os(boolean os) {
this.os = os;
return this;
}
/**
* Should the node Process be returned.
*/
public boolean process() {
return this.process;
}
/**
* Should the node Process be returned.
*/
public NodesStatsRequest process(boolean process) {
this.process = process;
return this;
}
/**
* Should the node JVM be returned.
*/
public boolean jvm() {
return this.jvm;
}
/**
* Should the node JVM be returned.
*/
public NodesStatsRequest jvm(boolean jvm) {
this.jvm = jvm;
return this;
}
/**
* Should the node Thread Pool be returned.
*/
public boolean threadPool() {
return this.threadPool;
}
/**
* Should the node Thread Pool be returned.
*/
public NodesStatsRequest threadPool(boolean threadPool) {
this.threadPool = threadPool;
return this;
}
/**
* Should the node Network be returned.
*/
public boolean network() {
return this.network;
}
/**
* Should the node Network be returned.
*/
public NodesStatsRequest network(boolean network) {
this.network = network;
return this;
}
/**
* Should the node file system stats be returned.
*/
public boolean fs() {
return this.fs;
}
/**
* Should the node file system stats be returned.
*/
public NodesStatsRequest fs(boolean fs) {
this.fs = fs;
return this;
}
/**
* Should the node Transport be returned.
*/
public boolean transport() {
return this.transport;
}
/**
* Should the node Transport be returned.
*/
public NodesStatsRequest transport(boolean transport) {
this.transport = transport;
return this;
}
/**
* Should the node HTTP be returned.
*/
public boolean http() {
return this.http;
}
/**
* Should the node HTTP be returned.
*/
public NodesStatsRequest http(boolean http) {
this.http = http;
return this;
}
public boolean breaker() {
return this.breaker;
}
/**
* Should the node's circuit breaker stats be returned.
*/
public NodesStatsRequest breaker(boolean breaker) {
this.breaker = breaker;
return this;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
indices = CommonStatsFlags.readCommonStatsFlags(in);
os = in.readBoolean();
process = in.readBoolean();
jvm = in.readBoolean();
threadPool = in.readBoolean();
network = in.readBoolean();
fs = in.readBoolean();
transport = in.readBoolean();
http = in.readBoolean();
breaker = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
indices.writeTo(out);
out.writeBoolean(os);
out.writeBoolean(process);
out.writeBoolean(jvm);
out.writeBoolean(threadPool);
out.writeBoolean(network);
out.writeBoolean(fs);
out.writeBoolean(transport);
out.writeBoolean(http);
out.writeBoolean(breaker);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_stats_NodesStatsRequest.java
|
2,441 |
public class EsExecutors {
/**
* Returns the number of processors available but at most <tt>32</tt>.
*/
public static int boundedNumberOfProcessors(Settings settings) {
/* This relates to issues where machines with large number of cores
* ie. >= 48 create too many threads and run into OOM see #3478
* We just use an 32 core upper-bound here to not stress the system
* too much with too many created threads */
return settings.getAsInt("processors", Math.min(32, Runtime.getRuntime().availableProcessors()));
}
public static PrioritizedEsThreadPoolExecutor newSinglePrioritizing(ThreadFactory threadFactory) {
return new PrioritizedEsThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, threadFactory);
}
public static EsThreadPoolExecutor newScaling(int min, int max, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) {
ExecutorScalingQueue<Runnable> queue = new ExecutorScalingQueue<Runnable>();
// we force the execution, since we might run into concurrency issues in offer for ScalingBlockingQueue
EsThreadPoolExecutor executor = new EsThreadPoolExecutor(min, max, keepAliveTime, unit, queue, threadFactory, new ForceQueuePolicy());
queue.executor = executor;
return executor;
}
public static EsThreadPoolExecutor newCached(long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) {
return new EsThreadPoolExecutor(0, Integer.MAX_VALUE, keepAliveTime, unit, new SynchronousQueue<Runnable>(), threadFactory, new EsAbortPolicy());
}
public static EsThreadPoolExecutor newFixed(int size, int queueCapacity, ThreadFactory threadFactory) {
BlockingQueue<Runnable> queue;
if (queueCapacity < 0) {
queue = ConcurrentCollections.newBlockingQueue();
} else {
queue = new SizeBlockingQueue<Runnable>(ConcurrentCollections.<Runnable>newBlockingQueue(), queueCapacity);
}
return new EsThreadPoolExecutor(size, size, 0, TimeUnit.MILLISECONDS, queue, threadFactory, new EsAbortPolicy());
}
public static String threadName(Settings settings, String namePrefix) {
String name = settings.get("name");
if (name == null) {
name = "elasticsearch";
} else {
name = "elasticsearch[" + name + "]";
}
return name + "[" + namePrefix + "]";
}
public static ThreadFactory daemonThreadFactory(Settings settings, String namePrefix) {
return daemonThreadFactory(threadName(settings, namePrefix));
}
public static ThreadFactory daemonThreadFactory(String namePrefix) {
return new EsThreadFactory(namePrefix);
}
static class EsThreadFactory implements ThreadFactory {
final ThreadGroup group;
final AtomicInteger threadNumber = new AtomicInteger(1);
final String namePrefix;
public EsThreadFactory(String namePrefix) {
this.namePrefix = namePrefix;
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + "[T#" + threadNumber.getAndIncrement() + "]",
0);
t.setDaemon(true);
return t;
}
}
/**
* Cannot instantiate.
*/
private EsExecutors() {
}
static class ExecutorScalingQueue<E> extends LinkedTransferQueue<E> {
ThreadPoolExecutor executor;
public ExecutorScalingQueue() {
}
@Override
public boolean offer(E e) {
if (!tryTransfer(e)) {
int left = executor.getMaximumPoolSize() - executor.getCorePoolSize();
if (left > 0) {
return false;
} else {
return super.offer(e);
}
} else {
return true;
}
}
}
/**
* A handler for rejected tasks that adds the specified element to this queue,
* waiting if necessary for space to become available.
*/
static class ForceQueuePolicy implements XRejectedExecutionHandler {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
//should never happen since we never wait
throw new EsRejectedExecutionException(e);
}
}
@Override
public long rejected() {
return 0;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_common_util_concurrent_EsExecutors.java
|
1,362 |
@ClusterScope(scope=Scope.TEST, numNodes=0)
public class AwarenessAllocationTests extends ElasticsearchIntegrationTest {
private final ESLogger logger = Loggers.getLogger(AwarenessAllocationTests.class);
@Test
public void testSimpleAwareness() throws Exception {
Settings commonSettings = ImmutableSettings.settingsBuilder()
.put("cluster.routing.schedule", "10ms")
.put("cluster.routing.allocation.awareness.attributes", "rack_id")
.build();
logger.info("--> starting 2 nodes on the same rack");
cluster().startNode(ImmutableSettings.settingsBuilder().put(commonSettings).put("node.rack_id", "rack_1").build());
cluster().startNode(ImmutableSettings.settingsBuilder().put(commonSettings).put("node.rack_id", "rack_1").build());
createIndex("test1");
createIndex("test2");
ClusterHealthResponse health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet();
assertThat(health.isTimedOut(), equalTo(false));
logger.info("--> starting 1 node on a different rack");
String node3 = cluster().startNode(ImmutableSettings.settingsBuilder().put(commonSettings).put("node.rack_id", "rack_2").build());
long start = System.currentTimeMillis();
ObjectIntOpenHashMap<String> counts;
// On slow machines the initial relocation might be delayed
do {
Thread.sleep(100);
logger.info("--> waiting for no relocation");
health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("3").setWaitForRelocatingShards(0).execute().actionGet();
assertThat(health.isTimedOut(), equalTo(false));
logger.info("--> checking current state");
ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
//System.out.println(clusterState.routingTable().prettyPrint());
// verify that we have 10 shards on node3
counts = new ObjectIntOpenHashMap<String>();
for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
for (ShardRouting shardRouting : indexShardRoutingTable) {
counts.addTo(clusterState.nodes().get(shardRouting.currentNodeId()).name(), 1);
}
}
}
} while (counts.get(node3) != 10 && (System.currentTimeMillis() - start) < 10000);
assertThat(counts.get(node3), equalTo(10));
}
@Test
@Slow
public void testAwarenessZones() throws InterruptedException {
Settings commonSettings = ImmutableSettings.settingsBuilder()
.put("cluster.routing.allocation.awareness.force.zone.values", "a,b")
.put("cluster.routing.allocation.awareness.attributes", "zone")
.build();
logger.info("--> starting 6 nodes on different zones");
String A_0 = cluster().startNode(ImmutableSettings.settingsBuilder().put(commonSettings).put("node.zone", "a").build());
String B_0 = cluster().startNode(ImmutableSettings.settingsBuilder().put(commonSettings).put("node.zone", "b").build());
String B_1 = cluster().startNode(ImmutableSettings.settingsBuilder().put(commonSettings).put("node.zone", "b").build());
String A_1 = cluster().startNode(ImmutableSettings.settingsBuilder().put(commonSettings).put("node.zone", "a").build());
client().admin().indices().prepareCreate("test")
.setSettings(settingsBuilder().put("index.number_of_shards", 5)
.put("index.number_of_replicas", 1)).execute().actionGet();
ClusterHealthResponse health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("4").setWaitForRelocatingShards(0).execute().actionGet();
assertThat(health.isTimedOut(), equalTo(false));
ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
ObjectIntOpenHashMap<String> counts = new ObjectIntOpenHashMap<String>();
for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
for (ShardRouting shardRouting : indexShardRoutingTable) {
counts.addTo(clusterState.nodes().get(shardRouting.currentNodeId()).name(), 1);
}
}
}
assertThat(counts.get(A_1), anyOf(equalTo(2),equalTo(3)));
assertThat(counts.get(B_1), anyOf(equalTo(2),equalTo(3)));
assertThat(counts.get(A_0), anyOf(equalTo(2),equalTo(3)));
assertThat(counts.get(B_0), anyOf(equalTo(2),equalTo(3)));
}
@Test
@Slow
public void testAwarenessZonesIncrementalNodes() throws InterruptedException {
Settings commonSettings = ImmutableSettings.settingsBuilder()
.put("cluster.routing.allocation.awareness.force.zone.values", "a,b")
.put("cluster.routing.allocation.awareness.attributes", "zone")
.build();
logger.info("--> starting 2 nodes on zones 'a' & 'b'");
String A_0 = cluster().startNode(ImmutableSettings.settingsBuilder().put(commonSettings).put("node.zone", "a").build());
String B_0 = cluster().startNode(ImmutableSettings.settingsBuilder().put(commonSettings).put("node.zone", "b").build());
client().admin().indices().prepareCreate("test")
.setSettings(settingsBuilder().put("index.number_of_shards", 5)
.put("index.number_of_replicas", 1)).execute().actionGet();
ClusterHealthResponse health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("2").setWaitForRelocatingShards(0).execute().actionGet();
assertThat(health.isTimedOut(), equalTo(false));
ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
ObjectIntOpenHashMap<String> counts = new ObjectIntOpenHashMap<String>();
for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
for (ShardRouting shardRouting : indexShardRoutingTable) {
counts.addTo(clusterState.nodes().get(shardRouting.currentNodeId()).name(), 1);
}
}
}
assertThat(counts.get(A_0), equalTo(5));
assertThat(counts.get(B_0), equalTo(5));
logger.info("--> starting another node in zone 'b'");
String B_1 = cluster().startNode(ImmutableSettings.settingsBuilder().put(commonSettings).put("node.zone", "b").build());
health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("3").execute().actionGet();
assertThat(health.isTimedOut(), equalTo(false));
client().admin().cluster().prepareReroute().get();
health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("3").setWaitForActiveShards(10).setWaitForRelocatingShards(0).execute().actionGet();
assertThat(health.isTimedOut(), equalTo(false));
clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
counts = new ObjectIntOpenHashMap<String>();
for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
for (ShardRouting shardRouting : indexShardRoutingTable) {
counts.addTo(clusterState.nodes().get(shardRouting.currentNodeId()).name(), 1);
}
}
}
assertThat(counts.get(A_0), equalTo(5));
assertThat(counts.get(B_0), equalTo(3));
assertThat(counts.get(B_1), equalTo(2));
String noZoneNode = cluster().startNode();
health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("4").execute().actionGet();
assertThat(health.isTimedOut(), equalTo(false));
client().admin().cluster().prepareReroute().get();
health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("4").setWaitForActiveShards(10).setWaitForRelocatingShards(0).execute().actionGet();
assertThat(health.isTimedOut(), equalTo(false));
clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
counts = new ObjectIntOpenHashMap<String>();
for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
for (ShardRouting shardRouting : indexShardRoutingTable) {
counts.addTo(clusterState.nodes().get(shardRouting.currentNodeId()).name(), 1);
}
}
}
assertThat(counts.get(A_0), equalTo(5));
assertThat(counts.get(B_0), equalTo(3));
assertThat(counts.get(B_1), equalTo(2));
assertThat(counts.containsKey(noZoneNode), equalTo(false));
client().admin().cluster().prepareUpdateSettings().setTransientSettings(ImmutableSettings.settingsBuilder().put("cluster.routing.allocation.awareness.attributes", "").build()).get();
health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("4").setWaitForActiveShards(10).setWaitForRelocatingShards(0).execute().actionGet();
assertThat(health.isTimedOut(), equalTo(false));
clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
counts = new ObjectIntOpenHashMap<String>();
for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
for (ShardRouting shardRouting : indexShardRoutingTable) {
counts.addTo(clusterState.nodes().get(shardRouting.currentNodeId()).name(), 1);
}
}
}
assertThat(counts.get(A_0), equalTo(3));
assertThat(counts.get(B_0), equalTo(3));
assertThat(counts.get(B_1), equalTo(2));
assertThat(counts.get(noZoneNode), equalTo(2));
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_allocation_AwarenessAllocationTests.java
|
129 |
public interface OBinaryConverter {
void putInt(byte[] buffer, int index, int value, ByteOrder byteOrder);
int getInt(byte[] buffer, int index, ByteOrder byteOrder);
void putShort(byte[] buffer, int index, short value, ByteOrder byteOrder);
short getShort(byte[] buffer, int index, ByteOrder byteOrder);
void putLong(byte[] buffer, int index, long value, ByteOrder byteOrder);
long getLong(byte[] buffer, int index, ByteOrder byteOrder);
void putChar(byte[] buffer, int index, char character, ByteOrder byteOrder);
char getChar(byte[] buffer, int index, ByteOrder byteOrder);
boolean nativeAccelerationUsed();
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_serialization_OBinaryConverter.java
|
846 |
public class AtomicReferencePortableHook implements PortableHook {
static final int F_ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.ATOMIC_REFERENCE_PORTABLE_FACTORY, -21);
static final int GET = 1;
static final int SET = 2;
static final int GET_AND_SET = 3;
static final int IS_NULL = 4;
static final int COMPARE_AND_SET = 5;
static final int CONTAINS = 6;
static final int APPLY = 7;
static final int ALTER = 8;
static final int ALTER_AND_GET = 9;
static final int GET_AND_ALTER = 10;
public int getFactoryId() {
return F_ID;
}
public PortableFactory createFactory() {
return new PortableFactory() {
public Portable create(int classId) {
switch (classId) {
case GET:
return new GetRequest();
case SET:
return new SetRequest();
case GET_AND_SET:
return new GetAndSetRequest();
case IS_NULL:
return new IsNullRequest();
case COMPARE_AND_SET:
return new CompareAndSetRequest();
case CONTAINS:
return new ContainsRequest();
case APPLY:
return new ApplyRequest();
case ALTER:
return new AlterRequest();
case ALTER_AND_GET:
return new AlterAndGetRequest();
case GET_AND_ALTER:
return new GetAndAlterRequest();
default:
return null;
}
}
};
}
@Override
public Collection<ClassDefinition> getBuiltinDefinitions() {
return null;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_AtomicReferencePortableHook.java
|
101 |
public enum Text implements TitanPredicate {
/**
* Whether the text contains a given term as a token in the text (case insensitive)
*/
CONTAINS {
@Override
public boolean evaluate(Object value, Object condition) {
this.preevaluate(value,condition);
if (value == null) return false;
return evaluateRaw(value.toString(),(String)condition);
}
@Override
public boolean evaluateRaw(String value, String terms) {
Set<String> tokens = Sets.newHashSet(tokenize(value.toLowerCase()));
terms = terms.trim();
List<String> tokenTerms = tokenize(terms.toLowerCase());
if (!terms.isEmpty() && tokenTerms.isEmpty()) return false;
for (String term : tokenTerms) {
if (!tokens.contains(term)) return false;
}
return true;
}
@Override
public boolean isValidCondition(Object condition) {
if (condition == null) return false;
else if (condition instanceof String && StringUtils.isNotBlank((String) condition)) return true;
else return false;
}
},
/**
* Whether the text contains a token that starts with a given term (case insensitive)
*/
CONTAINS_PREFIX {
@Override
public boolean evaluate(Object value, Object condition) {
this.preevaluate(value,condition);
if (value == null) return false;
return evaluateRaw(value.toString(),(String)condition);
}
@Override
public boolean evaluateRaw(String value, String prefix) {
for (String token : tokenize(value.toLowerCase())) {
if (PREFIX.evaluateRaw(token,prefix.toLowerCase())) return true;
}
return false;
}
@Override
public boolean isValidCondition(Object condition) {
return condition != null && condition instanceof String;
}
},
/**
* Whether the text contains a token that matches a regular expression
*/
CONTAINS_REGEX {
@Override
public boolean evaluate(Object value, Object condition) {
this.preevaluate(value,condition);
if (value == null) return false;
return evaluateRaw(value.toString(),(String)condition);
}
@Override
public boolean evaluateRaw(String value, String regex) {
for (String token : tokenize(value.toLowerCase())) {
if (REGEX.evaluateRaw(token,regex)) return true;
}
return false;
}
@Override
public boolean isValidCondition(Object condition) {
return condition != null && condition instanceof String && StringUtils.isNotBlank(condition.toString());
}
},
/**
* Whether the text starts with a given prefix (case sensitive)
*/
PREFIX {
@Override
public boolean evaluate(Object value, Object condition) {
this.preevaluate(value,condition);
if (value==null) return false;
return evaluateRaw(value.toString(),(String)condition);
}
@Override
public boolean evaluateRaw(String value, String prefix) {
return value.startsWith(prefix.trim());
}
@Override
public boolean isValidCondition(Object condition) {
return condition != null && condition instanceof String;
}
},
/**
* Whether the text matches a regular expression (case sensitive)
*/
REGEX {
@Override
public boolean evaluate(Object value, Object condition) {
this.preevaluate(value,condition);
if (value == null) return false;
return evaluateRaw(value.toString(),(String)condition);
}
public boolean evaluateRaw(String value, String regex) {
return value.matches(regex);
}
@Override
public boolean isValidCondition(Object condition) {
return condition != null && condition instanceof String && StringUtils.isNotBlank(condition.toString());
}
};
private static final Logger log = LoggerFactory.getLogger(Text.class);
public void preevaluate(Object value, Object condition) {
Preconditions.checkArgument(this.isValidCondition(condition), "Invalid condition provided: %s", condition);
if (!(value instanceof String)) log.debug("Value not a string: " + value);
}
abstract boolean evaluateRaw(String value, String condition);
private static final int MIN_TOKEN_LENGTH = 1;
public static List<String> tokenize(String str) {
ArrayList<String> tokens = new ArrayList<String>();
int previous = 0;
for (int p = 0; p < str.length(); p++) {
if (!Character.isLetterOrDigit(str.charAt(p))) {
if (p > previous + MIN_TOKEN_LENGTH) tokens.add(str.substring(previous, p));
previous = p + 1;
}
}
if (previous + MIN_TOKEN_LENGTH < str.length()) tokens.add(str.substring(previous, str.length()));
return tokens;
}
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return clazz.equals(String.class);
}
@Override
public boolean hasNegation() {
return false;
}
@Override
public TitanPredicate negate() {
throw new UnsupportedOperationException();
}
@Override
public boolean isQNF() {
return true;
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Text.java
|
905 |
return new Iterator<Entry<String, Object>>() {
private Entry<String, Object> current;
public boolean hasNext() {
return iterator.hasNext();
}
public Entry<String, Object> next() {
current = iterator.next();
return current;
}
public void remove() {
iterator.remove();
if (_trackingChanges) {
// SAVE THE OLD VALUE IN A SEPARATE MAP
if (_fieldOriginalValues == null)
_fieldOriginalValues = new HashMap<String, Object>();
// INSERT IT ONLY IF NOT EXISTS TO AVOID LOOSE OF THE ORIGINAL VALUE (FUNDAMENTAL FOR INDEX HOOK)
if (!_fieldOriginalValues.containsKey(current.getKey())) {
_fieldOriginalValues.put(current.getKey(), current.getValue());
}
}
removeCollectionChangeListener(current.getKey());
removeCollectionTimeLine(current.getKey());
}
};
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocument.java
|
1,687 |
public class OAsyncCommandResultListener extends OAbstractCommandResultListener {
private final ONetworkProtocolBinary protocol;
private final AtomicBoolean empty = new AtomicBoolean(true);
private final int txId;
public OAsyncCommandResultListener(final ONetworkProtocolBinary iNetworkProtocolBinary, final int txId) {
this.protocol = iNetworkProtocolBinary;
this.txId = txId;
}
@Override
public boolean result(final Object iRecord) {
if (empty.compareAndSet(true, false))
try {
protocol.sendOk(txId);
} catch (IOException e1) {
}
try {
protocol.channel.writeByte((byte) 1); // ONE MORE RECORD
protocol.writeIdentifiable((ORecordInternal<?>) ((OIdentifiable) iRecord).getRecord());
fetchRecord(iRecord);
} catch (IOException e) {
return false;
}
return true;
}
public boolean isEmpty() {
return empty.get();
}
}
| 1no label
|
server_src_main_java_com_orientechnologies_orient_server_network_protocol_binary_OAsyncCommandResultListener.java
|
780 |
public class CollectionTxnRemoveBackupOperation extends CollectionOperation implements BackupOperation {
private long itemId;
public CollectionTxnRemoveBackupOperation() {
}
public CollectionTxnRemoveBackupOperation(String name, long itemId) {
super(name);
this.itemId = itemId;
}
@Override
public int getId() {
return CollectionDataSerializerHook.COLLECTION_TXN_REMOVE_BACKUP;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
getOrCreateContainer().commitRemoveBackup(itemId);
}
@Override
public void afterRun() throws Exception {
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeLong(itemId);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
itemId = in.readLong();
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_txn_CollectionTxnRemoveBackupOperation.java
|
638 |
@Component("blTranslationFilter")
public class TranslationFilter extends GenericFilterBean {
@Resource(name = "blTranslationRequestProcessor")
protected TranslationRequestProcessor translationRequestProcessor;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
try {
translationRequestProcessor.process(new ServletWebRequest((HttpServletRequest) request, (HttpServletResponse) response));
filterChain.doFilter(request, response);
} finally {
translationRequestProcessor.postProcess(new ServletWebRequest((HttpServletRequest) request, (HttpServletResponse) response));
}
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_web_filter_TranslationFilter.java
|
16 |
class CommandExecutor implements Runnable {
final TextCommand command;
CommandExecutor(TextCommand command) {
this.command = command;
}
@Override
public void run() {
try {
TextCommandType type = command.getType();
TextCommandProcessor textCommandProcessor = textCommandProcessors[type.getValue()];
textCommandProcessor.handle(command);
} catch (Throwable e) {
logger.warning(e);
}
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_ascii_TextCommandServiceImpl.java
|
1,236 |
public interface ClusterAdminClient {
<Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute(final ClusterAction<Request, Response, RequestBuilder> action, final Request request);
<Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute(final ClusterAction<Request, Response, RequestBuilder> action, final Request request, ActionListener<Response> listener);
<Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> RequestBuilder prepareExecute(final ClusterAction<Request, Response, RequestBuilder> action);
/**
* The health of the cluster.
*
* @param request The cluster state request
* @return The result future
* @see Requests#clusterHealthRequest(String...)
*/
ActionFuture<ClusterHealthResponse> health(ClusterHealthRequest request);
/**
* The health of the cluster.
*
* @param request The cluster state request
* @param listener A listener to be notified with a result
* @see Requests#clusterHealthRequest(String...)
*/
void health(ClusterHealthRequest request, ActionListener<ClusterHealthResponse> listener);
/**
* The health of the cluster.
*/
ClusterHealthRequestBuilder prepareHealth(String... indices);
/**
* The state of the cluster.
*
* @param request The cluster state request.
* @return The result future
* @see Requests#clusterStateRequest()
*/
ActionFuture<ClusterStateResponse> state(ClusterStateRequest request);
/**
* The state of the cluster.
*
* @param request The cluster state request.
* @param listener A listener to be notified with a result
* @see Requests#clusterStateRequest()
*/
void state(ClusterStateRequest request, ActionListener<ClusterStateResponse> listener);
/**
* The state of the cluster.
*/
ClusterStateRequestBuilder prepareState();
/**
* Updates settings in the cluster.
*/
ActionFuture<ClusterUpdateSettingsResponse> updateSettings(ClusterUpdateSettingsRequest request);
/**
* Update settings in the cluster.
*/
void updateSettings(ClusterUpdateSettingsRequest request, ActionListener<ClusterUpdateSettingsResponse> listener);
/**
* Update settings in the cluster.
*/
ClusterUpdateSettingsRequestBuilder prepareUpdateSettings();
/**
* Reroutes allocation of shards. Advance API.
*/
ActionFuture<ClusterRerouteResponse> reroute(ClusterRerouteRequest request);
/**
* Reroutes allocation of shards. Advance API.
*/
void reroute(ClusterRerouteRequest request, ActionListener<ClusterRerouteResponse> listener);
/**
* Update settings in the cluster.
*/
ClusterRerouteRequestBuilder prepareReroute();
/**
* Nodes info of the cluster.
*
* @param request The nodes info request
* @return The result future
* @see org.elasticsearch.client.Requests#nodesInfoRequest(String...)
*/
ActionFuture<NodesInfoResponse> nodesInfo(NodesInfoRequest request);
/**
* Nodes info of the cluster.
*
* @param request The nodes info request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#nodesInfoRequest(String...)
*/
void nodesInfo(NodesInfoRequest request, ActionListener<NodesInfoResponse> listener);
/**
* Nodes info of the cluster.
*/
NodesInfoRequestBuilder prepareNodesInfo(String... nodesIds);
/**
* Cluster wide aggregated stats.
*
* @param request The cluster stats request
* @return The result future
* @see org.elasticsearch.client.Requests#clusterStatsRequest
*/
ActionFuture<ClusterStatsResponse> clusterStats(ClusterStatsRequest request);
/**
* Cluster wide aggregated stats
*
* @param request The cluster stats request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#clusterStatsRequest()
*/
void clusterStats(ClusterStatsRequest request, ActionListener<ClusterStatsResponse> listener);
ClusterStatsRequestBuilder prepareClusterStats();
/**
* Nodes stats of the cluster.
*
* @param request The nodes stats request
* @return The result future
* @see org.elasticsearch.client.Requests#nodesStatsRequest(String...)
*/
ActionFuture<NodesStatsResponse> nodesStats(NodesStatsRequest request);
/**
* Nodes stats of the cluster.
*
* @param request The nodes info request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#nodesStatsRequest(String...)
*/
void nodesStats(NodesStatsRequest request, ActionListener<NodesStatsResponse> listener);
/**
* Nodes stats of the cluster.
*/
NodesStatsRequestBuilder prepareNodesStats(String... nodesIds);
ActionFuture<NodesHotThreadsResponse> nodesHotThreads(NodesHotThreadsRequest request);
void nodesHotThreads(NodesHotThreadsRequest request, ActionListener<NodesHotThreadsResponse> listener);
NodesHotThreadsRequestBuilder prepareNodesHotThreads(String... nodesIds);
/**
* Shutdown nodes in the cluster.
*
* @param request The nodes shutdown request
* @return The result future
* @see org.elasticsearch.client.Requests#nodesShutdownRequest(String...)
*/
ActionFuture<NodesShutdownResponse> nodesShutdown(NodesShutdownRequest request);
/**
* Shutdown nodes in the cluster.
*
* @param request The nodes shutdown request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#nodesShutdownRequest(String...)
*/
void nodesShutdown(NodesShutdownRequest request, ActionListener<NodesShutdownResponse> listener);
/**
* Shutdown nodes in the cluster.
*/
NodesShutdownRequestBuilder prepareNodesShutdown(String... nodesIds);
/**
* Restarts nodes in the cluster.
*
* @param request The nodes restart request
* @return The result future
* @see org.elasticsearch.client.Requests#nodesRestartRequest(String...)
*/
ActionFuture<NodesRestartResponse> nodesRestart(NodesRestartRequest request);
/**
* Restarts nodes in the cluster.
*
* @param request The nodes restart request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#nodesRestartRequest(String...)
*/
void nodesRestart(NodesRestartRequest request, ActionListener<NodesRestartResponse> listener);
/**
* Restarts nodes in the cluster.
*/
NodesRestartRequestBuilder prepareNodesRestart(String... nodesIds);
/**
* Returns list of shards the given search would be executed on.
*/
ActionFuture<ClusterSearchShardsResponse> searchShards(ClusterSearchShardsRequest request);
/**
* Returns list of shards the given search would be executed on.
*/
void searchShards(ClusterSearchShardsRequest request, ActionListener<ClusterSearchShardsResponse> listener);
/**
* Returns list of shards the given search would be executed on.
*/
ClusterSearchShardsRequestBuilder prepareSearchShards();
/**
* Returns list of shards the given search would be executed on.
*/
ClusterSearchShardsRequestBuilder prepareSearchShards(String... indices);
/**
* Registers a snapshot repository.
*/
ActionFuture<PutRepositoryResponse> putRepository(PutRepositoryRequest request);
/**
* Registers a snapshot repository.
*/
void putRepository(PutRepositoryRequest request, ActionListener<PutRepositoryResponse> listener);
/**
* Registers a snapshot repository.
*/
PutRepositoryRequestBuilder preparePutRepository(String name);
/**
* Unregisters a repository.
*/
ActionFuture<DeleteRepositoryResponse> deleteRepository(DeleteRepositoryRequest request);
/**
* Unregisters a repository.
*/
void deleteRepository(DeleteRepositoryRequest request, ActionListener<DeleteRepositoryResponse> listener);
/**
* Unregisters a repository.
*/
DeleteRepositoryRequestBuilder prepareDeleteRepository(String name);
/**
* Gets repositories.
*/
ActionFuture<GetRepositoriesResponse> getRepositories(GetRepositoriesRequest request);
/**
* Gets repositories.
*/
void getRepositories(GetRepositoriesRequest request, ActionListener<GetRepositoriesResponse> listener);
/**
* Gets repositories.
*/
GetRepositoriesRequestBuilder prepareGetRepositories(String... name);
/**
* Creates a new snapshot.
*/
ActionFuture<CreateSnapshotResponse> createSnapshot(CreateSnapshotRequest request);
/**
* Creates a new snapshot.
*/
void createSnapshot(CreateSnapshotRequest request, ActionListener<CreateSnapshotResponse> listener);
/**
* Creates a new snapshot.
*/
CreateSnapshotRequestBuilder prepareCreateSnapshot(String repository, String name);
/**
* Get snapshot.
*/
ActionFuture<GetSnapshotsResponse> getSnapshots(GetSnapshotsRequest request);
/**
* Get snapshot.
*/
void getSnapshots(GetSnapshotsRequest request, ActionListener<GetSnapshotsResponse> listener);
/**
* Get snapshot.
*/
GetSnapshotsRequestBuilder prepareGetSnapshots(String repository);
/**
* Delete snapshot.
*/
ActionFuture<DeleteSnapshotResponse> deleteSnapshot(DeleteSnapshotRequest request);
/**
* Delete snapshot.
*/
void deleteSnapshot(DeleteSnapshotRequest request, ActionListener<DeleteSnapshotResponse> listener);
/**
* Delete snapshot.
*/
DeleteSnapshotRequestBuilder prepareDeleteSnapshot(String repository, String snapshot);
/**
* Restores a snapshot.
*/
ActionFuture<RestoreSnapshotResponse> restoreSnapshot(RestoreSnapshotRequest request);
/**
* Restores a snapshot.
*/
void restoreSnapshot(RestoreSnapshotRequest request, ActionListener<RestoreSnapshotResponse> listener);
/**
* Restores a snapshot.
*/
RestoreSnapshotRequestBuilder prepareRestoreSnapshot(String repository, String snapshot);
/**
* Returns a list of the pending cluster tasks, that are scheduled to be executed. This includes operations
* that update the cluster state (for example, a create index operation)
*/
void pendingClusterTasks(PendingClusterTasksRequest request, ActionListener<PendingClusterTasksResponse> listener);
/**
* Returns a list of the pending cluster tasks, that are scheduled to be executed. This includes operations
* that update the cluster state (for example, a create index operation)
*/
ActionFuture<PendingClusterTasksResponse> pendingClusterTasks(PendingClusterTasksRequest request);
/**
* Returns a list of the pending cluster tasks, that are scheduled to be executed. This includes operations
* that update the cluster state (for example, a create index operation)
*/
PendingClusterTasksRequestBuilder preparePendingClusterTasks();
}
| 0true
|
src_main_java_org_elasticsearch_client_ClusterAdminClient.java
|
777 |
public class StandardTitanGraph extends TitanBlueprintsGraph {
private static final Logger log =
LoggerFactory.getLogger(StandardTitanGraph.class);
private final GraphDatabaseConfiguration config;
private final Backend backend;
private final IDManager idManager;
private final VertexIDAssigner idAssigner;
private final TimestampProvider times;
//Serializers
protected final IndexSerializer indexSerializer;
protected final EdgeSerializer edgeSerializer;
protected final Serializer serializer;
//Caches
public final SliceQuery vertexExistenceQuery;
private final RelationQueryCache queryCache;
private final SchemaCache schemaCache;
//Log
private final ManagementLogger mgmtLogger;
//Shutdown hook
private final ShutdownThread shutdownHook;
private volatile boolean isOpen = true;
private AtomicLong txCounter;
private Set<StandardTitanTx> openTransactions;
public StandardTitanGraph(GraphDatabaseConfiguration configuration) {
this.config = configuration;
this.backend = configuration.getBackend();
this.idAssigner = config.getIDAssigner(backend);
this.idManager = idAssigner.getIDManager();
this.serializer = config.getSerializer();
StoreFeatures storeFeatures = backend.getStoreFeatures();
this.indexSerializer = new IndexSerializer(configuration.getConfiguration(), this.serializer,
this.backend.getIndexInformation(),storeFeatures.isDistributed() && storeFeatures.isKeyOrdered());
this.edgeSerializer = new EdgeSerializer(this.serializer);
this.vertexExistenceQuery = edgeSerializer.getQuery(BaseKey.VertexExists, Direction.OUT, new EdgeSerializer.TypedInterval[0]).setLimit(1);
this.queryCache = new RelationQueryCache(this.edgeSerializer);
this.schemaCache = configuration.getTypeCache(typeCacheRetrieval);
this.times = configuration.getTimestampProvider();
isOpen = true;
txCounter = new AtomicLong(0);
openTransactions = Collections.newSetFromMap(new ConcurrentHashMap<StandardTitanTx, Boolean>(100,0.75f,1));
//Register instance and ensure uniqueness
String uniqueInstanceId = configuration.getUniqueGraphId();
ModifiableConfiguration globalConfig = GraphDatabaseConfiguration.getGlobalSystemConfig(backend);
if (globalConfig.has(REGISTRATION_TIME,uniqueInstanceId)) {
throw new TitanException(String.format("A Titan graph with the same instance id [%s] is already open. Might required forced shutdown.",uniqueInstanceId));
}
globalConfig.set(REGISTRATION_TIME, times.getTime(), uniqueInstanceId);
Log mgmtLog = backend.getSystemMgmtLog();
mgmtLogger = new ManagementLogger(this,mgmtLog,schemaCache,this.times);
mgmtLog.registerReader(ReadMarker.fromNow(),mgmtLogger);
shutdownHook = new ShutdownThread(this);
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
@Override
public boolean isOpen() {
return isOpen;
}
@Override
public boolean isClosed() {
return !isOpen();
}
@Override
public synchronized void shutdown() throws TitanException {
if (!isOpen) return;
try {
//Unregister instance
ModifiableConfiguration globalConfig = GraphDatabaseConfiguration.getGlobalSystemConfig(backend);
globalConfig.remove(REGISTRATION_TIME,config.getUniqueGraphId());
super.shutdown();
idAssigner.close();
backend.close();
queryCache.close();
// Remove shutdown hook to avoid reference retention
Runtime.getRuntime().removeShutdownHook(shutdownHook);
} catch (BackendException e) {
throw new TitanException("Could not close storage backend", e);
} finally {
isOpen = false;
}
}
// ################### Simple Getters #########################
@Override
public Features getFeatures() {
return TitanFeatures.getFeatures(getConfiguration(), backend.getStoreFeatures());
}
public IndexSerializer getIndexSerializer() {
return indexSerializer;
}
public Backend getBackend() {
return backend;
}
public IDInspector getIDInspector() {
return idManager.getIdInspector();
}
public IDManager getIDManager() {
return idManager;
}
public EdgeSerializer getEdgeSerializer() {
return edgeSerializer;
}
public Serializer getDataSerializer() {
return serializer;
}
//TODO: premature optimization, re-evaluate later
// public RelationQueryCache getQueryCache() {
// return queryCache;
// }
public SchemaCache getSchemaCache() {
return schemaCache;
}
public GraphDatabaseConfiguration getConfiguration() {
return config;
}
@Override
public TitanManagement getManagementSystem() {
return new ManagementSystem(this,backend.getGlobalSystemConfig(),backend.getSystemMgmtLog(), mgmtLogger, schemaCache);
}
public Set<? extends TitanTransaction> getOpenTransactions() {
return Sets.newHashSet(openTransactions);
}
// ################### TRANSACTIONS #########################
@Override
public TitanTransaction newTransaction() {
return buildTransaction().start();
}
@Override
public StandardTransactionBuilder buildTransaction() {
return new StandardTransactionBuilder(getConfiguration(), this);
}
@Override
public TitanTransaction newThreadBoundTransaction() {
return buildTransaction().threadBound().start();
}
public StandardTitanTx newTransaction(final TransactionConfiguration configuration) {
if (!isOpen) ExceptionFactory.graphShutdown();
try {
StandardTitanTx tx = new StandardTitanTx(this, configuration);
tx.setBackendTransaction(openBackendTransaction(tx));
openTransactions.add(tx);
return tx;
} catch (BackendException e) {
throw new TitanException("Could not start new transaction", e);
}
}
private BackendTransaction openBackendTransaction(StandardTitanTx tx) throws BackendException {
IndexSerializer.IndexInfoRetriever retriever = indexSerializer.getIndexInfoRetriever(tx);
return backend.beginTransaction(tx.getConfiguration(),retriever);
}
public void closeTransaction(StandardTitanTx tx) {
openTransactions.remove(tx);
}
// ################### READ #########################
private final SchemaCache.StoreRetrieval typeCacheRetrieval = new SchemaCache.StoreRetrieval() {
@Override
public Long retrieveSchemaByName(String typeName, StandardTitanTx tx) {
tx.getTxHandle().disableCache(); //Disable cache to make sure that schema is only cached once and cache eviction works!
TitanVertex v = Iterables.getOnlyElement(tx.getVertices(BaseKey.SchemaName, typeName),null);
tx.getTxHandle().enableCache();
return v!=null?v.getLongId():null;
}
@Override
public EntryList retrieveSchemaRelations(final long schemaId, final BaseRelationType type, final Direction dir, final StandardTitanTx tx) {
SliceQuery query = queryCache.getQuery(type,dir);
tx.getTxHandle().disableCache(); //Disable cache to make sure that schema is only cached once!
EntryList result = edgeQuery(schemaId, query, tx.getTxHandle());
tx.getTxHandle().enableCache();
return result;
}
};
public RecordIterator<Long> getVertexIDs(final BackendTransaction tx) {
Preconditions.checkArgument(backend.getStoreFeatures().hasOrderedScan() ||
backend.getStoreFeatures().hasUnorderedScan(),
"The configured storage backend does not support global graph operations - use Faunus instead");
final KeyIterator keyiter;
if (backend.getStoreFeatures().hasUnorderedScan()) {
keyiter = tx.edgeStoreKeys(vertexExistenceQuery);
} else {
keyiter = tx.edgeStoreKeys(new KeyRangeQuery(IDHandler.MIN_KEY, IDHandler.MAX_KEY, vertexExistenceQuery));
}
return new RecordIterator<Long>() {
@Override
public boolean hasNext() {
return keyiter.hasNext();
}
@Override
public Long next() {
return idManager.getKeyID(keyiter.next());
}
@Override
public void close() throws IOException {
keyiter.close();
}
@Override
public void remove() {
throw new UnsupportedOperationException("Removal not supported");
}
};
}
public EntryList edgeQuery(long vid, SliceQuery query, BackendTransaction tx) {
Preconditions.checkArgument(vid > 0);
return tx.edgeStoreQuery(new KeySliceQuery(idManager.getKey(vid), query));
}
public List<EntryList> edgeMultiQuery(LongArrayList vids, SliceQuery query, BackendTransaction tx) {
Preconditions.checkArgument(vids != null && !vids.isEmpty());
List<StaticBuffer> vertexIds = new ArrayList<StaticBuffer>(vids.size());
for (int i = 0; i < vids.size(); i++) {
Preconditions.checkArgument(vids.get(i) > 0);
vertexIds.add(idManager.getKey(vids.get(i)));
}
Map<StaticBuffer,EntryList> result = tx.edgeStoreMultiQuery(vertexIds, query);
List<EntryList> resultList = new ArrayList<EntryList>(result.size());
for (StaticBuffer v : vertexIds) resultList.add(result.get(v));
return resultList;
}
// ################### WRITE #########################
public void assignID(InternalRelation relation) {
idAssigner.assignID(relation);
}
public void assignID(InternalVertex vertex, VertexLabel label) {
idAssigner.assignID(vertex,label);
}
public static boolean acquireLock(InternalRelation relation, int pos, boolean acquireLocksConfig) {
InternalRelationType type = (InternalRelationType)relation.getType();
return acquireLocksConfig && type.getConsistencyModifier()== ConsistencyModifier.LOCK &&
( type.getMultiplicity().isUnique(EdgeDirection.fromPosition(pos))
|| pos==0 && type.getMultiplicity()== Multiplicity.SIMPLE);
}
public static boolean acquireLock(CompositeIndexType index, boolean acquireLocksConfig) {
return acquireLocksConfig && index.getConsistencyModifier()==ConsistencyModifier.LOCK
&& index.getCardinality()!= Cardinality.LIST;
}
/**
* The TTL of a relation (edge or property) is the minimum of:
* 1) The TTL configured of the relation type (if exists)
* 2) The TTL configured for the label any of the relation end point vertices (if exists)
*
* @param rel relation to determine the TTL for
* @return
*/
public static int getTTL(InternalRelation rel) {
assert rel.isNew();
InternalRelationType baseType = (InternalRelationType) rel.getType();
assert baseType.getBaseType()==null;
int ttl = 0;
Integer ettl = baseType.getTTL();
if (ettl>0) ttl = ettl;
for (int i=0;i<rel.getArity();i++) {
int vttl = getTTL(rel.getVertex(i));
if (vttl>0 && (vttl<ttl || ttl<=0)) ttl = vttl;
}
return ttl;
}
public static int getTTL(InternalVertex v) {
assert v.hasId();
if (IDManager.VertexIDType.UnmodifiableVertex.is(v.getLongId())) {
assert v.isNew() : "Should not be able to add relations to existing static vertices: " + v;
return ((InternalVertexLabel)v.getVertexLabel()).getTTL();
} else return 0;
}
private static class ModificationSummary {
final boolean hasModifications;
final boolean has2iModifications;
private ModificationSummary(boolean hasModifications, boolean has2iModifications) {
this.hasModifications = hasModifications;
this.has2iModifications = has2iModifications;
}
}
public ModificationSummary prepareCommit(final Collection<InternalRelation> addedRelations,
final Collection<InternalRelation> deletedRelations,
final Predicate<InternalRelation> filter,
final BackendTransaction mutator, final StandardTitanTx tx,
final boolean acquireLocks) throws BackendException {
ListMultimap<Long, InternalRelation> mutations = ArrayListMultimap.create();
ListMultimap<InternalVertex, InternalRelation> mutatedProperties = ArrayListMultimap.create();
List<IndexSerializer.IndexUpdate> indexUpdates = Lists.newArrayList();
//1) Collect deleted edges and their index updates and acquire edge locks
for (InternalRelation del : Iterables.filter(deletedRelations,filter)) {
Preconditions.checkArgument(del.isRemoved());
for (int pos = 0; pos < del.getLen(); pos++) {
InternalVertex vertex = del.getVertex(pos);
if (pos == 0 || !del.isLoop()) {
if (del.isProperty()) mutatedProperties.put(vertex,del);
mutations.put(vertex.getLongId(), del);
}
if (acquireLock(del,pos,acquireLocks)) {
Entry entry = edgeSerializer.writeRelation(del, pos, tx);
mutator.acquireEdgeLock(idManager.getKey(vertex.getLongId()), entry);
}
}
indexUpdates.addAll(indexSerializer.getIndexUpdates(del));
}
//2) Collect added edges and their index updates and acquire edge locks
for (InternalRelation add : Iterables.filter(addedRelations,filter)) {
Preconditions.checkArgument(add.isNew());
for (int pos = 0; pos < add.getLen(); pos++) {
InternalVertex vertex = add.getVertex(pos);
if (pos == 0 || !add.isLoop()) {
if (add.isProperty()) mutatedProperties.put(vertex,add);
mutations.put(vertex.getLongId(), add);
}
if (!vertex.isNew() && acquireLock(add,pos,acquireLocks)) {
Entry entry = edgeSerializer.writeRelation(add, pos, tx);
mutator.acquireEdgeLock(idManager.getKey(vertex.getLongId()), entry.getColumn());
}
}
indexUpdates.addAll(indexSerializer.getIndexUpdates(add));
}
//3) Collect all index update for vertices
for (InternalVertex v : mutatedProperties.keySet()) {
indexUpdates.addAll(indexSerializer.getIndexUpdates(v,mutatedProperties.get(v)));
}
//4) Acquire index locks (deletions first)
for (IndexSerializer.IndexUpdate update : indexUpdates) {
if (!update.isCompositeIndex() || !update.isDeletion()) continue;
CompositeIndexType iIndex = (CompositeIndexType) update.getIndex();
if (acquireLock(iIndex,acquireLocks)) {
mutator.acquireIndexLock((StaticBuffer)update.getKey(), (Entry)update.getEntry());
}
}
for (IndexSerializer.IndexUpdate update : indexUpdates) {
if (!update.isCompositeIndex() || !update.isAddition()) continue;
CompositeIndexType iIndex = (CompositeIndexType) update.getIndex();
if (acquireLock(iIndex,acquireLocks)) {
mutator.acquireIndexLock((StaticBuffer)update.getKey(), ((Entry)update.getEntry()).getColumn());
}
}
//5) Add relation mutations
for (Long vertexid : mutations.keySet()) {
Preconditions.checkArgument(vertexid > 0, "Vertex has no id: %s", vertexid);
List<InternalRelation> edges = mutations.get(vertexid);
List<Entry> additions = new ArrayList<Entry>(edges.size());
List<Entry> deletions = new ArrayList<Entry>(Math.max(10, edges.size() / 10));
for (InternalRelation edge : edges) {
InternalRelationType baseType = (InternalRelationType) edge.getType();
assert baseType.getBaseType()==null;
for (InternalRelationType type : baseType.getRelationIndexes()) {
if (type.getStatus()== SchemaStatus.DISABLED) continue;
for (int pos = 0; pos < edge.getArity(); pos++) {
if (!type.isUnidirected(Direction.BOTH) && !type.isUnidirected(EdgeDirection.fromPosition(pos)))
continue; //Directionality is not covered
if (edge.getVertex(pos).getLongId()==vertexid) {
StaticArrayEntry entry = edgeSerializer.writeRelation(edge, type, pos, tx);
if (edge.isRemoved()) {
deletions.add(entry);
} else {
Preconditions.checkArgument(edge.isNew());
int ttl = getTTL(edge);
if (ttl > 0) {
entry.setMetaData(EntryMetaData.TTL, ttl);
}
additions.add(entry);
}
}
}
}
}
StaticBuffer vertexKey = idManager.getKey(vertexid);
mutator.mutateEdges(vertexKey, additions, deletions);
}
//6) Add index updates
boolean has2iMods = false;
for (IndexSerializer.IndexUpdate indexUpdate : indexUpdates) {
assert indexUpdate.isAddition() || indexUpdate.isDeletion();
if (indexUpdate.isCompositeIndex()) {
IndexSerializer.IndexUpdate<StaticBuffer,Entry> update = indexUpdate;
if (update.isAddition())
mutator.mutateIndex(update.getKey(), Lists.newArrayList(update.getEntry()), KCVSCache.NO_DELETIONS);
else
mutator.mutateIndex(update.getKey(), KeyColumnValueStore.NO_ADDITIONS, Lists.newArrayList(update.getEntry()));
} else {
IndexSerializer.IndexUpdate<String,IndexEntry> update = indexUpdate;
has2iMods = true;
IndexTransaction itx = mutator.getIndexTransaction(update.getIndex().getBackingIndexName());
String indexStore = ((MixedIndexType)update.getIndex()).getStoreName();
if (update.isAddition())
itx.add(indexStore, update.getKey(), update.getEntry(), update.getElement().isNew());
else
itx.delete(indexStore,update.getKey(),update.getEntry().field,update.getEntry().value,update.getElement().isRemoved());
}
}
return new ModificationSummary(!mutations.isEmpty(),has2iMods);
}
private static final Predicate<InternalRelation> SCHEMA_FILTER = new Predicate<InternalRelation>() {
@Override
public boolean apply(@Nullable InternalRelation internalRelation) {
return internalRelation.getType() instanceof BaseRelationType && internalRelation.getVertex(0) instanceof TitanSchemaVertex;
}
};
private static final Predicate<InternalRelation> NO_SCHEMA_FILTER = new Predicate<InternalRelation>() {
@Override
public boolean apply(@Nullable InternalRelation internalRelation) {
return !SCHEMA_FILTER.apply(internalRelation);
}
};
private static final Predicate<InternalRelation> NO_FILTER = Predicates.alwaysTrue();
public void commit(final Collection<InternalRelation> addedRelations,
final Collection<InternalRelation> deletedRelations, final StandardTitanTx tx) {
if (addedRelations.isEmpty() && deletedRelations.isEmpty()) return;
//1. Finalize transaction
log.debug("Saving transaction. Added {}, removed {}", addedRelations.size(), deletedRelations.size());
if (!tx.getConfiguration().hasCommitTime()) tx.getConfiguration().setCommitTime(times.getTime());
final Timepoint txTimestamp = tx.getConfiguration().getCommitTime();
final long transactionId = txCounter.incrementAndGet();
//2. Assign TitanVertex IDs
if (!tx.getConfiguration().hasAssignIDsImmediately())
idAssigner.assignIDs(addedRelations);
//3. Commit
BackendTransaction mutator = tx.getTxHandle();
final boolean acquireLocks = tx.getConfiguration().hasAcquireLocks();
final boolean hasTxIsolation = backend.getStoreFeatures().hasTxIsolation();
final boolean logTransaction = config.hasLogTransactions() && !tx.getConfiguration().hasEnabledBatchLoading();
final KCVSLog txLog = logTransaction?backend.getSystemTxLog():null;
final TransactionLogHeader txLogHeader = new TransactionLogHeader(transactionId,txTimestamp);
ModificationSummary commitSummary;
try {
//3.1 Log transaction (write-ahead log) if enabled
if (logTransaction) {
//[FAILURE] Inability to log transaction fails the transaction by escalation since it's likely due to unavailability of primary
//storage backend.
txLog.add(txLogHeader.serializeModifications(serializer, LogTxStatus.PRECOMMIT, tx, addedRelations, deletedRelations),txLogHeader.getLogKey());
}
//3.2 Commit schema elements and their associated relations in a separate transaction if backend does not support
// transactional isolation
boolean hasSchemaElements = !Iterables.isEmpty(Iterables.filter(deletedRelations,SCHEMA_FILTER))
|| !Iterables.isEmpty(Iterables.filter(addedRelations,SCHEMA_FILTER));
Preconditions.checkArgument(!hasSchemaElements || (!tx.getConfiguration().hasEnabledBatchLoading() && acquireLocks),
"Attempting to create schema elements in inconsistent state");
if (hasSchemaElements && !hasTxIsolation) {
/*
* On storage without transactional isolation, create separate
* backend transaction for schema aspects to make sure that
* those are persisted prior to and independently of other
* mutations in the tx. If the storage supports transactional
* isolation, then don't create a separate tx.
*/
final BackendTransaction schemaMutator = openBackendTransaction(tx);
try {
//[FAILURE] If the preparation throws an exception abort directly - nothing persisted since batch-loading cannot be enabled for schema elements
commitSummary = prepareCommit(addedRelations,deletedRelations, SCHEMA_FILTER, schemaMutator, tx, acquireLocks);
assert commitSummary.hasModifications && !commitSummary.has2iModifications;
} catch (Throwable e) {
//Roll back schema tx and escalate exception
schemaMutator.rollback();
throw e;
}
try {
schemaMutator.commit();
} catch (Throwable e) {
//[FAILURE] Primary persistence failed => abort and escalate exception, nothing should have been persisted
log.error("Could not commit transaction ["+transactionId+"] due to storage exception in system-commit",e);
throw e;
}
}
//[FAILURE] Exceptions during preparation here cause the entire transaction to fail on transactional systems
//or just the non-system part on others. Nothing has been persisted unless batch-loading
commitSummary = prepareCommit(addedRelations,deletedRelations, hasTxIsolation? NO_FILTER : NO_SCHEMA_FILTER, mutator, tx, acquireLocks);
if (commitSummary.hasModifications) {
String logTxIdentifier = tx.getConfiguration().getLogIdentifier();
boolean hasSecondaryPersistence = logTxIdentifier!=null || commitSummary.has2iModifications;
//1. Commit storage - failures lead to immediate abort
//1a. Add success message to tx log which will be committed atomically with all transactional changes so that we can recover secondary failures
// This should not throw an exception since the mutations are just cached. If it does, it will be escalated since its critical
if (logTransaction) {
txLog.add(txLogHeader.serializePrimary(serializer,
hasSecondaryPersistence?LogTxStatus.PRIMARY_SUCCESS:LogTxStatus.COMPLETE_SUCCESS),
txLogHeader.getLogKey(),mutator.getTxLogPersistor());
}
try {
mutator.commitStorage();
} catch (Throwable e) {
//[FAILURE] If primary storage persistence fails abort directly (only schema could have been persisted)
log.error("Could not commit transaction ["+transactionId+"] due to storage exception in commit",e);
throw e;
}
if (hasSecondaryPersistence) {
LogTxStatus status = LogTxStatus.SECONDARY_SUCCESS;
Map<String,Throwable> indexFailures = ImmutableMap.of();
boolean userlogSuccess = true;
try {
//2. Commit indexes - [FAILURE] all exceptions are collected and logged but nothing is aborted
indexFailures = mutator.commitIndexes();
if (!indexFailures.isEmpty()) {
status = LogTxStatus.SECONDARY_FAILURE;
for (Map.Entry<String,Throwable> entry : indexFailures.entrySet()) {
log.error("Error while commiting index mutations for transaction ["+transactionId+"] on index: " +entry.getKey(),entry.getValue());
}
}
//3. Log transaction if configured - [FAILURE] is recorded but does not cause exception
if (logTxIdentifier!=null) {
try {
userlogSuccess = false;
final Log userLog = backend.getUserLog(logTxIdentifier);
Future<Message> env = userLog.add(txLogHeader.serializeModifications(serializer, LogTxStatus.USER_LOG, tx, addedRelations, deletedRelations));
if (env.isDone()) {
try {
env.get();
} catch (ExecutionException ex) {
throw ex.getCause();
}
}
userlogSuccess=true;
} catch (Throwable e) {
status = LogTxStatus.SECONDARY_FAILURE;
log.error("Could not user-log committed transaction ["+transactionId+"] to " + logTxIdentifier, e);
}
}
} finally {
if (logTransaction) {
//[FAILURE] An exception here will be logged and not escalated; tx considered success and
// needs to be cleaned up later
try {
txLog.add(txLogHeader.serializeSecondary(serializer,status,indexFailures,userlogSuccess),txLogHeader.getLogKey());
} catch (Throwable e) {
log.error("Could not tx-log secondary persistence status on transaction ["+transactionId+"]",e);
}
}
}
} else {
//This just closes the transaction since there are no modifications
mutator.commitIndexes();
}
} else { //Just commit everything at once
//[FAILURE] This case only happens when there are no non-system mutations in which case all changes
//are already flushed. Hence, an exception here is unlikely and should abort
mutator.commit();
}
} catch (Throwable e) {
log.error("Could not commit transaction ["+transactionId+"] due to exception",e);
try {
//Clean up any left-over transaction handles
mutator.rollback();
} catch (Throwable e2) {
log.error("Could not roll-back transaction ["+transactionId+"] after failure due to exception",e2);
}
if (e instanceof RuntimeException) throw (RuntimeException)e;
else throw new TitanException("Unexpected exception",e);
}
}
private static class ShutdownThread extends Thread {
private final StandardTitanGraph graph;
public ShutdownThread(StandardTitanGraph graph) {
this.graph = graph;
}
@Override
public void start() {
if (graph.isOpen && log.isDebugEnabled())
log.debug("Shutting down graph {} using built-in shutdown hook.", graph);
graph.shutdown();
}
}
}
| 1no label
|
titan-core_src_main_java_com_thinkaurelius_titan_graphdb_database_StandardTitanGraph.java
|
4,031 |
public class MatchQuery {
public static enum Type {
BOOLEAN,
PHRASE,
PHRASE_PREFIX
}
public static enum ZeroTermsQuery {
NONE,
ALL
}
protected final QueryParseContext parseContext;
protected String analyzer;
protected BooleanClause.Occur occur = BooleanClause.Occur.SHOULD;
protected boolean enablePositionIncrements = true;
protected int phraseSlop = 0;
protected Fuzziness fuzziness = null;
protected int fuzzyPrefixLength = FuzzyQuery.defaultPrefixLength;
protected int maxExpansions = FuzzyQuery.defaultMaxExpansions;
//LUCENE 4 UPGRADE we need a default value for this!
protected boolean transpositions = false;
protected MultiTermQuery.RewriteMethod rewriteMethod;
protected MultiTermQuery.RewriteMethod fuzzyRewriteMethod;
protected boolean lenient;
protected ZeroTermsQuery zeroTermsQuery = ZeroTermsQuery.NONE;
protected Float commonTermsCutoff = null;
public MatchQuery(QueryParseContext parseContext) {
this.parseContext = parseContext;
}
public void setAnalyzer(String analyzer) {
this.analyzer = analyzer;
}
public void setOccur(BooleanClause.Occur occur) {
this.occur = occur;
}
public void setCommonTermsCutoff(float cutoff) {
this.commonTermsCutoff = Float.valueOf(cutoff);
}
public void setEnablePositionIncrements(boolean enablePositionIncrements) {
this.enablePositionIncrements = enablePositionIncrements;
}
public void setPhraseSlop(int phraseSlop) {
this.phraseSlop = phraseSlop;
}
public void setFuzziness(Fuzziness fuzziness) {
this.fuzziness = fuzziness;
}
public void setFuzzyPrefixLength(int fuzzyPrefixLength) {
this.fuzzyPrefixLength = fuzzyPrefixLength;
}
public void setMaxExpansions(int maxExpansions) {
this.maxExpansions = maxExpansions;
}
public void setTranspositions(boolean transpositions) {
this.transpositions = transpositions;
}
public void setRewriteMethod(MultiTermQuery.RewriteMethod rewriteMethod) {
this.rewriteMethod = rewriteMethod;
}
public void setFuzzyRewriteMethod(MultiTermQuery.RewriteMethod fuzzyRewriteMethod) {
this.fuzzyRewriteMethod = fuzzyRewriteMethod;
}
public void setLenient(boolean lenient) {
this.lenient = lenient;
}
public void setZeroTermsQuery(ZeroTermsQuery zeroTermsQuery) {
this.zeroTermsQuery = zeroTermsQuery;
}
public Query parse(Type type, String fieldName, Object value) throws IOException {
FieldMapper mapper = null;
final String field;
MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName);
if (smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) {
mapper = smartNameFieldMappers.mapper();
field = mapper.names().indexName();
} else {
field = fieldName;
}
if (mapper != null && mapper.useTermQueryWithQueryString()) {
if (smartNameFieldMappers.explicitTypeInNameWithDocMapper()) {
String[] previousTypes = QueryParseContext.setTypesWithPrevious(new String[]{smartNameFieldMappers.docMapper().type()});
try {
return wrapSmartNameQuery(mapper.termQuery(value, parseContext), smartNameFieldMappers, parseContext);
} catch (RuntimeException e) {
if (lenient) {
return null;
}
throw e;
} finally {
QueryParseContext.setTypes(previousTypes);
}
} else {
try {
return wrapSmartNameQuery(mapper.termQuery(value, parseContext), smartNameFieldMappers, parseContext);
} catch (RuntimeException e) {
if (lenient) {
return null;
}
throw e;
}
}
}
Analyzer analyzer = null;
if (this.analyzer == null) {
if (mapper != null) {
analyzer = mapper.searchAnalyzer();
}
if (analyzer == null && smartNameFieldMappers != null) {
analyzer = smartNameFieldMappers.searchAnalyzer();
}
if (analyzer == null) {
analyzer = parseContext.mapperService().searchAnalyzer();
}
} else {
analyzer = parseContext.mapperService().analysisService().analyzer(this.analyzer);
if (analyzer == null) {
throw new ElasticsearchIllegalArgumentException("No analyzer found for [" + this.analyzer + "]");
}
}
// Logic similar to QueryParser#getFieldQuery
final TokenStream source = analyzer.tokenStream(field, value.toString());
source.reset();
int numTokens = 0;
int positionCount = 0;
boolean severalTokensAtSamePosition = false;
final CachingTokenFilter buffer = new CachingTokenFilter(source);
buffer.reset();
final CharTermAttribute termAtt = buffer.addAttribute(CharTermAttribute.class);
final PositionIncrementAttribute posIncrAtt = buffer.addAttribute(PositionIncrementAttribute.class);
boolean hasMoreTokens = buffer.incrementToken();
while (hasMoreTokens) {
numTokens++;
int positionIncrement = posIncrAtt.getPositionIncrement();
if (positionIncrement != 0) {
positionCount += positionIncrement;
} else {
severalTokensAtSamePosition = true;
}
hasMoreTokens = buffer.incrementToken();
}
// rewind the buffer stream
buffer.reset();
source.close();
if (numTokens == 0) {
return zeroTermsQuery();
} else if (type == Type.BOOLEAN) {
if (numTokens == 1) {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
final Query q = newTermQuery(mapper, new Term(field, termToByteRef(termAtt)));
return wrapSmartNameQuery(q, smartNameFieldMappers, parseContext);
}
if (commonTermsCutoff != null) {
ExtendedCommonTermsQuery q = new ExtendedCommonTermsQuery(occur, occur, commonTermsCutoff, positionCount == 1);
for (int i = 0; i < numTokens; i++) {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
q.add(new Term(field, termToByteRef(termAtt)));
}
return wrapSmartNameQuery(q, smartNameFieldMappers, parseContext);
} if (severalTokensAtSamePosition && occur == Occur.MUST) {
BooleanQuery q = new BooleanQuery(positionCount == 1);
Query currentQuery = null;
for (int i = 0; i < numTokens; i++) {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
if (posIncrAtt != null && posIncrAtt.getPositionIncrement() == 0) {
if (!(currentQuery instanceof BooleanQuery)) {
Query t = currentQuery;
currentQuery = new BooleanQuery(true);
((BooleanQuery)currentQuery).add(t, BooleanClause.Occur.SHOULD);
}
((BooleanQuery)currentQuery).add(newTermQuery(mapper, new Term(field, termToByteRef(termAtt))), BooleanClause.Occur.SHOULD);
} else {
if (currentQuery != null) {
q.add(currentQuery, occur);
}
currentQuery = newTermQuery(mapper, new Term(field, termToByteRef(termAtt)));
}
}
q.add(currentQuery, occur);
return wrapSmartNameQuery(q, smartNameFieldMappers, parseContext);
} else {
BooleanQuery q = new BooleanQuery(positionCount == 1);
for (int i = 0; i < numTokens; i++) {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
final Query currentQuery = newTermQuery(mapper, new Term(field, termToByteRef(termAtt)));
q.add(currentQuery, occur);
}
return wrapSmartNameQuery(q, smartNameFieldMappers, parseContext);
}
} else if (type == Type.PHRASE) {
if (severalTokensAtSamePosition) {
final MultiPhraseQuery mpq = new MultiPhraseQuery();
mpq.setSlop(phraseSlop);
final List<Term> multiTerms = new ArrayList<Term>();
int position = -1;
for (int i = 0; i < numTokens; i++) {
int positionIncrement = 1;
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
positionIncrement = posIncrAtt.getPositionIncrement();
if (positionIncrement > 0 && multiTerms.size() > 0) {
if (enablePositionIncrements) {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]), position);
} else {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]));
}
multiTerms.clear();
}
position += positionIncrement;
//LUCENE 4 UPGRADE instead of string term we can convert directly from utf-16 to utf-8
multiTerms.add(new Term(field, termToByteRef(termAtt)));
}
if (enablePositionIncrements) {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]), position);
} else {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]));
}
return wrapSmartNameQuery(mpq, smartNameFieldMappers, parseContext);
} else {
PhraseQuery pq = new PhraseQuery();
pq.setSlop(phraseSlop);
int position = -1;
for (int i = 0; i < numTokens; i++) {
int positionIncrement = 1;
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
positionIncrement = posIncrAtt.getPositionIncrement();
if (enablePositionIncrements) {
position += positionIncrement;
//LUCENE 4 UPGRADE instead of string term we can convert directly from utf-16 to utf-8
pq.add(new Term(field, termToByteRef(termAtt)), position);
} else {
pq.add(new Term(field, termToByteRef(termAtt)));
}
}
return wrapSmartNameQuery(pq, smartNameFieldMappers, parseContext);
}
} else if (type == Type.PHRASE_PREFIX) {
MultiPhrasePrefixQuery mpq = new MultiPhrasePrefixQuery();
mpq.setSlop(phraseSlop);
mpq.setMaxExpansions(maxExpansions);
List<Term> multiTerms = new ArrayList<Term>();
int position = -1;
for (int i = 0; i < numTokens; i++) {
int positionIncrement = 1;
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
positionIncrement = posIncrAtt.getPositionIncrement();
if (positionIncrement > 0 && multiTerms.size() > 0) {
if (enablePositionIncrements) {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]), position);
} else {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]));
}
multiTerms.clear();
}
position += positionIncrement;
multiTerms.add(new Term(field, termToByteRef(termAtt)));
}
if (enablePositionIncrements) {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]), position);
} else {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]));
}
return wrapSmartNameQuery(mpq, smartNameFieldMappers, parseContext);
}
throw new ElasticsearchIllegalStateException("No type found for [" + type + "]");
}
private Query newTermQuery(@Nullable FieldMapper mapper, Term term) {
if (fuzziness != null) {
if (mapper != null) {
Query query = mapper.fuzzyQuery(term.text(), fuzziness, fuzzyPrefixLength, maxExpansions, transpositions);
if (query instanceof FuzzyQuery) {
QueryParsers.setRewriteMethod((FuzzyQuery) query, fuzzyRewriteMethod);
}
}
int edits = fuzziness.asDistance(term.text());
FuzzyQuery query = new FuzzyQuery(term, edits, fuzzyPrefixLength, maxExpansions, transpositions);
QueryParsers.setRewriteMethod(query, rewriteMethod);
return query;
}
if (mapper != null) {
Query termQuery = mapper.queryStringTermQuery(term);
if (termQuery != null) {
return termQuery;
}
}
return new TermQuery(term);
}
private static BytesRef termToByteRef(CharTermAttribute attr) {
final BytesRef ref = new BytesRef();
UnicodeUtil.UTF16toUTF8(attr.buffer(), 0, attr.length(), ref);
return ref;
}
protected Query zeroTermsQuery() {
return zeroTermsQuery == ZeroTermsQuery.NONE ? Queries.newMatchNoDocsQuery() : Queries.newMatchAllQuery();
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_search_MatchQuery.java
|
1,017 |
class AsyncSingleAction {
private final ActionListener<Response> listener;
private final Request request;
private ShardIterator shardIt;
private DiscoveryNodes nodes;
private final AtomicBoolean operationStarted = new AtomicBoolean();
private AsyncSingleAction(Request request, ActionListener<Response> listener) {
this.request = request;
this.listener = listener;
}
public void start() {
start(false);
}
public boolean start(final boolean fromClusterEvent) throws ElasticsearchException {
final ClusterState clusterState = clusterService.state();
nodes = clusterState.nodes();
try {
ClusterBlockException blockException = checkGlobalBlock(clusterState, request);
if (blockException != null) {
if (blockException.retryable()) {
retry(fromClusterEvent, blockException);
return false;
} else {
throw blockException;
}
}
// check if we need to execute, and if not, return
if (!resolveRequest(clusterState, request, listener)) {
return true;
}
blockException = checkRequestBlock(clusterState, request);
if (blockException != null) {
if (blockException.retryable()) {
retry(fromClusterEvent, blockException);
return false;
} else {
throw blockException;
}
}
shardIt = shards(clusterState, request);
} catch (Throwable e) {
listener.onFailure(e);
return true;
}
// no shardIt, might be in the case between index gateway recovery and shardIt initialization
if (shardIt.size() == 0) {
retry(fromClusterEvent, null);
return false;
}
// this transport only make sense with an iterator that returns a single shard routing (like primary)
assert shardIt.size() == 1;
ShardRouting shard = shardIt.nextOrNull();
assert shard != null;
if (!shard.active()) {
retry(fromClusterEvent, null);
return false;
}
if (!operationStarted.compareAndSet(false, true)) {
return true;
}
request.shardId = shardIt.shardId().id();
if (shard.currentNodeId().equals(nodes.localNodeId())) {
request.beforeLocalFork();
try {
threadPool.executor(executor).execute(new Runnable() {
@Override
public void run() {
try {
shardOperation(request, listener);
} catch (Throwable e) {
if (retryOnFailure(e)) {
operationStarted.set(false);
// we already marked it as started when we executed it (removed the listener) so pass false
// to re-add to the cluster listener
retry(false, null);
} else {
listener.onFailure(e);
}
}
}
});
} catch (Throwable e) {
if (retryOnFailure(e)) {
retry(fromClusterEvent, null);
} else {
listener.onFailure(e);
}
}
} else {
DiscoveryNode node = nodes.get(shard.currentNodeId());
transportService.sendRequest(node, transportAction, request, transportOptions(), new BaseTransportResponseHandler<Response>() {
@Override
public Response newInstance() {
return newResponse();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(Response response) {
listener.onResponse(response);
}
@Override
public void handleException(TransportException exp) {
// if we got disconnected from the node, or the node / shard is not in the right state (being closed)
if (exp.unwrapCause() instanceof ConnectTransportException || exp.unwrapCause() instanceof NodeClosedException ||
retryOnFailure(exp)) {
operationStarted.set(false);
// we already marked it as started when we executed it (removed the listener) so pass false
// to re-add to the cluster listener
retry(false, null);
} else {
listener.onFailure(exp);
}
}
});
}
return true;
}
void retry(final boolean fromClusterEvent, final @Nullable Throwable failure) {
if (!fromClusterEvent) {
// make it threaded operation so we fork on the discovery listener thread
request.beforeLocalFork();
clusterService.add(request.timeout(), new TimeoutClusterStateListener() {
@Override
public void postAdded() {
if (start(true)) {
// if we managed to start and perform the operation on the primary, we can remove this listener
clusterService.remove(this);
}
}
@Override
public void onClose() {
clusterService.remove(this);
listener.onFailure(new NodeClosedException(nodes.localNode()));
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
if (start(true)) {
// if we managed to start and perform the operation on the primary, we can remove this listener
clusterService.remove(this);
}
}
@Override
public void onTimeout(TimeValue timeValue) {
// just to be on the safe side, see if we can start it now?
if (start(true)) {
clusterService.remove(this);
return;
}
clusterService.remove(this);
Throwable listenFailure = failure;
if (listenFailure == null) {
if (shardIt == null) {
listenFailure = new UnavailableShardsException(new ShardId(request.index(), -1), "Timeout waiting for [" + timeValue + "], request: " + request.toString());
} else {
listenFailure = new UnavailableShardsException(shardIt.shardId(), "[" + shardIt.size() + "] shardIt, [" + shardIt.sizeActive() + "] active : Timeout waiting for [" + timeValue + "], request: " + request.toString());
}
}
listener.onFailure(listenFailure);
}
});
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_single_instance_TransportInstanceSingleOperationAction.java
|
178 |
private static class FailingFunction implements IFunction<Long, Long> {
@Override
public Long apply(Long input) {
throw new WoohaaException();
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_atomiclong_ClientAtomicLongTest.java
|
408 |
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD);
Assert.assertNull(event.getOldValue());
Assert.assertEquals(event.getKey().intValue(), 0);
Assert.assertEquals(event.getValue(), "value1");
changed.value = true;
}
});
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java
|
751 |
public class MultiGetAction extends Action<MultiGetRequest, MultiGetResponse, MultiGetRequestBuilder> {
public static final MultiGetAction INSTANCE = new MultiGetAction();
public static final String NAME = "mget";
private MultiGetAction() {
super(NAME);
}
@Override
public MultiGetResponse newResponse() {
return new MultiGetResponse();
}
@Override
public MultiGetRequestBuilder newRequestBuilder(Client client) {
return new MultiGetRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_get_MultiGetAction.java
|
2 |
public class Prover
{
private final Queue<ClusterState> unexploredKnownStates = new LinkedList<>( );
private final ProofDatabase db = new ProofDatabase("./clusterproof");
public static void main(String ... args) throws Exception
{
new Prover().prove();
}
public void prove() throws Exception
{
try
{
System.out.println("Bootstrap genesis state..");
bootstrapCluster();
System.out.println("Begin exploring delivery orders.");
exploreUnexploredStates();
System.out.println("Exporting graphviz..");
db.export(new GraphVizExporter(new File("./proof.gs")));
}
finally
{
db.shutdown();
}
// Generate .svg :
// dot -Tsvg proof.gs -o proof.svg
}
private void bootstrapCluster() throws Exception
{
Logging logging = new TestLogging();
String instance1 = "cluster://localhost:5001";
String instance2 = "cluster://localhost:5002";
String instance3 = "cluster://localhost:5003";
ClusterConfiguration config = new ClusterConfiguration( "default",
logging.getMessagesLog( ClusterConfiguration.class ),
instance1,
instance2,
instance3 );
ClusterState state = new ClusterState(
asList(
newClusterInstance( new InstanceId( 1 ), new URI( instance1 ), config, logging ),
newClusterInstance( new InstanceId( 2 ), new URI( instance2 ), config, logging ),
newClusterInstance( new InstanceId( 3 ), new URI( instance3 ), config, logging )),
emptySetOf( ClusterAction.class ));
state = state.performAction( new MessageDeliveryAction( Message.to( ClusterMessage.create,
new URI( instance3 ), "defaultcluster" ).setHeader( Message.CONVERSATION_ID, "-1" ).setHeader( Message.FROM, instance3 ) ) );
state = state.performAction( new MessageDeliveryAction( Message.to( ClusterMessage.join, new URI( instance2 ), new Object[]{"defaultcluster", new URI[]{new URI( instance3 )}} ).setHeader( Message.CONVERSATION_ID, "-1" ).setHeader( Message.FROM, instance2 ) ) );
state = state.performAction( new MessageDeliveryAction( Message.to( ClusterMessage.join, new URI( instance1 ), new Object[]{"defaultcluster", new URI[]{new URI( instance3 )}} ).setHeader( Message.CONVERSATION_ID, "-1" ).setHeader( Message.FROM, instance1 ) ) );
state.addPendingActions( new InstanceCrashedAction( instance3 ) );
unexploredKnownStates.add( state );
db.newState( state );
}
private void exploreUnexploredStates()
{
while(!unexploredKnownStates.isEmpty())
{
ClusterState state = unexploredKnownStates.poll();
Iterator<Pair<ClusterAction, ClusterState>> newStates = state.transitions();
while(newStates.hasNext())
{
Pair<ClusterAction, ClusterState> next = newStates.next();
System.out.println( db.numberOfKnownStates() + " ("+unexploredKnownStates.size()+")" );
ClusterState nextState = next.other();
if(!db.isKnownState( nextState ))
{
db.newStateTransition( state, next );
unexploredKnownStates.offer( nextState );
if(nextState.isDeadEnd())
{
System.out.println("DEAD END: " + nextState.toString() + " (" + db.id(nextState) + ")");
}
}
}
}
}
}
| 1no label
|
enterprise_ha_src_test_java_org_neo4j_ha_correctness_Prover.java
|
583 |
getEntriesMinor(toKey, isInclusive, new IndexEntriesResultListener() {
@Override
public boolean addResult(ODocument entry) {
result.add(entry);
return true;
}
});
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_index_OIndexAbstract.java
|
3,266 |
public class TopicPermission extends InstancePermission {
private static final int PUBLISH = 0x4;
private static final int LISTEN = 0x8;
private static final int ALL = CREATE | DESTROY | LISTEN | PUBLISH;
public TopicPermission(String name, String... actions) {
super(name, actions);
}
@Override
protected int initMask(String[] actions) {
int mask = NONE;
for (String action : actions) {
if (ActionConstants.ACTION_ALL.equals(action)) {
return ALL;
}
if (ActionConstants.ACTION_CREATE.equals(action)) {
mask |= CREATE;
} else if (ActionConstants.ACTION_PUBLISH.equals(action)) {
mask |= PUBLISH;
} else if (ActionConstants.ACTION_DESTROY.equals(action)) {
mask |= DESTROY;
} else if (ActionConstants.ACTION_LISTEN.equals(action)) {
mask |= LISTEN;
}
}
return mask;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_security_permission_TopicPermission.java
|
35 |
@Service("blSkuFieldService")
public class SkuFieldServiceImpl extends AbstractRuleBuilderFieldService {
@Override
public void init() {
fields.add(new FieldData.Builder()
.label("rule_skuName")
.name("name")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuFulfillmentType")
.name("fulfillmentType")
.operators("blcOperators_Enumeration")
.options("blcOptions_FulfillmentType")
.type(SupportedFieldType.BROADLEAF_ENUMERATION)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuInventoryType")
.name("inventoryType")
.operators("blcOperators_Enumeration")
.options("blcOptions_InventoryType")
.type(SupportedFieldType.BROADLEAF_ENUMERATION)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuDescription")
.name("description")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuLongDescription")
.name("longDescription")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuTaxable")
.name("taxable")
.operators("blcOperators_Boolean")
.options("[]")
.type(SupportedFieldType.BOOLEAN)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuAvailable")
.name("available")
.operators("blcOperators_Boolean")
.options("[]")
.type(SupportedFieldType.BOOLEAN)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuStartDate")
.name("activeStartDate")
.operators("blcOperators_Date")
.options("[]")
.type(SupportedFieldType.DATE)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuEndDate")
.name("activeEndDate")
.operators("blcOperators_Date")
.options("[]")
.type(SupportedFieldType.DATE)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuProductUrl")
.name("product.url")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuProductIsFeatured")
.name("product.isFeaturedProduct")
.operators("blcOperators_Boolean")
.options("[]")
.type(SupportedFieldType.BOOLEAN)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuProductManufacturer")
.name("product.manufacturer")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuProductModel")
.name("product.model")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
}
@Override
public String getName() {
return RuleIdentifier.SKU;
}
@Override
public String getDtoClassName() {
return "org.broadleafcommerce.core.catalog.domain.SkuImpl";
}
}
| 0true
|
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_web_rulebuilder_service_SkuFieldServiceImpl.java
|
860 |
public class ApplyOperation extends AtomicReferenceBaseOperation {
protected Data function;
protected Data returnValue;
public ApplyOperation() {
super();
}
public ApplyOperation(String name, Data function) {
super(name);
this.function = function;
}
@Override
public void run() throws Exception {
NodeEngine nodeEngine = getNodeEngine();
IFunction f = nodeEngine.toObject(function);
ReferenceWrapper reference = getReference();
Object input = nodeEngine.toObject(reference.get());
//noinspection unchecked
Object output = f.apply(input);
returnValue = nodeEngine.toData(output);
}
@Override
public Object getResponse() {
return returnValue;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeObject(function);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
function = in.readObject();
}
@Override
public int getId() {
return AtomicReferenceDataSerializerHook.APPLY;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_operations_ApplyOperation.java
|
259 |
public class OBasicCommandContext implements OCommandContext {
public static final String EXECUTION_BEGUN = "EXECUTION_BEGUN";
public static final String TIMEOUT_MS = "TIMEOUT_MS";
public static final String TIMEOUT_STRATEGY = "TIMEOUT_STARTEGY";
protected boolean recordMetrics = false;
protected OCommandContext parent;
protected OCommandContext child;
protected Map<String, Object> variables;
// MANAGES THE TIMEOUT
private long executionStartedOn;
private long timeoutMs;
private com.orientechnologies.orient.core.command.OCommandContext.TIMEOUT_STRATEGY timeoutStrategy;
public OBasicCommandContext() {
}
public Object getVariable(String iName) {
return getVariable(iName, null);
}
public Object getVariable(String iName, final Object iDefault) {
if (iName == null)
return iDefault;
Object result = null;
if (iName.startsWith("$"))
iName = iName.substring(1);
int pos = OStringSerializerHelper.getLowerIndexOf(iName, 0, ".", "[");
String firstPart;
String lastPart;
if (pos > -1) {
firstPart = iName.substring(0, pos);
if (iName.charAt(pos) == '.')
pos++;
lastPart = iName.substring(pos);
if (firstPart.equalsIgnoreCase("PARENT") && parent != null) {
// UP TO THE PARENT
if (lastPart.startsWith("$"))
result = parent.getVariable(lastPart.substring(1));
else
result = ODocumentHelper.getFieldValue(parent, lastPart);
return result != null ? result : iDefault;
} else if (firstPart.equalsIgnoreCase("ROOT")) {
OCommandContext p = this;
while (p.getParent() != null)
p = p.getParent();
if (lastPart.startsWith("$"))
result = p.getVariable(lastPart.substring(1));
else
result = ODocumentHelper.getFieldValue(p, lastPart, this);
return result != null ? result : iDefault;
}
} else {
firstPart = iName;
lastPart = null;
}
if (firstPart.equalsIgnoreCase("CONTEXT"))
result = getVariables();
else if (firstPart.equalsIgnoreCase("PARENT"))
result = parent;
else if (firstPart.equalsIgnoreCase("ROOT")) {
OCommandContext p = this;
while (p.getParent() != null)
p = p.getParent();
result = p;
} else {
if (variables != null && variables.containsKey(firstPart))
result = variables.get(firstPart);
else if (child != null)
result = child.getVariable(firstPart);
}
if (pos > -1)
result = ODocumentHelper.getFieldValue(result, lastPart, this);
return result != null ? result : iDefault;
}
public OCommandContext setVariable(String iName, final Object iValue) {
if (iName == null)
return null;
if (iName.startsWith("$"))
iName = iName.substring(1);
init();
int pos = OStringSerializerHelper.getHigherIndexOf(iName, 0, ".", "[");
if (pos > -1) {
Object nested = getVariable(iName.substring(0, pos));
if (nested != null && nested instanceof OCommandContext)
((OCommandContext) nested).setVariable(iName.substring(pos + 1), iValue);
} else
variables.put(iName, iValue);
return this;
}
public long updateMetric(final String iName, final long iValue) {
if (!recordMetrics)
return -1;
init();
Long value = (Long) variables.get(iName);
if (value == null)
value = iValue;
else
value = new Long(value.longValue() + iValue);
variables.put(iName, value);
return value.longValue();
}
/**
* Returns a read-only map with all the variables.
*/
public Map<String, Object> getVariables() {
final HashMap<String, Object> map = new HashMap<String, Object>();
if (child != null)
map.putAll(child.getVariables());
if (variables != null)
map.putAll(variables);
return map;
}
/**
* Set the inherited context avoiding to copy all the values every time.
*
* @return
*/
public OCommandContext setChild(final OCommandContext iContext) {
if (iContext == null) {
if (child != null) {
// REMOVE IT
child.setParent(null);
child = null;
}
} else if (child != iContext) {
// ADD IT
child = iContext;
iContext.setParent(this);
}
return this;
}
public OCommandContext getParent() {
return parent;
}
public OCommandContext setParent(final OCommandContext iParentContext) {
if (parent != iParentContext) {
parent = iParentContext;
if (parent != null)
parent.setChild(this);
}
return this;
}
@Override
public String toString() {
return getVariables().toString();
}
private void init() {
if (variables == null)
variables = new HashMap<String, Object>();
}
public boolean isRecordingMetrics() {
return recordMetrics;
}
public OCommandContext setRecordingMetrics(final boolean recordMetrics) {
this.recordMetrics = recordMetrics;
return this;
}
@Override
public void beginExecution(final long iTimeout, final TIMEOUT_STRATEGY iStrategy) {
if (iTimeout > 0) {
executionStartedOn = System.currentTimeMillis();
timeoutMs = iTimeout;
timeoutStrategy = iStrategy;
}
}
public boolean checkTimeout() {
if (timeoutMs > 0) {
if (System.currentTimeMillis() - executionStartedOn > timeoutMs) {
// TIMEOUT!
switch (timeoutStrategy) {
case RETURN:
return false;
case EXCEPTION:
throw new OTimeoutException("Command execution timeout exceed (" + timeoutMs + "ms)");
}
}
}
return true;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_command_OBasicCommandContext.java
|
364 |
public class OGraphDatabaseMigration {
public static void main(final String[] iArgs) {
if (iArgs.length < 1) {
System.err.println("Error: wrong parameters. Syntax: <database-url> [<user> <password>]");
return;
}
final String dbURL = iArgs[0];
final String user = iArgs.length > 1 ? iArgs[1] : null;
final String password = iArgs.length > 2 ? iArgs[2] : null;
migrate(dbURL, user, password);
}
public static void migrate(final String dbURL, final String user, final String password) {
migrate((OGraphDatabase) new OGraphDatabase(dbURL).open(user, password));
}
public static void migrate(final OGraphDatabase db) {
System.out.println("Migration of database started...");
final long start = System.currentTimeMillis();
try {
// CONVERT ALL THE VERTICES
long convertedVertices = 0;
for (ODocument doc : db.browseVertices()) {
boolean converted = false;
if (doc.containsField(OGraphDatabase.VERTEX_FIELD_IN_OLD)) {
doc.field(OGraphDatabase.VERTEX_FIELD_IN, doc.field(OGraphDatabase.VERTEX_FIELD_IN_OLD));
doc.removeField(OGraphDatabase.VERTEX_FIELD_IN_OLD);
converted = true;
}
if (doc.containsField(OGraphDatabase.VERTEX_FIELD_OUT_OLD)) {
doc.field(OGraphDatabase.VERTEX_FIELD_OUT, doc.field(OGraphDatabase.VERTEX_FIELD_OUT_OLD));
doc.removeField(OGraphDatabase.VERTEX_FIELD_OUT_OLD);
converted = true;
}
if (converted) {
doc.save();
convertedVertices++;
}
}
System.out.println(String.format("Migration complete in %d seconds. Vertices converted: %d",
(System.currentTimeMillis() - start) / 1000, convertedVertices));
} finally {
db.close();
}
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_graph_OGraphDatabaseMigration.java
|
1,274 |
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<Response>>() {
@Override
public ActionFuture<Response> doWithNode(DiscoveryNode node) throws ElasticsearchException {
return proxy.execute(node, request);
}
});
| 1no label
|
src_main_java_org_elasticsearch_client_transport_support_InternalTransportIndicesAdminClient.java
|
3,492 |
public static class Names {
private final String name;
private final String indexName;
private final String indexNameClean;
private final String fullName;
private final String sourcePath;
public Names(String name) {
this(name, name, name, name);
}
public Names(String name, String indexName, String indexNameClean, String fullName) {
this(name, indexName, indexNameClean, fullName, fullName);
}
public Names(String name, String indexName, String indexNameClean, String fullName, @Nullable String sourcePath) {
this.name = name.intern();
this.indexName = indexName.intern();
this.indexNameClean = indexNameClean.intern();
this.fullName = fullName.intern();
this.sourcePath = sourcePath == null ? this.fullName : sourcePath.intern();
}
/**
* The logical name of the field.
*/
public String name() {
return name;
}
/**
* The indexed name of the field. This is the name under which we will
* store it in the index.
*/
public String indexName() {
return indexName;
}
/**
* The cleaned index name, before any "path" modifications performed on it.
*/
public String indexNameClean() {
return indexNameClean;
}
/**
* The full name, including dot path.
*/
public String fullName() {
return fullName;
}
/**
* The dot path notation to extract the value from source.
*/
public String sourcePath() {
return sourcePath;
}
/**
* Creates a new index term based on the provided value.
*/
public Term createIndexNameTerm(String value) {
return new Term(indexName, value);
}
/**
* Creates a new index term based on the provided value.
*/
public Term createIndexNameTerm(BytesRef value) {
return new Term(indexName, value);
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_mapper_FieldMapper.java
|
478 |
listener.onMessage("\n--- DB1: " + makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<String>() {
public String call() {
return indexOneValue.toString();
}
}));
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java
|
356 |
public class DirectCopyClassTransformer implements BroadleafClassTransformer {
protected SupportLogger logger;
protected String moduleName;
protected Map<String, String> xformTemplates = new HashMap<String, String>();
protected static List<String> transformedMethods = new ArrayList<String>();
public DirectCopyClassTransformer(String moduleName) {
this.moduleName = moduleName;
logger = SupportLogManager.getLogger(moduleName, this.getClass());
}
@Override
public void compileJPAProperties(Properties props, Object key) throws Exception {
// When simply copying properties over for Java class files, JPA properties do not need modification
}
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String convertedClassName = className.replace('/', '.');
if (xformTemplates.containsKey(convertedClassName)) {
String xformKey = convertedClassName;
String[] xformVals = xformTemplates.get(xformKey).split(",");
logger.lifecycle(LifeCycleEvent.START, String.format("Transform - Copying into [%s] from [%s]", xformKey,
StringUtils.join(xformVals, ",")));
try {
// Load the destination class and defrost it so it is eligible for modifications
ClassPool classPool = ClassPool.getDefault();
CtClass clazz = classPool.makeClass(new ByteArrayInputStream(classfileBuffer), false);
clazz.defrost();
for (String xformVal : xformVals) {
// Load the source class
String trimmed = xformVal.trim();
classPool.appendClassPath(new LoaderClassPath(Class.forName(trimmed).getClassLoader()));
CtClass template = classPool.get(trimmed);
// Add in extra interfaces
CtClass[] interfacesToCopy = template.getInterfaces();
for (CtClass i : interfacesToCopy) {
logger.debug(String.format("Adding interface [%s]", i.getName()));
clazz.addInterface(i);
}
// Copy over all declared fields from the template class
// Note that we do not copy over fields with the @NonCopiedField annotation
CtField[] fieldsToCopy = template.getDeclaredFields();
for (CtField field : fieldsToCopy) {
if (field.hasAnnotation(NonCopied.class)) {
logger.debug(String.format("Not adding field [%s]", field.getName()));
} else {
logger.debug(String.format("Adding field [%s]", field.getName()));
CtField copiedField = new CtField(field, clazz);
boolean defaultConstructorFound = false;
String implClass = getImplementationType(field.getType().getName());
// Look through all of the constructors in the implClass to see
// if there is one that takes zero parameters
try {
CtConstructor[] implConstructors = classPool.get(implClass).getConstructors();
if (implConstructors != null) {
for (CtConstructor cons : implConstructors) {
if (cons.getParameterTypes().length == 0) {
defaultConstructorFound = true;
break;
}
}
}
} catch (NotFoundException e) {
// Do nothing -- if we don't find this implementation, it's probably because it's
// an array. In this case, we will not initialize the field.
}
if (defaultConstructorFound) {
clazz.addField(copiedField, "new " + implClass + "()");
} else {
clazz.addField(copiedField);
}
}
}
// Copy over all declared methods from the template class
CtMethod[] methodsToCopy = template.getDeclaredMethods();
for (CtMethod method : methodsToCopy) {
if (method.hasAnnotation(NonCopied.class)) {
logger.debug(String.format("Not adding method [%s]", method.getName()));
} else {
try {
CtClass[] paramTypes = method.getParameterTypes();
CtMethod originalMethod = clazz.getDeclaredMethod(method.getName(), paramTypes);
if (transformedMethods.contains(methodDescription(originalMethod))) {
throw new RuntimeException("Method already replaced " + methodDescription(originalMethod));
} else {
logger.debug(String.format("Marking as replaced [%s]", methodDescription(originalMethod)));
transformedMethods.add(methodDescription(originalMethod));
}
logger.debug(String.format("Removing method [%s]", method.getName()));
clazz.removeMethod(originalMethod);
} catch (NotFoundException e) {
// Do nothing -- we don't need to remove a method because it doesn't exist
}
logger.debug(String.format("Adding method [%s]", method.getName()));
CtMethod copiedMethod = new CtMethod(method, clazz, null);
clazz.addMethod(copiedMethod);
}
}
}
logger.lifecycle(LifeCycleEvent.END, String.format("Transform - Copying into [%s] from [%s]", xformKey,
StringUtils.join(xformVals, ",")));
return clazz.toBytecode();
} catch (Exception e) {
throw new RuntimeException("Unable to transform class", e);
}
}
return null;
}
/**
* This method will do its best to return an implementation type for a given classname. This will allow weaving
* template classes to have initialized values.
*
* We provide default implementations for List, Map, and Set, and will attempt to utilize a default constructor for
* other classes.
*
* If the className contains an '[', we will return null.
*/
protected String getImplementationType(String className) {
if (className.equals("java.util.List")) {
return "java.util.ArrayList";
} else if (className.equals("java.util.Map")) {
return "java.util.HashMap";
} else if (className.equals("java.util.Set")) {
return "java.util.HashSet";
} else if (className.contains("[")) {
return null;
}
return className;
}
protected String methodDescription(CtMethod method) {
return method.getDeclaringClass().getName() + "|" + method.getName() + "|" + method.getSignature();
}
public Map<String, String> getXformTemplates() {
return xformTemplates;
}
public void setXformTemplates(Map<String, String> xformTemplates) {
this.xformTemplates = xformTemplates;
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_extensibility_jpa_copy_DirectCopyClassTransformer.java
|
3,972 |
public class TopChildrenQueryParser implements QueryParser {
public static final String NAME = "top_children";
@Inject
public TopChildrenQueryParser() {
}
@Override
public String[] names() {
return new String[]{NAME, Strings.toCamelCase(NAME)};
}
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
Query innerQuery = null;
boolean queryFound = false;
float boost = 1.0f;
String childType = null;
ScoreType scoreType = ScoreType.MAX;
int factor = 5;
int incrementalFactor = 2;
String queryName = null;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("query".equals(currentFieldName)) {
queryFound = true;
// TODO we need to set the type, but, `query` can come before `type`... (see HasChildFilterParser)
// since we switch types, make sure we change the context
String[] origTypes = QueryParseContext.setTypesWithPrevious(childType == null ? null : new String[]{childType});
try {
innerQuery = parseContext.parseInnerQuery();
} finally {
QueryParseContext.setTypes(origTypes);
}
} else {
throw new QueryParsingException(parseContext.index(), "[top_children] query does not support [" + currentFieldName + "]");
}
} else if (token.isValue()) {
if ("type".equals(currentFieldName)) {
childType = parser.text();
} else if ("_scope".equals(currentFieldName)) {
throw new QueryParsingException(parseContext.index(), "the [_scope] support in [top_children] query has been removed, use a filter as a facet_filter in the relevant global facet");
} else if ("score".equals(currentFieldName)) {
scoreType = ScoreType.fromString(parser.text());
} else if ("score_mode".equals(currentFieldName) || "scoreMode".equals(currentFieldName)) {
scoreType = ScoreType.fromString(parser.text());
} else if ("boost".equals(currentFieldName)) {
boost = parser.floatValue();
} else if ("factor".equals(currentFieldName)) {
factor = parser.intValue();
} else if ("incremental_factor".equals(currentFieldName) || "incrementalFactor".equals(currentFieldName)) {
incrementalFactor = parser.intValue();
} else if ("_name".equals(currentFieldName)) {
queryName = parser.text();
} else {
throw new QueryParsingException(parseContext.index(), "[top_children] query does not support [" + currentFieldName + "]");
}
}
}
if (!queryFound) {
throw new QueryParsingException(parseContext.index(), "[top_children] requires 'query' field");
}
if (childType == null) {
throw new QueryParsingException(parseContext.index(), "[top_children] requires 'type' field");
}
if (innerQuery == null) {
return null;
}
if ("delete_by_query".equals(SearchContext.current().source())) {
throw new QueryParsingException(parseContext.index(), "[top_children] unsupported in delete_by_query api");
}
DocumentMapper childDocMapper = parseContext.mapperService().documentMapper(childType);
if (childDocMapper == null) {
throw new QueryParsingException(parseContext.index(), "No mapping for for type [" + childType + "]");
}
if (!childDocMapper.parentFieldMapper().active()) {
throw new QueryParsingException(parseContext.index(), "Type [" + childType + "] does not have parent mapping");
}
String parentType = childDocMapper.parentFieldMapper().type();
innerQuery.setBoost(boost);
// wrap the query with type query
innerQuery = new XFilteredQuery(innerQuery, parseContext.cacheFilter(childDocMapper.typeFilter(), null));
TopChildrenQuery query = new TopChildrenQuery(innerQuery, childType, parentType, scoreType, factor, incrementalFactor, parseContext.cacheRecycler());
if (queryName != null) {
parseContext.addNamedFilter(queryName, new CustomQueryWrappingFilter(query));
}
return query;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_query_TopChildrenQueryParser.java
|
542 |
public class RecoverAllTransactionsRequest extends InvocationClientRequest {
public RecoverAllTransactionsRequest() {
}
@Override
public void invoke() {
ClientEngine clientEngine = getClientEngine();
ClusterService clusterService = clientEngine.getClusterService();
Collection<MemberImpl> memberList = clusterService.getMemberList();
TransactionManagerServiceImpl service = getService();
List<Future<SerializableCollection>> futures = recoverTransactions(memberList);
Set<Data> xids = new HashSet<Data>();
for (Future<SerializableCollection> future : futures) {
try {
SerializableCollection collectionWrapper = future.get(RECOVER_TIMEOUT, TimeUnit.MILLISECONDS);
for (Data data : collectionWrapper) {
RecoveredTransaction rt = (RecoveredTransaction) clientEngine.toObject(data);
service.addClientRecoveredTransaction(rt);
xids.add(clientEngine.toData(rt.getXid()));
}
} catch (MemberLeftException e) {
ILogger logger = clientEngine.getLogger(RecoverAllTransactionsRequest.class);
logger.warning("Member left while recovering: " + e);
} catch (Throwable e) {
handleException(clientEngine, e);
}
}
ClientEndpoint endpoint = getEndpoint();
endpoint.sendResponse(new SerializableCollection(xids), getCallId());
}
private List<Future<SerializableCollection>> recoverTransactions(Collection<MemberImpl> memberList) {
List<Future<SerializableCollection>> futures = new ArrayList<Future<SerializableCollection>>(memberList.size());
for (MemberImpl member : memberList) {
RecoverTxnOperation op = new RecoverTxnOperation();
Future<SerializableCollection> f = createInvocationBuilder(TransactionManagerServiceImpl.SERVICE_NAME,
op, member.getAddress()).invoke();
futures.add(f);
}
return futures;
}
private void handleException(ClientEngine clientEngine, Throwable e) {
Throwable cause = getCause(e);
if (cause instanceof TargetNotMemberException) {
ILogger logger = clientEngine.getLogger(RecoverAllTransactionsRequest.class);
logger.warning("Member left while recovering: " + cause);
} else {
throw ExceptionUtil.rethrow(e);
}
}
private Throwable getCause(Throwable e) {
if (e instanceof ExecutionException) {
if (e.getCause() != null) {
return e.getCause();
}
}
return e;
}
@Deprecated
public String getServiceName() {
return TransactionManagerServiceImpl.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return ClientTxnPortableHook.F_ID;
}
@Override
public int getClassId() {
return ClientTxnPortableHook.RECOVER_ALL;
}
@Override
public Permission getRequiredPermission() {
return new TransactionPermission();
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_txn_RecoverAllTransactionsRequest.java
|
828 |
getDatabase().getStorage().callInLock(new Callable<Object>() {
@Override
public Object call() throws Exception {
final OClass cls = classes.get(key);
if (cls == null)
throw new OSchemaException("Class " + iClassName + " was not found in current database");
if (cls.getBaseClasses().hasNext())
throw new OSchemaException("Class " + iClassName
+ " cannot be dropped because it has sub classes. Remove the dependencies before trying to drop it again");
if (cls.getSuperClass() != null) {
// REMOVE DEPENDENCY FROM SUPERCLASS
((OClassImpl) cls.getSuperClass()).removeBaseClassInternal(cls);
}
dropClassIndexes(cls);
classes.remove(key);
if (cls.getShortName() != null)
// REMOVE THE ALIAS TOO
classes.remove(cls.getShortName().toLowerCase());
return null;
}
}, true);
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OSchemaShared.java
|
417 |
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface AdminPresentationMapField {
/**
* <p>Represents the field name for this field.</p>
*
* @return the name for this field
*/
String fieldName();
/**
* <p>Represents the metadata for this field. The <tt>AdminPresentation</tt> properties will be used
* by the system to determine how this field should be treated in the admin tool (e.g. date fields get
* a date picker in the UI)</p>
*
* @return the descriptive metadata for this field
*/
AdminPresentation fieldPresentation();
/**
* <p>Optional - if the Map structure is using generics, then the system can usually infer the concrete
* type for the Map value. However, if not using generics for the Map, or if the value cannot be clearly
* inferred, you can explicitly set the Map structure value type here. Map fields can only understand
* maps whose values are basic types (String, Long, Date, etc...). Complex types require additional
* support. Support is provided out-of-the-box for complex types <tt>ValueAssignable</tt>,
* <tt>Searchable</tt> and <tt>SimpleRule</tt>.</p>
*
* @return the concrete type for the Map structure value
*/
Class<?> targetClass() default Void.class;
/**
* <p>Optional - if the map field value contains searchable information and should be included in Broadleaf
* search engine indexing and searching. If set, the map value class must implement the <tt>Searchable</tt> interface.
* Note, support for indexing and searching this field must be explicitly added to the Broadleaf search service
* as well.</p>
*
* @return Whether or not this field is searchable with the Broadleaf search engine
*/
CustomFieldSearchableTypes searchable() default CustomFieldSearchableTypes.NOT_SPECIFIED;
/**
* <p>Optional - if the value is not primitive and contains a bi-directional reference back to the entity containing
* this map structure, you can declare the field name in the value class for this reference. Note, if the map
* uses the JPA mappedBy property, the system will try to infer the manyToField value so you don't have to set
* it here.</p>
*
* @return the parent entity referring field name
*/
String manyToField() default "";
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentationMapField.java
|
713 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_PRODUCT_OPTION_VALUE")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
@AdminPresentationClass(friendlyName = "Product Option Value")
public class ProductOptionValueImpl implements ProductOptionValue {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "ProductOptionValueId")
@GenericGenerator(
name = "ProductOptionValueId",
strategy = "org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name = "segment_value", value = "ProductOptionValueImpl"),
@Parameter(name = "entity_name", value = "org.broadleafcommerce.core.catalog.domain.ProductOptionValueImpl")
})
@Column(name = "PRODUCT_OPTION_VALUE_ID")
protected Long id;
@Column(name = "ATTRIBUTE_VALUE")
@AdminPresentation(friendlyName = "productOptionValue_attributeValue",
prominent = true,
translatable = true)
protected String attributeValue;
@Column(name = "DISPLAY_ORDER")
@AdminPresentation(friendlyName = "productOptionValue_displayOrder", prominent = true)
protected Long displayOrder;
@Column(name = "PRICE_ADJUSTMENT", precision = 19, scale = 5)
@AdminPresentation(friendlyName = "productOptionValue_adjustment", fieldType = SupportedFieldType.MONEY, prominent = true)
protected BigDecimal priceAdjustment;
@ManyToOne(targetEntity = ProductOptionImpl.class)
@JoinColumn(name = "PRODUCT_OPTION_ID")
protected ProductOption productOption;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getAttributeValue() {
return DynamicTranslationProvider.getValue(this, "attributeValue", attributeValue);
}
@Override
public void setAttributeValue(String attributeValue) {
this.attributeValue = attributeValue;
}
@Override
public Long getDisplayOrder() {
return displayOrder;
}
@Override
public void setDisplayOrder(Long displayOrder) {
this.displayOrder = displayOrder;
}
@Override
public Money getPriceAdjustment() {
Money returnPrice = null;
if (SkuPricingConsiderationContext.hasDynamicPricing()) {
DynamicSkuPrices dynamicPrices = SkuPricingConsiderationContext.getSkuPricingService().getPriceAdjustment(this, priceAdjustment == null ? null : new Money(priceAdjustment), SkuPricingConsiderationContext.getSkuPricingConsiderationContext());
returnPrice = dynamicPrices.getPriceAdjustment();
} else {
if (priceAdjustment != null) {
returnPrice = new Money(priceAdjustment, Money.defaultCurrency());
}
}
return returnPrice;
}
@Override
public void setPriceAdjustment(Money priceAdjustment) {
this.priceAdjustment = Money.toAmount(priceAdjustment);
}
@Override
public ProductOption getProductOption() {
return productOption;
}
@Override
public void setProductOption(ProductOption productOption) {
this.productOption = productOption;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ProductOptionValueImpl other = (ProductOptionValueImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (getAttributeValue() == null) {
if (other.getAttributeValue() != null) {
return false;
}
} else if (!getAttributeValue().equals(other.getAttributeValue())) {
return false;
}
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_ProductOptionValueImpl.java
|
171 |
private class TxManagerDataSourceRegistrationListener implements DataSourceRegistrationListener
{
@Override
public void registeredDataSource( XaDataSource ds )
{
branches.put( new RecoveredBranchInfo( ds.getBranchId() ), true );
boolean everythingRegistered = true;
for ( boolean dsRegistered : branches.values() )
{
everythingRegistered &= dsRegistered;
}
if ( everythingRegistered )
{
doRecovery();
}
}
@Override
public void unregisteredDataSource( XaDataSource ds )
{
branches.put( new RecoveredBranchInfo( ds.getBranchId() ), false );
boolean everythingUnregistered = true;
for ( boolean dsRegistered : branches.values() )
{
everythingUnregistered &= !dsRegistered;
}
if ( everythingUnregistered )
{
closeLog();
}
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TxManager.java
|
1,255 |
public class CeylonApplicationLaunchShortcut implements ILaunchShortcut {
@Override
public void launch(ISelection selection, String mode) {
if (! (selection instanceof IStructuredSelection)) {
return;
}
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
List<IFile> files = new LinkedList<IFile>();
for (Object object : structuredSelection.toList()) {
if (object instanceof IAdaptable) {
IResource resource = (IResource) ((IAdaptable)object).getAdapter(IResource.class);
if (resource != null) {
addFiles(files, resource);
}
}
}
searchAndLaunch(files, mode);
}
public void addFiles(List<IFile> files, IResource resource) {
switch (resource.getType()) {
case IResource.FILE:
IFile file = (IFile) resource;
IPath path = file.getFullPath(); //getProjectRelativePath();
if (path!=null && "ceylon".equals(path.getFileExtension()) ) {
files.add(file);
}
break;
case IResource.FOLDER:
case IResource.PROJECT:
IContainer folder = (IContainer) resource;
try {
for (IResource child: folder.members()) {
addFiles(files, child);
}
}
catch (CoreException e) {
e.printStackTrace();
}
break;
}
}
@Override
public void launch(IEditorPart editor, String mode) {
IFile file = EditorUtil.getFile(editor.getEditorInput());
if (editor instanceof CeylonEditor) {
CeylonEditor ce = (CeylonEditor) editor;
CeylonParseController cpc = ce.getParseController();
if (cpc!=null) {
Tree.CompilationUnit cu = cpc.getRootNode();
if (cu!=null) {
ISelection selection = ce.getSelectionProvider().getSelection();
if (selection instanceof ITextSelection) {
Node node = Nodes.findToplevelStatement(cu, Nodes.findNode(cu, (ITextSelection) selection));
if (node instanceof Tree.AnyMethod) {
Method method = ((Tree.AnyMethod) node).getDeclarationModel();
if (method.isToplevel() &&
method.isShared() &&
!method.getParameterLists().isEmpty() &&
method.getParameterLists().get(0).getParameters().isEmpty()) {
launch(method, file, mode);
return;
}
}
if (node instanceof Tree.AnyClass) {
Class clazz = ((Tree.AnyClass) node).getDeclarationModel();
if (clazz.isToplevel() &&
clazz.isShared() &&
!clazz.isAbstract() &&
clazz.getParameterList()!=null &&
clazz.getParameterList().getParameters().isEmpty()) {
launch(clazz, file, mode);
return;
}
}
}
}
}
}
searchAndLaunch(Arrays.asList(file), mode);
}
private void searchAndLaunch(List<IFile> files, String mode) {
List<Declaration> topLevelDeclarations = new LinkedList<Declaration>();
List<IFile> correspondingfiles = new LinkedList<IFile>();
for (IFile file : files) {
IProject project = file.getProject();
TypeChecker typeChecker = CeylonBuilder.getProjectTypeChecker(project);
if (typeChecker != null) {
PhasedUnit phasedUnit = typeChecker.getPhasedUnits()
.getPhasedUnit(ResourceVirtualFile.createResourceVirtualFile(file));
if (phasedUnit!=null) {
List<Declaration> declarations = phasedUnit.getDeclarations();
for (Declaration d : declarations) {
boolean candidateDeclaration = true;
if (!d.isToplevel() || !d.isShared()) {
candidateDeclaration = false;
}
if (d instanceof Method) {
Method methodDecl = (Method) d;
if (!methodDecl.getParameterLists().isEmpty() &&
!methodDecl.getParameterLists().get(0).getParameters().isEmpty()) {
candidateDeclaration = false;
}
}
else if (d instanceof Class) {
Class classDecl = (Class) d;
if (classDecl.isAbstract() ||
classDecl.getParameterList()==null ||
!classDecl.getParameterList().getParameters().isEmpty()) {
candidateDeclaration = false;
}
}
else {
candidateDeclaration = false;
}
if (candidateDeclaration) {
topLevelDeclarations.add(d);
correspondingfiles.add(file);
}
}
}
}
}
Declaration declarationToRun = null;
IFile fileToRun = null;
if (topLevelDeclarations.size() == 0) {
MessageDialog.openError(EditorUtil.getShell(), "Ceylon Launcher",
"No ceylon runnable element");
}
else if (topLevelDeclarations.size() > 1) {
declarationToRun = chooseDeclaration(topLevelDeclarations);
if (declarationToRun!=null) {
fileToRun = correspondingfiles.get(topLevelDeclarations.indexOf(declarationToRun));
}
}
else {
declarationToRun = topLevelDeclarations.get(0);
fileToRun = correspondingfiles.get(0);
}
if (declarationToRun != null) {
launch(declarationToRun, fileToRun, mode);
}
}
private static final String SETTINGS_ID = CeylonPlugin.PLUGIN_ID + ".TOPLEVEL_DECLARATION_SELECTION_DIALOG";
public static Declaration chooseDeclaration(final List<Declaration> declarations) {
FilteredItemsSelectionDialog sd = new FilteredItemsSelectionDialog(EditorUtil.getShell())
{
{
setTitle("Ceylon Launcher");
setMessage("Select the toplevel method or class to launch:");
setListLabelProvider(new LabelProvider());
setDetailsLabelProvider(new DetailsLabelProvider());
setListSelectionLabelDecorator(new SelectionLabelDecorator());
}
@Override
protected Control createExtendedContentArea(Composite parent) {
return null;
}
@Override
protected IDialogSettings getDialogSettings() {
IDialogSettings settings = CeylonPlugin.getInstance().getDialogSettings();
IDialogSettings section = settings.getSection(SETTINGS_ID);
if (section == null) {
section = settings.addNewSection(SETTINGS_ID);
}
return section;
}
@Override
protected IStatus validateItem(Object item) {
return Status.OK_STATUS;
}
@Override
protected ItemsFilter createFilter() {
return new ItemsFilter() {
@Override
public boolean matchItem(Object item) {
return matches(getElementName(item));
}
@Override
public boolean isConsistentItem(Object item) {
return true;
}
@Override
public String getPattern() {
String pattern = super.getPattern();
return pattern.isEmpty() ? "**" : pattern;
}
};
}
@Override
protected Comparator<?> getItemsComparator() {
Comparator<Object> comp = new Comparator<Object>() {
public int compare(Object o1, Object o2) {
if(o1 instanceof Declaration && o2 instanceof Declaration) {
if (o1 instanceof TypedDeclaration && o2 instanceof TypeDeclaration) {
return -1;
}
else if (o2 instanceof TypedDeclaration && o1 instanceof TypeDeclaration) {
return 1;
}
else {
return ((Declaration)o1).getName().compareTo(((Declaration)o2).getName());
}
}
return 0;
}
};
return comp;
}
@Override
protected void fillContentProvider(
AbstractContentProvider contentProvider,
ItemsFilter itemsFilter, IProgressMonitor progressMonitor)
throws CoreException {
if(declarations != null) {
for(Declaration d : declarations) {
if(itemsFilter.isConsistentItem(d)) {
contentProvider.add(d, itemsFilter);
}
}
}
}
@Override
public String getElementName(Object item) {
return ((Declaration) item).getName();
}
};
if (sd.open() == Window.OK) {
return (Declaration)sd.getFirstResult();
}
return null;
}
static class LabelProvider extends StyledCellLabelProvider
implements DelegatingStyledCellLabelProvider.IStyledLabelProvider, ILabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {}
@Override
public void dispose() {}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public void removeListener(ILabelProviderListener listener) {}
@Override
public Image getImage(Object element) {
Declaration d = (Declaration) element;
return d==null ? null : CeylonLabelProvider.getImageForDeclaration(d);
}
@Override
public String getText(Object element) {
Declaration d = (Declaration) element;
return d==null ? null : getLabelDescriptionFor(d);
}
@Override
public StyledString getStyledText(Object element) {
if (element==null) {
return new StyledString();
}
else {
Declaration d = (Declaration) element;
return getStyledDescriptionFor(d);
}
}
@Override
public void update(ViewerCell cell) {
Object element = cell.getElement();
if (element!=null) {
StyledString styledText = getStyledText(element);
cell.setText(styledText.toString());
cell.setStyleRanges(styledText.getStyleRanges());
cell.setImage(getImage(element));
super.update(cell);
}
}
}
static class DetailsLabelProvider implements ILabelProvider {
@Override
public void removeListener(ILabelProviderListener listener) {}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public void dispose() {}
@Override
public void addListener(ILabelProviderListener listener) {}
@Override
public String getText(Object element) {
return getPackageLabel((Declaration) element);
}
@Override
public Image getImage(Object element) {
return PACKAGE;
}
}
static class SelectionLabelDecorator implements ILabelDecorator {
@Override
public void removeListener(ILabelProviderListener listener) {}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public void dispose() {}
@Override
public void addListener(ILabelProviderListener listener) {}
@Override
public String decorateText(String text, Object element) {
return text + " - " + getPackageLabel((Declaration) element);
}
@Override
public Image decorateImage(Image image, Object element) {
return null;
}
}
protected String canLaunch(Declaration declarationToRun, IFile fileToRun, String mode) {
if (!CeylonBuilder.compileToJava(fileToRun.getProject())) {
return "JVM compilation is not enabled for this project";
}
return null;
}
private void launch(Declaration declarationToRun, IFile fileToRun, String mode) {
String err = canLaunch(declarationToRun, fileToRun, mode);
if (err != null) {
MessageDialog.openError(EditorUtil.getShell(), "Ceylon Launcher Error", err);
return;
}
ILaunchConfiguration config = findLaunchConfiguration(declarationToRun, fileToRun, getConfigurationType());
if (config == null) {
config = createConfiguration(declarationToRun, fileToRun);
}
if (config != null) {
DebugUITools.launch(config, mode);
}
}
protected ILaunchConfigurationType getConfigurationType() {
return getLaunchManager().getLaunchConfigurationType(ID_CEYLON_APPLICATION);
}
protected ILaunchManager getLaunchManager() {
return DebugPlugin.getDefault().getLaunchManager();
}
/**
* Finds and returns an <b>existing</b> configuration to re-launch for the given type,
* or <code>null</code> if there is no existing configuration.
*
* @return a configuration to use for launching the given type or <code>null</code> if none
*/
protected ILaunchConfiguration findLaunchConfiguration(Declaration declaration, IFile file,
ILaunchConfigurationType configType) {
List<ILaunchConfiguration> candidateConfigs = Collections.<ILaunchConfiguration>emptyList();
try {
ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager()
.getLaunchConfigurations(configType);
candidateConfigs = new ArrayList<ILaunchConfiguration>(configs.length);
String mainClass = getJavaClassName(declaration);
for (int i = 0; i < configs.length; i++) {
ILaunchConfiguration config = configs[i];
if (config.getAttribute(ATTR_MAIN_TYPE_NAME, "")
.equals(mainClass)) {
if (config.getAttribute(ATTR_PROJECT_NAME, "")
.equals(file.getProject().getName())) {
candidateConfigs.add(config);
}
}
}
} catch (CoreException e) {
e.printStackTrace(); // TODO : Use a logger
}
int candidateCount = candidateConfigs.size();
if (candidateCount == 1) {
return candidateConfigs.get(0);
}
else if (candidateCount > 1) {
return chooseConfiguration(candidateConfigs);
}
return null;
}
/**
* Returns a configuration from the given collection of configurations that should be launched,
* or <code>null</code> to cancel. Default implementation opens a selection dialog that allows
* the user to choose one of the specified launch configurations. Returns the chosen configuration,
* or <code>null</code> if the user cancels.
*
* @param configList list of configurations to choose from
* @return configuration to launch or <code>null</code> to cancel
*/
protected ILaunchConfiguration chooseConfiguration(List<ILaunchConfiguration> configList) {
IDebugModelPresentation labelProvider = DebugUITools.newDebugModelPresentation();
ElementListSelectionDialog dialog= new ElementListSelectionDialog(EditorUtil.getShell(), labelProvider);
dialog.setElements(configList.toArray());
dialog.setTitle("Ceylon Launcher");
dialog.setMessage("Please choose a configuration to start the Ceylon application");
dialog.setMultipleSelection(false);
int result = dialog.open();
labelProvider.dispose();
if (result == Window.OK) {
return (ILaunchConfiguration) dialog.getFirstResult();
}
return null;
}
protected ILaunchConfiguration createConfiguration(Declaration declarationToRun, IFile file) {
ILaunchConfiguration config = null;
ILaunchConfigurationWorkingCopy wc = null;
try {
ILaunchConfigurationType configType = getConfigurationType();
String configurationName = "";
if (declarationToRun instanceof Class) {
configurationName += "class ";
}
else {
if (declarationToRun instanceof Method) {
Method method = (Method) declarationToRun;
if (method.isDeclaredVoid()) {
configurationName += "void ";
}
else {
configurationName += "function ";
}
}
}
configurationName += declarationToRun.getName() + "() - ";
String packageName = declarationToRun.getContainer().getQualifiedNameString();
configurationName += packageName.isEmpty() ? "default package" : packageName;
configurationName = configurationName.replaceAll("[\u00c0-\ufffe]", "_");
wc = configType.newInstance(null, getLaunchManager().generateLaunchConfigurationName(configurationName));
wc.setAttribute(ATTR_MAIN_TYPE_NAME, getJavaClassName(declarationToRun));
wc.setAttribute(ATTR_PROJECT_NAME, file.getProject().getName());
wc.setMappedResources(new IResource[] {file});
config = wc.doSave();
} catch (CoreException exception) {
MessageDialog.openError(EditorUtil.getShell(), "Ceylon Launcher Error",
exception.getStatus().getMessage());
}
return config;
}
private String getJavaClassName(Declaration declaration) {
String name = declClassName(declaration.getQualifiedNameString());
if(declaration instanceof Method)
name += "_";
return name;
}
}
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_launch_CeylonApplicationLaunchShortcut.java
|
1,071 |
createIndexAction.execute(new CreateIndexRequest(request.index()).cause("auto(update api)").masterNodeTimeout(request.timeout()), new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse result) {
innerExecute(request, listener);
}
@Override
public void onFailure(Throwable e) {
if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) {
// we have the index, do it
try {
innerExecute(request, listener);
} catch (Throwable e1) {
listener.onFailure(e1);
}
} else {
listener.onFailure(e);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_update_TransportUpdateAction.java
|
1,115 |
public class OSQLFunctionMax extends OSQLFunctionMathAbstract {
public static final String NAME = "max";
private Object context;
public OSQLFunctionMax() {
super(NAME, 1, -1);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object execute(final OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters,
OCommandContext iContext) {
// calculate max value for current record
// consider both collection of parameters and collection in each parameter
Object max = null;
for (Object item : iParameters) {
if (item instanceof Collection<?>) {
for (Object subitem : ((Collection<?>) item)) {
if (max == null || subitem != null && ((Comparable) subitem).compareTo(max) > 0)
max = subitem;
}
} else {
if (max == null || item != null && ((Comparable) item).compareTo(max) > 0)
max = item;
}
}
// what to do with the result, for current record, depends on how this function has been invoked
// for an unique result aggregated from all output records
if (aggregateResults() && max != null) {
if (context == null)
// FIRST TIME
context = (Comparable) max;
else {
if (context instanceof Number && max instanceof Number) {
final Number[] casted = OType.castComparableNumber((Number) context, (Number) max);
context = casted[0];
max = casted[1];
}
if (((Comparable<Object>) context).compareTo((Comparable) max) < 0)
// BIGGER
context = (Comparable) max;
}
return null;
}
// for non aggregated results (a result per output record)
return max;
}
public boolean aggregateResults() {
// LET definitions (contain $current) does not require results aggregation
return ((configuredParameters.length == 1) && !configuredParameters[0].toString().contains("$current"));
}
public String getSyntax() {
return "Syntax error: max(<field> [,<field>*])";
}
@Override
public Object getResult() {
return context;
}
@SuppressWarnings("unchecked")
@Override
public Object mergeDistributedResult(List<Object> resultsToMerge) {
Comparable<Object> context = null;
for (Object iParameter : resultsToMerge) {
final Comparable<Object> value = (Comparable<Object>) iParameter;
if (context == null)
// FIRST TIME
context = value;
else if (context.compareTo(value) < 0)
// BIGGER
context = value;
}
return context;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_functions_math_OSQLFunctionMax.java
|
467 |
new ODbRelatedCall<Iterator<Map.Entry<Object, Object>>>() {
public Iterator<Map.Entry<Object, Object>> call() {
return indexOne.iterator();
}
});
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java
|
535 |
public class OJSONFetchContext implements OFetchContext {
protected final OJSONWriter jsonWriter;
protected final FormatSettings settings;
protected final Stack<StringBuilder> typesStack = new Stack<StringBuilder>();
protected final Stack<ORecordSchemaAware<?>> collectionStack = new Stack<ORecordSchemaAware<?>>();
public OJSONFetchContext(final OJSONWriter iJsonWriter, final FormatSettings iSettings) {
jsonWriter = iJsonWriter;
settings = iSettings;
}
public void onBeforeFetch(final ORecordSchemaAware<?> iRootRecord) {
typesStack.add(new StringBuilder());
}
public void onAfterFetch(final ORecordSchemaAware<?> iRootRecord) {
StringBuilder buffer = typesStack.pop();
if (settings.keepTypes && buffer.length() > 0)
try {
jsonWriter.writeAttribute(settings.indentLevel > -1 ? settings.indentLevel + 1 : -1, true,
ORecordSerializerJSON.ATTRIBUTE_FIELD_TYPES, buffer.toString());
} catch (IOException e) {
throw new OFetchException("Error writing field types", e);
}
}
public void onBeforeStandardField(final Object iFieldValue, final String iFieldName, final Object iUserObject) {
manageTypes(iFieldName, iFieldValue);
}
public void onAfterStandardField(Object iFieldValue, String iFieldName, Object iUserObject) {
}
public void onBeforeArray(final ORecordSchemaAware<?> iRootRecord, final String iFieldName, final Object iUserObject,
final OIdentifiable[] iArray) {
onBeforeCollection(iRootRecord, iFieldName, iUserObject, null);
}
public void onAfterArray(final ORecordSchemaAware<?> iRootRecord, final String iFieldName, final Object iUserObject) {
onAfterCollection(iRootRecord, iFieldName, iUserObject);
}
public void onBeforeCollection(final ORecordSchemaAware<?> iRootRecord, final String iFieldName, final Object iUserObject,
final Collection<?> iCollection) {
try {
manageTypes(iFieldName, iCollection);
jsonWriter.beginCollection(settings.indentLevel, true, iFieldName);
collectionStack.add(iRootRecord);
} catch (IOException e) {
throw new OFetchException("Error writing collection field " + iFieldName + " of record " + iRootRecord.getIdentity(), e);
}
}
public void onAfterCollection(final ORecordSchemaAware<?> iRootRecord, final String iFieldName, final Object iUserObject) {
try {
jsonWriter.endCollection(settings.indentLevel, false);
collectionStack.pop();
} catch (IOException e) {
throw new OFetchException("Error writing collection field " + iFieldName + " of record " + iRootRecord.getIdentity(), e);
}
}
public void onBeforeMap(final ORecordSchemaAware<?> iRootRecord, final String iFieldName, final Object iUserObject) {
settings.indentLevel++;
try {
jsonWriter.beginObject(settings.indentLevel, true, iFieldName);
} catch (IOException e) {
throw new OFetchException("Error writing map field " + iFieldName + " of record " + iRootRecord.getIdentity(), e);
}
}
public void onAfterMap(final ORecordSchemaAware<?> iRootRecord, final String iFieldName, final Object iUserObject) {
try {
jsonWriter.endObject(settings.indentLevel, true);
} catch (IOException e) {
throw new OFetchException("Error writing map field " + iFieldName + " of record " + iRootRecord.getIdentity(), e);
}
settings.indentLevel--;
}
public void onBeforeDocument(final ORecordSchemaAware<?> iRootRecord, final ORecordSchemaAware<?> iDocument,
final String iFieldName, final Object iUserObject) {
settings.indentLevel++;
try {
final String fieldName;
if (!collectionStack.isEmpty() && collectionStack.peek().equals(iRootRecord))
fieldName = null;
else
fieldName = iFieldName;
jsonWriter.beginObject(settings.indentLevel, false, fieldName);
writeSignature(jsonWriter, iDocument);
} catch (IOException e) {
throw new OFetchException("Error writing link field " + iFieldName + " of record " + iRootRecord.getIdentity(), e);
}
}
public void onAfterDocument(final ORecordSchemaAware<?> iRootRecord, final ORecordSchemaAware<?> iDocument,
final String iFieldName, final Object iUserObject) {
try {
jsonWriter.endObject(settings.indentLevel--, true);
} catch (IOException e) {
throw new OFetchException("Error writing link field " + iFieldName + " of record " + iRootRecord.getIdentity(), e);
}
}
public void writeLinkedValue(final OIdentifiable iRecord, final String iFieldName) throws IOException {
jsonWriter.writeValue(settings.indentLevel, true, OJSONWriter.encode(iRecord.getIdentity()));
}
public void writeLinkedAttribute(final OIdentifiable iRecord, final String iFieldName) throws IOException {
jsonWriter.writeAttribute(settings.indentLevel, true, iFieldName, OJSONWriter.encode(iRecord.getIdentity()));
}
public boolean isInCollection(ORecordSchemaAware<?> record) {
return !collectionStack.isEmpty() && collectionStack.peek().equals(record);
}
public OJSONWriter getJsonWriter() {
return jsonWriter;
}
public int getIndentLevel() {
return settings.indentLevel;
}
private void appendType(final StringBuilder iBuffer, final String iFieldName, final char iType) {
if (iBuffer.length() > 0)
iBuffer.append(',');
iBuffer.append(iFieldName);
iBuffer.append('=');
iBuffer.append(iType);
}
public void writeSignature(final OJSONWriter json, final ORecordInternal<?> record) throws IOException {
boolean firstAttribute = true;
if (settings.includeType) {
json.writeAttribute(firstAttribute ? settings.indentLevel : 0, firstAttribute, ODocumentHelper.ATTRIBUTE_TYPE, ""
+ (char) record.getRecordType());
if (settings.attribSameRow)
firstAttribute = false;
}
if (settings.includeId && record.getIdentity() != null && record.getIdentity().isValid()) {
json.writeAttribute(!firstAttribute ? settings.indentLevel : 0, firstAttribute, ODocumentHelper.ATTRIBUTE_RID, record
.getIdentity().toString());
if (settings.attribSameRow)
firstAttribute = false;
}
if (settings.includeVer) {
json.writeAttribute(firstAttribute ? settings.indentLevel : 0, firstAttribute, ODocumentHelper.ATTRIBUTE_VERSION, record
.getRecordVersion().getCounter());
if (settings.attribSameRow)
firstAttribute = false;
if (OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean()) {
final ODistributedVersion ver = (ODistributedVersion) record.getRecordVersion();
json.writeAttribute(firstAttribute ? settings.indentLevel : 0, firstAttribute, ODocumentHelper.ATTRIBUTE_VERSION_TIMESTAMP,
ver.getTimestamp());
json.writeAttribute(firstAttribute ? settings.indentLevel : 0, firstAttribute,
ODocumentHelper.ATTRIBUTE_VERSION_MACADDRESS, ver.getMacAddress());
}
}
if (settings.includeClazz && record instanceof ORecordSchemaAware<?> && ((ORecordSchemaAware<?>) record).getClassName() != null) {
json.writeAttribute(firstAttribute ? settings.indentLevel : 0, firstAttribute, ODocumentHelper.ATTRIBUTE_CLASS,
((ORecordSchemaAware<?>) record).getClassName());
if (settings.attribSameRow)
firstAttribute = false;
}
}
public boolean fetchEmbeddedDocuments() {
return settings.alwaysFetchEmbeddedDocuments;
}
protected void manageTypes(final String iFieldName, final Object iFieldValue) {
if (settings.keepTypes) {
if (iFieldValue instanceof Long)
appendType(typesStack.peek(), iFieldName, 'l');
else if (iFieldValue instanceof Float)
appendType(typesStack.peek(), iFieldName, 'f');
else if (iFieldValue instanceof Short)
appendType(typesStack.peek(), iFieldName, 's');
else if (iFieldValue instanceof Double)
appendType(typesStack.peek(), iFieldName, 'd');
else if (iFieldValue instanceof Date)
appendType(typesStack.peek(), iFieldName, 't');
else if (iFieldValue instanceof Byte || iFieldValue instanceof byte[])
appendType(typesStack.peek(), iFieldName, 'b');
else if (iFieldValue instanceof BigDecimal)
appendType(typesStack.peek(), iFieldName, 'c');
else if (iFieldValue instanceof Set<?>)
appendType(typesStack.peek(), iFieldName, 'e');
}
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_fetch_json_OJSONFetchContext.java
|
6,417 |
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
targetTransport.messageReceived(data, action, LocalTransport.this, version, requestId);
}
});
| 1no label
|
src_main_java_org_elasticsearch_transport_local_LocalTransport.java
|
474 |
public abstract class ClientProxy implements DistributedObject {
protected final String instanceName;
private final String serviceName;
private final String objectName;
private volatile ClientContext context;
protected ClientProxy(String instanceName, String serviceName, String objectName) {
this.instanceName = instanceName;
this.serviceName = serviceName;
this.objectName = objectName;
}
protected final String listen(ClientRequest registrationRequest, Object partitionKey, EventHandler handler) {
return ListenerUtil.listen(context, registrationRequest, partitionKey, handler);
}
protected final String listen(ClientRequest registrationRequest, EventHandler handler) {
return ListenerUtil.listen(context, registrationRequest, null, handler);
}
protected final boolean stopListening(BaseClientRemoveListenerRequest request, String registrationId) {
return ListenerUtil.stopListening(context, request, registrationId);
}
protected final ClientContext getContext() {
final ClientContext ctx = context;
if (ctx == null) {
throw new DistributedObjectDestroyedException(serviceName, objectName);
}
return ctx;
}
protected final void setContext(ClientContext context) {
this.context = context;
}
@Deprecated
public final Object getId() {
return objectName;
}
public final String getName() {
return objectName;
}
public String getPartitionKey() {
return StringPartitioningStrategy.getPartitionKey(getName());
}
public final String getServiceName() {
return serviceName;
}
public final void destroy() {
onDestroy();
ClientDestroyRequest request = new ClientDestroyRequest(objectName, getServiceName());
try {
context.getInvocationService().invokeOnRandomTarget(request).get();
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
context.removeProxy(this);
context = null;
}
protected abstract void onDestroy();
protected void onShutdown() {
}
protected <T> T invoke(ClientRequest req, Object key) {
try {
final Future future = getInvocationService().invokeOnKeyOwner(req, key);
Object result = future.get();
return toObject(result);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
protected <T> T invokeInterruptibly(ClientRequest req, Object key) throws InterruptedException {
try {
final Future future = getInvocationService().invokeOnKeyOwner(req, key);
Object result = future.get();
return toObject(result);
} catch (Exception e) {
throw ExceptionUtil.rethrowAllowInterrupted(e);
}
}
private ClientInvocationService getInvocationService() {
return getContext().getInvocationService();
}
protected <T> T invoke(ClientRequest req) {
try {
final Future future = getInvocationService().invokeOnRandomTarget(req);
Object result = future.get();
return toObject(result);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
protected <T> T invoke(ClientRequest req, Address address) {
try {
final Future future = getInvocationService().invokeOnTarget(req, address);
Object result = future.get();
return toObject(result);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
protected Data toData(Object o) {
return getContext().getSerializationService().toData(o);
}
protected <T> T toObject(Object data) {
return getContext().getSerializationService().toObject(data);
}
protected void throwExceptionIfNull(Object o) {
if (o == null) {
throw new NullPointerException("Object is null");
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClientProxy that = (ClientProxy) o;
if (!instanceName.equals(that.instanceName)) {
return false;
}
if (!objectName.equals(that.objectName)) {
return false;
}
if (!serviceName.equals(that.serviceName)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = instanceName.hashCode();
result = 31 * result + serviceName.hashCode();
result = 31 * result + objectName.hashCode();
return result;
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_spi_ClientProxy.java
|
75 |
@SuppressWarnings("serial")
static final class MapReduceKeysToIntTask<K,V>
extends BulkTask<K,V,Integer> {
final ObjectToInt<? super K> transformer;
final IntByIntToInt reducer;
final int basis;
int result;
MapReduceKeysToIntTask<K,V> rights, nextRight;
MapReduceKeysToIntTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceKeysToIntTask<K,V> nextRight,
ObjectToInt<? super K> transformer,
int basis,
IntByIntToInt reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Integer getRawResult() { return result; }
public final void compute() {
final ObjectToInt<? super K> transformer;
final IntByIntToInt reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
int r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceKeysToIntTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.apply(r, transformer.apply(p.key));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
t = (MapReduceKeysToIntTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.apply(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
92 |
private static class GenericEvent implements Serializable {
private static final long serialVersionUID = -933111044641052844L;
private int userId;
public GenericEvent(int userId) {
this.setUserId(userId);
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_ClientEntryListenerDisconnectTest.java
|
1,482 |
clusterService.submitStateUpdateTask(CLUSTER_UPDATE_TASK_SOURCE, Priority.HIGH, new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
RoutingAllocation.Result routingResult = allocationService.reroute(currentState);
if (!routingResult.changed()) {
// no state changed
return currentState;
}
return ClusterState.builder(currentState).routingResult(routingResult).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
}
});
| 1no label
|
src_main_java_org_elasticsearch_cluster_routing_RoutingService.java
|
321 |
Comparator<Object> nameCompare = new Comparator<Object>() {
public int compare(Object arg0, Object arg1) {
return ((MergeHandler) arg0).getName().compareTo(((MergeHandler) arg1).getName());
}
};
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_MergeManager.java
|
1,927 |
public abstract class AbstractRuleBuilderFieldService implements RuleBuilderFieldService, ApplicationContextAware, InitializingBean {
protected DynamicEntityDao dynamicEntityDao;
protected ApplicationContext applicationContext;
protected List<FieldData> fields = new ArrayList<FieldData>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public FieldWrapper buildFields() {
FieldWrapper wrapper = new FieldWrapper();
for (FieldData field : getFields()) {
FieldDTO fieldDTO = new FieldDTO();
fieldDTO.setLabel(field.getFieldLabel());
//translate the label to display
String label = field.getFieldLabel();
BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
MessageSource messages = context.getMessageSource();
label = messages.getMessage(label, null, label, context.getJavaLocale());
fieldDTO.setLabel(label);
fieldDTO.setName(field.getFieldName());
fieldDTO.setOperators(field.getOperators());
fieldDTO.setOptions(field.getOptions());
wrapper.getFields().add(fieldDTO);
}
return wrapper;
}
@Override
public SupportedFieldType getSupportedFieldType(String fieldName) {
SupportedFieldType type = null;
if (fieldName != null) {
for (FieldData field : getFields()) {
if (fieldName.equals(field.getFieldName())){
return field.getFieldType();
}
}
}
return type;
}
@Override
public SupportedFieldType getSecondaryFieldType(String fieldName) {
SupportedFieldType type = null;
if (fieldName != null) {
for (FieldData field : getFields()) {
if (fieldName.equals(field.getFieldName())){
return field.getSecondaryFieldType();
}
}
}
return type;
}
@Override
public FieldDTO getField(String fieldName) {
for (FieldData field : getFields()) {
if (field.getFieldName().equals(fieldName)) {
FieldDTO fieldDTO = new FieldDTO();
fieldDTO.setLabel(field.getFieldLabel());
fieldDTO.setName(field.getFieldName());
fieldDTO.setOperators(field.getOperators());
fieldDTO.setOptions(field.getOptions());
return fieldDTO;
}
}
return null;
}
@Override
public List<FieldData> getFields() {
return fields;
}
@Override
@SuppressWarnings("unchecked")
public void setFields(final List<FieldData> fields) {
List<FieldData> proxyFields = (List<FieldData>) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{List.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("add")) {
FieldData fieldData = (FieldData) args[0];
testFieldName(fieldData);
}
if (method.getName().equals("addAll")) {
Collection<FieldData> addCollection = (Collection<FieldData>) args[0];
Iterator<FieldData> itr = addCollection.iterator();
while (itr.hasNext()) {
FieldData fieldData = itr.next();
testFieldName(fieldData);
}
}
return method.invoke(fields, args);
}
private void testFieldName(FieldData fieldData) throws ClassNotFoundException {
if (!StringUtils.isEmpty(fieldData.getFieldName()) && dynamicEntityDao != null) {
Class<?>[] dtos = dynamicEntityDao.getAllPolymorphicEntitiesFromCeiling(Class.forName(getDtoClassName()));
if (ArrayUtils.isEmpty(dtos)) {
dtos = new Class<?>[]{Class.forName(getDtoClassName())};
}
Field field = null;
for (Class<?> dto : dtos) {
field = dynamicEntityDao.getFieldManager().getField(dto, fieldData.getFieldName());
if (field != null) {
break;
}
}
if (field == null) {
throw new IllegalArgumentException("Unable to find the field declared in FieldData (" + fieldData.getFieldName() + ") on the target class (" + getDtoClassName() + "), or any registered entity class that derives from it.");
}
}
}
});
this.fields = proxyFields;
}
@Override
public RuleBuilderFieldService clone() throws CloneNotSupportedException {
try {
RuleBuilderFieldService clone = this.getClass().newInstance();
clone.setFields(this.fields);
return clone;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public abstract String getDtoClassName();
public abstract void init();
@Override
public void afterPropertiesSet() throws Exception {
// This bean only is valid when the following bean is active. (admin)
if (applicationContext.containsBean(DynamicEntityRemoteService.DEFAULTPERSISTENCEMANAGERREF)) {
PersistenceManager persistenceManager = (PersistenceManager) applicationContext.getBean(DynamicEntityRemoteService.DEFAULTPERSISTENCEMANAGERREF);
persistenceManager.setTargetMode(TargetModeType.SANDBOX);
dynamicEntityDao = persistenceManager.getDynamicEntityDao();
setFields(new ArrayList<FieldData>());
// This cannot be null during startup as we do not want to remove the null safety checks in a multi-tenant env.
boolean contextWasNull = false;
if (BroadleafRequestContext.getBroadleafRequestContext() == null) {
BroadleafRequestContext brc = new BroadleafRequestContext();
brc.setIgnoreSite(true);
BroadleafRequestContext.setBroadleafRequestContext(brc);
contextWasNull = true;
}
try {
init();
} finally {
if (contextWasNull) {
BroadleafRequestContext.setBroadleafRequestContext(null);
}
}
}
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_web_rulebuilder_service_AbstractRuleBuilderFieldService.java
|
117 |
public class OStringParser {
public static final String WHITE_SPACE = " ";
public static final String COMMON_JUMP = " \r\n";
public static String[] getWords(String iRecord, final String iSeparatorChars) {
return getWords(iRecord, iSeparatorChars, false);
}
public static String[] getWords(String iRecord, final String iSeparatorChars, final boolean iIncludeStringSep) {
return getWords(iRecord, iSeparatorChars, " \n\r\t", iIncludeStringSep);
}
public static String[] getWords(String iText, final String iSeparatorChars, final String iJumpChars,
final boolean iIncludeStringSep) {
iText = iText.trim();
final ArrayList<String> fields = new ArrayList<String>();
final StringBuilder buffer = new StringBuilder();
char stringBeginChar = ' ';
char c;
int openBraket = 0;
int openGraph = 0;
boolean charFound;
boolean escape = false;
for (int i = 0; i < iText.length(); ++i) {
c = iText.charAt(i);
if (!escape && c == '\\' && ((i + 1) < iText.length())) {
// ESCAPE CHARS
final char nextChar = iText.charAt(i + 1);
if (nextChar == 'u') {
i = readUnicode(iText, i + 2, buffer);
} else if (nextChar == 'n') {
buffer.append(stringBeginChar == ' ' ? "\n" : "\\\n");
i++;
} else if (nextChar == 'r') {
buffer.append(stringBeginChar == ' ' ? "\r" : "\\\r");
i++;
} else if (nextChar == 't') {
buffer.append(stringBeginChar == ' ' ? "\t" : "\\\t");
i++;
} else if (nextChar == 'f') {
buffer.append(stringBeginChar == ' ' ? "\f" : "\\\f");
i++;
} else if (stringBeginChar != ' ' && nextChar == '\'' || nextChar == '"') {
buffer.append('\\');
buffer.append(nextChar);
i++;
} else
escape = true;
continue;
}
if (!escape && (c == '\'' || c == '"')) {
if (stringBeginChar != ' ') {
// CLOSE THE STRING?
if (stringBeginChar == c) {
// SAME CHAR AS THE BEGIN OF THE STRING: CLOSE IT AND PUSH
stringBeginChar = ' ';
if (iIncludeStringSep)
buffer.append(c);
continue;
}
} else {
// START STRING
stringBeginChar = c;
if (iIncludeStringSep)
buffer.append(c);
continue;
}
} else if (stringBeginChar == ' ') {
if (c == '[')
openBraket++;
else if (c == ']')
openBraket--;
else if (c == '{')
openGraph++;
else if (c == '}')
openGraph--;
else if (openBraket == 0 && openGraph == 0) {
charFound = false;
for (int sepIndex = 0; sepIndex < iSeparatorChars.length(); ++sepIndex) {
if (iSeparatorChars.charAt(sepIndex) == c) {
charFound = true;
if (buffer.length() > 0) {
// SEPARATOR (OUTSIDE A STRING): PUSH
fields.add(buffer.toString());
buffer.setLength(0);
}
break;
}
}
if (charFound)
continue;
}
if (stringBeginChar == ' ') {
// CHECK FOR CHAR TO JUMP
charFound = false;
for (int jumpIndex = 0; jumpIndex < iJumpChars.length(); ++jumpIndex) {
if (iJumpChars.charAt(jumpIndex) == c) {
charFound = true;
break;
}
}
if (charFound)
continue;
}
}
buffer.append(c);
if (escape)
escape = false;
}
if (buffer.length() > 0) {
// ADD THE LAST WORD IF ANY
fields.add(buffer.toString());
}
String[] result = new String[fields.size()];
fields.toArray(result);
return result;
}
public static String[] split(String iText, final char iSplitChar, String iJumpChars) {
iText = iText.trim();
ArrayList<String> fields = new ArrayList<String>();
StringBuilder buffer = new StringBuilder();
char c;
char stringChar = ' ';
boolean escape = false;
boolean jumpSplitChar = false;
boolean charFound;
for (int i = 0; i < iText.length(); i++) {
c = iText.charAt(i);
if (!escape && c == '\\' && ((i + 1) < iText.length())) {
if (iText.charAt(i + 1) == 'u') {
i = readUnicode(iText, i + 2, buffer);
} else {
escape = true;
buffer.append(c);
}
continue;
}
if (c == '\'' || c == '"') {
if (!jumpSplitChar) {
jumpSplitChar = true;
stringChar = c;
} else {
if (!escape && c == stringChar)
jumpSplitChar = false;
}
}
if (c == iSplitChar) {
if (!jumpSplitChar) {
fields.add(buffer.toString());
buffer.setLength(0);
continue;
}
}
// CHECK IF IT MUST JUMP THE CHAR
if (buffer.length() == 0) {
charFound = false;
for (int jumpIndex = 0; jumpIndex < iJumpChars.length(); ++jumpIndex) {
if (iJumpChars.charAt(jumpIndex) == c) {
charFound = true;
break;
}
}
if (charFound)
continue;
}
buffer.append(c);
if (escape)
escape = false;
}
if (buffer.length() > 0) {
fields.add(buffer.toString());
buffer.setLength(0);
}
String[] result = new String[fields.size()];
fields.toArray(result);
return result;
}
/**
* Finds a character inside a string specyfing the limits and direction. If iFrom is minor than iTo, then it moves forward,
* otherwise backward.
*/
public static int indexOfOutsideStrings(final String iText, final char iToFind, int iFrom, int iTo) {
if (iTo == -1)
iTo = iText.length() - 1;
if (iFrom == -1)
iFrom = iText.length() - 1;
char c;
char stringChar = ' ';
boolean escape = false;
final StringBuilder buffer = new StringBuilder();
int i = iFrom;
while (true) {
c = iText.charAt(i);
if (!escape && c == '\\' && ((i + 1) < iText.length())) {
if (iText.charAt(i + 1) == 'u') {
i = readUnicode(iText, i + 2, buffer);
} else
escape = true;
} else {
if (c == '\'' || c == '"') {
// BEGIN/END STRING
if (stringChar == ' ') {
// BEGIN
stringChar = c;
} else {
// END
if (!escape && c == stringChar)
stringChar = ' ';
}
}
if (c == iToFind && stringChar == ' ')
return i;
if (escape)
escape = false;
}
if (iFrom < iTo) {
// MOVE FORWARD
if (++i > iTo)
break;
} else {
// MOVE BACKWARD
if (--i < iFrom)
break;
}
}
return -1;
}
/**
* Jump white spaces.
*
* @param iText
* String to analyze
* @param iCurrentPosition
* Current position in text
* @param iMaxPosition
* TODO
* @return The new offset inside the string analyzed
*/
public static int jumpWhiteSpaces(final CharSequence iText, final int iCurrentPosition, final int iMaxPosition) {
return jump(iText, iCurrentPosition, iMaxPosition, COMMON_JUMP);
}
/**
* Jump some characters reading from an offset of a String.
*
* @param iText
* String to analyze
* @param iCurrentPosition
* Current position in text
* @param iMaxPosition
* Maximum position to read
* @param iJumpChars
* String as char array of chars to jump
* @return The new offset inside the string analyzed
*/
public static int jump(final CharSequence iText, int iCurrentPosition, final int iMaxPosition, final String iJumpChars) {
if (iCurrentPosition < 0)
return -1;
final int size = iMaxPosition > -1 ? Math.min(iMaxPosition, iText.length()) : iText.length();
final int jumpCharSize = iJumpChars.length();
boolean found = true;
char c;
for (; iCurrentPosition < size; ++iCurrentPosition) {
found = false;
c = iText.charAt(iCurrentPosition);
for (int jumpIndex = 0; jumpIndex < jumpCharSize; ++jumpIndex) {
if (iJumpChars.charAt(jumpIndex) == c) {
found = true;
break;
}
}
if (!found)
break;
}
return iCurrentPosition >= size ? -1 : iCurrentPosition;
}
public static int readUnicode(String iText, int position, final StringBuilder buffer) {
// DECODE UNICODE CHAR
final StringBuilder buff = new StringBuilder();
final int lastPos = position + 4;
for (; position < lastPos; ++position)
buff.append(iText.charAt(position));
buffer.append((char) Integer.parseInt(buff.toString(), 16));
return position - 1;
}
public static int readUnicode(char[] iText, int position, final StringBuilder buffer) {
// DECODE UNICODE CHAR
final StringBuilder buff = new StringBuilder();
final int lastPos = position + 4;
for (; position < lastPos; ++position)
buff.append(iText[position]);
buffer.append((char) Integer.parseInt(buff.toString(), 16));
return position - 1;
}
public static String replaceAll(final String iText, final String iToReplace, final String iReplacement) {
if (iText == null || iText.length() <= 0 || iToReplace == null || iToReplace.length() <= 0)
return iText;
int pos = iText.indexOf(iToReplace);
int lastAppend = 0;
final StringBuffer buffer = new StringBuffer();
while (pos > -1) {
buffer.append(iText.substring(lastAppend, pos));
buffer.append(iReplacement);
lastAppend = pos + iToReplace.length();
pos = iText.indexOf(iToReplace, lastAppend);
}
buffer.append(iText.substring(lastAppend));
return buffer.toString();
}
/**
* Like String.startsWith() but ignoring case
*/
public static boolean startsWithIgnoreCase(final String iText, final String iToFind) {
if (iText.length() < iToFind.length())
return false;
return iText.substring(0, iToFind.length()).equalsIgnoreCase(iToFind);
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_parser_OStringParser.java
|
1,150 |
public class NestedSearchBenchMark {
public static void main(String[] args) throws Exception {
Settings settings = settingsBuilder()
.put("index.refresh_interval", "-1")
.put("gateway.type", "local")
.put(SETTING_NUMBER_OF_SHARDS, 1)
.put(SETTING_NUMBER_OF_REPLICAS, 0)
.build();
Node node1 = nodeBuilder()
.settings(settingsBuilder().put(settings).put("name", "node1"))
.node();
Client client = node1.client();
int count = (int) SizeValue.parseSizeValue("1m").singles();
int nestedCount = 10;
int rootDocs = count / nestedCount;
int batch = 100;
int queryWarmup = 5;
int queryCount = 500;
String indexName = "test";
ClusterHealthResponse clusterHealthResponse = client.admin().cluster().prepareHealth()
.setWaitForGreenStatus().execute().actionGet();
if (clusterHealthResponse.isTimedOut()) {
System.err.println("--> Timed out waiting for cluster health");
}
try {
client.admin().indices().prepareCreate(indexName)
.addMapping("type", XContentFactory.jsonBuilder()
.startObject()
.startObject("type")
.startObject("properties")
.startObject("field1")
.field("type", "integer")
.endObject()
.startObject("field2")
.field("type", "nested")
.startObject("properties")
.startObject("field3")
.field("type", "integer")
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()
).execute().actionGet();
clusterHealthResponse = client.admin().cluster().prepareHealth(indexName).setWaitForGreenStatus().execute().actionGet();
if (clusterHealthResponse.isTimedOut()) {
System.err.println("--> Timed out waiting for cluster health");
}
StopWatch stopWatch = new StopWatch().start();
System.out.println("--> Indexing [" + rootDocs + "] root documents and [" + (rootDocs * nestedCount) + "] nested objects");
long ITERS = rootDocs / batch;
long i = 1;
int counter = 0;
for (; i <= ITERS; i++) {
BulkRequestBuilder request = client.prepareBulk();
for (int j = 0; j < batch; j++) {
counter++;
XContentBuilder doc = XContentFactory.jsonBuilder().startObject()
.field("field1", counter)
.startArray("field2");
for (int k = 0; k < nestedCount; k++) {
doc = doc.startObject()
.field("field3", k)
.endObject();
}
doc = doc.endArray();
request.add(
Requests.indexRequest(indexName).type("type").id(Integer.toString(counter)).source(doc)
);
}
BulkResponse response = request.execute().actionGet();
if (response.hasFailures()) {
System.err.println("--> failures...");
}
if (((i * batch) % 10000) == 0) {
System.out.println("--> Indexed " + (i * batch) + " took " + stopWatch.stop().lastTaskTime());
stopWatch.start();
}
}
System.out.println("--> Indexing took " + stopWatch.totalTime() + ", TPS " + (((double) (count * (1 + nestedCount))) / stopWatch.totalTime().secondsFrac()));
} catch (Exception e) {
System.out.println("--> Index already exists, ignoring indexing phase, waiting for green");
clusterHealthResponse = client.admin().cluster().prepareHealth(indexName).setWaitForGreenStatus().setTimeout("10m").execute().actionGet();
if (clusterHealthResponse.isTimedOut()) {
System.err.println("--> Timed out waiting for cluster health");
}
}
client.admin().indices().prepareRefresh().execute().actionGet();
System.out.println("--> Number of docs in index: " + client.prepareCount().setQuery(matchAllQuery()).execute().actionGet().getCount());
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());
System.out.println("--> Running match_all with sorting on nested field");
// run just the child query, warm up first
for (int j = 0; j < queryWarmup; j++) {
SearchResponse searchResponse = client.prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("field2.field3")
.setNestedPath("field2")
.sortMode("avg")
.order(SortOrder.ASC)
)
.execute().actionGet();
if (j == 0) {
System.out.println("--> Warmup took: " + searchResponse.getTook());
}
if (searchResponse.getHits().totalHits() != rootDocs) {
System.err.println("--> mismatch on hits");
}
}
long totalQueryTime = 0;
for (int j = 0; j < queryCount; j++) {
SearchResponse searchResponse = client.prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("field2.field3")
.setNestedPath("field2")
.sortMode("avg")
.order(j % 2 == 0 ? SortOrder.ASC : SortOrder.DESC)
)
.execute().actionGet();
if (searchResponse.getHits().totalHits() != rootDocs) {
System.err.println("--> mismatch on hits");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> Sorting by nested fields took: " + (totalQueryTime / queryCount) + "ms");
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());
}
}
| 0true
|
src_test_java_org_elasticsearch_benchmark_search_nested_NestedSearchBenchMark.java
|
3,147 |
public class TxnPrepareBackupOperation extends QueueOperation implements BackupOperation {
private long itemId;
private boolean pollOperation;
private String transactionId;
public TxnPrepareBackupOperation() {
}
public TxnPrepareBackupOperation(String name, long itemId, boolean pollOperation, String transactionId) {
super(name);
this.itemId = itemId;
this.pollOperation = pollOperation;
this.transactionId = transactionId;
}
@Override
public void run() throws Exception {
QueueContainer container = getOrCreateContainer();
if (pollOperation) {
response = container.txnPollBackupReserve(itemId, transactionId);
} else {
container.txnOfferBackupReserve(itemId, transactionId);
response = true;
}
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeLong(itemId);
out.writeBoolean(pollOperation);
out.writeUTF(transactionId);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
itemId = in.readLong();
pollOperation = in.readBoolean();
transactionId = in.readUTF();
}
@Override
public int getId() {
return QueueDataSerializerHook.TXN_PREPARE_BACKUP;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_queue_tx_TxnPrepareBackupOperation.java
|
159 |
public interface StructuredContentRuleProcessor {
/**
* Returns true if the passed in <code>StructuredContent</code> is valid according
* to this rule processor.
*
* @param sc
* @return
*/
public boolean checkForMatch(StructuredContentDTO sc, Map<String,Object> valueMap);
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_service_StructuredContentRuleProcessor.java
|
182 |
public class BroadleafPageController extends BroadleafAbstractController implements Controller {
protected static String MODEL_ATTRIBUTE_NAME="page";
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView();
PageDTO page = (PageDTO) request.getAttribute(PageHandlerMapping.PAGE_ATTRIBUTE_NAME);
assert page != null;
model.addObject(MODEL_ATTRIBUTE_NAME, page);
model.setViewName(page.getTemplatePath());
return model;
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_web_controller_BroadleafPageController.java
|
307 |
public class MergeApplicationContextXmlConfigResource extends MergeXmlConfigResource {
private static final Log LOG = LogFactory.getLog(MergeApplicationContextXmlConfigResource.class);
/**
* Generate a merged configuration resource, loading the definitions from the given streams. Note,
* all sourceLocation streams will be merged using standard Spring configuration override rules. However, the patch
* streams are fully merged into the result of the sourceLocations simple merge. Patch merges are first executed according
* to beans with the same id. Subsequent merges within a bean are executed against tagnames - ignoring any
* further id attributes.
*
* @param sources array of input streams for the source application context files
* @param patches array of input streams for the patch application context files
* @throws BeansException
*/
public Resource[] getConfigResources(ResourceInputStream[] sources, ResourceInputStream[] patches) throws BeansException {
Resource[] configResources = null;
ResourceInputStream merged = null;
try {
merged = merge(sources);
if (patches != null) {
ResourceInputStream[] patches2 = new ResourceInputStream[patches.length+1];
patches2[0] = merged;
System.arraycopy(patches, 0, patches2, 1, patches.length);
merged = merge(patches2);
}
//read the final stream into a byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
boolean eof = false;
while (!eof) {
int temp = merged.read();
if (temp == -1) {
eof = true;
} else {
baos.write(temp);
}
}
configResources = new Resource[]{new ByteArrayResource(baos.toByteArray())};
if (LOG.isDebugEnabled()) {
LOG.debug("Merged ApplicationContext Including Patches: \n" + serialize(configResources[0]));
}
} catch (MergeException e) {
throw new FatalBeanException("Unable to merge source and patch locations", e);
} catch (MergeManagerSetupException e) {
throw new FatalBeanException("Unable to merge source and patch locations", e);
} catch (IOException e) {
throw new FatalBeanException("Unable to merge source and patch locations", e);
} finally {
if (merged != null) {
try{ merged.close(); } catch (Throwable e) {
LOG.error("Unable to merge source and patch locations", e);
}
}
}
return configResources;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_MergeApplicationContextXmlConfigResource.java
|
1,048 |
@SuppressWarnings("unchecked")
public abstract class OCommandExecutorSQLResultsetAbstract extends OCommandExecutorSQLAbstract implements Iterator<OIdentifiable>,
Iterable<OIdentifiable> {
protected static final String KEYWORD_FROM_2FIND = " " + KEYWORD_FROM + " ";
protected static final String KEYWORD_LET_2FIND = " " + KEYWORD_LET + " ";
protected OSQLAsynchQuery<ORecordSchemaAware<?>> request;
protected OSQLTarget parsedTarget;
protected OSQLFilter compiledFilter;
protected Map<String, Object> let = null;
protected Iterator<? extends OIdentifiable> target;
protected Iterable<OIdentifiable> tempResult;
protected int resultCount;
protected int skip = 0;
/**
* Compile the filter conditions only the first time.
*/
public OCommandExecutorSQLResultsetAbstract parse(final OCommandRequest iRequest) {
final OCommandRequestText textRequest = (OCommandRequestText) iRequest;
init(textRequest);
if (iRequest instanceof OSQLSynchQuery) {
request = (OSQLSynchQuery<ORecordSchemaAware<?>>) iRequest;
} else if (iRequest instanceof OSQLAsynchQuery)
request = (OSQLAsynchQuery<ORecordSchemaAware<?>>) iRequest;
else {
// BUILD A QUERY OBJECT FROM THE COMMAND REQUEST
request = new OSQLSynchQuery<ORecordSchemaAware<?>>(textRequest.getText());
if (textRequest.getResultListener() != null)
request.setResultListener(textRequest.getResultListener());
}
return this;
}
@Override
public boolean isReplicated() {
return true;
}
@Override
public boolean isIdempotent() {
return true;
}
/**
* Assign the right TARGET if found.
*
* @param iArgs
* Parameters to bind
* @return true if the target has been recognized, otherwise false
*/
protected boolean assignTarget(final Map<Object, Object> iArgs) {
parameters = iArgs;
if (parsedTarget == null)
return true;
if (iArgs != null && iArgs.size() > 0 && compiledFilter != null)
compiledFilter.bindParameters(iArgs);
if (target == null)
if (parsedTarget.getTargetClasses() != null)
searchInClasses();
else if (parsedTarget.getTargetClusters() != null)
searchInClusters();
else if (parsedTarget.getTargetRecords() != null)
target = parsedTarget.getTargetRecords().iterator();
else if (parsedTarget.getTargetVariable() != null) {
final Object var = getContext().getVariable(parsedTarget.getTargetVariable());
if (var == null) {
target = Collections.EMPTY_LIST.iterator();
return true;
} else if (var instanceof OIdentifiable) {
final ArrayList<OIdentifiable> list = new ArrayList<OIdentifiable>();
list.add((OIdentifiable) var);
target = list.iterator();
} else if (var instanceof Iterable<?>)
target = ((Iterable<? extends OIdentifiable>) var).iterator();
} else
return false;
return true;
}
protected Object getResult() {
if (tempResult != null) {
for (Object d : tempResult)
if (d != null) {
if (!(d instanceof OIdentifiable))
// NON-DOCUMENT AS RESULT, COMES FROM EXPAND? CREATE A DOCUMENT AT THE FLY
d = new ODocument().field("value", d);
request.getResultListener().result(d);
}
}
if (request instanceof OSQLSynchQuery)
return ((OSQLSynchQuery<ORecordSchemaAware<?>>) request).getResult();
return null;
}
protected boolean handleResult(final OIdentifiable iRecord, boolean iCloneIt) {
if (iRecord != null) {
resultCount++;
OIdentifiable recordCopy = iRecord instanceof ORecord<?> ? ((ORecord<?>) iRecord).copy() : iRecord.getIdentity().copy();
if (recordCopy != null)
// CALL THE LISTENER NOW
if (request.getResultListener() != null)
request.getResultListener().result(recordCopy);
if (limit > -1 && resultCount >= limit)
// BREAK THE EXECUTION
return false;
}
return true;
}
protected void parseLet() {
let = new LinkedHashMap<String, Object>();
boolean stop = false;
while (!stop) {
// PARSE THE KEY
parserNextWord(false);
final String letName = parserGetLastWord();
parserOptionalKeyword("=");
parserNextWord(false, " =><,\r\n");
// PARSE THE VALUE
String letValueAsString = parserGetLastWord();
final Object letValue;
// TRY TO PARSE AS FUNCTION
final Object func = OSQLHelper.getFunction(parsedTarget, letValueAsString);
if (func != null)
letValue = func;
else if (letValueAsString.startsWith("(")) {
letValue = new OSQLSynchQuery<Object>(letValueAsString.substring(1, letValueAsString.length() - 1));
} else
letValue = letValueAsString;
let.put(letName, letValue);
stop = parserGetLastSeparator() == ' ';
}
}
/**
* Parses the limit keyword if found.
*
* @param w
*
* @return
* @return the limit found as integer, or -1 if no limit is found. -1 means no limits.
* @throws OCommandSQLParsingException
* if no valid limit has been found
*/
protected int parseLimit(final String w) throws OCommandSQLParsingException {
if (!w.equals(KEYWORD_LIMIT))
return -1;
parserNextWord(true);
final String word = parserGetLastWord();
try {
limit = Integer.parseInt(word);
} catch (Exception e) {
throwParsingException("Invalid LIMIT value setted to '" + word + "' but it should be a valid integer. Example: LIMIT 10");
}
if (limit == 0)
throwParsingException("Invalid LIMIT value setted to ZERO. Use -1 to ignore the limit or use a positive number. Example: LIMIT 10");
return limit;
}
/**
* Parses the skip keyword if found.
*
* @param w
*
* @return
* @return the skip found as integer, or -1 if no skip is found. -1 means no skip.
* @throws OCommandSQLParsingException
* if no valid skip has been found
*/
protected int parseSkip(final String w) throws OCommandSQLParsingException {
if (!w.equals(KEYWORD_SKIP))
return -1;
parserNextWord(true);
final String word = parserGetLastWord();
try {
skip = Integer.parseInt(word);
} catch (Exception e) {
throwParsingException("Invalid SKIP value setted to '" + word
+ "' but it should be a valid positive integer. Example: SKIP 10");
}
if (skip < 0)
throwParsingException("Invalid SKIP value setted to the negative number '" + word
+ "'. Only positive numbers are valid. Example: SKIP 10");
return skip;
}
protected boolean filter(final ORecordInternal<?> iRecord) {
context.setVariable("current", iRecord);
if (iRecord instanceof ORecordSchemaAware<?>) {
// CHECK THE TARGET CLASS
final ORecordSchemaAware<?> recordSchemaAware = (ORecordSchemaAware<?>) iRecord;
Map<OClass, String> targetClasses = parsedTarget.getTargetClasses();
// check only classes that specified in query will go to result set
if ((targetClasses != null) && (!targetClasses.isEmpty())) {
for (OClass targetClass : targetClasses.keySet()) {
if (!targetClass.isSuperClassOf(recordSchemaAware.getSchemaClass()))
return false;
}
context.updateMetric("documentAnalyzedCompatibleClass", +1);
}
}
return evaluateRecord(iRecord);
}
protected boolean evaluateRecord(final ORecord<?> iRecord) {
assignLetClauses(iRecord);
if (compiledFilter == null)
return true;
return (Boolean) compiledFilter.evaluate(iRecord, null, context);
}
protected void assignLetClauses(final ORecord<?> iRecord) {
if (let != null && !let.isEmpty()) {
// BIND CONTEXT VARIABLES
for (Entry<String, Object> entry : let.entrySet()) {
String varName = entry.getKey();
if (varName.startsWith("$"))
varName = varName.substring(1);
final Object letValue = entry.getValue();
Object varValue;
if (letValue instanceof OSQLSynchQuery<?>) {
final OSQLSynchQuery<Object> subQuery = (OSQLSynchQuery<Object>) letValue;
subQuery.reset();
subQuery.resetPagination();
subQuery.getContext().setParent(context);
subQuery.getContext().setVariable("current", iRecord);
varValue = ODatabaseRecordThreadLocal.INSTANCE.get().query(subQuery);
} else if (letValue instanceof OSQLFunctionRuntime) {
final OSQLFunctionRuntime f = (OSQLFunctionRuntime) letValue;
if (f.getFunction().aggregateResults()) {
f.execute(iRecord, null, context);
varValue = f.getFunction().getResult();
} else
varValue = f.execute(iRecord, null, context);
} else
varValue = ODocumentHelper.getFieldValue(iRecord, ((String) letValue).trim(), context);
context.setVariable(varName, varValue);
}
}
}
protected void searchInClasses() {
final OClass cls = parsedTarget.getTargetClasses().keySet().iterator().next();
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.CLASS, ORole.PERMISSION_READ, cls.getName().toLowerCase());
// NO INDEXES: SCAN THE ENTIRE CLUSTER
final ORID[] range = getRange();
target = new ORecordIteratorClass<ORecordInternal<?>>(database, (ODatabaseRecordAbstract) database, cls.getName(), true,
request.isUseCache(), false).setRange(range[0], range[1]);
}
protected void searchInClusters() {
final ODatabaseRecord database = getDatabase();
final Set<Integer> clusterIds = new HashSet<Integer>();
for (String clusterName : parsedTarget.getTargetClusters().keySet()) {
if (clusterName == null || clusterName.length() == 0)
throw new OCommandExecutionException("No cluster or schema class selected in query");
database.checkSecurity(ODatabaseSecurityResources.CLUSTER, ORole.PERMISSION_READ, clusterName.toLowerCase());
if (Character.isDigit(clusterName.charAt(0))) {
// GET THE CLUSTER NUMBER
for (int clusterId : OStringSerializerHelper.splitIntArray(clusterName)) {
if (clusterId == -1)
throw new OCommandExecutionException("Cluster '" + clusterName + "' not found");
clusterIds.add(clusterId);
}
} else {
// GET THE CLUSTER NUMBER BY THE CLASS NAME
final int clusterId = database.getClusterIdByName(clusterName.toLowerCase());
if (clusterId == -1)
throw new OCommandExecutionException("Cluster '" + clusterName + "' not found");
clusterIds.add(clusterId);
}
}
// CREATE CLUSTER AS ARRAY OF INT
final int[] clIds = new int[clusterIds.size()];
int i = 0;
for (int c : clusterIds)
clIds[i++] = c;
final ORID[] range = getRange();
target = new ORecordIteratorClusters<ORecordInternal<?>>(database, database, clIds, request.isUseCache(), false).setRange(
range[0], range[1]);
}
protected void applyLimitAndSkip() {
if (tempResult != null && (limit > 0 || skip > 0)) {
final List<OIdentifiable> newList = new ArrayList<OIdentifiable>();
// APPLY LIMIT
if (tempResult instanceof List<?>) {
final List<OIdentifiable> t = (List<OIdentifiable>) tempResult;
final int start = Math.min(skip, t.size());
final int tot = Math.min(limit + start, t.size());
for (int i = start; i < tot; ++i)
newList.add(t.get(i));
t.clear();
tempResult = newList;
}
}
}
/**
* Optimizes the condition tree.
*
* @return
*/
protected void optimize() {
if (compiledFilter != null)
optimizeBranch(null, compiledFilter.getRootCondition());
}
/**
* Check function arguments and pre calculate it if possible
*
* @param function
* @return optimized function, same function if no change
*/
protected Object optimizeFunction(OSQLFunctionRuntime function) {
// boolean precalculate = true;
// for (int i = 0; i < function.configuredParameters.length; ++i) {
// if (function.configuredParameters[i] instanceof OSQLFilterItemField) {
// precalculate = false;
// } else if (function.configuredParameters[i] instanceof OSQLFunctionRuntime) {
// final Object res = optimizeFunction((OSQLFunctionRuntime) function.configuredParameters[i]);
// function.configuredParameters[i] = res;
// if (res instanceof OSQLFunctionRuntime || res instanceof OSQLFilterItemField) {
// // function might have been optimized but result is still not static
// precalculate = false;
// }
// }
// }
//
// if (precalculate) {
// // all fields are static, we can calculate it only once.
// return function.execute(null, null, null); // we can pass nulls here, they wont be used
// } else {
return function;
// }
}
protected void optimizeBranch(final OSQLFilterCondition iParentCondition, OSQLFilterCondition iCondition) {
if (iCondition == null)
return;
Object left = iCondition.getLeft();
if (left instanceof OSQLFilterCondition) {
// ANALYSE LEFT RECURSIVELY
optimizeBranch(iCondition, (OSQLFilterCondition) left);
} else if (left instanceof OSQLFunctionRuntime) {
left = optimizeFunction((OSQLFunctionRuntime) left);
iCondition.setLeft(left);
}
Object right = iCondition.getRight();
if (right instanceof OSQLFilterCondition) {
// ANALYSE RIGHT RECURSIVELY
optimizeBranch(iCondition, (OSQLFilterCondition) right);
} else if (right instanceof OSQLFunctionRuntime) {
right = optimizeFunction((OSQLFunctionRuntime) right);
iCondition.setRight(right);
}
final OQueryOperator oper = iCondition.getOperator();
Object result = null;
if (left instanceof OSQLFilterItemField && right instanceof OSQLFilterItemField) {
if (((OSQLFilterItemField) left).getRoot().equals(((OSQLFilterItemField) right).getRoot())) {
if (oper instanceof OQueryOperatorEquals)
result = Boolean.TRUE;
else if (oper instanceof OQueryOperatorNotEquals)
result = Boolean.FALSE;
}
}
if (result != null) {
if (iParentCondition != null)
if (iCondition == iParentCondition.getLeft())
// REPLACE LEFT
iCondition.setLeft(result);
else
// REPLACE RIGHT
iCondition.setRight(result);
else {
// REPLACE ROOT CONDITION
if (result instanceof Boolean && ((Boolean) result))
compiledFilter.setRootCondition(null);
}
}
}
protected ORID[] getRange() {
final ORID beginRange;
final ORID endRange;
final OSQLFilterCondition rootCondition = compiledFilter == null ? null : compiledFilter.getRootCondition();
if (compiledFilter == null || rootCondition == null) {
if (request instanceof OSQLSynchQuery)
beginRange = ((OSQLSynchQuery<ORecordSchemaAware<?>>) request).getNextPageRID();
else
beginRange = null;
endRange = null;
} else {
final ORID conditionBeginRange = rootCondition.getBeginRidRange();
final ORID conditionEndRange = rootCondition.getEndRidRange();
final ORID nextPageRid;
if (request instanceof OSQLSynchQuery)
nextPageRid = ((OSQLSynchQuery<ORecordSchemaAware<?>>) request).getNextPageRID();
else
nextPageRid = null;
if (conditionBeginRange != null && nextPageRid != null)
beginRange = conditionBeginRange.compareTo(nextPageRid) > 0 ? conditionBeginRange : nextPageRid;
else if (conditionBeginRange != null)
beginRange = conditionBeginRange;
else
beginRange = nextPageRid;
endRange = conditionEndRange;
}
return new ORID[] { beginRange, endRange };
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLResultsetAbstract.java
|
581 |
public class FulfillmentPriceHostException extends FulfillmentPriceException {
private static final long serialVersionUID = 1L;
public FulfillmentPriceHostException() {
super();
}
public FulfillmentPriceHostException(String message, Throwable cause) {
super(message, cause);
}
public FulfillmentPriceHostException(String message) {
super(message);
}
public FulfillmentPriceHostException(Throwable cause) {
super(cause);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_vendor_service_exception_FulfillmentPriceHostException.java
|
477 |
public final class RandomGenerator {
private final static char[] CHARSET = new char[] { 'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9' };
private RandomGenerator() {
/**
* Intentionally blank to force static usage
*/
}
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public static String generateRandomId(String prng, int len) throws NoSuchAlgorithmException {
return generateRandomId(SecureRandom.getInstance(prng), len);
}
public static String generateRandomId(SecureRandom sr, int len) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len + 1; i++) {
int index = sr.nextInt(CHARSET.length);
char c = CHARSET[index];
sb.append(c);
if ((i % 4) == 0 && i != 0 && i < len) {
sb.append('-');
}
}
return sb.toString();
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_security_RandomGenerator.java
|
1,570 |
public abstract class Decision {
public static final Decision ALWAYS = new Single(Type.YES);
public static final Decision YES = new Single(Type.YES);
public static final Decision NO = new Single(Type.NO);
public static final Decision THROTTLE = new Single(Type.THROTTLE);
/**
* Creates a simple decision
* @param type {@link Type} of the decision
* @param explanation explanation of the decision
* @param explanationParams additional parameters for the decision
* @return new {@link Decision} instance
*/
public static Decision single(Type type, String explanation, Object... explanationParams) {
return new Single(type, explanation, explanationParams);
}
/**
* This enumeration defines the
* possible types of decisions
*/
public static enum Type {
YES,
NO,
THROTTLE
}
/**
* Get the {@link Type} of this decision
* @return {@link Type} of this decision
*/
public abstract Type type();
/**
* Simple class representing a single decision
*/
public static class Single extends Decision {
private final Type type;
private final String explanation;
private final Object[] explanationParams;
/**
* Creates a new {@link Single} decision of a given type
* @param type {@link Type} of the decision
*/
public Single(Type type) {
this(type, null, (Object[]) null);
}
/**
* Creates a new {@link Single} decision of a given type
*
* @param type {@link Type} of the decision
* @param explanation An explanation of this {@link Decision}
* @param explanationParams A set of additional parameters
*/
public Single(Type type, String explanation, Object... explanationParams) {
this.type = type;
this.explanation = explanation;
this.explanationParams = explanationParams;
}
@Override
public Type type() {
return this.type;
}
@Override
public String toString() {
if (explanation == null) {
return type + "()";
}
return type + "(" + String.format(Locale.ROOT, explanation, explanationParams) + ")";
}
}
/**
* Simple class representing a list of decisions
*/
public static class Multi extends Decision {
private final List<Decision> decisions = Lists.newArrayList();
/**
* Add a decission to this {@link Multi}decision instance
* @param decision {@link Decision} to add
* @return {@link Multi}decision instance with the given decision added
*/
public Multi add(Decision decision) {
decisions.add(decision);
return this;
}
@Override
public Type type() {
Type ret = Type.YES;
for (int i = 0; i < decisions.size(); i++) {
Type type = decisions.get(i).type();
if (type == Type.NO) {
return type;
} else if (type == Type.THROTTLE) {
ret = type;
}
}
return ret;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Decision decision : decisions) {
sb.append("[").append(decision.toString()).append("]");
}
return sb.toString();
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_cluster_routing_allocation_decider_Decision.java
|
250 |
public class CustomFieldQuery extends FieldQuery {
private static Field multiTermQueryWrapperFilterQueryField;
static {
try {
multiTermQueryWrapperFilterQueryField = MultiTermQueryWrapperFilter.class.getDeclaredField("query");
multiTermQueryWrapperFilterQueryField.setAccessible(true);
} catch (NoSuchFieldException e) {
// ignore
}
}
public static final ThreadLocal<Boolean> highlightFilters = new ThreadLocal<Boolean>();
public CustomFieldQuery(Query query, IndexReader reader, FastVectorHighlighter highlighter) throws IOException {
this(query, reader, highlighter.isPhraseHighlight(), highlighter.isFieldMatch());
}
public CustomFieldQuery(Query query, IndexReader reader, boolean phraseHighlight, boolean fieldMatch) throws IOException {
super(query, reader, phraseHighlight, fieldMatch);
highlightFilters.remove();
}
@Override
void flatten(Query sourceQuery, IndexReader reader, Collection<Query> flatQueries) throws IOException {
if (sourceQuery instanceof SpanTermQuery) {
super.flatten(new TermQuery(((SpanTermQuery) sourceQuery).getTerm()), reader, flatQueries);
} else if (sourceQuery instanceof ConstantScoreQuery) {
ConstantScoreQuery constantScoreQuery = (ConstantScoreQuery) sourceQuery;
if (constantScoreQuery.getFilter() != null) {
flatten(constantScoreQuery.getFilter(), reader, flatQueries);
} else {
flatten(constantScoreQuery.getQuery(), reader, flatQueries);
}
} else if (sourceQuery instanceof FunctionScoreQuery) {
flatten(((FunctionScoreQuery) sourceQuery).getSubQuery(), reader, flatQueries);
} else if (sourceQuery instanceof FilteredQuery) {
flatten(((FilteredQuery) sourceQuery).getQuery(), reader, flatQueries);
flatten(((FilteredQuery) sourceQuery).getFilter(), reader, flatQueries);
} else if (sourceQuery instanceof XFilteredQuery) {
flatten(((XFilteredQuery) sourceQuery).getQuery(), reader, flatQueries);
flatten(((XFilteredQuery) sourceQuery).getFilter(), reader, flatQueries);
} else if (sourceQuery instanceof MultiPhrasePrefixQuery) {
flatten(sourceQuery.rewrite(reader), reader, flatQueries);
} else if (sourceQuery instanceof FiltersFunctionScoreQuery) {
flatten(((FiltersFunctionScoreQuery) sourceQuery).getSubQuery(), reader, flatQueries);
} else if (sourceQuery instanceof MultiPhraseQuery) {
MultiPhraseQuery q = ((MultiPhraseQuery) sourceQuery);
convertMultiPhraseQuery(0, new int[q.getTermArrays().size()] , q, q.getTermArrays(), q.getPositions(), reader, flatQueries);
} else {
super.flatten(sourceQuery, reader, flatQueries);
}
}
private void convertMultiPhraseQuery(int currentPos, int[] termsIdx, MultiPhraseQuery orig, List<Term[]> terms, int[] pos, IndexReader reader, Collection<Query> flatQueries) throws IOException {
if (currentPos == 0) {
// if we have more than 16 terms
int numTerms = 0;
for (Term[] currentPosTerm : terms) {
numTerms += currentPosTerm.length;
}
if (numTerms > 16) {
for (Term[] currentPosTerm : terms) {
for (Term term : currentPosTerm) {
super.flatten(new TermQuery(term), reader, flatQueries);
}
}
return;
}
}
/*
* we walk all possible ways and for each path down the MPQ we create a PhraseQuery this is what FieldQuery supports.
* It seems expensive but most queries will pretty small.
*/
if (currentPos == terms.size()) {
PhraseQuery query = new PhraseQuery();
query.setBoost(orig.getBoost());
query.setSlop(orig.getSlop());
for (int i = 0; i < termsIdx.length; i++) {
query.add(terms.get(i)[termsIdx[i]], pos[i]);
}
this.flatten(query, reader, flatQueries);
} else {
Term[] t = terms.get(currentPos);
for (int i = 0; i < t.length; i++) {
termsIdx[currentPos] = i;
convertMultiPhraseQuery(currentPos+1, termsIdx, orig, terms, pos, reader, flatQueries);
}
}
}
void flatten(Filter sourceFilter, IndexReader reader, Collection<Query> flatQueries) throws IOException {
Boolean highlight = highlightFilters.get();
if (highlight == null || highlight.equals(Boolean.FALSE)) {
return;
}
if (sourceFilter instanceof TermFilter) {
flatten(new TermQuery(((TermFilter) sourceFilter).getTerm()), reader, flatQueries);
} else if (sourceFilter instanceof MultiTermQueryWrapperFilter) {
if (multiTermQueryWrapperFilterQueryField != null) {
try {
flatten((Query) multiTermQueryWrapperFilterQueryField.get(sourceFilter), reader, flatQueries);
} catch (IllegalAccessException e) {
// ignore
}
}
} else if (sourceFilter instanceof XBooleanFilter) {
XBooleanFilter booleanFilter = (XBooleanFilter) sourceFilter;
for (FilterClause clause : booleanFilter.clauses()) {
if (clause.getOccur() == BooleanClause.Occur.MUST || clause.getOccur() == BooleanClause.Occur.SHOULD) {
flatten(clause.getFilter(), reader, flatQueries);
}
}
}
}
}
| 1no label
|
src_main_java_org_apache_lucene_search_vectorhighlight_CustomFieldQuery.java
|
157 |
public class OLongSerializer implements OBinarySerializer<Long> {
private static final OBinaryConverter CONVERTER = OBinaryConverterFactory.getConverter();
public static OLongSerializer INSTANCE = new OLongSerializer();
public static final byte ID = 10;
/**
* size of long value in bytes
*/
public static final int LONG_SIZE = 8;
public int getObjectSize(Long object, Object... hints) {
return LONG_SIZE;
}
public void serialize(Long object, byte[] stream, int startPosition, Object... hints) {
final long value = object;
stream[startPosition] = (byte) ((value >>> 56) & 0xFF);
stream[startPosition + 1] = (byte) ((value >>> 48) & 0xFF);
stream[startPosition + 2] = (byte) ((value >>> 40) & 0xFF);
stream[startPosition + 3] = (byte) ((value >>> 32) & 0xFF);
stream[startPosition + 4] = (byte) ((value >>> 24) & 0xFF);
stream[startPosition + 5] = (byte) ((value >>> 16) & 0xFF);
stream[startPosition + 6] = (byte) ((value >>> 8) & 0xFF);
stream[startPosition + 7] = (byte) ((value >>> 0) & 0xFF);
}
public Long deserialize(byte[] stream, int startPosition) {
return ((0xff & stream[startPosition + 7]) | (0xff & stream[startPosition + 6]) << 8 | (0xff & stream[startPosition + 5]) << 16
| (long) (0xff & stream[startPosition + 4]) << 24 | (long) (0xff & stream[startPosition + 3]) << 32
| (long) (0xff & stream[startPosition + 2]) << 40 | (long) (0xff & stream[startPosition + 1]) << 48 | (long) (0xff & stream[startPosition]) << 56);
}
public int getObjectSize(byte[] stream, int startPosition) {
return LONG_SIZE;
}
public byte getId() {
return ID;
}
public int getObjectSizeNative(byte[] stream, int startPosition) {
return LONG_SIZE;
}
public void serializeNative(Long object, byte[] stream, int startPosition, Object... hints) {
CONVERTER.putLong(stream, startPosition, object, ByteOrder.nativeOrder());
}
public Long deserializeNative(byte[] stream, int startPosition) {
return CONVERTER.getLong(stream, startPosition, ByteOrder.nativeOrder());
}
@Override
public void serializeInDirectMemory(Long object, ODirectMemoryPointer pointer, long offset, Object... hints) {
pointer.setLong(offset, object);
}
@Override
public Long deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) {
return pointer.getLong(offset);
}
@Override
public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) {
return LONG_SIZE;
}
public boolean isFixedLength() {
return true;
}
public int getFixedLength() {
return LONG_SIZE;
}
@Override
public Long preprocess(Long value, Object... hints) {
return value;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_serialization_types_OLongSerializer.java
|
677 |
public class GetWarmersResponse extends ActionResponse {
private ImmutableOpenMap<String, ImmutableList<IndexWarmersMetaData.Entry>> warmers = ImmutableOpenMap.of();
GetWarmersResponse(ImmutableOpenMap<String, ImmutableList<IndexWarmersMetaData.Entry>> warmers) {
this.warmers = warmers;
}
GetWarmersResponse() {
}
public ImmutableOpenMap<String, ImmutableList<IndexWarmersMetaData.Entry>> warmers() {
return warmers;
}
public ImmutableOpenMap<String, ImmutableList<IndexWarmersMetaData.Entry>> getWarmers() {
return warmers();
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
int size = in.readVInt();
ImmutableOpenMap.Builder<String, ImmutableList<IndexWarmersMetaData.Entry>> indexMapBuilder = ImmutableOpenMap.builder();
for (int i = 0; i < size; i++) {
String key = in.readString();
int valueSize = in.readVInt();
ImmutableList.Builder<IndexWarmersMetaData.Entry> warmerEntryBuilder = ImmutableList.builder();
for (int j = 0; j < valueSize; j++) {
warmerEntryBuilder.add(new IndexWarmersMetaData.Entry(
in.readString(),
in.readStringArray(),
in.readBytesReference())
);
}
indexMapBuilder.put(key, warmerEntryBuilder.build());
}
warmers = indexMapBuilder.build();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(warmers.size());
for (ObjectObjectCursor<String, ImmutableList<IndexWarmersMetaData.Entry>> indexEntry : warmers) {
out.writeString(indexEntry.key);
out.writeVInt(indexEntry.value.size());
for (IndexWarmersMetaData.Entry warmerEntry : indexEntry.value) {
out.writeString(warmerEntry.name());
out.writeStringArray(warmerEntry.types());
out.writeBytesReference(warmerEntry.source());
}
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_warmer_get_GetWarmersResponse.java
|
781 |
METRIC_TYPE.COUNTER, new OProfilerHookValue() {
public Object getValue() {
return alertTimes;
}
});
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_memory_OMemoryWatchDog.java
|
1,842 |
public class ContextType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, ContextType> TYPES = new LinkedHashMap<String, ContextType>();
public static final ContextType GLOBAL = new ContextType("GLOBAL", "Global");
public static final ContextType SITE = new ContextType("SITE", "Site");
public static final ContextType CATALOG = new ContextType("CATALOG", "Catalog");
public static final ContextType TEMPLATE = new ContextType("TEMPLATE", "Template");
public static ContextType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public ContextType() {
//do nothing
}
public ContextType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
@Override
public String getType() {
return type;
}
@Override
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;
ContextType other = (ContextType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_type_ContextType.java
|
4,077 |
public class TopChildrenQuery extends Query {
private static final ParentDocComparator PARENT_DOC_COMP = new ParentDocComparator();
private final CacheRecycler cacheRecycler;
private final String parentType;
private final String childType;
private final ScoreType scoreType;
private final int factor;
private final int incrementalFactor;
private final Query originalChildQuery;
// This field will hold the rewritten form of originalChildQuery, so that we can reuse it
private Query rewrittenChildQuery;
private IndexReader rewriteIndexReader;
// Note, the query is expected to already be filtered to only child type docs
public TopChildrenQuery(Query childQuery, String childType, String parentType, ScoreType scoreType, int factor, int incrementalFactor, CacheRecycler cacheRecycler) {
this.originalChildQuery = childQuery;
this.childType = childType;
this.parentType = parentType;
this.scoreType = scoreType;
this.factor = factor;
this.incrementalFactor = incrementalFactor;
this.cacheRecycler = cacheRecycler;
}
// Rewrite invocation logic:
// 1) query_then_fetch (default): Rewrite is execute as part of the createWeight invocation, when search child docs.
// 2) dfs_query_then_fetch:: First rewrite and then createWeight is executed. During query phase rewrite isn't
// executed any more because searchContext#queryRewritten() returns true.
@Override
public Query rewrite(IndexReader reader) throws IOException {
if (rewrittenChildQuery == null) {
rewrittenChildQuery = originalChildQuery.rewrite(reader);
rewriteIndexReader = reader;
}
// We can always return the current instance, and we can do this b/c the child query is executed separately
// before the main query (other scope) in a different IS#search() invocation than the main query.
// In fact we only need override the rewrite method because for the dfs phase, to get also global document
// frequency for the child query.
return this;
}
@Override
public void extractTerms(Set<Term> terms) {
rewrittenChildQuery.extractTerms(terms);
}
@Override
public Weight createWeight(IndexSearcher searcher) throws IOException {
Recycler.V<ObjectObjectOpenHashMap<Object, ParentDoc[]>> parentDocs = cacheRecycler.hashMap(-1);
SearchContext searchContext = SearchContext.current();
searchContext.idCache().refresh(searchContext.searcher().getTopReaderContext().leaves());
int parentHitsResolved;
int requestedDocs = (searchContext.from() + searchContext.size());
if (requestedDocs <= 0) {
requestedDocs = 1;
}
int numChildDocs = requestedDocs * factor;
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());
while (true) {
parentDocs.v().clear();
TopDocs topChildDocs = indexSearcher.search(childQuery, numChildDocs);
parentHitsResolved = resolveParentDocuments(topChildDocs, searchContext, parentDocs);
// check if we found enough docs, if so, break
if (parentHitsResolved >= requestedDocs) {
break;
}
// if we did not find enough docs, check if it make sense to search further
if (topChildDocs.totalHits <= numChildDocs) {
break;
}
// if not, update numDocs, and search again
numChildDocs *= incrementalFactor;
if (numChildDocs > topChildDocs.totalHits) {
numChildDocs = topChildDocs.totalHits;
}
}
ParentWeight parentWeight = new ParentWeight(rewrittenChildQuery.createWeight(searcher), parentDocs);
searchContext.addReleasable(parentWeight);
return parentWeight;
}
int resolveParentDocuments(TopDocs topDocs, SearchContext context, Recycler.V<ObjectObjectOpenHashMap<Object, ParentDoc[]>> parentDocs) {
int parentHitsResolved = 0;
Recycler.V<ObjectObjectOpenHashMap<Object, Recycler.V<IntObjectOpenHashMap<ParentDoc>>>> parentDocsPerReader = cacheRecycler.hashMap(context.searcher().getIndexReader().leaves().size());
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
int readerIndex = ReaderUtil.subIndex(scoreDoc.doc, context.searcher().getIndexReader().leaves());
AtomicReaderContext subContext = context.searcher().getIndexReader().leaves().get(readerIndex);
int subDoc = scoreDoc.doc - subContext.docBase;
// find the parent id
HashedBytesArray parentId = context.idCache().reader(subContext.reader()).parentIdByDoc(parentType, subDoc);
if (parentId == null) {
// no parent found
continue;
}
// now go over and find the parent doc Id and reader tuple
for (AtomicReaderContext atomicReaderContext : context.searcher().getIndexReader().leaves()) {
AtomicReader indexReader = atomicReaderContext.reader();
int parentDocId = context.idCache().reader(indexReader).docById(parentType, parentId);
Bits liveDocs = indexReader.getLiveDocs();
if (parentDocId != -1 && (liveDocs == null || liveDocs.get(parentDocId))) {
// we found a match, add it and break
Recycler.V<IntObjectOpenHashMap<ParentDoc>> readerParentDocs = parentDocsPerReader.v().get(indexReader.getCoreCacheKey());
if (readerParentDocs == null) {
readerParentDocs = cacheRecycler.intObjectMap(indexReader.maxDoc());
parentDocsPerReader.v().put(indexReader.getCoreCacheKey(), readerParentDocs);
}
ParentDoc parentDoc = readerParentDocs.v().get(parentDocId);
if (parentDoc == null) {
parentHitsResolved++; // we have a hit on a parent
parentDoc = new ParentDoc();
parentDoc.docId = parentDocId;
parentDoc.count = 1;
parentDoc.maxScore = scoreDoc.score;
parentDoc.sumScores = scoreDoc.score;
readerParentDocs.v().put(parentDocId, parentDoc);
} else {
parentDoc.count++;
parentDoc.sumScores += scoreDoc.score;
if (scoreDoc.score > parentDoc.maxScore) {
parentDoc.maxScore = scoreDoc.score;
}
}
}
}
}
boolean[] states = parentDocsPerReader.v().allocated;
Object[] keys = parentDocsPerReader.v().keys;
Object[] values = parentDocsPerReader.v().values;
for (int i = 0; i < states.length; i++) {
if (states[i]) {
Recycler.V<IntObjectOpenHashMap<ParentDoc>> value = (Recycler.V<IntObjectOpenHashMap<ParentDoc>>) values[i];
ParentDoc[] _parentDocs = value.v().values().toArray(ParentDoc.class);
Arrays.sort(_parentDocs, PARENT_DOC_COMP);
parentDocs.v().put(keys[i], _parentDocs);
Releasables.release(value);
}
}
Releasables.release(parentDocsPerReader);
return parentHitsResolved;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
TopChildrenQuery that = (TopChildrenQuery) obj;
if (!originalChildQuery.equals(that.originalChildQuery)) {
return false;
}
if (!childType.equals(that.childType)) {
return false;
}
if (incrementalFactor != that.incrementalFactor) {
return false;
}
if (getBoost() != that.getBoost()) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = originalChildQuery.hashCode();
result = 31 * result + parentType.hashCode();
result = 31 * result + incrementalFactor;
result = 31 * result + Float.floatToIntBits(getBoost());
return result;
}
public String toString(String field) {
StringBuilder sb = new StringBuilder();
sb.append("score_child[").append(childType).append("/").append(parentType).append("](").append(originalChildQuery.toString(field)).append(')');
sb.append(ToStringUtils.boost(getBoost()));
return sb.toString();
}
private class ParentWeight extends Weight implements Releasable {
private final Weight queryWeight;
private final Recycler.V<ObjectObjectOpenHashMap<Object, ParentDoc[]>> parentDocs;
public ParentWeight(Weight queryWeight, Recycler.V<ObjectObjectOpenHashMap<Object, ParentDoc[]>> parentDocs) throws IOException {
this.queryWeight = queryWeight;
this.parentDocs = parentDocs;
}
public Query getQuery() {
return TopChildrenQuery.this;
}
@Override
public float getValueForNormalization() throws IOException {
float sum = queryWeight.getValueForNormalization();
sum *= getBoost() * getBoost();
return sum;
}
@Override
public void normalize(float norm, float topLevelBoost) {
// Nothing to normalize
}
@Override
public boolean release() throws ElasticsearchException {
Releasables.release(parentDocs);
return true;
}
@Override
public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException {
ParentDoc[] readerParentDocs = parentDocs.v().get(context.reader().getCoreCacheKey());
if (readerParentDocs != null) {
if (scoreType == ScoreType.MAX) {
return new ParentScorer(this, readerParentDocs) {
@Override
public float score() throws IOException {
assert doc.docId >= 0 || doc.docId < NO_MORE_DOCS;
return doc.maxScore;
}
};
} else if (scoreType == ScoreType.AVG) {
return new ParentScorer(this, readerParentDocs) {
@Override
public float score() throws IOException {
assert doc.docId >= 0 || doc.docId < NO_MORE_DOCS;
return doc.sumScores / doc.count;
}
};
} else if (scoreType == ScoreType.SUM) {
return new ParentScorer(this, readerParentDocs) {
@Override
public float score() throws IOException {
assert doc.docId >= 0 || doc.docId < NO_MORE_DOCS;
return doc.sumScores;
}
};
}
throw new ElasticsearchIllegalStateException("No support for score type [" + scoreType + "]");
}
return new EmptyScorer(this);
}
@Override
public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
return new Explanation(getBoost(), "not implemented yet...");
}
}
private static abstract class ParentScorer extends Scorer {
private final ParentDoc spare = new ParentDoc();
protected final ParentDoc[] docs;
protected ParentDoc doc = spare;
private int index = -1;
ParentScorer(ParentWeight weight, ParentDoc[] docs) throws IOException {
super(weight);
this.docs = docs;
spare.docId = -1;
spare.count = -1;
}
@Override
public final int docID() {
return doc.docId;
}
@Override
public final int advance(int target) throws IOException {
return slowAdvance(target);
}
@Override
public final int nextDoc() throws IOException {
if (++index >= docs.length) {
doc = spare;
doc.count = 0;
return (doc.docId = NO_MORE_DOCS);
}
return (doc = docs[index]).docId;
}
@Override
public final int freq() throws IOException {
return doc.count; // The number of matches in the child doc, which is propagated to parent
}
@Override
public final long cost() {
return docs.length;
}
}
private static class ParentDocComparator implements Comparator<ParentDoc> {
@Override
public int compare(ParentDoc o1, ParentDoc o2) {
return o1.docId - o2.docId;
}
}
private static class ParentDoc {
public int docId;
public int count;
public float maxScore = Float.NaN;
public float sumScores = 0;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_search_child_TopChildrenQuery.java
|
1,773 |
public class OMailPlugin extends OServerPluginAbstract implements OScriptInjection {
private static final String CONFIG_PROFILE_PREFIX = "profile.";
private static final String CONFIG_MAIL_PREFIX = "mail.";
private Map<String, OMailProfile> profiles = new HashMap<String, OMailProfile>();
public OMailPlugin() {
Orient.instance().getScriptManager().registerInjection(this);
}
@Override
public void config(final OServer oServer, final OServerParameterConfiguration[] iParams) {
for (OServerParameterConfiguration param : iParams) {
if (param.name.equalsIgnoreCase("enabled")) {
if (!Boolean.parseBoolean(param.value))
// DISABLE IT
return;
} else if (param.name.startsWith(CONFIG_PROFILE_PREFIX)) {
final String parts = param.name.substring(CONFIG_PROFILE_PREFIX.length());
int pos = parts.indexOf('.');
if (pos == -1)
continue;
final String profileName = parts.substring(0, pos);
final String profileParam = parts.substring(pos + 1);
OMailProfile profile = profiles.get(profileName);
if (profile == null) {
profile = new OMailProfile();
profiles.put(profileName, profile);
}
if (profileParam.startsWith(CONFIG_MAIL_PREFIX)) {
profile.put("mail." + profileParam.substring(CONFIG_MAIL_PREFIX.length()), param.value);
}
}
}
OLogManager.instance().info(this, "Mail plugin installed and active. Loaded %d profile(s): %s", profiles.size(),
profiles.keySet());
}
/**
* Sends an email. Supports the following configuration: subject, message, to, cc, bcc, date, attachments
*
* @param iMessage
* Configuration as Map<String,Object>
* @throws AddressException
* @throws MessagingException
* @throws ParseException
*/
public void send(final Map<String, Object> iMessage) throws AddressException, MessagingException, ParseException {
final String profileName = (String) iMessage.get("profile");
final OMailProfile profile = profiles.get(profileName);
if (profile == null)
throw new IllegalArgumentException("Mail profile '" + profileName + "' is not configured on server");
// creates a new session with an authenticator
Authenticator auth = new OSMTPAuthenticator((String) profile.getProperty("mail.smtp.user"),
(String) profile.getProperty("mail.smtp.password"));
Session session = Session.getInstance(profile, auth);
// creates a new e-mail message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress((String) iMessage.get("from")));
InternetAddress[] toAddresses = { new InternetAddress(
(String) iMessage.get("to")) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
String cc = (String) iMessage.get("cc");
if (cc != null && !cc.isEmpty()) {
InternetAddress[] ccAddresses = { new InternetAddress(cc) };
msg.setRecipients(Message.RecipientType.CC, ccAddresses);
}
String bcc = (String) iMessage.get("bcc");
if (bcc != null && !bcc.isEmpty()) {
InternetAddress[] bccAddresses = { new InternetAddress(bcc) };
msg.setRecipients(Message.RecipientType.BCC, bccAddresses);
}
msg.setSubject((String) iMessage.get("subject"));
// DATE
Object date = iMessage.get("date");
final Date sendDate;
if (date == null)
// NOT SPECIFIED = NOW
sendDate = new Date();
else if (date instanceof Date)
// PASSED
sendDate = (Date) date;
else {
// FORMAT IT
String dateFormat = (String) profile.getProperty("mail.date.format");
if (dateFormat == null)
dateFormat = "yyyy-MM-dd HH:mm:ss";
sendDate = new SimpleDateFormat(dateFormat).parse(date.toString());
}
msg.setSentDate(sendDate);
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(iMessage.get("message"), "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
final String[] attachments = (String[]) iMessage.get("attachments");
// adds attachments
if (attachments != null && attachments.length > 0) {
for (String filePath : attachments) {
addAttachment(multipart, filePath);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
/**
* Adds a file as an attachment to the email's content
*
* @param multipart
* @param filePath
* @throws MessagingException
*/
private void addAttachment(final Multipart multipart, final String filePath) throws MessagingException {
MimeBodyPart attachPart = new MimeBodyPart();
DataSource source = new FileDataSource(filePath);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(new File(filePath).getName());
multipart.addBodyPart(attachPart);
}
@Override
public void bind(Bindings binding) {
binding.put("mail", this);
}
@Override
public void unbind(Bindings binding) {
binding.remove("mail");
}
@Override
public String getName() {
return "mail";
}
public Set<String> getProfileNames() {
return profiles.keySet();
}
public OMailProfile getProfile(final String iName) {
return profiles.get(iName);
}
public OMailPlugin registerProfile(final String iName, final OMailProfile iProfile) {
profiles.put(iName, iProfile);
return this;
}
}
| 1no label
|
server_src_main_java_com_orientechnologies_orient_server_plugin_mail_OMailPlugin.java
|
409 |
@Repository("blSequenceGeneratorCorruptionDetection")
public class SequenceGeneratorCorruptionDetection implements ApplicationListener<ContextRefreshedEvent> {
private static final Log LOG = LogFactory.getLog(SequenceGeneratorCorruptionDetection.class);
@PersistenceContext(unitName="blPU")
protected EntityManager em;
@Value("${detect.sequence.generator.inconsistencies}")
protected boolean detectSequenceGeneratorInconsistencies = true;
@Value("${auto.correct.sequence.generator.inconsistencies}")
protected boolean automaticallyCorrectInconsistencies = false;
@Value("${default.schema.sequence.generator}")
protected String defaultSchemaSequenceGenerator = "";
@Override
@Transactional("blTransactionManager")
public void onApplicationEvent(ContextRefreshedEvent event) {
if (detectSequenceGeneratorInconsistencies) {
SessionFactory sessionFactory = ((HibernateEntityManager) em).getSession().getSessionFactory();
for (Object item : sessionFactory.getAllClassMetadata().values()) {
ClassMetadata metadata = (ClassMetadata) item;
String idProperty = metadata.getIdentifierPropertyName();
Class<?> mappedClass = metadata.getMappedClass();
Field idField;
try {
idField = mappedClass.getDeclaredField(idProperty);
} catch (NoSuchFieldException e) {
continue;
}
idField.setAccessible(true);
GenericGenerator genericAnnot = idField.getAnnotation(GenericGenerator.class);
TableGenerator tableAnnot = idField.getAnnotation(TableGenerator.class);
String segmentValue = null;
String tableName = null;
String segmentColumnName = null;
String valueColumnName = null;
if (genericAnnot != null && genericAnnot.strategy().equals("org.broadleafcommerce.common.persistence.IdOverrideTableGenerator")) {
//This is a BLC style ID generator
for (Parameter param : genericAnnot.parameters()) {
if (param.name().equals("segment_value")) {
segmentValue = param.value();
}
if (param.name().equals("table_name")) {
tableName = param.value();
}
if (param.name().equals("segment_column_name")) {
segmentColumnName = param.value();
}
if (param.name().equals("value_column_name")) {
valueColumnName = param.value();
}
}
} else if (tableAnnot != null) {
//This is a traditional Hibernate generator
segmentValue = tableAnnot.pkColumnValue();
tableName = tableAnnot.table();
segmentColumnName = tableAnnot.pkColumnName();
valueColumnName = tableAnnot.valueColumnName();
}
if (!StringUtils.isEmpty(segmentValue) && !StringUtils.isEmpty(tableName) && !StringUtils.isEmpty(segmentColumnName) && !StringUtils.isEmpty(valueColumnName)) {
StringBuilder sb2 = new StringBuilder();
sb2.append("select ");
sb2.append(valueColumnName);
sb2.append(" from ");
if (!tableName.contains(".") && !StringUtils.isEmpty(defaultSchemaSequenceGenerator)) {
sb2.append(defaultSchemaSequenceGenerator);
sb2.append(".");
}
sb2.append(tableName);
sb2.append(" where ");
sb2.append(segmentColumnName);
sb2.append(" = '");
sb2.append(segmentValue);
sb2.append("'");
List results2 = em.createNativeQuery(sb2.toString()).getResultList();
if (results2 != null && !results2.isEmpty() && results2.get(0) != null) {
Long maxSequenceId = ((Number) results2.get(0)).longValue();
LOG.info("Detecting id sequence state between " + mappedClass.getName() + " and " + segmentValue + " in " + tableName);
StringBuilder sb = new StringBuilder();
sb.append("select max(");
sb.append(idField.getName());
sb.append(") from ");
sb.append(mappedClass.getName());
sb.append(" entity");
List results = em.createQuery(sb.toString()).getResultList();
if (results != null && !results.isEmpty() && results.get(0) != null) {
Long maxEntityId = (Long) results.get(0);
if (maxEntityId > maxSequenceId) {
if (automaticallyCorrectInconsistencies) {
StringBuilder sb3 = new StringBuilder();
sb3.append("update ");
if (!tableName.contains(".") && !StringUtils.isEmpty(defaultSchemaSequenceGenerator)) {
sb2.append(defaultSchemaSequenceGenerator);
sb2.append(".");
}
sb3.append(tableName);
sb3.append(" set ");
sb3.append(valueColumnName);
sb3.append(" = ");
sb3.append(String.valueOf(maxEntityId + 10));
sb3.append(" where ");
sb3.append(segmentColumnName);
sb3.append(" = '");
sb3.append(segmentValue);
sb3.append("'");
int response = em.createNativeQuery(sb3.toString()).executeUpdate();
if (response <= 0) {
throw new RuntimeException("Unable to update " + tableName + " with the sequence generator id for " + segmentValue);
}
} else {
String reason = "A data inconsistency has been detected between the " + tableName + " table and one or more entity tables for which it manages current max primary key values.\n" +
"The inconsistency was detected between the managed class (" + mappedClass.getName() + ") and the identifier (" + segmentValue + ") in " + tableName + ". Broadleaf\n" +
"has stopped startup of the application in order to allow you to resolve the issue and avoid possible data corruption. If you wish to disable this detection, you may\n" +
"set the 'detect.sequence.generator.inconsistencies' property to false in your application's common.properties or common-shared.properties. If you would like for this component\n" +
"to autocorrect these problems by setting the sequence generator value to a value greater than the max entity id, then set the 'auto.correct.sequence.generator.inconsistencies'\n" +
"property to true in your application's common.properties or common-shared.properties. If you would like to provide a default schema to be used to qualify table names used in the\n" +
"queries for this detection, set the 'default.schema.sequence.generator' property in your application's common.properties or common-shared.properties. Also, if you are upgrading\n" +
"from 1.6 or below, please refer to http://docs.broadleafcommerce.org/current/1.6-to-2.0-Migration.html for important information regarding migrating your SEQUENCE_GENERATOR table.";
LOG.error("Broadleaf Commerce failed to start", new RuntimeException(reason));
System.exit(1);
}
}
}
}
}
}
}
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_persistence_SequenceGeneratorCorruptionDetection.java
|
525 |
public class BroadleafMergeResourceBundleMessageSource extends ReloadableResourceBundleMessageSource {
/**
* The super implementation ensures the basenames defined at the beginning take precedence. We require the opposite in
* order to be in line with previous assumptions about the applicationContext merge process (meaning, beans defined in
* later applicationContexts take precedence). Thus, this reverses <b>basenames</b> before passing it up to the super
* implementation.
*
* @param basenames
* @param resourceBundleExtensionPoint
* @see {@link ReloadableResourceBundleMessageSource#setBasenames(String...)}
*/
@Override
public void setBasenames(String... basenames) {
CollectionUtils.reverseArray(basenames);
super.setBasenames(basenames);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_util_BroadleafMergeResourceBundleMessageSource.java
|
348 |
public class EntityClassNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public EntityClassNotFoundException() {
super();
}
public EntityClassNotFoundException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public EntityClassNotFoundException(String arg0) {
super(arg0);
}
public EntityClassNotFoundException(Throwable arg0) {
super(arg0);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_jpa_EntityClassNotFoundException.java
|
51 |
public class HttpDeleteCommand extends HttpCommand {
boolean nextLine;
public HttpDeleteCommand(String uri) {
super(TextCommandType.HTTP_DELETE, uri);
}
public boolean readFrom(ByteBuffer cb) {
while (cb.hasRemaining()) {
char c = (char) cb.get();
if (c == '\n') {
if (nextLine) {
return true;
}
nextLine = true;
} else if (c != '\r') {
nextLine = false;
}
}
return false;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpDeleteCommand.java
|
135 |
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
public sun.misc.Unsafe run() throws Exception {
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
for (java.lang.reflect.Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x))
return k.cast(x);
}
throw new NoSuchFieldError("the Unsafe");
}});
| 0true
|
src_main_java_jsr166e_StampedLock.java
|
1,434 |
updateSettings(updateRequest, new ClusterStateUpdateListener() {
@Override
public void onResponse(ClusterStateUpdateResponse response) {
for (String index : indices) {
logger.info("[{}] auto expanded replicas to [{}]", index, fNumberOfReplicas);
}
}
@Override
public void onFailure(Throwable t) {
for (String index : indices) {
logger.warn("[{}] fail to auto expand replicas to [{}]", index, fNumberOfReplicas);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_cluster_metadata_MetaDataUpdateSettingsService.java
|
387 |
public class ClusterUpdateSettingsRequestBuilder extends AcknowledgedRequestBuilder<ClusterUpdateSettingsRequest, ClusterUpdateSettingsResponse, ClusterUpdateSettingsRequestBuilder> {
public ClusterUpdateSettingsRequestBuilder(ClusterAdminClient clusterClient) {
super((InternalClusterAdminClient) clusterClient, new ClusterUpdateSettingsRequest());
}
/**
* Sets the transient settings to be updated. They will not survive a full cluster restart
*/
public ClusterUpdateSettingsRequestBuilder setTransientSettings(Settings settings) {
request.transientSettings(settings);
return this;
}
/**
* Sets the transient settings to be updated. They will not survive a full cluster restart
*/
public ClusterUpdateSettingsRequestBuilder setTransientSettings(Settings.Builder settings) {
request.transientSettings(settings);
return this;
}
/**
* Sets the source containing the transient settings to be updated. They will not survive a full cluster restart
*/
public ClusterUpdateSettingsRequestBuilder setTransientSettings(String settings) {
request.transientSettings(settings);
return this;
}
/**
* Sets the transient settings to be updated. They will not survive a full cluster restart
*/
public ClusterUpdateSettingsRequestBuilder setTransientSettings(Map settings) {
request.transientSettings(settings);
return this;
}
/**
* Sets the persistent settings to be updated. They will get applied cross restarts
*/
public ClusterUpdateSettingsRequestBuilder setPersistentSettings(Settings settings) {
request.persistentSettings(settings);
return this;
}
/**
* Sets the persistent settings to be updated. They will get applied cross restarts
*/
public ClusterUpdateSettingsRequestBuilder setPersistentSettings(Settings.Builder settings) {
request.persistentSettings(settings);
return this;
}
/**
* Sets the source containing the persistent settings to be updated. They will get applied cross restarts
*/
public ClusterUpdateSettingsRequestBuilder setPersistentSettings(String settings) {
request.persistentSettings(settings);
return this;
}
/**
* Sets the persistent settings to be updated. They will get applied cross restarts
*/
public ClusterUpdateSettingsRequestBuilder setPersistentSettings(Map settings) {
request.persistentSettings(settings);
return this;
}
@Override
protected void doExecute(ActionListener<ClusterUpdateSettingsResponse> listener) {
((ClusterAdminClient) client).updateSettings(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_settings_ClusterUpdateSettingsRequestBuilder.java
|
90 |
public interface ObjectToInt<A> {int apply(A a); }
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
100 |
public class OUnsafeMemoryJava7 extends OUnsafeMemory {
@Override
public byte[] get(long pointer, final int length) {
final byte[] result = new byte[length];
unsafe.copyMemory(null, pointer, result, unsafe.arrayBaseOffset(byte[].class), length);
return result;
}
@Override
public void get(long pointer, byte[] array, int arrayOffset, int length) {
pointer += arrayOffset;
unsafe.copyMemory(null, pointer, array, arrayOffset + unsafe.arrayBaseOffset(byte[].class), length);
}
@Override
public void set(long pointer, byte[] content, int arrayOffset, int length) {
unsafe.copyMemory(content, unsafe.arrayBaseOffset(byte[].class) + arrayOffset, null, pointer, length);
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_directmemory_OUnsafeMemoryJava7.java
|
139 |
public static class Group {
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";
}
public static class Order {
public static final int Description = 1000;
public static final int Internal = 2000;
public static final int Rules = 1000;
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentImpl.java
|
352 |
static class NodeShutdownRequest extends TransportRequest {
boolean exit;
NodeShutdownRequest() {
}
NodeShutdownRequest(NodesShutdownRequest request) {
super(request);
this.exit = request.exit();
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
exit = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(exit);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_shutdown_TransportNodesShutdownAction.java
|
2,573 |
clusterService.submitStateUpdateTask("zen-disco-node_failed(" + node + "), reason " + reason, Priority.URGENT, new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
DiscoveryNodes.Builder builder = DiscoveryNodes.builder(currentState.nodes())
.remove(node.id());
latestDiscoNodes = builder.build();
currentState = ClusterState.builder(currentState).nodes(latestDiscoNodes).build();
// check if we have enough master nodes, if not, we need to move into joining the cluster again
if (!electMaster.hasEnoughMasterNodes(currentState.nodes())) {
return rejoin(currentState, "not enough master nodes");
}
// eagerly run reroute to remove dead nodes from routing table
RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder(currentState).build());
return ClusterState.builder(currentState).routingResult(routingResult).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
sendInitialStateEventIfNeeded();
}
});
| 1no label
|
src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java
|
471 |
public class BroadleafAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
private String defaultFailureUrl;
public BroadleafAuthenticationFailureHandler() {
super();
}
public BroadleafAuthenticationFailureHandler(String defaultFailureUrl) {
super(defaultFailureUrl);
this.defaultFailureUrl = defaultFailureUrl;
}
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
String failureUrlParam = StringUtil.cleanseUrlString(request.getParameter("failureUrl"));
String successUrlParam = StringUtil.cleanseUrlString(request.getParameter("successUrl"));
String failureUrl = StringUtils.trimToNull(failureUrlParam);
// Verify that the url passed in is a servlet path and not a link redirecting away from the webapp.
failureUrl = validateUrlParam(failureUrl);
successUrlParam = validateUrlParam(successUrlParam);
if (failureUrl == null) {
failureUrl = StringUtils.trimToNull(defaultFailureUrl);
}
if (failureUrl != null) {
if (StringUtils.isNotEmpty(successUrlParam)) {
if (!failureUrl.contains("?")) {
failureUrl += "?successUrl=" + successUrlParam;
} else {
failureUrl += "&successUrl=" + successUrlParam;
}
}
saveException(request, exception);
getRedirectStrategy().sendRedirect(request, response, failureUrl);
} else {
super.onAuthenticationFailure(request, response, exception);
}
}
public String validateUrlParam(String url) {
if (url != null) {
if (url.contains("http") || url.contains("www") || url.contains(".")) {
return null;
}
}
return url;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_security_BroadleafAuthenticationFailureHandler.java
|
308 |
Long.class, 134217728, new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
OMMapManagerOld.setMaxMemory(OFileUtils.getSizeAsNumber(iNewValue));
}
}),
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_config_OGlobalConfiguration.java
|
1,245 |
public class NodeClientModule extends AbstractModule {
@Override
protected void configure() {
bind(ClusterAdminClient.class).to(NodeClusterAdminClient.class).asEagerSingleton();
bind(IndicesAdminClient.class).to(NodeIndicesAdminClient.class).asEagerSingleton();
bind(AdminClient.class).to(NodeAdminClient.class).asEagerSingleton();
bind(Client.class).to(NodeClient.class).asEagerSingleton();
}
}
| 0true
|
src_main_java_org_elasticsearch_client_node_NodeClientModule.java
|
410 |
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
|
1,340 |
metaDataMappingService.updateMapping(request.index(), request.indexUUID(), request.type(), request.mappingSource(), request.order, request.nodeId, new ClusterStateUpdateListener() {
@Override
public void onResponse(ClusterStateUpdateResponse response) {
listener.onResponse(new MappingUpdatedResponse());
}
@Override
public void onFailure(Throwable t) {
logger.warn("[{}] update-mapping [{}] failed to dynamically update the mapping in cluster_state from shard", t, request.index(), request.type());
listener.onFailure(t);
}
});
| 0true
|
src_main_java_org_elasticsearch_cluster_action_index_MappingUpdatedAction.java
|
613 |
public class CommonStatsFlags implements Streamable, Cloneable {
public final static CommonStatsFlags ALL = new CommonStatsFlags().all();
public final static CommonStatsFlags NONE = new CommonStatsFlags().clear();
private EnumSet<Flag> flags = EnumSet.allOf(Flag.class);
private String[] types = null;
private String[] groups = null;
private String[] fieldDataFields = null;
private String[] completionDataFields = null;
/**
* @param flags flags to set. If no flags are supplied, default flags will be set.
*/
public CommonStatsFlags(Flag... flags) {
if (flags.length > 0) {
clear();
for (Flag f : flags) {
this.flags.add(f);
}
}
}
/**
* Sets all flags to return all stats.
*/
public CommonStatsFlags all() {
flags = EnumSet.allOf(Flag.class);
types = null;
groups = null;
fieldDataFields = null;
completionDataFields = null;
return this;
}
/**
* Clears all stats.
*/
public CommonStatsFlags clear() {
flags = EnumSet.noneOf(Flag.class);
types = null;
groups = null;
fieldDataFields = null;
completionDataFields = null;
return this;
}
public boolean anySet() {
return !flags.isEmpty();
}
public Flag[] getFlags() {
return flags.toArray(new Flag[flags.size()]);
}
/**
* Document types to return stats for. Mainly affects {@link Flag#Indexing} when
* enabled, returning specific indexing stats for those types.
*/
public CommonStatsFlags types(String... types) {
this.types = types;
return this;
}
/**
* Document types to return stats for. Mainly affects {@link Flag#Indexing} when
* enabled, returning specific indexing stats for those types.
*/
public String[] types() {
return this.types;
}
/**
* Sets specific search group stats to retrieve the stats for. Mainly affects search
* when enabled.
*/
public CommonStatsFlags groups(String... groups) {
this.groups = groups;
return this;
}
public String[] groups() {
return this.groups;
}
/**
* Sets specific search group stats to retrieve the stats for. Mainly affects search
* when enabled.
*/
public CommonStatsFlags fieldDataFields(String... fieldDataFields) {
this.fieldDataFields = fieldDataFields;
return this;
}
public String[] fieldDataFields() {
return this.fieldDataFields;
}
public CommonStatsFlags completionDataFields(String... completionDataFields) {
this.completionDataFields = completionDataFields;
return this;
}
public String[] completionDataFields() {
return this.completionDataFields;
}
public boolean isSet(Flag flag) {
return flags.contains(flag);
}
boolean unSet(Flag flag) {
return flags.remove(flag);
}
void set(Flag flag) {
flags.add(flag);
}
public CommonStatsFlags set(Flag flag, boolean add) {
if (add) {
set(flag);
} else {
unSet(flag);
}
return this;
}
public static CommonStatsFlags readCommonStatsFlags(StreamInput in) throws IOException {
CommonStatsFlags flags = new CommonStatsFlags();
flags.readFrom(in);
return flags;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
long longFlags = 0;
for (Flag flag : flags) {
longFlags |= (1 << flag.ordinal());
}
out.writeLong(longFlags);
out.writeStringArrayNullable(types);
out.writeStringArrayNullable(groups);
out.writeStringArrayNullable(fieldDataFields);
out.writeStringArrayNullable(completionDataFields);
}
@Override
public void readFrom(StreamInput in) throws IOException {
final long longFlags = in.readLong();
flags.clear();
for (Flag flag : Flag.values()) {
if ((longFlags & (1 << flag.ordinal())) != 0) {
flags.add(flag);
}
}
types = in.readStringArray();
groups = in.readStringArray();
fieldDataFields = in.readStringArray();
completionDataFields = in.readStringArray();
}
@Override
public CommonStatsFlags clone() {
try {
CommonStatsFlags cloned = (CommonStatsFlags) super.clone();
cloned.flags = flags.clone();
return cloned;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
public static enum Flag {
// Do not change the order of these flags we use
// the ordinal for encoding! Only append to the end!
Store("store"),
Indexing("indexing"),
Get("get"),
Search("search"),
Merge("merge"),
Flush("flush"),
Refresh("refresh"),
FilterCache("filter_cache"),
IdCache("id_cache"),
FieldData("fielddata"),
Docs("docs"),
Warmer("warmer"),
Percolate("percolate"),
Completion("completion"),
Segments("segments"),
Translog("translog");
private final String restName;
Flag(String restName) {
this.restName = restName;
}
public String getRestName() {
return restName;
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_stats_CommonStatsFlags.java
|
424 |
restoreService.restoreSnapshot(restoreRequest, new RestoreSnapshotListener() {
@Override
public void onResponse(RestoreInfo restoreInfo) {
if (restoreInfo == null) {
if (request.waitForCompletion()) {
restoreService.addListener(new RestoreService.RestoreCompletionListener() {
SnapshotId snapshotId = new SnapshotId(request.repository(), request.snapshot());
@Override
public void onRestoreCompletion(SnapshotId snapshotId, RestoreInfo snapshot) {
if (this.snapshotId.equals(snapshotId)) {
listener.onResponse(new RestoreSnapshotResponse(snapshot));
restoreService.removeListener(this);
}
}
});
} else {
listener.onResponse(new RestoreSnapshotResponse(null));
}
} else {
listener.onResponse(new RestoreSnapshotResponse(restoreInfo));
}
}
@Override
public void onFailure(Throwable t) {
listener.onFailure(t);
}
});
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_restore_TransportRestoreSnapshotAction.java
|
617 |
new OIndexEngine.EntriesResultListener() {
@Override
public boolean addResult(ODocument entry) {
return indexEntriesResultListener.addResult(entry);
}
});
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_index_OIndexMultiValues.java
|
276 |
public static class Module extends AbstractModule {
private final Version version;
public Module(Version version) {
this.version = version;
}
@Override
protected void configure() {
bind(Version.class).toInstance(version);
}
}
| 0true
|
src_main_java_org_elasticsearch_Version.java
|
791 |
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class AtomicLongTest extends HazelcastTestSupport {
@Test
@ClientCompatibleTest
public void testSimpleAtomicLong() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong an = hazelcastInstance.getAtomicLong("testAtomicLong");
assertEquals(0, an.get());
assertEquals(-1, an.decrementAndGet());
assertEquals(0, an.incrementAndGet());
assertEquals(1, an.incrementAndGet());
assertEquals(2, an.incrementAndGet());
assertEquals(1, an.decrementAndGet());
assertEquals(1, an.getAndSet(23));
assertEquals(28, an.addAndGet(5));
assertEquals(28, an.get());
assertEquals(28, an.getAndAdd(-3));
assertEquals(24, an.decrementAndGet());
Assert.assertFalse(an.compareAndSet(23, 50));
assertTrue(an.compareAndSet(24, 50));
assertTrue(an.compareAndSet(50, 0));
}
@Test
@ClientCompatibleTest
public void testMultipleThreadAtomicLong() throws InterruptedException {
final HazelcastInstance instance = createHazelcastInstance();
final int k = 10;
final CountDownLatch countDownLatch = new CountDownLatch(k);
final IAtomicLong atomicLong = instance.getAtomicLong("testMultipleThreadAtomicLong");
for (int i = 0; i < k; i++) {
new Thread() {
public void run() {
long delta = (long) (Math.random() * 1000);
for (int j = 0; j < 10000; j++) {
atomicLong.addAndGet(delta);
}
for (int j = 0; j < 10000; j++) {
atomicLong.addAndGet(-1 * delta);
}
countDownLatch.countDown();
}
}.start();
}
assertOpenEventually(countDownLatch, 50);
assertEquals(0, atomicLong.get());
}
@Test
@ClientCompatibleTest
public void testAtomicLongFailure() {
int k = 4;
TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(k + 1);
HazelcastInstance instance = nodeFactory.newHazelcastInstance();
String name = "testAtomicLongFailure";
IAtomicLong atomicLong = instance.getAtomicLong(name);
atomicLong.set(100);
for (int i = 0; i < k; i++) {
HazelcastInstance newInstance = nodeFactory.newHazelcastInstance();
IAtomicLong newAtomicLong = newInstance.getAtomicLong(name);
assertEquals((long) 100 + i, newAtomicLong.get());
newAtomicLong.incrementAndGet();
instance.shutdown();
instance = newInstance;
}
}
@Test
@ClientCompatibleTest
public void testAtomicLongSpawnNodeInParallel() throws InterruptedException {
int total = 6;
int parallel = 2;
final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(total + 1);
HazelcastInstance instance = nodeFactory.newHazelcastInstance();
final String name = "testAtomicLongSpawnNodeInParallel";
IAtomicLong atomicLong = instance.getAtomicLong(name);
atomicLong.set(100);
final ExecutorService ex = Executors.newFixedThreadPool(parallel);
try {
for (int i = 0; i < total / parallel; i++) {
final HazelcastInstance[] instances = new HazelcastInstance[parallel];
final CountDownLatch countDownLatch = new CountDownLatch(parallel);
for (int j = 0; j < parallel; j++) {
final int id = j;
ex.execute(new Runnable() {
public void run() {
instances[id] = nodeFactory.newHazelcastInstance();
instances[id].getAtomicLong(name).incrementAndGet();
countDownLatch.countDown();
}
});
}
assertTrue(countDownLatch.await(1, TimeUnit.MINUTES));
IAtomicLong newAtomicLong = instance.getAtomicLong(name);
assertEquals((long) 100 + (i + 1) * parallel, newAtomicLong.get());
instance.shutdown();
instance = instances[0];
}
} finally {
ex.shutdownNow();
}
}
@Test(expected = IllegalArgumentException.class)
@ClientCompatibleTest
public void apply_whenCalledWithNullFunction() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("apply_whenCalledWithNullFunction");
ref.apply(null);
}
@Test
@ClientCompatibleTest
public void apply() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("apply");
assertEquals(new Long(1), ref.apply(new AddOneFunction()));
assertEquals(0, ref.get());
}
@Test
@ClientCompatibleTest
public void apply_whenException() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("apply");
ref.set(1);
try {
ref.apply(new FailingFunction());
fail();
} catch (WoohaaException expected) {
}
assertEquals(1, ref.get());
}
@Test(expected = IllegalArgumentException.class)
@ClientCompatibleTest
public void alter_whenCalledWithNullFunction() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("alter_whenCalledWithNullFunction");
ref.alter(null);
}
@Test
@ClientCompatibleTest
public void alter_whenException() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("alter_whenException");
ref.set(10);
try {
ref.alter(new FailingFunction());
fail();
} catch (WoohaaException expected) {
}
assertEquals(10, ref.get());
}
@Test
@ClientCompatibleTest
public void alter() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("alter");
ref.set(10);
ref.alter(new AddOneFunction());
assertEquals(11, ref.get());
}
@Test(expected = IllegalArgumentException.class)
@ClientCompatibleTest
public void alterAndGet_whenCalledWithNullFunction() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("alterAndGet_whenCalledWithNullFunction");
ref.alterAndGet(null);
}
@Test
@ClientCompatibleTest
public void alterAndGet_whenException() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("alterAndGet_whenException");
ref.set(10);
try {
ref.alterAndGet(new FailingFunction());
fail();
} catch (WoohaaException expected) {
}
assertEquals(10, ref.get());
}
@Test
@ClientCompatibleTest
public void alterAndGet() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("alterAndGet");
ref.set(10);
assertEquals(11, ref.alterAndGet(new AddOneFunction()));
assertEquals(11, ref.get());
}
@Test(expected = IllegalArgumentException.class)
@ClientCompatibleTest
public void getAndAlter_whenCalledWithNullFunction() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("getAndAlter_whenCalledWithNullFunction");
ref.getAndAlter(null);
}
@Test
@ClientCompatibleTest
public void getAndAlter_whenException() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("getAndAlter_whenException");
ref.set(10);
try {
ref.getAndAlter(new FailingFunction());
fail();
} catch (WoohaaException expected) {
}
assertEquals(10, ref.get());
}
@Test
@ClientCompatibleTest
public void getAndAlter() {
HazelcastInstance hazelcastInstance = createHazelcastInstance();
IAtomicLong ref = hazelcastInstance.getAtomicLong("getAndAlter");
ref.set(10);
assertEquals(10, ref.getAndAlter(new AddOneFunction()));
assertEquals(11, ref.get());
}
private static class AddOneFunction implements IFunction<Long, Long> {
@Override
public Long apply(Long input) {
return input+1;
}
}
private static class FailingFunction implements IFunction<Long, Long> {
@Override
public Long apply(Long input) {
throw new WoohaaException();
}
}
private static class WoohaaException extends RuntimeException {
}
}
| 0true
|
hazelcast_src_test_java_com_hazelcast_concurrent_atomiclong_AtomicLongTest.java
|
620 |
public class IndicesStatsResponse extends BroadcastOperationResponse implements ToXContent {
private ShardStats[] shards;
private ImmutableMap<ShardRouting, CommonStats> shardStatsMap;
IndicesStatsResponse() {
}
IndicesStatsResponse(ShardStats[] shards, ClusterState clusterState, int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
super(totalShards, successfulShards, failedShards, shardFailures);
this.shards = shards;
}
public ImmutableMap<ShardRouting, CommonStats> asMap() {
if (shardStatsMap == null) {
ImmutableMap.Builder<ShardRouting, CommonStats> mb = ImmutableMap.builder();
for (ShardStats ss : shards) {
mb.put(ss.getShardRouting(), ss.getStats());
}
shardStatsMap = mb.build();
}
return shardStatsMap;
}
public ShardStats[] getShards() {
return this.shards;
}
public ShardStats getAt(int position) {
return shards[position];
}
public IndexStats getIndex(String index) {
return getIndices().get(index);
}
private Map<String, IndexStats> indicesStats;
public Map<String, IndexStats> getIndices() {
if (indicesStats != null) {
return indicesStats;
}
Map<String, IndexStats> indicesStats = Maps.newHashMap();
Set<String> indices = Sets.newHashSet();
for (ShardStats shard : shards) {
indices.add(shard.getIndex());
}
for (String index : indices) {
List<ShardStats> shards = Lists.newArrayList();
for (ShardStats shard : this.shards) {
if (shard.getShardRouting().index().equals(index)) {
shards.add(shard);
}
}
indicesStats.put(index, new IndexStats(index, shards.toArray(new ShardStats[shards.size()])));
}
this.indicesStats = indicesStats;
return indicesStats;
}
private CommonStats total = null;
public CommonStats getTotal() {
if (total != null) {
return total;
}
CommonStats stats = new CommonStats();
for (ShardStats shard : shards) {
stats.add(shard.getStats());
}
total = stats;
return stats;
}
private CommonStats primary = null;
public CommonStats getPrimaries() {
if (primary != null) {
return primary;
}
CommonStats stats = new CommonStats();
for (ShardStats shard : shards) {
if (shard.getShardRouting().primary()) {
stats.add(shard.getStats());
}
}
primary = stats;
return stats;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shards = new ShardStats[in.readVInt()];
for (int i = 0; i < shards.length; i++) {
shards[i] = ShardStats.readShardStats(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(shards.length);
for (ShardStats shard : shards) {
shard.writeTo(out);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
String level = params.param("level", "indices");
boolean isLevelValid = "indices".equalsIgnoreCase(level) || "shards".equalsIgnoreCase(level) || "cluster".equalsIgnoreCase(level);
if (!isLevelValid) {
return builder;
}
builder.startObject("_all");
builder.startObject("primaries");
getPrimaries().toXContent(builder, params);
builder.endObject();
builder.startObject("total");
getTotal().toXContent(builder, params);
builder.endObject();
builder.endObject();
if ("indices".equalsIgnoreCase(level) || "shards".equalsIgnoreCase(level)) {
builder.startObject(Fields.INDICES);
for (IndexStats indexStats : getIndices().values()) {
builder.startObject(indexStats.getIndex(), XContentBuilder.FieldCaseConversion.NONE);
builder.startObject("primaries");
indexStats.getPrimaries().toXContent(builder, params);
builder.endObject();
builder.startObject("total");
indexStats.getTotal().toXContent(builder, params);
builder.endObject();
if ("shards".equalsIgnoreCase(level)) {
builder.startObject(Fields.SHARDS);
for (IndexShardStats indexShardStats : indexStats) {
builder.startArray(Integer.toString(indexShardStats.getShardId().id()));
for (ShardStats shardStats : indexShardStats) {
builder.startObject();
shardStats.toXContent(builder, params);
builder.endObject();
}
builder.endArray();
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
}
return builder;
}
static final class Fields {
static final XContentBuilderString INDICES = new XContentBuilderString("indices");
static final XContentBuilderString SHARDS = new XContentBuilderString("shards");
}
@Override
public String toString() {
try {
XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
builder.startObject();
toXContent(builder, EMPTY_PARAMS);
builder.endObject();
return builder.string();
} catch (IOException e) {
return "{ \"error\" : \"" + e.getMessage() + "\"}";
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_stats_IndicesStatsResponse.java
|
355 |
public class NodeStats extends NodeOperationResponse implements ToXContent {
private long timestamp;
@Nullable
private NodeIndicesStats indices;
@Nullable
private OsStats os;
@Nullable
private ProcessStats process;
@Nullable
private JvmStats jvm;
@Nullable
private ThreadPoolStats threadPool;
@Nullable
private NetworkStats network;
@Nullable
private FsStats fs;
@Nullable
private TransportStats transport;
@Nullable
private HttpStats http;
@Nullable
private FieldDataBreakerStats breaker;
NodeStats() {
}
public NodeStats(DiscoveryNode node, long timestamp, @Nullable NodeIndicesStats indices,
@Nullable OsStats os, @Nullable ProcessStats process, @Nullable JvmStats jvm, @Nullable ThreadPoolStats threadPool,
@Nullable NetworkStats network, @Nullable FsStats fs, @Nullable TransportStats transport, @Nullable HttpStats http,
@Nullable FieldDataBreakerStats breaker) {
super(node);
this.timestamp = timestamp;
this.indices = indices;
this.os = os;
this.process = process;
this.jvm = jvm;
this.threadPool = threadPool;
this.network = network;
this.fs = fs;
this.transport = transport;
this.http = http;
this.breaker = breaker;
}
public long getTimestamp() {
return this.timestamp;
}
@Nullable
public String getHostname() {
return getNode().getHostName();
}
/**
* Indices level stats.
*/
@Nullable
public NodeIndicesStats getIndices() {
return this.indices;
}
/**
* Operating System level statistics.
*/
@Nullable
public OsStats getOs() {
return this.os;
}
/**
* Process level statistics.
*/
@Nullable
public ProcessStats getProcess() {
return process;
}
/**
* JVM level statistics.
*/
@Nullable
public JvmStats getJvm() {
return jvm;
}
/**
* Thread Pool level statistics.
*/
@Nullable
public ThreadPoolStats getThreadPool() {
return this.threadPool;
}
/**
* Network level statistics.
*/
@Nullable
public NetworkStats getNetwork() {
return network;
}
/**
* File system level stats.
*/
@Nullable
public FsStats getFs() {
return fs;
}
@Nullable
public TransportStats getTransport() {
return this.transport;
}
@Nullable
public HttpStats getHttp() {
return this.http;
}
@Nullable
public FieldDataBreakerStats getBreaker() {
return this.breaker;
}
public static NodeStats readNodeStats(StreamInput in) throws IOException {
NodeStats nodeInfo = new NodeStats();
nodeInfo.readFrom(in);
return nodeInfo;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
timestamp = in.readVLong();
if (in.readBoolean()) {
indices = NodeIndicesStats.readIndicesStats(in);
}
if (in.readBoolean()) {
os = OsStats.readOsStats(in);
}
if (in.readBoolean()) {
process = ProcessStats.readProcessStats(in);
}
if (in.readBoolean()) {
jvm = JvmStats.readJvmStats(in);
}
if (in.readBoolean()) {
threadPool = ThreadPoolStats.readThreadPoolStats(in);
}
if (in.readBoolean()) {
network = NetworkStats.readNetworkStats(in);
}
if (in.readBoolean()) {
fs = FsStats.readFsStats(in);
}
if (in.readBoolean()) {
transport = TransportStats.readTransportStats(in);
}
if (in.readBoolean()) {
http = HttpStats.readHttpStats(in);
}
breaker = FieldDataBreakerStats.readOptionalCircuitBreakerStats(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVLong(timestamp);
if (indices == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
indices.writeTo(out);
}
if (os == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
os.writeTo(out);
}
if (process == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
process.writeTo(out);
}
if (jvm == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
jvm.writeTo(out);
}
if (threadPool == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
threadPool.writeTo(out);
}
if (network == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
network.writeTo(out);
}
if (fs == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
fs.writeTo(out);
}
if (transport == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
transport.writeTo(out);
}
if (http == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
http.writeTo(out);
}
out.writeOptionalStreamable(breaker);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (!params.param("node_info_format", "default").equals("none")) {
builder.field("name", getNode().name(), XContentBuilder.FieldCaseConversion.NONE);
builder.field("transport_address", getNode().address().toString(), XContentBuilder.FieldCaseConversion.NONE);
builder.field("host", getNode().getHostName(), XContentBuilder.FieldCaseConversion.NONE);
builder.field("ip", getNode().getAddress(), XContentBuilder.FieldCaseConversion.NONE);
if (!getNode().attributes().isEmpty()) {
builder.startObject("attributes");
for (Map.Entry<String, String> attr : getNode().attributes().entrySet()) {
builder.field(attr.getKey(), attr.getValue(), XContentBuilder.FieldCaseConversion.NONE);
}
builder.endObject();
}
}
if (getIndices() != null) {
getIndices().toXContent(builder, params);
}
if (getOs() != null) {
getOs().toXContent(builder, params);
}
if (getProcess() != null) {
getProcess().toXContent(builder, params);
}
if (getJvm() != null) {
getJvm().toXContent(builder, params);
}
if (getThreadPool() != null) {
getThreadPool().toXContent(builder, params);
}
if (getNetwork() != null) {
getNetwork().toXContent(builder, params);
}
if (getFs() != null) {
getFs().toXContent(builder, params);
}
if (getTransport() != null) {
getTransport().toXContent(builder, params);
}
if (getHttp() != null) {
getHttp().toXContent(builder, params);
}
if (getBreaker() != null) {
getBreaker().toXContent(builder, params);
}
return builder;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_stats_NodeStats.java
|
203 |
public class HydratedSetup {
private static final Log LOG = LogFactory.getLog(HydratedSetup.class);
private static Map<String, String> inheritanceHierarchyRoots = Collections.synchronizedMap(new HashMap<String, String>());
private static String getInheritanceHierarchyRoot(Class<?> myEntityClass) {
String myEntityName = myEntityClass.getName();
if (inheritanceHierarchyRoots.containsKey(myEntityName)) {
return inheritanceHierarchyRoots.get(myEntityName);
}
Class<?> currentClass = myEntityClass;
boolean eof = false;
while (!eof) {
Class<?> superclass = currentClass.getSuperclass();
if (superclass.equals(Object.class) || !superclass.isAnnotationPresent(Entity.class)) {
eof = true;
} else {
currentClass = superclass;
}
}
if (!currentClass.isAnnotationPresent(Cache.class)) {
currentClass = myEntityClass;
}
inheritanceHierarchyRoots.put(myEntityName, currentClass.getName());
return inheritanceHierarchyRoots.get(myEntityName);
}
public static void populateFromCache(Object entity) {
populateFromCache(entity, null);
}
public static void populateFromCache(Object entity, String propertyName) {
HydratedCacheManager manager = HydratedCacheEventListenerFactory.getConfiguredManager();
HydrationDescriptor descriptor = ((HydratedAnnotationManager) manager).getHydrationDescriptor(entity);
if (!MapUtils.isEmpty(descriptor.getHydratedMutators())) {
Method[] idMutators = descriptor.getIdMutators();
String cacheRegion = descriptor.getCacheRegion();
for (String field : descriptor.getHydratedMutators().keySet()) {
if (StringUtils.isEmpty(propertyName) || field.equals(propertyName)) {
try {
Serializable entityId = (Serializable) idMutators[0].invoke(entity);
Object hydratedItem = manager.getHydratedCacheElementItem(cacheRegion, getInheritanceHierarchyRoot(entity.getClass()), entityId, field);
if (hydratedItem == null) {
Method factoryMethod = entity.getClass().getMethod(descriptor.getHydratedMutators().get(field).getFactoryMethod(), new Class[]{});
Object fieldVal = factoryMethod.invoke(entity);
manager.addHydratedCacheElementItem(cacheRegion, getInheritanceHierarchyRoot(entity.getClass()), entityId, field, fieldVal);
hydratedItem = fieldVal;
}
descriptor.getHydratedMutators().get(field).getMutators()[1].invoke(entity, hydratedItem);
} catch (InvocationTargetException e) {
if (e.getTargetException() != null && e.getTargetException() instanceof CacheFactoryException) {
LOG.warn("Unable to setup the hydrated cache for an entity. " + e.getTargetException().getMessage());
} else {
throw new RuntimeException("There was a problem while replacing a hydrated cache item - field("+field+") : entity("+entity.getClass().getName()+')', e);
}
} catch (Exception e) {
throw new RuntimeException("There was a problem while replacing a hydrated cache item - field("+field+") : entity("+entity.getClass().getName()+')', e);
}
}
}
}
}
public static void addCacheItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName, Object elementValue) {
HydratedCacheManager manager = HydratedCacheEventListenerFactory.getConfiguredManager();
manager.addHydratedCacheElementItem(cacheRegion, cacheName, elementKey, elementItemName, elementValue);
}
public static Object getCacheItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName) {
HydratedCacheManager manager = HydratedCacheEventListenerFactory.getConfiguredManager();
return manager.getHydratedCacheElementItem(cacheRegion, cacheName, elementKey, elementItemName);
}
public static EntityManager retrieveBoundEntityManager() {
Map<Object, Object> resources = TransactionSynchronizationManager.getResourceMap();
for (Map.Entry<Object, Object> entry : resources.entrySet()) {
if (entry.getKey() instanceof EntityManagerFactory) {
EntityManagerFactory emf = (EntityManagerFactory) entry.getKey();
//return the entityManager from the first found
return ((EntityManagerHolder) entry.getValue()).getEntityManager();
}
}
throw new RuntimeException("Unable to restore skus from hydrated cache. Please make sure that the OpenEntityManagerInViewFilter is configured in web.xml for the blPU persistence unit.");
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_cache_HydratedSetup.java
|
204 |
public class OStorageRemote extends OStorageAbstract implements OStorageProxy, OChannelListener {
private static final String DEFAULT_HOST = "localhost";
private static final int DEFAULT_PORT = 2424;
private static final String ADDRESS_SEPARATOR = ";";
public static final String PARAM_MIN_POOL = "minpool";
public static final String PARAM_MAX_POOL = "maxpool";
public static final String PARAM_DB_TYPE = "dbtype";
private static final String DRIVER_NAME = "OrientDB Java";
private final ExecutorService asynchExecutor;
private OContextConfiguration clientConfiguration;
private int connectionRetry;
private int connectionRetryDelay;
private final List<OChannelBinaryAsynchClient> networkPool = new ArrayList<OChannelBinaryAsynchClient>();
private final OLock networkPoolLock = new OAdaptiveLock();
private int networkPoolCursor = 0;
protected final List<String> serverURLs = new ArrayList<String>();
private OCluster[] clusters = new OCluster[0];
protected final Map<String, OCluster> clusterMap = new ConcurrentHashMap<String, OCluster>();
private int defaultClusterId;
private int minPool;
private int maxPool;
private final ODocument clusterConfiguration = new ODocument();
private ORemoteServerEventListener asynchEventListener;
private String connectionDbType;
private String connectionUserName;
private String connectionUserPassword;
private Map<String, Object> connectionOptions;
private final String clientId;
private final int maxReadQueue;
public OStorageRemote(final String iClientId, final String iURL, final String iMode) throws IOException {
super(iURL, iURL, iMode, 0, new OCacheLevelTwoLocatorRemote()); // NO TIMEOUT @SINCE 1.5
clientId = iClientId;
configuration = null;
clientConfiguration = new OContextConfiguration();
connectionRetry = clientConfiguration.getValueAsInteger(OGlobalConfiguration.NETWORK_SOCKET_RETRY);
connectionRetryDelay = clientConfiguration.getValueAsInteger(OGlobalConfiguration.NETWORK_SOCKET_RETRY_DELAY);
asynchEventListener = new OStorageRemoteAsynchEventListener(this);
parseServerURLs();
asynchExecutor = Executors.newSingleThreadScheduledExecutor();
maxReadQueue = Runtime.getRuntime().availableProcessors() - 1;
}
public int getSessionId() {
return OStorageRemoteThreadLocal.INSTANCE.get().sessionId.intValue();
}
public String getServerURL() {
return OStorageRemoteThreadLocal.INSTANCE.get().serverURL;
}
public void setSessionId(final String iServerURL, final int iSessionId) {
final OStorageRemoteSession tl = OStorageRemoteThreadLocal.INSTANCE.get();
tl.serverURL = iServerURL;
tl.sessionId = iSessionId;
}
public ORemoteServerEventListener getAsynchEventListener() {
return asynchEventListener;
}
public void setAsynchEventListener(final ORemoteServerEventListener iListener) {
asynchEventListener = iListener;
}
public void removeRemoteServerEventListener() {
asynchEventListener = null;
}
public void open(final String iUserName, final String iUserPassword, final Map<String, Object> iOptions) {
addUser();
lock.acquireExclusiveLock();
try {
connectionUserName = iUserName;
connectionUserPassword = iUserPassword;
connectionOptions = iOptions != null ? new HashMap<String, Object>(iOptions) : null; // CREATE A COPY TO AVOID USER
// MANIPULATION
// POST OPEN
openRemoteDatabase();
configuration = new OStorageConfiguration(this);
configuration.load();
} catch (Exception e) {
if (!OGlobalConfiguration.STORAGE_KEEP_OPEN.getValueAsBoolean())
close();
if (e instanceof RuntimeException)
// PASS THROUGH
throw (RuntimeException) e;
else
throw new OStorageException("Cannot open the remote storage: " + name, e);
} finally {
lock.releaseExclusiveLock();
}
}
public void reload() {
checkConnection();
lock.acquireExclusiveLock();
try {
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_DB_RELOAD);
} finally {
endRequest(network);
}
try {
beginResponse(network);
readDatabaseInformation(network);
break;
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Error on reloading database information", e);
}
} while (true);
} finally {
lock.releaseExclusiveLock();
}
}
public void create(final Map<String, Object> iOptions) {
throw new UnsupportedOperationException(
"Cannot create a database in a remote server. Please use the console or the OServerAdmin class.");
}
public boolean exists() {
throw new UnsupportedOperationException(
"Cannot check the existance of a database in a remote server. Please use the console or the OServerAdmin class.");
}
public void close(final boolean iForce) {
OChannelBinaryAsynchClient network = null;
lock.acquireExclusiveLock();
try {
networkPoolLock.lock();
try {
if (networkPool.size() > 0) {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_DB_CLOSE);
} finally {
endRequest(network);
}
}
} finally {
networkPoolLock.unlock();
}
setSessionId(null, -1);
if (!checkForClose(iForce))
return;
networkPoolLock.lock();
try {
for (OChannelBinaryAsynchClient n : new ArrayList<OChannelBinaryAsynchClient>(networkPool))
n.close();
networkPool.clear();
} finally {
networkPoolLock.unlock();
}
level2Cache.shutdown();
super.close(iForce);
status = STATUS.CLOSED;
Orient.instance().unregisterStorage(this);
} catch (Exception e) {
OLogManager.instance().debug(this, "Error on closing remote connection: %s", network);
network.close();
} finally {
lock.releaseExclusiveLock();
}
}
public void delete() {
throw new UnsupportedOperationException(
"Cannot delete a database in a remote server. Please use the console or the OServerAdmin class.");
}
public Set<String> getClusterNames() {
lock.acquireSharedLock();
try {
return new HashSet<String>(clusterMap.keySet());
} finally {
lock.releaseSharedLock();
}
}
public OStorageOperationResult<OPhysicalPosition> createRecord(final int iDataSegmentId, final ORecordId iRid,
final byte[] iContent, ORecordVersion iRecordVersion, final byte iRecordType, int iMode,
final ORecordCallback<OClusterPosition> iCallback) {
checkConnection();
if (iMode == 1 && iCallback == null)
// ASYNCHRONOUS MODE NO ANSWER
iMode = 2;
final OPhysicalPosition ppos = new OPhysicalPosition(iDataSegmentId, -1, iRecordType);
OChannelBinaryAsynchClient lastNetworkUsed = null;
do {
try {
final OChannelBinaryAsynchClient network = beginRequest(OChannelBinaryProtocol.REQUEST_RECORD_CREATE);
lastNetworkUsed = network;
try {
if (network.getSrvProtocolVersion() >= 10)
// SEND THE DATA SEGMENT ID
network.writeInt(iDataSegmentId);
network.writeShort((short) iRid.clusterId);
network.writeBytes(iContent);
network.writeByte(iRecordType);
network.writeByte((byte) iMode);
} finally {
endRequest(network);
}
switch (iMode) {
case 0:
// SYNCHRONOUS
try {
beginResponse(network);
iRid.clusterPosition = network.readClusterPosition();
ppos.clusterPosition = iRid.clusterPosition;
if (network.getSrvProtocolVersion() >= 11) {
ppos.recordVersion = network.readVersion();
} else
ppos.recordVersion = OVersionFactory.instance().createVersion();
return new OStorageOperationResult<OPhysicalPosition>(ppos);
} finally {
endResponse(network);
}
case 1:
// ASYNCHRONOUS
if (iCallback != null) {
final int sessionId = getSessionId();
Callable<Object> response = new Callable<Object>() {
public Object call() throws Exception {
final OClusterPosition result;
try {
OStorageRemoteThreadLocal.INSTANCE.get().sessionId = sessionId;
beginResponse(network);
result = network.readClusterPosition();
if (network.getSrvProtocolVersion() >= 11)
network.readVersion();
} finally {
endResponse(network);
OStorageRemoteThreadLocal.INSTANCE.get().sessionId = -1;
}
iCallback.call(iRid, result);
return null;
}
};
asynchExecutor.submit(new FutureTask<Object>(response));
}
}
return new OStorageOperationResult<OPhysicalPosition>(ppos);
} catch (OModificationOperationProhibitedException mope) {
handleDBFreeze();
} catch (Exception e) {
handleException(lastNetworkUsed, "Error on create record in cluster: " + iRid.clusterId, e);
}
} while (true);
}
@Override
public boolean updateReplica(int dataSegmentId, ORecordId rid, byte[] content, ORecordVersion recordVersion, byte recordType)
throws IOException {
throw new UnsupportedOperationException("updateReplica()");
}
@Override
public <V> V callInRecordLock(Callable<V> iCallable, ORID rid, boolean iExclusiveLock) {
throw new UnsupportedOperationException("callInRecordLock()");
}
@Override
public ORecordMetadata getRecordMetadata(final ORID rid) {
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_RECORD_METADATA);
network.writeRID(rid);
} finally {
endRequest(network);
}
try {
beginResponse(network);
final ORID responseRid = network.readRID();
final ORecordVersion responseVersion = network.readVersion();
return new ORecordMetadata(responseRid, responseVersion);
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Error on read record " + rid, e);
}
} while (true);
}
public OStorageOperationResult<ORawBuffer> readRecord(final ORecordId iRid, final String iFetchPlan, final boolean iIgnoreCache,
final ORecordCallback<ORawBuffer> iCallback, boolean loadTombstones) {
checkConnection();
if (OStorageRemoteThreadLocal.INSTANCE.get().commandExecuting)
// PENDING NETWORK OPERATION, CAN'T EXECUTE IT NOW
return new OStorageOperationResult<ORawBuffer>(null);
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_RECORD_LOAD);
network.writeRID(iRid);
network.writeString(iFetchPlan != null ? iFetchPlan : "");
if (network.getSrvProtocolVersion() >= 9)
network.writeByte((byte) (iIgnoreCache ? 1 : 0));
if (network.getSrvProtocolVersion() >= 13)
network.writeByte(loadTombstones ? (byte) 1 : (byte) 0);
} finally {
endRequest(network);
}
try {
beginResponse(network);
if (network.readByte() == 0)
return new OStorageOperationResult<ORawBuffer>(null);
final ORawBuffer buffer = new ORawBuffer(network.readBytes(), network.readVersion(), network.readByte());
final ODatabaseRecord database = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
ORecordInternal<?> record;
while (network.readByte() == 2) {
record = (ORecordInternal<?>) OChannelBinaryProtocol.readIdentifiable(network);
if (database != null)
// PUT IN THE CLIENT LOCAL CACHE
database.getLevel1Cache().updateRecord(record);
}
return new OStorageOperationResult<ORawBuffer>(buffer);
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Error on read record " + iRid, e);
}
} while (true);
}
public OStorageOperationResult<ORecordVersion> updateRecord(final ORecordId iRid, final byte[] iContent,
final ORecordVersion iVersion, final byte iRecordType, int iMode, final ORecordCallback<ORecordVersion> iCallback) {
checkConnection();
if (iMode == 1 && iCallback == null)
// ASYNCHRONOUS MODE NO ANSWER
iMode = 2;
OChannelBinaryAsynchClient lastNetworkUsed = null;
do {
try {
final OChannelBinaryAsynchClient network = beginRequest(OChannelBinaryProtocol.REQUEST_RECORD_UPDATE);
lastNetworkUsed = network;
try {
network.writeRID(iRid);
network.writeBytes(iContent);
network.writeVersion(iVersion);
network.writeByte(iRecordType);
network.writeByte((byte) iMode);
} finally {
endRequest(network);
}
switch (iMode) {
case 0:
// SYNCHRONOUS
try {
beginResponse(network);
return new OStorageOperationResult<ORecordVersion>(network.readVersion());
} finally {
endResponse(network);
}
case 1:
// ASYNCHRONOUS
if (iCallback != null) {
final int sessionId = getSessionId();
Callable<Object> response = new Callable<Object>() {
public Object call() throws Exception {
ORecordVersion result;
try {
OStorageRemoteThreadLocal.INSTANCE.get().sessionId = sessionId;
beginResponse(network);
result = network.readVersion();
} finally {
endResponse(network);
OStorageRemoteThreadLocal.INSTANCE.get().sessionId = -1;
}
iCallback.call(iRid, result);
return null;
}
};
asynchExecutor.submit(new FutureTask<Object>(response));
}
}
return new OStorageOperationResult<ORecordVersion>(iVersion);
} catch (OModificationOperationProhibitedException mope) {
handleDBFreeze();
} catch (Exception e) {
handleException(lastNetworkUsed, "Error on update record " + iRid, e);
}
} while (true);
}
public OStorageOperationResult<Boolean> deleteRecord(final ORecordId iRid, final ORecordVersion iVersion, int iMode,
final ORecordCallback<Boolean> iCallback) {
checkConnection();
if (iMode == 1 && iCallback == null)
// ASYNCHRONOUS MODE NO ANSWER
iMode = 2;
OChannelBinaryAsynchClient network = null;
do {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_RECORD_DELETE);
return new OStorageOperationResult<Boolean>(deleteRecord(iRid, iVersion, iMode, iCallback, network));
} catch (OModificationOperationProhibitedException mope) {
handleDBFreeze();
} catch (Exception e) {
handleException(network, "Error on delete record " + iRid, e);
}
} while (true);
}
@Override
public boolean cleanOutRecord(ORecordId recordId, ORecordVersion recordVersion, int iMode, ORecordCallback<Boolean> callback) {
checkConnection();
if (iMode == 1 && callback == null)
// ASYNCHRONOUS MODE NO ANSWER
iMode = 2;
OChannelBinaryAsynchClient network = null;
do {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_RECORD_CLEAN_OUT);
return deleteRecord(recordId, recordVersion, iMode, callback, network);
} catch (OModificationOperationProhibitedException mope) {
handleDBFreeze();
} catch (Exception e) {
handleException(network, "Error on clean out record " + recordId, e);
}
} while (true);
}
@Override
public void backup(OutputStream out, Map<String, Object> options, Callable<Object> callable) throws IOException {
throw new UnsupportedOperationException("backup");
}
@Override
public void restore(InputStream in, Map<String, Object> options, Callable<Object> callable) throws IOException {
throw new UnsupportedOperationException("restore");
}
public long count(final int iClusterId) {
return count(new int[] { iClusterId });
}
@Override
public long count(int iClusterId, boolean countTombstones) {
return count(new int[] { iClusterId }, countTombstones);
}
public OClusterPosition[] getClusterDataRange(final int iClusterId) {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_DATACLUSTER_DATARANGE);
network.writeShort((short) iClusterId);
} finally {
endRequest(network);
}
try {
beginResponse(network);
return new OClusterPosition[] { network.readClusterPosition(), network.readClusterPosition() };
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Error on getting last entry position count in cluster: " + iClusterId, e);
}
} while (true);
}
@Override
public OPhysicalPosition[] higherPhysicalPositions(int iClusterId, OPhysicalPosition iClusterPosition) {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_POSITIONS_HIGHER);
network.writeInt(iClusterId);
network.writeClusterPosition(iClusterPosition.clusterPosition);
} finally {
endRequest(network);
}
try {
beginResponse(network);
final int positionsCount = network.readInt();
if (positionsCount == 0) {
return new OPhysicalPosition[0];
} else {
return readPhysicalPositions(network, positionsCount);
}
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Error on retrieving higher positions after " + iClusterPosition.clusterPosition, e);
}
} while (true);
}
@Override
public OPhysicalPosition[] ceilingPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_POSITIONS_CEILING);
network.writeInt(clusterId);
network.writeClusterPosition(physicalPosition.clusterPosition);
} finally {
endRequest(network);
}
try {
beginResponse(network);
final int positionsCount = network.readInt();
if (positionsCount == 0) {
return new OPhysicalPosition[0];
} else {
return readPhysicalPositions(network, positionsCount);
}
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Error on retrieving ceiling positions after " + physicalPosition.clusterPosition, e);
}
} while (true);
}
private OPhysicalPosition[] readPhysicalPositions(OChannelBinaryAsynchClient network, int positionsCount) throws IOException {
final OPhysicalPosition[] physicalPositions = new OPhysicalPosition[positionsCount];
for (int i = 0; i < physicalPositions.length; i++) {
final OPhysicalPosition position = new OPhysicalPosition();
position.clusterPosition = network.readClusterPosition();
position.dataSegmentId = network.readInt();
position.dataSegmentPos = network.readLong();
position.recordSize = network.readInt();
position.recordVersion = network.readVersion();
physicalPositions[i] = position;
}
return physicalPositions;
}
@Override
public OPhysicalPosition[] lowerPhysicalPositions(int iClusterId, OPhysicalPosition physicalPosition) {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_POSITIONS_LOWER);
network.writeInt(iClusterId);
network.writeClusterPosition(physicalPosition.clusterPosition);
} finally {
endRequest(network);
}
try {
beginResponse(network);
final int positionsCount = network.readInt();
if (positionsCount == 0) {
return new OPhysicalPosition[0];
} else {
return readPhysicalPositions(network, positionsCount);
}
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Error on retrieving lower positions after " + physicalPosition.clusterPosition, e);
}
} while (true);
}
@Override
public OPhysicalPosition[] floorPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_POSITIONS_FLOOR);
network.writeInt(clusterId);
network.writeClusterPosition(physicalPosition.clusterPosition);
} finally {
endRequest(network);
}
try {
beginResponse(network);
final int positionsCount = network.readInt();
if (positionsCount == 0) {
return new OPhysicalPosition[0];
} else {
return readPhysicalPositions(network, positionsCount);
}
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Error on retrieving floor positions after " + physicalPosition.clusterPosition, e);
}
} while (true);
}
public long getSize() {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_DB_SIZE);
} finally {
endRequest(network);
}
try {
beginResponse(network);
return network.readLong();
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Error on read database size", e);
}
} while (true);
}
@Override
public long countRecords() {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_DB_COUNTRECORDS);
} finally {
endRequest(network);
}
try {
beginResponse(network);
return network.readLong();
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Error on read database record count", e);
}
} while (true);
}
public long count(final int[] iClusterIds) {
return count(iClusterIds, false);
}
public long count(final int[] iClusterIds, boolean countTombstones) {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_DATACLUSTER_COUNT);
network.writeShort((short) iClusterIds.length);
for (int iClusterId : iClusterIds)
network.writeShort((short) iClusterId);
if (network.getSrvProtocolVersion() >= 13)
network.writeByte(countTombstones ? (byte) 1 : (byte) 0);
} finally {
endRequest(network);
}
try {
beginResponse(network);
return network.readLong();
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Error on read record count in clusters: " + Arrays.toString(iClusterIds), e);
}
} while (true);
}
/**
* Execute the command remotely and get the results back.
*/
public Object command(final OCommandRequestText iCommand) {
checkConnection();
if (!(iCommand instanceof OSerializableStream))
throw new OCommandExecutionException("Cannot serialize the command to be executed to the server side.");
OSerializableStream command = iCommand;
Object result = null;
final ODatabaseRecord database = ODatabaseRecordThreadLocal.INSTANCE.get();
OChannelBinaryAsynchClient network = null;
do {
OStorageRemoteThreadLocal.INSTANCE.get().commandExecuting = true;
try {
final OCommandRequestText aquery = iCommand;
final boolean asynch = iCommand instanceof OCommandRequestAsynch && ((OCommandRequestAsynch) iCommand).isAsynchronous();
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_COMMAND);
network.writeByte((byte) (asynch ? 'a' : 's')); // ASYNC / SYNC
network.writeBytes(OStreamSerializerAnyStreamable.INSTANCE.toStream(command));
} finally {
endRequest(network);
}
try {
beginResponse(network);
if (asynch) {
byte status;
// ASYNCH: READ ONE RECORD AT TIME
while ((status = network.readByte()) > 0) {
final ORecordInternal<?> record = (ORecordInternal<?>) OChannelBinaryProtocol.readIdentifiable(network);
if (record == null)
continue;
switch (status) {
case 1:
// PUT AS PART OF THE RESULT SET. INVOKE THE LISTENER
try {
if (!aquery.getResultListener().result(record)) {
// EMPTY THE INPUT CHANNEL
while (network.in.available() > 0)
network.in.read();
break;
}
} catch (Throwable t) {
// ABSORBE ALL THE USER EXCEPTIONS
t.printStackTrace();
}
database.getLevel1Cache().updateRecord(record);
break;
case 2:
// PUT IN THE CLIENT LOCAL CACHE
database.getLevel1Cache().updateRecord(record);
}
}
} else {
final byte type = network.readByte();
switch (type) {
case 'n':
result = null;
break;
case 'r':
result = OChannelBinaryProtocol.readIdentifiable(network);
if (result instanceof ORecord<?>)
database.getLevel1Cache().updateRecord((ORecordInternal<?>) result);
break;
case 'l':
final int tot = network.readInt();
final Collection<OIdentifiable> list = new ArrayList<OIdentifiable>(tot);
for (int i = 0; i < tot; ++i) {
final OIdentifiable resultItem = OChannelBinaryProtocol.readIdentifiable(network);
if (resultItem instanceof ORecord<?>)
database.getLevel1Cache().updateRecord((ORecordInternal<?>) resultItem);
list.add(resultItem);
}
result = list;
break;
case 'a':
final String value = new String(network.readBytes());
result = ORecordSerializerStringAbstract.fieldTypeFromStream(null, ORecordSerializerStringAbstract.getType(value),
value);
break;
default:
OLogManager.instance().warn(this, "Received unexpected result from query: %d", type);
}
if (network.getSrvProtocolVersion() >= 17) {
// LOAD THE FETCHED RECORDS IN CACHE
byte status;
while ((status = network.readByte()) > 0) {
final ORecordInternal<?> record = (ORecordInternal<?>) OChannelBinaryProtocol.readIdentifiable(network);
if (record != null && status == 2)
// PUT IN THE CLIENT LOCAL CACHE
database.getLevel1Cache().updateRecord(record);
}
}
}
break;
} finally {
if (aquery.getResultListener() != null) {
aquery.getResultListener().end();
}
endResponse(network);
}
} catch (OModificationOperationProhibitedException mope) {
handleDBFreeze();
} catch (Exception e) {
handleException(network, "Error on executing command: " + iCommand, e);
} finally {
OStorageRemoteThreadLocal.INSTANCE.get().commandExecuting = false;
}
} while (true);
return result;
}
public void commit(final OTransaction iTx, Runnable callback) {
checkConnection();
final List<ORecordOperation> committedEntries = new ArrayList<ORecordOperation>();
OChannelBinaryAsynchClient network = null;
do {
try {
OStorageRemoteThreadLocal.INSTANCE.get().commandExecuting = true;
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_TX_COMMIT);
network.writeInt(iTx.getId());
network.writeByte((byte) (iTx.isUsingLog() ? 1 : 0));
final List<ORecordOperation> tmpEntries = new ArrayList<ORecordOperation>();
if (iTx.getCurrentRecordEntries().iterator().hasNext()) {
while (iTx.getCurrentRecordEntries().iterator().hasNext()) {
for (ORecordOperation txEntry : iTx.getCurrentRecordEntries())
tmpEntries.add(txEntry);
iTx.clearRecordEntries();
if (tmpEntries.size() > 0) {
for (ORecordOperation txEntry : tmpEntries) {
commitEntry(network, txEntry);
committedEntries.add(txEntry);
}
tmpEntries.clear();
}
}
} else if (committedEntries.size() > 0) {
for (ORecordOperation txEntry : committedEntries)
commitEntry(network, txEntry);
}
// END OF RECORD ENTRIES
network.writeByte((byte) 0);
// SEND INDEX ENTRIES
network.writeBytes(iTx.getIndexChanges().toStream());
} finally {
endRequest(network);
}
try {
beginResponse(network);
final int createdRecords = network.readInt();
ORecordId currentRid;
ORecordId createdRid;
for (int i = 0; i < createdRecords; i++) {
currentRid = network.readRID();
createdRid = network.readRID();
iTx.updateIdentityAfterCommit(currentRid, createdRid);
}
final int updatedRecords = network.readInt();
ORecordId rid;
for (int i = 0; i < updatedRecords; ++i) {
rid = network.readRID();
ORecordOperation rop = iTx.getRecordEntry(rid);
if (rop != null)
rop.getRecord().getRecordVersion().copyFrom(network.readVersion());
}
committedEntries.clear();
} finally {
endResponse(network);
}
// SET ALL THE RECORDS AS UNDIRTY
for (ORecordOperation txEntry : iTx.getAllRecordEntries())
txEntry.getRecord().unload();
// UPDATE THE CACHE ONLY IF THE ITERATOR ALLOWS IT. USE THE STRATEGY TO ALWAYS REMOVE ALL THE RECORDS SINCE THEY COULD BE
// CHANGED AS CONTENT IN CASE OF TREE AND GRAPH DUE TO CROSS REFERENCES
OTransactionAbstract.updateCacheFromEntries(iTx, iTx.getAllRecordEntries(), false);
break;
} catch (OModificationOperationProhibitedException mope) {
handleDBFreeze();
} catch (Exception e) {
handleException(network, "Error on commit", e);
} finally {
OStorageRemoteThreadLocal.INSTANCE.get().commandExecuting = false;
}
} while (true);
}
public void rollback(OTransaction iTx) {
}
public int getClusterIdByName(final String iClusterName) {
checkConnection();
if (iClusterName == null)
return -1;
if (Character.isDigit(iClusterName.charAt(0)))
return Integer.parseInt(iClusterName);
final OCluster cluster = clusterMap.get(iClusterName.toLowerCase());
if (cluster == null)
return -1;
return cluster.getId();
}
public String getClusterTypeByName(final String iClusterName) {
checkConnection();
if (iClusterName == null)
return null;
final OCluster cluster = clusterMap.get(iClusterName.toLowerCase());
if (cluster == null)
return null;
return cluster.getType();
}
public int getDefaultClusterId() {
return defaultClusterId;
}
public int addCluster(final String iClusterType, final String iClusterName, final String iLocation,
final String iDataSegmentName, boolean forceListBased, final Object... iArguments) {
return addCluster(iClusterType, iClusterName, -1, iLocation, iDataSegmentName, forceListBased, iArguments);
}
public int addCluster(String iClusterType, String iClusterName, int iRequestedId, String iLocation, String iDataSegmentName,
boolean forceListBased, Object... iParameters) {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_DATACLUSTER_ADD);
network.writeString(iClusterType.toString());
network.writeString(iClusterName);
if (network.getSrvProtocolVersion() >= 10 || iClusterType.equalsIgnoreCase("PHYSICAL"))
network.writeString(iLocation);
if (network.getSrvProtocolVersion() >= 10)
network.writeString(iDataSegmentName);
else
network.writeInt(-1);
if (network.getSrvProtocolVersion() >= 18)
network.writeShort((short) iRequestedId);
} finally {
endRequest(network);
}
try {
beginResponse(network);
final int clusterId = network.readShort();
final OClusterRemote cluster = new OClusterRemote();
cluster.setType(iClusterType);
cluster.configure(this, clusterId, iClusterName.toLowerCase(), null, 0);
if (clusters.length <= clusterId)
clusters = Arrays.copyOf(clusters, clusterId + 1);
clusters[cluster.getId()] = cluster;
clusterMap.put(cluster.getName().toLowerCase(), cluster);
return clusterId;
} finally {
endResponse(network);
}
} catch (OModificationOperationProhibitedException mphe) {
handleDBFreeze();
} catch (Exception e) {
handleException(network, "Error on add new cluster", e);
}
} while (true);
}
public boolean dropCluster(final int iClusterId, final boolean iTruncate) {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_DATACLUSTER_DROP);
network.writeShort((short) iClusterId);
} finally {
endRequest(network);
}
byte result = 0;
try {
beginResponse(network);
result = network.readByte();
} finally {
endResponse(network);
}
if (result == 1) {
// REMOVE THE CLUSTER LOCALLY
final OCluster cluster = clusters[iClusterId];
clusters[iClusterId] = null;
clusterMap.remove(cluster.getName());
if (configuration.clusters.size() > iClusterId)
configuration.dropCluster(iClusterId); // endResponse must be called before this line, which call updateRecord
getLevel2Cache().freeCluster(iClusterId);
return true;
}
return false;
} catch (OModificationOperationProhibitedException mope) {
handleDBFreeze();
} catch (Exception e) {
handleException(network, "Error on removing of cluster", e);
}
} while (true);
}
public int addDataSegment(final String iDataSegmentName) {
return addDataSegment(iDataSegmentName, null);
}
public int addDataSegment(final String iSegmentName, final String iLocation) {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_DATASEGMENT_ADD);
network.writeString(iSegmentName).writeString(iLocation);
} finally {
endRequest(network);
}
try {
beginResponse(network);
return network.readInt();
} finally {
endResponse(network);
}
} catch (OModificationOperationProhibitedException mphe) {
handleDBFreeze();
} catch (Exception e) {
handleException(network, "Error on add new data segment", e);
}
} while (true);
}
public boolean dropDataSegment(final String iSegmentName) {
checkConnection();
OChannelBinaryAsynchClient network = null;
do {
try {
try {
network = beginRequest(OChannelBinaryProtocol.REQUEST_DATASEGMENT_DROP);
network.writeString(iSegmentName);
} finally {
endRequest(network);
}
try {
beginResponse(network);
return network.readByte() == 1;
} finally {
endResponse(network);
}
} catch (OModificationOperationProhibitedException mope) {
handleDBFreeze();
} catch (Exception e) {
handleException(network, "Error on remove data segment", e);
}
} while (true);
}
public void synch() {
}
public String getPhysicalClusterNameById(final int iClusterId) {
lock.acquireSharedLock();
try {
if (iClusterId >= clusters.length)
return null;
final OCluster cluster = clusters[iClusterId];
return cluster != null ? cluster.getName() : null;
} finally {
lock.releaseSharedLock();
}
}
public int getClusterMap() {
return clusterMap.size();
}
public Collection<OCluster> getClusterInstances() {
lock.acquireSharedLock();
try {
return Arrays.asList(clusters);
} finally {
lock.releaseSharedLock();
}
}
public OCluster getClusterById(int iClusterId) {
lock.acquireSharedLock();
try {
if (iClusterId == ORID.CLUSTER_ID_INVALID)
// GET THE DEFAULT CLUSTER
iClusterId = defaultClusterId;
return clusters[iClusterId];
} finally {
lock.releaseSharedLock();
}
}
@Override
public long getVersion() {
throw new UnsupportedOperationException("getVersion");
}
public ODocument getClusterConfiguration() {
return clusterConfiguration;
}
/**
* Handles exceptions. In case of IO errors retries to reconnect until the configured retry times has reached.
*
* @param message
* @param exception
*/
protected void handleException(final OChannelBinaryAsynchClient iNetwork, final String message, final Exception exception) {
if (exception instanceof OTimeoutException)
// TIMEOUT, AVOID LOOP, RE-THROW IT
throw (OTimeoutException) exception;
else if (exception instanceof OException)
// RE-THROW IT
throw (OException) exception;
else if (!(exception instanceof IOException))
throw new OStorageException(message, exception);
if (status != STATUS.OPEN)
// STORAGE CLOSED: DON'T HANDLE RECONNECTION
return;
OLogManager.instance().warn(this, "Caught I/O errors from %s (local socket=%s), trying to reconnect (error: %s)", iNetwork,
iNetwork.socket.getLocalSocketAddress(), exception);
try {
iNetwork.close();
} catch (Exception e) {
// IGNORE ANY EXCEPTION
}
final long lostConnectionTime = System.currentTimeMillis();
final int currentMaxRetry;
final int currentRetryDelay;
synchronized (clusterConfiguration) {
if (!clusterConfiguration.isEmpty()) {
// IN CLUSTER: NO RETRY AND 0 SLEEP TIME BETWEEN NODES
currentMaxRetry = 1;
currentRetryDelay = 0;
} else {
currentMaxRetry = connectionRetry;
currentRetryDelay = connectionRetryDelay;
}
}
for (int retry = 0; retry < currentMaxRetry; ++retry) {
// WAIT THE DELAY BEFORE TO RETRY
if (currentRetryDelay > 0)
try {
Thread.sleep(currentRetryDelay);
} catch (InterruptedException e) {
// THREAD INTERRUPTED: RETURN EXCEPTION
Thread.currentThread().interrupt();
break;
}
try {
if (OLogManager.instance().isDebugEnabled())
OLogManager.instance()
.debug(this, "Retrying to connect to remote server #" + (retry + 1) + "/" + currentMaxRetry + "...");
// FORCE RESET OF THREAD DATA (SERVER URL + SESSION ID)
setSessionId(null, -1);
if (createConnectionPool() == 0)
// NO CONNECTION!
break;
// REACQUIRE DB SESSION ID
openRemoteDatabase();
OLogManager.instance().warn(this,
"Connection re-acquired transparently after %dms and %d retries: no errors will be thrown at application level",
System.currentTimeMillis() - lostConnectionTime, retry + 1);
// RECONNECTED!
return;
} catch (Throwable t) {
// DO NOTHING BUT CONTINUE IN THE LOOP
}
}
// RECONNECTION FAILED: THROW+LOG THE ORIGINAL EXCEPTION
throw new OStorageException(message, exception);
}
protected OChannelBinaryAsynchClient openRemoteDatabase() throws IOException {
minPool = OGlobalConfiguration.CLIENT_CHANNEL_MIN_POOL.getValueAsInteger();
maxPool = OGlobalConfiguration.CLIENT_CHANNEL_MAX_POOL.getValueAsInteger();
connectionDbType = ODatabaseDocument.TYPE;
if (connectionOptions != null && connectionOptions.size() > 0) {
if (connectionOptions.containsKey(PARAM_MIN_POOL))
minPool = Integer.parseInt(connectionOptions.get(PARAM_MIN_POOL).toString());
if (connectionOptions.containsKey(PARAM_MAX_POOL))
maxPool = Integer.parseInt(connectionOptions.get(PARAM_MAX_POOL).toString());
if (connectionOptions.containsKey(PARAM_DB_TYPE))
connectionDbType = connectionOptions.get(PARAM_DB_TYPE).toString();
}
boolean availableConnections = true;
OChannelBinaryAsynchClient network = null;
while (availableConnections) {
try {
network = getAvailableNetwork();
try {
network.writeByte(OChannelBinaryProtocol.REQUEST_DB_OPEN);
network.writeInt(getSessionId());
// @SINCE 1.0rc8
sendClientInfo(network);
network.writeString(name);
if (network.getSrvProtocolVersion() >= 8)
network.writeString(connectionDbType);
network.writeString(connectionUserName);
network.writeString(connectionUserPassword);
} finally {
endRequest(network);
}
final int sessionId;
try {
beginResponse(network);
sessionId = network.readInt();
setSessionId(network.getServerURL(), sessionId);
OLogManager.instance().debug(this, "Client connected to %s with session id=%d", network.getServerURL(), sessionId);
readDatabaseInformation(network);
// READ CLUSTER CONFIGURATION
updateClusterConfiguration(network.readBytes());
// read OrientDB release info
if (network.getSrvProtocolVersion() >= 14)
network.readString();
status = STATUS.OPEN;
return network;
} finally {
endResponse(network);
}
} catch (Exception e) {
handleException(network, "Cannot create a connection to remote server address(es): " + serverURLs, e);
}
networkPoolLock.lock();
try {
availableConnections = !networkPool.isEmpty();
} finally {
networkPoolLock.unlock();
}
}
throw new OStorageException("Cannot create a connection to remote server address(es): " + serverURLs);
}
protected void sendClientInfo(OChannelBinaryAsynchClient network) throws IOException {
if (network.getSrvProtocolVersion() >= 7) {
// @COMPATIBILITY 1.0rc8
network.writeString(DRIVER_NAME).writeString(OConstants.ORIENT_VERSION)
.writeShort((short) OChannelBinaryProtocol.CURRENT_PROTOCOL_VERSION).writeString(clientId);
}
}
/**
* Parse the URL in the following formats:<br/>
*/
protected void parseServerURLs() {
int dbPos = url.indexOf('/');
if (dbPos == -1) {
// SHORT FORM
addHost(url);
name = url;
} else {
name = url.substring(url.lastIndexOf("/") + 1);
for (String host : url.substring(0, dbPos).split(ADDRESS_SEPARATOR))
addHost(host);
}
if (serverURLs.size() == 1 && OGlobalConfiguration.NETWORK_BINARY_DNS_LOADBALANCING_ENABLED.getValueAsBoolean()) {
// LOOK FOR LOAD BALANCING DNS TXT RECORD
final String primaryServer = serverURLs.get(0);
try {
final Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
env.put("com.sun.jndi.ldap.connect.timeout",
OGlobalConfiguration.NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT.getValueAsString());
final DirContext ictx = new InitialDirContext(env);
final String hostName = primaryServer.indexOf(":") == -1 ? primaryServer : primaryServer.substring(0,
primaryServer.indexOf(":"));
final Attributes attrs = ictx.getAttributes(hostName, new String[] { "TXT" });
final Attribute attr = attrs.get("TXT");
if (attr != null) {
String configuration = (String) attr.get();
if (configuration.startsWith(""))
configuration = configuration.substring(1, configuration.length() - 1);
if (configuration != null) {
final String[] parts = configuration.split(" ");
for (String part : parts) {
if (part.startsWith("s=")) {
addHost(part.substring("s=".length()));
}
}
}
}
} catch (NamingException e) {
}
}
}
/**
* Registers the remote server with port.
*/
protected String addHost(String host) {
if (host.startsWith("localhost"))
host = "127.0.0.1" + host.substring("localhost".length());
// REGISTER THE REMOTE SERVER+PORT
if (host.indexOf(":") == -1)
host += ":" + getDefaultPort();
if (!serverURLs.contains(host))
serverURLs.add(host);
return host;
}
protected String getDefaultHost() {
return DEFAULT_HOST;
}
protected int getDefaultPort() {
return DEFAULT_PORT;
}
protected OChannelBinaryAsynchClient createNetworkConnection() throws IOException, UnknownHostException {
final String currentServerURL = getServerURL();
if (currentServerURL != null) {
// TRY WITH CURRENT URL IF ANY
try {
return connect(currentServerURL);
} catch (Exception e) {
OLogManager.instance().debug(this, "Error on connecting to %s", e, currentServerURL);
}
}
for (int serverIdx = 0; serverIdx < serverURLs.size(); ++serverIdx) {
final String server = serverURLs.get(serverIdx);
try {
final OChannelBinaryAsynchClient ch = connect(server);
if (serverIdx > 0) {
// UPDATE SERVER LIST WITH THE REACHABLE ONE AS HEAD TO SPEED UP FURTHER CONNECTIONS
serverURLs.remove(serverIdx);
serverURLs.add(0, server);
OLogManager.instance().debug(this, "New server list priority: %s...", serverURLs);
}
return ch;
} catch (Exception e) {
OLogManager.instance().debug(this, "Error on connecting to %s", e, server);
}
}
// ERROR, NO URL IS REACHABLE
final StringBuilder buffer = new StringBuilder();
for (String server : serverURLs) {
if (buffer.length() > 0)
buffer.append(',');
buffer.append(server);
}
throw new OIOException("Cannot connect to any configured remote nodes: " + buffer);
}
protected OChannelBinaryAsynchClient connect(final String server) throws IOException {
OLogManager.instance().debug(this, "Trying to connect to the remote host %s...", server);
final int sepPos = server.indexOf(":");
final String remoteHost = server.substring(0, sepPos);
final int remotePort = Integer.parseInt(server.substring(sepPos + 1));
final OChannelBinaryAsynchClient ch = new OChannelBinaryAsynchClient(remoteHost, remotePort, clientConfiguration,
OChannelBinaryProtocol.CURRENT_PROTOCOL_VERSION, asynchEventListener);
// REGISTER MYSELF AS LISTENER TO REMOVE THE CHANNEL FROM THE POOL IN CASE OF CLOSING
ch.registerListener(this);
// REGISTER IT IN THE POOL
networkPool.add(ch);
return ch;
}
protected void checkConnection() {
// lock.acquireSharedLock();
//
// try {
// synchronized (networkPool) {
//
// if (networkPool.size() == 0)
// throw new ODatabaseException("Connection is closed");
// }
//
// } finally {
// lock.releaseSharedLock();
// }
}
/**
* Acquire a network channel from the pool. Don't lock the write stream since the connection usage is exclusive.
*
* @param iCommand
* @return
* @throws IOException
*/
protected OChannelBinaryAsynchClient beginRequest(final byte iCommand) throws IOException {
final OChannelBinaryAsynchClient network = getAvailableNetwork();
network.writeByte(iCommand);
network.writeInt(getSessionId());
return network;
}
protected OChannelBinaryAsynchClient getAvailableNetwork() throws IOException, UnknownHostException {
// FIND THE FIRST FREE CHANNEL AVAILABLE
OChannelBinaryAsynchClient network = null;
int beginCursor = networkPoolCursor;
while (network == null) {
networkPoolLock.lock();
try {
if (networkPoolCursor < 0)
networkPoolCursor = 0;
else if (networkPoolCursor >= networkPool.size())
// RESTART FROM THE BEGINNING
networkPoolCursor = 0;
if (networkPool.size() == 0) {
createConnectionPool();
networkPoolCursor = 0;
}
if (networkPool.size() == 0)
throw new ONetworkProtocolException("Connection pool closed");
network = networkPool.get(networkPoolCursor);
networkPoolCursor++;
final String serverURL = getServerURL();
if (serverURL == null || network.getServerURL().equals(serverURL)) {
if (network.getLockWrite().tryAcquireLock())
// WAS UNLOCKED! USE THIS
break;
}
network = null;
if (beginCursor >= networkPool.size())
// THE POOL HAS BEEN REDUCED: RSTART FROM CURRENT POSITION
beginCursor = networkPoolCursor;
if (networkPoolCursor == beginCursor) {
// COMPLETE ROUND AND NOT FREE CONNECTIONS FOUND
if (networkPool.size() < maxPool) {
// CREATE NEW CONNECTION
network = createNetworkConnection();
network.getLockWrite().lock();
} else {
OLogManager.instance().info(this,
"Network connection pool is full (max=%d): increase max size to avoid such bottleneck on connections", maxPool);
removeDeadConnections();
final long startToWait = System.currentTimeMillis();
// TEMPORARY UNLOCK
networkPoolLock.unlock();
try {
synchronized (networkPool) {
networkPool.wait(5000);
}
} catch (InterruptedException e) {
// THREAD INTERRUPTED: RETURN EXCEPTION
Thread.currentThread().interrupt();
throw new OStorageException("Cannot acquire a connection because the thread has been interrupted");
} finally {
networkPoolLock.lock();
}
Orient
.instance()
.getProfiler()
.stopChrono("system.network.connectionPool.waitingTime", "Waiting for a free connection from the pool of channels",
startToWait);
}
}
} finally {
networkPoolLock.unlock();
}
}
return network;
}
private void removeDeadConnections() {
// FREE DEAD CONNECTIONS
int removedDeadConnections = 0;
for (OChannelBinaryAsynchClient n : new ArrayList<OChannelBinaryAsynchClient>(networkPool)) {
if (n != null && !n.isConnected()) //Fixed issue with removing of network connections though connection is active.
{
try {
n.close();
} catch (Exception e) {
}
networkPool.remove(n);
removedDeadConnections++;
}
}
OLogManager.instance().debug(this, "Found and removed %d dead connections from the network pool", removedDeadConnections);
}
/**
* Ends the request and unlock the write lock
*/
public void endRequest(final OChannelBinaryAsynchClient iNetwork) throws IOException {
if (iNetwork == null)
return;
try {
iNetwork.flush();
} catch (IOException e) {
try {
iNetwork.close();
} catch (Exception e2) {
} finally {
networkPoolLock.lock();
try {
networkPool.remove(iNetwork);
} finally {
networkPoolLock.unlock();
}
}
throw e;
} finally {
iNetwork.releaseWriteLock();
networkPoolLock.lock();
try {
synchronized (networkPool) {
networkPool.notifyAll();
}
} finally {
networkPoolLock.unlock();
}
}
}
/**
* Starts listening the response.
*/
protected void beginResponse(final OChannelBinaryAsynchClient iNetwork) throws IOException {
iNetwork.beginResponse(getSessionId());
}
/**
* End response reached: release the channel in the pool to being reused
*/
public void endResponse(final OChannelBinaryAsynchClient iNetwork) {
iNetwork.endResponse();
}
public boolean isPermanentRequester() {
return false;
}
protected void getResponse(final OChannelBinaryAsynchClient iNetwork) throws IOException {
try {
beginResponse(iNetwork);
} finally {
endResponse(iNetwork);
}
}
@SuppressWarnings("unchecked")
public void updateClusterConfiguration(final byte[] obj) {
if (obj == null)
return;
// UPDATE IT
synchronized (clusterConfiguration) {
clusterConfiguration.fromStream(obj);
final List<ODocument> members = clusterConfiguration.field("members");
if (members != null) {
serverURLs.clear();
parseServerURLs();
for (ODocument m : members)
if (m != null && !serverURLs.contains((String) m.field("name"))) {
for (Map<String, Object> listener : ((Collection<Map<String, Object>>) m.field("listeners"))) {
if (((String) listener.get("protocol")).equals("ONetworkProtocolBinary")) {
String url = (String) listener.get("listen");
if (!serverURLs.contains(url))
addHost(url);
}
}
}
}
}
}
private void commitEntry(final OChannelBinaryAsynchClient iNetwork, final ORecordOperation txEntry) throws IOException {
if (txEntry.type == ORecordOperation.LOADED)
// JUMP LOADED OBJECTS
return;
// SERIALIZE THE RECORD IF NEEDED. THIS IS DONE HERE TO CATCH EXCEPTION AND SEND A -1 AS ERROR TO THE SERVER TO SIGNAL THE ABORT
// OF TX COMMIT
byte[] stream = null;
try {
switch (txEntry.type) {
case ORecordOperation.CREATED:
case ORecordOperation.UPDATED:
stream = txEntry.getRecord().toStream();
break;
}
} catch (Exception e) {
// ABORT TX COMMIT
iNetwork.writeByte((byte) -1);
throw new OTransactionException("Error on transaction commit", e);
}
iNetwork.writeByte((byte) 1);
iNetwork.writeByte(txEntry.type);
iNetwork.writeRID(txEntry.getRecord().getIdentity());
iNetwork.writeByte(txEntry.getRecord().getRecordType());
switch (txEntry.type) {
case ORecordOperation.CREATED:
iNetwork.writeBytes(stream);
break;
case ORecordOperation.UPDATED:
iNetwork.writeVersion(txEntry.getRecord().getRecordVersion());
iNetwork.writeBytes(stream);
break;
case ORecordOperation.DELETED:
iNetwork.writeVersion(txEntry.getRecord().getRecordVersion());
break;
}
}
protected int createConnectionPool() throws IOException, UnknownHostException {
networkPoolLock.lock();
try {
if (networkPool.isEmpty())
// ALWAYS CREATE THE FIRST CONNECTION
createNetworkConnection();
// CREATE THE MINIMUM POOL
for (int i = networkPool.size(); i < minPool; ++i)
createNetworkConnection();
return networkPool.size();
} finally {
networkPoolLock.unlock();
}
}
private boolean handleDBFreeze() {
boolean retry;
OLogManager.instance().warn(this,
"DB is frozen will wait for " + OGlobalConfiguration.CLIENT_DB_RELEASE_WAIT_TIMEOUT.getValue() + " ms. and then retry.");
retry = true;
try {
Thread.sleep(OGlobalConfiguration.CLIENT_DB_RELEASE_WAIT_TIMEOUT.getValueAsInteger());
} catch (InterruptedException ie) {
retry = false;
Thread.currentThread().interrupt();
}
return retry;
}
private void readDatabaseInformation(final OChannelBinaryAsynchClient network) throws IOException {
// @COMPATIBILITY 1.0rc8
final int tot = network.getSrvProtocolVersion() >= 7 ? network.readShort() : network.readInt();
clusters = new OCluster[tot];
clusterMap.clear();
for (int i = 0; i < tot; ++i) {
final OClusterRemote cluster = new OClusterRemote();
String clusterName = network.readString();
if (clusterName != null)
clusterName = clusterName.toLowerCase();
final int clusterId = network.readShort();
final String clusterType = network.readString();
final int dataSegmentId = network.getSrvProtocolVersion() >= 12 ? (int) network.readShort() : 0;
cluster.setType(clusterType);
cluster.configure(this, clusterId, clusterName, null, dataSegmentId);
if (clusterId >= clusters.length)
clusters = Arrays.copyOf(clusters, clusterId + 1);
clusters[clusterId] = cluster;
clusterMap.put(clusterName, cluster);
}
defaultClusterId = clusterMap.get(CLUSTER_DEFAULT_NAME).getId();
}
@Override
public String getURL() {
return OEngineRemote.NAME + ":" + url;
}
public String getClientId() {
return clientId;
}
public int getDataSegmentIdByName(final String iName) {
if (iName == null)
return 0;
throw new UnsupportedOperationException("getDataSegmentIdByName()");
}
public ODataSegment getDataSegmentById(final int iDataSegmentId) {
throw new UnsupportedOperationException("getDataSegmentById()");
}
public int getClusters() {
return clusterMap.size();
}
public void setDefaultClusterId(int defaultClusterId) {
this.defaultClusterId = defaultClusterId;
}
@Override
public String getType() {
return OEngineRemote.NAME;
}
@Override
public void onChannelClose(final OChannel iChannel) {
networkPoolLock.lock();
try {
networkPool.remove(iChannel);
} finally {
networkPoolLock.unlock();
}
}
private boolean deleteRecord(final ORecordId iRid, ORecordVersion iVersion, int iMode, final ORecordCallback<Boolean> iCallback,
final OChannelBinaryAsynchClient network) throws IOException {
try {
network.writeRID(iRid);
network.writeVersion(iVersion);
network.writeByte((byte) iMode);
} finally {
endRequest(network);
}
switch (iMode) {
case 0:
// SYNCHRONOUS
try {
beginResponse(network);
return network.readByte() == 1;
} finally {
endResponse(network);
}
case 1:
// ASYNCHRONOUS
if (iCallback != null) {
final int sessionId = getSessionId();
Callable<Object> response = new Callable<Object>() {
public Object call() throws Exception {
Boolean result;
try {
OStorageRemoteThreadLocal.INSTANCE.get().sessionId = sessionId;
beginResponse(network);
result = network.readByte() == 1;
} finally {
endResponse(network);
OStorageRemoteThreadLocal.INSTANCE.get().sessionId = -1;
}
iCallback.call(iRid, result);
return null;
}
};
asynchExecutor.submit(new FutureTask<Object>(response));
}
}
return false;
}
}
| 1no label
|
client_src_main_java_com_orientechnologies_orient_client_remote_OStorageRemote.java
|
940 |
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response response) {
try {
channel.sendResponse(response);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response", e1);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_support_broadcast_TransportBroadcastOperationAction.java
|
185 |
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
public sun.misc.Unsafe run() throws Exception {
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
for (java.lang.reflect.Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x))
return k.cast(x);
}
throw new NoSuchFieldError("the Unsafe");
}});
| 0true
|
src_main_java_jsr166y_Phaser.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.