Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
127 | public interface PropertyKeyMaker extends RelationTypeMaker {
/**
* Configures the {@link com.thinkaurelius.titan.core.Cardinality} of this property key.
*
* @param cardinality
* @return this PropertyKeyMaker
*/
public PropertyKeyMaker cardinality(Cardinality cardinality);
/**
* Configures the data type for this property key.
* <p/>
* Property instances for this key will only accept values that are instances of this class.
* Every property key must have its data type configured. Setting the data type to Object.class allows
* any type of value but comes at the expense of longer serialization because class information
* is stored with the value.
* <p/>
* It is strongly advised to pick an appropriate data type class so Titan can enforce it throughout the database.
*
* @param clazz Data type to be configured.
* @return this PropertyKeyMaker
* @see com.thinkaurelius.titan.core.PropertyKey#getDataType()
*/
public PropertyKeyMaker dataType(Class<?> clazz);
@Override
public PropertyKeyMaker signature(RelationType... types);
/**
* Defines the {@link com.thinkaurelius.titan.core.PropertyKey} specified by this PropertyKeyMaker and returns the resulting key.
*
* @return the created {@link PropertyKey}
*/
@Override
public PropertyKey make();
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_schema_PropertyKeyMaker.java |
2,841 | private static class DefaultNodeGroup implements NodeGroup {
final PartitionTable groupPartitionTable = new PartitionTable();
final Map<Address, PartitionTable> nodePartitionTables = new HashMap<Address, PartitionTable>();
final Set<Address> nodes = nodePartitionTables.keySet();
final Collection<PartitionTable> nodeTables = nodePartitionTables.values();
final LinkedList<Integer> partitionQ = new LinkedList<Integer>();
@Override
public void addNode(Address address) {
nodePartitionTables.put(address, new PartitionTable());
}
@Override
public boolean hasNode(Address address) {
return nodes.contains(address);
}
@Override
public Set<Address> getNodes() {
return nodes;
}
@Override
public PartitionTable getPartitionTable(Address address) {
return nodePartitionTables.get(address);
}
@Override
public void resetPartitions() {
groupPartitionTable.reset();
partitionQ.clear();
for (PartitionTable table : nodeTables) {
table.reset();
}
}
@Override
public int getPartitionCount(int index) {
return groupPartitionTable.size(index);
}
@Override
public boolean containsPartition(Integer partitionId) {
return groupPartitionTable.contains(partitionId);
}
@Override
public boolean ownPartition(Address address, int index, Integer partitionId) {
if (!hasNode(address)) {
String error = "Address does not belong to this group: " + address.toString();
logger.warning(error);
return false;
}
if (containsPartition(partitionId)) {
if (logger.isFinestEnabled()) {
String error = "Partition[" + partitionId + "] is already owned by this group! " +
"Duplicate!";
logger.finest(error);
}
return false;
}
groupPartitionTable.add(index, partitionId);
return nodePartitionTables.get(address).add(index, partitionId);
}
@Override
public boolean addPartition(int replicaIndex, Integer partitionId) {
if (containsPartition(partitionId)) {
return false;
}
if (groupPartitionTable.add(replicaIndex, partitionId)) {
partitionQ.add(partitionId);
return true;
}
return false;
}
@Override
public Iterator<Integer> getPartitionsIterator(final int index) {
final Iterator<Integer> iter = groupPartitionTable.getPartitions(index).iterator();
return new Iterator<Integer>() {
Integer current = null;
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public Integer next() {
return (current = iter.next());
}
@Override
public void remove() {
iter.remove();
doRemovePartition(index, current);
}
};
}
@Override
public boolean removePartition(int index, Integer partitionId) {
if (groupPartitionTable.remove(index, partitionId)) {
doRemovePartition(index, partitionId);
return true;
}
return false;
}
private void doRemovePartition(int index, Integer partitionId) {
for (PartitionTable table : nodeTables) {
if (table.remove(index, partitionId)) {
break;
}
}
}
@Override
public void postProcessPartitionTable(int index) {
if (nodes.size() == 1) {
PartitionTable table = nodeTables.iterator().next();
while (!partitionQ.isEmpty()) {
table.add(index, partitionQ.poll());
}
} else {
int totalCount = getPartitionCount(index);
int avgCount = totalCount / nodes.size();
List<PartitionTable> underLoadedStates = new LinkedList<PartitionTable>();
for (PartitionTable table : nodeTables) {
Set<Integer> partitions = table.getPartitions(index);
if (partitions.size() > avgCount) {
Iterator<Integer> iter = partitions.iterator();
while (partitions.size() > avgCount) {
Integer partitionId = iter.next();
iter.remove();
partitionQ.add(partitionId);
}
} else {
underLoadedStates.add(table);
}
}
if (!partitionQ.isEmpty()) {
for (PartitionTable table : underLoadedStates) {
while (table.size(index) < avgCount) {
table.add(index, partitionQ.poll());
}
}
}
while (!partitionQ.isEmpty()) {
for (PartitionTable table : nodeTables) {
table.add(index, partitionQ.poll());
if (partitionQ.isEmpty()) {
break;
}
}
}
}
}
@Override
public String toString() {
return "DefaultNodeGroupRegistry [nodes=" + nodes + "]";
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_partition_impl_PartitionStateGeneratorImpl.java |
5,393 | public class InternalValueCount extends MetricsAggregation implements ValueCount {
public static final Type TYPE = new Type("value_count", "vcount");
private static final AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public InternalValueCount readResult(StreamInput in) throws IOException {
InternalValueCount count = new InternalValueCount();
count.readFrom(in);
return count;
}
};
public static void registerStreams() {
AggregationStreams.registerStream(STREAM, TYPE.stream());
}
private long value;
InternalValueCount() {} // for serialization
public InternalValueCount(String name, long value) {
super(name);
this.value = value;
}
@Override
public long getValue() {
return value;
}
@Override
public Type type() {
return TYPE;
}
@Override
public InternalAggregation reduce(ReduceContext reduceContext) {
List<InternalAggregation> aggregations = reduceContext.aggregations();
if (aggregations.size() == 1) {
return aggregations.get(0);
}
InternalValueCount reduced = null;
for (InternalAggregation aggregation : aggregations) {
if (reduced == null) {
reduced = (InternalValueCount) aggregation;
} else {
reduced.value += ((InternalValueCount) aggregation).value;
}
}
return reduced;
}
@Override
public void readFrom(StreamInput in) throws IOException {
name = in.readString();
value = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
out.writeVLong(value);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.startObject(name)
.field(CommonFields.VALUE, value)
.endObject();
}
@Override
public String toString() {
return "count[" + value + "]";
}
} | 1no label
| src_main_java_org_elasticsearch_search_aggregations_metrics_valuecount_InternalValueCount.java |
159 | public abstract class MultiTargetClientRequest extends ClientRequest {
public static final int TRY_COUNT = 100;
@Override
final void process() throws Exception {
ClientEndpoint endpoint = getEndpoint();
OperationFactory operationFactory = createOperationFactory();
Collection<Address> targets = getTargets();
if (targets.isEmpty()) {
endpoint.sendResponse(reduce(new HashMap<Address, Object>()), getCallId());
return;
}
MultiTargetCallback callback = new MultiTargetCallback(targets);
for (Address target : targets) {
Operation op = operationFactory.createOperation();
op.setCallerUuid(endpoint.getUuid());
InvocationBuilder builder = clientEngine.createInvocationBuilder(getServiceName(), op, target)
.setTryCount(TRY_COUNT)
.setResultDeserialized(false)
.setCallback(new SingleTargetCallback(target, callback));
builder.invoke();
}
}
protected abstract OperationFactory createOperationFactory();
protected abstract Object reduce(Map<Address, Object> map);
public abstract Collection<Address> getTargets();
private final class MultiTargetCallback {
final Collection<Address> targets;
final ConcurrentMap<Address, Object> results;
private MultiTargetCallback(Collection<Address> targets) {
this.targets = synchronizedSet(new HashSet<Address>(targets));
this.results = new ConcurrentHashMap<Address, Object>(targets.size());
}
public void notify(Address target, Object result) {
if (targets.remove(target)) {
results.put(target, result);
} else {
if (results.containsKey(target)) {
throw new IllegalArgumentException("Duplicate response from -> " + target);
}
throw new IllegalArgumentException("Unknown target! -> " + target);
}
if (targets.isEmpty()) {
Object response = reduce(results);
endpoint.sendResponse(response, getCallId());
}
}
}
private static final class SingleTargetCallback implements Callback<Object> {
final Address target;
final MultiTargetCallback parent;
private SingleTargetCallback(Address target, MultiTargetCallback parent) {
this.target = target;
this.parent = parent;
}
@Override
public void notify(Object object) {
parent.notify(target, object);
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_client_MultiTargetClientRequest.java |
138 | public static class Presentation {
public static class Tab {
public static class Name {
public static final String Rules = "StructuredContentImpl_Rules_Tab";
}
public static class Order {
public static final int Rules = 1000;
}
}
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 |
193 | public class TruncateTokenFilter extends TokenFilter {
private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);
private final int size;
public TruncateTokenFilter(TokenStream in, int size) {
super(in);
this.size = size;
}
@Override
public final boolean incrementToken() throws IOException {
if (input.incrementToken()) {
final int length = termAttribute.length();
if (length > size) {
termAttribute.setLength(size);
}
return true;
} else {
return false;
}
}
} | 0true
| src_main_java_org_apache_lucene_analysis_miscellaneous_TruncateTokenFilter.java |
514 | public class KillMemberThread extends TestThread {
@Override
public void doRun() throws Exception {
while (!stopTest) {
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(KILL_DELAY_SECONDS));
} catch (InterruptedException e) {
}
int index = random.nextInt(CLUSTER_SIZE);
HazelcastInstance instance = instances.remove(index);
instance.shutdown();
HazelcastInstance newInstance = newHazelcastInstance(createClusterConfig());
instances.add(newInstance);
}
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_stress_StressTestSupport.java |
1,969 | @Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_COUNTRY")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@AdminPresentationClass(friendlyName = "CountryImpl_baseCountry")
public class CountryImpl implements Country {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ABBREVIATION")
protected String abbreviation;
@Column(name = "NAME", nullable=false)
@AdminPresentation(friendlyName = "CountryImpl_Country", order=12, group = "CountryImpl_Address", prominent = true)
protected String name;
public String getAbbreviation() {
return abbreviation;
}
public void setAbbreviation(String Abbreviation) {
this.abbreviation = Abbreviation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CountryImpl other = (CountryImpl) obj;
if (abbreviation == null) {
if (other.abbreviation != null)
return false;
} else if (!abbreviation.equals(other.abbreviation))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((abbreviation == null) ? 0 : abbreviation.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
} | 1no label
| core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_domain_CountryImpl.java |
505 | public interface SiteConfigProvider {
public void configSite(Site site);
public void init(Map<String, Object> map);
} | 0true
| common_src_main_java_org_broadleafcommerce_common_site_service_provider_SiteConfigProvider.java |
686 | clusterService.submitStateUpdateTask("put_warmer [" + request.name() + "]", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return true;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
listener.onResponse(new PutWarmerResponse(true));
}
@Override
public void onAckTimeout() {
listener.onResponse(new PutWarmerResponse(false));
}
@Override
public TimeValue ackTimeout() {
return request.timeout();
}
@Override
public TimeValue timeout() {
return request.masterNodeTimeout();
}
@Override
public void onFailure(String source, Throwable t) {
logger.debug("failed to put warmer [{}] on indices [{}]", t, request.name(), request.searchRequest().indices());
listener.onFailure(t);
}
@Override
public ClusterState execute(ClusterState currentState) {
MetaData metaData = currentState.metaData();
String[] concreteIndices = metaData.concreteIndices(request.searchRequest().indices(), request.searchRequest().indicesOptions());
BytesReference source = null;
if (request.searchRequest().source() != null && request.searchRequest().source().length() > 0) {
source = request.searchRequest().source();
} else if (request.searchRequest().extraSource() != null && request.searchRequest().extraSource().length() > 0) {
source = request.searchRequest().extraSource();
}
// now replace it on the metadata
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
for (String index : concreteIndices) {
IndexMetaData indexMetaData = metaData.index(index);
if (indexMetaData == null) {
throw new IndexMissingException(new Index(index));
}
IndexWarmersMetaData warmers = indexMetaData.custom(IndexWarmersMetaData.TYPE);
if (warmers == null) {
logger.info("[{}] putting warmer [{}]", index, request.name());
warmers = new IndexWarmersMetaData(new IndexWarmersMetaData.Entry(request.name(), request.searchRequest().types(), source));
} else {
boolean found = false;
List<IndexWarmersMetaData.Entry> entries = new ArrayList<IndexWarmersMetaData.Entry>(warmers.entries().size() + 1);
for (IndexWarmersMetaData.Entry entry : warmers.entries()) {
if (entry.name().equals(request.name())) {
found = true;
entries.add(new IndexWarmersMetaData.Entry(request.name(), request.searchRequest().types(), source));
} else {
entries.add(entry);
}
}
if (!found) {
logger.info("[{}] put warmer [{}]", index, request.name());
entries.add(new IndexWarmersMetaData.Entry(request.name(), request.searchRequest().types(), source));
} else {
logger.info("[{}] update warmer [{}]", index, request.name());
}
warmers = new IndexWarmersMetaData(entries.toArray(new IndexWarmersMetaData.Entry[entries.size()]));
}
IndexMetaData.Builder indexBuilder = IndexMetaData.builder(indexMetaData).putCustom(IndexWarmersMetaData.TYPE, warmers);
mdBuilder.put(indexBuilder);
}
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
}); | 0true
| src_main_java_org_elasticsearch_action_admin_indices_warmer_put_TransportPutWarmerAction.java |
850 | private class TransportHandler extends BaseTransportRequestHandler<SearchRequest> {
@Override
public SearchRequest newInstance() {
return new SearchRequest();
}
@Override
public void messageReceived(SearchRequest request, final TransportChannel channel) throws Exception {
// no need for a threaded listener
request.listenerThreaded(false);
// we don't spawn, so if we get a request with no threading, change it to single threaded
if (request.operationThreading() == SearchOperationThreading.NO_THREADS) {
request.operationThreading(SearchOperationThreading.SINGLE_THREAD);
}
execute(request, new ActionListener<SearchResponse>() {
@Override
public void onResponse(SearchResponse result) {
try {
channel.sendResponse(result);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response for search", e1);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
} | 0true
| src_main_java_org_elasticsearch_action_search_TransportSearchAction.java |
116 | public class ClientOutOfMemoryHandler extends OutOfMemoryHandler {
@Override
public void onOutOfMemory(OutOfMemoryError oom, HazelcastInstance[] hazelcastInstances) {
System.err.println(oom);
for (HazelcastInstance instance : hazelcastInstances) {
if (instance instanceof HazelcastClient) {
ClientHelper.cleanResources((HazelcastClient) instance);
}
}
}
public static final class ClientHelper {
private ClientHelper() {
}
public static void cleanResources(HazelcastClient client) {
closeSockets(client);
tryStopThreads(client);
tryShutdown(client);
}
private static void closeSockets(HazelcastClient client) {
final ClientConnectionManager connectionManager = client.getConnectionManager();
if (connectionManager != null) {
try {
connectionManager.shutdown();
} catch (Throwable ignored) {
}
}
}
private static void tryShutdown(HazelcastClient client) {
if (client == null) {
return;
}
try {
client.doShutdown();
} catch (Throwable ignored) {
}
}
public static void tryStopThreads(HazelcastClient client) {
if (client == null) {
return;
}
try {
client.getThreadGroup().interrupt();
} catch (Throwable ignored) {
}
}
}
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_ClientOutOfMemoryHandler.java |
1,151 | public class OSQLMethodPrefix extends OAbstractSQLMethod {
public static final String NAME = "prefix";
public OSQLMethodPrefix() {
super(NAME, 1);
}
@Override
public Object execute(OIdentifiable iRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) {
final Object v = getParameterValue(iRecord, iMethodParams[0].toString());
if (v != null) {
ioResult = ioResult != null ? v + ioResult.toString() : null;
}
return ioResult;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodPrefix.java |
877 | threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
executeFetch(entry.index, queryResult.shardTarget(), counter, fetchSearchRequest, node);
}
}); | 0true
| src_main_java_org_elasticsearch_action_search_type_TransportSearchQueryThenFetchAction.java |
531 | @Deprecated
public class GatewaySnapshotAction extends IndicesAction<GatewaySnapshotRequest, GatewaySnapshotResponse, GatewaySnapshotRequestBuilder> {
public static final GatewaySnapshotAction INSTANCE = new GatewaySnapshotAction();
public static final String NAME = "indices/gateway/snapshot";
private GatewaySnapshotAction() {
super(NAME);
}
@Override
public GatewaySnapshotResponse newResponse() {
return new GatewaySnapshotResponse();
}
@Override
public GatewaySnapshotRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new GatewaySnapshotRequestBuilder(client);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_gateway_snapshot_GatewaySnapshotAction.java |
929 | public enum BroadcastOperationThreading {
/**
* No threads are used, all the local shards operations will be performed on the calling
* thread.
*/
NO_THREADS((byte) 0),
/**
* The local shards operations will be performed in serial manner on a single forked thread.
*/
SINGLE_THREAD((byte) 1),
/**
* Each local shard operation will execute on its own thread.
*/
THREAD_PER_SHARD((byte) 2);
private final byte id;
BroadcastOperationThreading(byte id) {
this.id = id;
}
public byte id() {
return this.id;
}
public static BroadcastOperationThreading fromId(byte id) {
if (id == 0) {
return NO_THREADS;
}
if (id == 1) {
return SINGLE_THREAD;
}
if (id == 2) {
return THREAD_PER_SHARD;
}
throw new ElasticsearchIllegalArgumentException("No type matching id [" + id + "]");
}
public static BroadcastOperationThreading fromString(String value, BroadcastOperationThreading defaultValue) {
if (value == null) {
return defaultValue;
}
return BroadcastOperationThreading.valueOf(value.toUpperCase(Locale.ROOT));
}
} | 0true
| src_main_java_org_elasticsearch_action_support_broadcast_BroadcastOperationThreading.java |
754 | phasedUnit.getCompilationUnit().visit(new Visitor() {
@Override
public void visit(ImportMemberOrType that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclarationModel());
}
@Override
public void visit(BaseMemberOrTypeExpression that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclaration());
}
@Override
public void visit(BaseType that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclarationModel());
}
@Override
public void visit(ModuleDescriptor that) {
super.visit(that);
visitIt(that.getImportPath());
}
@Override
public void visit(PackageDescriptor that) {
super.visit(that);
visitIt(that.getImportPath());
}
private void visitIt(Tree.ImportPath importPath) {
if (formatPath(importPath.getIdentifiers()).equals(oldName)) {
edits.add(new ReplaceEdit(importPath.getStartIndex(),
oldName.length(), newName));
}
}
private void visitIt(Tree.Identifier id, Declaration dec) {
if (dec!=null && !declarations.contains(dec)) {
String pn = dec.getUnit().getPackage().getNameAsString();
if (pn.equals(oldName) && !pn.isEmpty() &&
!pn.equals(Module.LANGUAGE_MODULE_NAME)) {
imports.put(dec, id.getText());
}
}
}
}); | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_refactor_CopyFileRefactoringParticipant.java |
1,161 | public class OSQLMethodToLowerCase extends OAbstractSQLMethod {
public static final String NAME = "tolowercase";
public OSQLMethodToLowerCase() {
super(NAME);
}
@Override
public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) {
ioResult = ioResult != null ? ioResult.toString().toLowerCase() : null;
return ioResult;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodToLowerCase.java |
672 | public class TransportDeleteWarmerAction extends TransportMasterNodeOperationAction<DeleteWarmerRequest, DeleteWarmerResponse> {
@Inject
public TransportDeleteWarmerAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool) {
super(settings, transportService, clusterService, threadPool);
}
@Override
protected String executor() {
// we go async right away
return ThreadPool.Names.SAME;
}
@Override
protected String transportAction() {
return DeleteWarmerAction.NAME;
}
@Override
protected DeleteWarmerRequest newRequest() {
return new DeleteWarmerRequest();
}
@Override
protected DeleteWarmerResponse newResponse() {
return new DeleteWarmerResponse();
}
@Override
protected void doExecute(DeleteWarmerRequest request, ActionListener<DeleteWarmerResponse> listener) {
// update to concrete indices
request.indices(clusterService.state().metaData().concreteIndices(request.indices(), request.indicesOptions()));
super.doExecute(request, listener);
}
@Override
protected ClusterBlockException checkBlock(DeleteWarmerRequest request, ClusterState state) {
return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA, request.indices());
}
@Override
protected void masterOperation(final DeleteWarmerRequest request, final ClusterState state, final ActionListener<DeleteWarmerResponse> listener) throws ElasticsearchException {
clusterService.submitStateUpdateTask("delete_warmer [" + Arrays.toString(request.names()) + "]", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return true;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
listener.onResponse(new DeleteWarmerResponse(true));
}
@Override
public void onAckTimeout() {
listener.onResponse(new DeleteWarmerResponse(false));
}
@Override
public TimeValue ackTimeout() {
return request.timeout();
}
@Override
public TimeValue timeout() {
return request.masterNodeTimeout();
}
@Override
public void onFailure(String source, Throwable t) {
logger.debug("failed to delete warmer [{}] on indices [{}]", t, Arrays.toString(request.names()), request.indices());
listener.onFailure(t);
}
@Override
public ClusterState execute(ClusterState currentState) {
MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
boolean globalFoundAtLeastOne = false;
for (String index : request.indices()) {
IndexMetaData indexMetaData = currentState.metaData().index(index);
if (indexMetaData == null) {
throw new IndexMissingException(new Index(index));
}
IndexWarmersMetaData warmers = indexMetaData.custom(IndexWarmersMetaData.TYPE);
if (warmers != null) {
List<IndexWarmersMetaData.Entry> entries = Lists.newArrayList();
for (IndexWarmersMetaData.Entry entry : warmers.entries()) {
boolean keepWarmer = true;
for (String warmer : request.names()) {
if (Regex.simpleMatch(warmer, entry.name()) || warmer.equals("_all")) {
globalFoundAtLeastOne = true;
keepWarmer = false;
// don't add it...
break;
}
}
if (keepWarmer) {
entries.add(entry);
}
}
// a change, update it...
if (entries.size() != warmers.entries().size()) {
warmers = new IndexWarmersMetaData(entries.toArray(new IndexWarmersMetaData.Entry[entries.size()]));
IndexMetaData.Builder indexBuilder = IndexMetaData.builder(indexMetaData).putCustom(IndexWarmersMetaData.TYPE, warmers);
mdBuilder.put(indexBuilder);
}
}
}
if (!globalFoundAtLeastOne) {
throw new IndexWarmerMissingException(request.names());
}
if (logger.isInfoEnabled()) {
for (String index : request.indices()) {
IndexMetaData indexMetaData = currentState.metaData().index(index);
if (indexMetaData == null) {
throw new IndexMissingException(new Index(index));
}
IndexWarmersMetaData warmers = indexMetaData.custom(IndexWarmersMetaData.TYPE);
if (warmers != null) {
for (IndexWarmersMetaData.Entry entry : warmers.entries()) {
for (String warmer : request.names()) {
if (Regex.simpleMatch(warmer, entry.name()) || warmer.equals("_all")) {
logger.info("[{}] delete warmer [{}]", index, entry.name());
}
}
}
}
}
}
return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
});
}
} | 1no label
| src_main_java_org_elasticsearch_action_admin_indices_warmer_delete_TransportDeleteWarmerAction.java |
829 | public class SearchPhaseExecutionException extends ElasticsearchException {
private final String phaseName;
private ShardSearchFailure[] shardFailures;
public SearchPhaseExecutionException(String phaseName, String msg, ShardSearchFailure[] shardFailures) {
super(buildMessage(phaseName, msg, shardFailures));
this.phaseName = phaseName;
this.shardFailures = shardFailures;
}
public SearchPhaseExecutionException(String phaseName, String msg, Throwable cause, ShardSearchFailure[] shardFailures) {
super(buildMessage(phaseName, msg, shardFailures), cause);
this.phaseName = phaseName;
this.shardFailures = shardFailures;
}
@Override
public RestStatus status() {
if (shardFailures.length == 0) {
// if no successful shards, it means no active shards, so just return SERVICE_UNAVAILABLE
return RestStatus.SERVICE_UNAVAILABLE;
}
RestStatus status = shardFailures[0].status();
if (shardFailures.length > 1) {
for (int i = 1; i < shardFailures.length; i++) {
if (shardFailures[i].status().getStatus() >= 500) {
status = shardFailures[i].status();
}
}
}
return status;
}
public String phaseName() {
return phaseName;
}
public ShardSearchFailure[] shardFailures() {
return shardFailures;
}
private static String buildMessage(String phaseName, String msg, ShardSearchFailure[] shardFailures) {
StringBuilder sb = new StringBuilder();
sb.append("Failed to execute phase [").append(phaseName).append("], ").append(msg);
if (shardFailures != null && shardFailures.length > 0) {
sb.append("; shardFailures ");
for (ShardSearchFailure shardFailure : shardFailures) {
if (shardFailure.shard() != null) {
sb.append("{").append(shardFailure.shard()).append(": ").append(shardFailure.reason()).append("}");
} else {
sb.append("{").append(shardFailure.reason()).append("}");
}
}
}
return sb.toString();
}
} | 0true
| src_main_java_org_elasticsearch_action_search_SearchPhaseExecutionException.java |
5,057 | public class SearchContextMissingException extends ElasticsearchException {
private final long id;
public SearchContextMissingException(long id) {
super("No search context found for id [" + id + "]");
this.id = id;
}
public long id() {
return this.id;
}
} | 1no label
| src_main_java_org_elasticsearch_search_SearchContextMissingException.java |
267 | public class LoggingMailSender extends JavaMailSenderImpl {
private static final Log LOG = LogFactory.getLog(LoggingMailSender.class);
@Override
public void send(MimeMessagePreparator[] mimeMessagePreparators) throws MailException {
for (MimeMessagePreparator preparator : mimeMessagePreparators) {
try {
MimeMessage mimeMessage = createMimeMessage();
preparator.prepare(mimeMessage);
LOG.info("\"Sending\" email: ");
if (mimeMessage.getContent() instanceof MimeMultipart) {
MimeMultipart msg = (MimeMultipart) mimeMessage.getContent();
DataHandler dh = msg.getBodyPart(0).getDataHandler();
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
dh.writeTo(baos);
} catch (Exception e) {
// Do nothing
} finally {
try {
baos.close();
} catch (Exception e) {
LOG.error("Couldn't close byte array output stream");
}
}
} else {
LOG.info(mimeMessage.getContent());
}
} catch (Exception e) {
LOG.error("Could not create message", e);
}
}
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_email_service_LoggingMailSender.java |
552 | public class UrlUtil {
public static String generateUrlKey(String toConvert) {
if (toConvert.matches(".*?\\W.*?")) {
//remove all non-word characters
String result = toConvert.replaceAll("\\W","");
//uncapitalizes the first letter of the url key
return StringUtils.uncapitalize(result);
} else {
return StringUtils.uncapitalize(toConvert);
}
}
/**
* If the url does not include "//" then the system will ensure that the
* application context is added to the start of the URL.
*
* @param url
* @return
*/
public static String fixRedirectUrl(String contextPath, String url) {
if (url.indexOf("//") < 0) {
if (contextPath != null && (!"".equals(contextPath))) {
if (!url.startsWith("/")) {
url = "/" + url;
}
if (!url.startsWith(contextPath)) {
url = contextPath + url;
}
}
}
return url;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_util_UrlUtil.java |
1,176 | serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new EchoServerHandler());
}
}); | 0true
| src_test_java_org_elasticsearch_benchmark_transport_netty_NettyEchoBenchmark.java |
191 | public class TimeDTO {
@AdminPresentation(excluded = true)
private Calendar cal;
@AdminPresentation(friendlyName = "TimeDTO_Hour_Of_Day", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.common.time.HourOfDayType")
private Integer hour;
@AdminPresentation(friendlyName = "TimeDTO_Day_Of_Week", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.common.time.DayOfWeekType")
private Integer dayOfWeek;
@AdminPresentation(friendlyName = "TimeDTO_Month", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.common.time.MonthType")
private Integer month;
@AdminPresentation(friendlyName = "TimeDTO_Day_Of_Month", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.common.time.DayOfMonthType")
private Integer dayOfMonth;
@AdminPresentation(friendlyName = "TimeDTO_Minute", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.common.time.MinuteType")
private Integer minute;
@AdminPresentation(friendlyName = "TimeDTO_Date")
private Date date;
public TimeDTO() {
cal = SystemTime.asCalendar();
}
public TimeDTO(Calendar cal) {
this.cal = cal;
}
/**
* @return int representing the hour of day as 0 - 23
*/
public HourOfDayType getHour() {
if (hour == null) {
hour = cal.get(Calendar.HOUR_OF_DAY);
}
return HourOfDayType.getInstance(hour.toString());
}
/**
* @return int representing the day of week using Calendar.DAY_OF_WEEK values.
* 1 = Sunday, 7 = Saturday
*/
public DayOfWeekType getDayOfWeek() {
if (dayOfWeek == null) {
dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
}
return DayOfWeekType.getInstance(dayOfWeek.toString());
}
/**
* @return the current day of the month (1-31).
*/
public DayOfMonthType getDayOfMonth() {
if (dayOfMonth == null) {
dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
}
return DayOfMonthType.getInstance(dayOfMonth.toString());
}
/**
* @return int representing the current month (1-12)
*/
public MonthType getMonth() {
if (month == null) {
month = cal.get(Calendar.MONTH);
}
return MonthType.getInstance(month.toString());
}
public MinuteType getMinute() {
if (minute == null) {
minute = cal.get(Calendar.MINUTE);
}
return MinuteType.getInstance(minute.toString());
}
public Date getDate() {
if (date == null) {
date = cal.getTime();
}
return date;
}
public void setCal(Calendar cal) {
this.cal = cal;
}
public void setHour(HourOfDayType hour) {
this.hour = Integer.valueOf(hour.getType());
;
}
public void setDayOfWeek(DayOfWeekType dayOfWeek) {
this.dayOfWeek = Integer.valueOf(dayOfWeek.getType());
}
public void setMonth(MonthType month) {
this.month = Integer.valueOf(month.getType());
}
public void setDayOfMonth(DayOfMonthType dayOfMonth) {
this.dayOfMonth = Integer.valueOf(dayOfMonth.getType());
}
public void setDate(Date date) {
this.date = date;
}
public void setMinute(MinuteType minute) {
this.minute = Integer.valueOf(minute.getType());
;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_TimeDTO.java |
1,391 | public class EditedPhasedUnit extends IdePhasedUnit {
WeakReference<ProjectPhasedUnit> savedPhasedUnitRef;
public EditedPhasedUnit(VirtualFile unitFile, VirtualFile srcDir,
CompilationUnit cu, Package p, ModuleManager moduleManager,
TypeChecker typeChecker, List<CommonToken> tokenStream, ProjectPhasedUnit savedPhasedUnit) {
super(unitFile, srcDir, cu, p, moduleManager, typeChecker, tokenStream);
savedPhasedUnitRef = new WeakReference<ProjectPhasedUnit>(savedPhasedUnit);
if (savedPhasedUnit!=null) {
savedPhasedUnit.addWorkingCopy(this);
}
}
public EditedPhasedUnit(PhasedUnit other) {
super(other);
}
@Override
public Unit newUnit() {
return new EditedSourceFile(this);
}
@Override
public EditedSourceFile getUnit() {
return (EditedSourceFile) super.getUnit();
}
public ProjectPhasedUnit getOriginalPhasedUnit() {
return savedPhasedUnitRef.get();
}
public IFile getSourceFileResource() {
return getOriginalPhasedUnit() == null ? null
: getOriginalPhasedUnit().getSourceFileResource();
}
public IFolder getSourceFolderResource() {
return getOriginalPhasedUnit() == null ? null
: getOriginalPhasedUnit().getSourceFolderResource();
}
public IProject getProjectResource() {
return getOriginalPhasedUnit() == null ? null
: getOriginalPhasedUnit().getProjectResource();
}
@Override
protected boolean reuseExistingDescriptorModels() {
return true;
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_typechecker_EditedPhasedUnit.java |
5,806 | public final class CustomQueryScorer extends QueryScorer {
public CustomQueryScorer(Query query, IndexReader reader, String field,
String defaultField) {
super(query, reader, field, defaultField);
}
public CustomQueryScorer(Query query, IndexReader reader, String field) {
super(query, reader, field);
}
public CustomQueryScorer(Query query, String field, String defaultField) {
super(query, field, defaultField);
}
public CustomQueryScorer(Query query, String field) {
super(query, field);
}
public CustomQueryScorer(Query query) {
super(query);
}
public CustomQueryScorer(WeightedSpanTerm[] weightedTerms) {
super(weightedTerms);
}
@Override
protected WeightedSpanTermExtractor newTermExtractor(String defaultField) {
return defaultField == null ? new CustomWeightedSpanTermExtractor()
: new CustomWeightedSpanTermExtractor(defaultField);
}
private static class CustomWeightedSpanTermExtractor extends WeightedSpanTermExtractor {
public CustomWeightedSpanTermExtractor() {
super();
}
public CustomWeightedSpanTermExtractor(String defaultField) {
super(defaultField);
}
@Override
protected void extractUnknownQuery(Query query,
Map<String, WeightedSpanTerm> terms) throws IOException {
if (query instanceof FunctionScoreQuery) {
query = ((FunctionScoreQuery) query).getSubQuery();
extract(query, terms);
} else if (query instanceof FiltersFunctionScoreQuery) {
query = ((FiltersFunctionScoreQuery) query).getSubQuery();
extract(query, terms);
} else if (query instanceof XFilteredQuery) {
query = ((XFilteredQuery) query).getQuery();
extract(query, terms);
}
}
}
} | 1no label
| src_main_java_org_elasticsearch_search_highlight_CustomQueryScorer.java |
398 | public interface CurrencyConversionService {
/**
* Converts the given Money into the destination. The starting currency is determined by {@code source.getCurrency()}
*
* @param source - the Money to convert
* @param destinationCurrency - which Currency to convert to
* @param destinationScale - the scale that the result will be in. If zero, this defaults to the scale of <b>source</b>
* and if that is zero, defaults to {@code BankersRounding.DEFAULT_SCALE}
* @return a new Money in <b>destinationCurrency</b>. If the source and destination are the same currency, the original
* source is returned unchanged
*/
public Money convertCurrency(Money source, Currency destinationCurrency, int destinationScale);
} | 0true
| common_src_main_java_org_broadleafcommerce_common_money_CurrencyConversionService.java |
168 | public abstract class SpeedTestMonoThread extends SpeedTestAbstract {
protected SpeedTestMonoThread() {
}
protected SpeedTestMonoThread(final long iCycles) {
super(iCycles);
}
} | 0true
| commons_src_test_java_com_orientechnologies_common_test_SpeedTestMonoThread.java |
8 | public class LabelAbbreviationsTest {
@Test
public void getAbbreviation() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
AbbreviationsImpl availableAbbreviations = new AbbreviationsImpl("value");
availableAbbreviations.addPhrase("Amps", Collections.singletonList("A"));
availableAbbreviations.addPhrase("BCA1", Collections.<String>emptyList());
availableAbbreviations.addPhrase("Ch1", Collections.<String>emptyList());
availableAbbreviations.addPhrase("Serial", Collections.<String>emptyList());
AbbreviationSettings aSettings = new AbbreviationSettings("fullLabel", availableAbbreviations, new LabelAbbreviations());
String abbreviatedLabel = aSettings.getAbbreviatedLabel();
Assert.assertEquals(abbreviatedLabel, "Amps BCA1 Ch1 Serial");
LabelAbbreviations available2 = aSettings.getAbbreviations();
Assert.assertEquals(available2.getAbbreviation("BCA1"), "BCA1");
Assert.assertEquals(available2.getAbbreviation("Amps"), "Amps");
// Change the state of the control panel via currentAbbreviations
LabelAbbreviations currentAbbreviations = new LabelAbbreviations();
currentAbbreviations.addAbbreviation("Amps", "A | a | Amp");
currentAbbreviations.addAbbreviation("BCA1", "B | bca1");
currentAbbreviations.addAbbreviation("CAT", "C");
currentAbbreviations.addAbbreviation("DOG", "D");
currentAbbreviations.addAbbreviation("Ace", "ace");
currentAbbreviations.addAbbreviation("Abb", "a");
currentAbbreviations.addAbbreviation("Rabbit", "R");
AbbreviationSettings a2Settings = new AbbreviationSettings("fullLabel", availableAbbreviations, currentAbbreviations);
LabelAbbreviations available2afterSelect = a2Settings.getAbbreviations();
Assert.assertEquals(available2afterSelect.getAbbreviation("BCA1"), "B | bca1");
Assert.assertEquals(available2afterSelect.getAbbreviation("Amps"), "A | a | Amp");
Map<String, String> map = getAbbreviations(currentAbbreviations);
Assert.assertEquals(map.size(), 7);
}
private Map<String, String> getAbbreviations(
LabelAbbreviations currentAbbreviations) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field f = currentAbbreviations.getClass().getDeclaredField("abbreviations"); //NoSuchFieldException
f.setAccessible(true);
@SuppressWarnings("unchecked")
Map<String, String> map = (HashMap<String,String>) f.get(currentAbbreviations); //IllegalAccessException
return map;
}
} | 0true
| tableViews_src_test_java_gov_nasa_arc_mct_abbreviation_impl_LabelAbbreviationsTest.java |
427 | public enum RequiredOverride {
REQUIRED,
NOT_REQUIRED,
IGNORED
} | 0true
| common_src_main_java_org_broadleafcommerce_common_presentation_RequiredOverride.java |
249 | public final class XFuzzySuggester extends XAnalyzingSuggester {
private final int maxEdits;
private final boolean transpositions;
private final int nonFuzzyPrefix;
private final int minFuzzyLength;
private final boolean unicodeAware;
/**
* Measure maxEdits, minFuzzyLength, transpositions and nonFuzzyPrefix
* parameters in Unicode code points (actual letters)
* instead of bytes.
*/
public static final boolean DEFAULT_UNICODE_AWARE = false;
/**
* The default minimum length of the key passed to {@link
* #lookup} before any edits are allowed.
*/
public static final int DEFAULT_MIN_FUZZY_LENGTH = 3;
/**
* The default prefix length where edits are not allowed.
*/
public static final int DEFAULT_NON_FUZZY_PREFIX = 1;
/**
* The default maximum number of edits for fuzzy
* suggestions.
*/
public static final int DEFAULT_MAX_EDITS = 1;
/**
* The default transposition value passed to {@link org.apache.lucene.util.automaton.LevenshteinAutomata}
*/
public static final boolean DEFAULT_TRANSPOSITIONS = true;
/**
* Creates a {@link FuzzySuggester} instance initialized with default values.
*
* @param analyzer the analyzer used for this suggester
*/
public XFuzzySuggester(Analyzer analyzer) {
this(analyzer, analyzer);
}
/**
* Creates a {@link FuzzySuggester} instance with an index & a query analyzer initialized with default values.
*
* @param indexAnalyzer
* Analyzer that will be used for analyzing suggestions while building the index.
* @param queryAnalyzer
* Analyzer that will be used for analyzing query text during lookup
*/
public XFuzzySuggester(Analyzer indexAnalyzer, Analyzer queryAnalyzer) {
this(indexAnalyzer, queryAnalyzer, EXACT_FIRST | PRESERVE_SEP, 256, -1, DEFAULT_MAX_EDITS, DEFAULT_TRANSPOSITIONS,
DEFAULT_NON_FUZZY_PREFIX, DEFAULT_MIN_FUZZY_LENGTH, DEFAULT_UNICODE_AWARE, null, false, 0, SEP_LABEL, PAYLOAD_SEP, END_BYTE, HOLE_CHARACTER);
}
/**
* Creates a {@link FuzzySuggester} instance.
*
* @param indexAnalyzer Analyzer that will be used for
* analyzing suggestions while building the index.
* @param queryAnalyzer Analyzer that will be used for
* analyzing query text during lookup
* @param options see {@link #EXACT_FIRST}, {@link #PRESERVE_SEP}
* @param maxSurfaceFormsPerAnalyzedForm Maximum number of
* surface forms to keep for a single analyzed form.
* When there are too many surface forms we discard the
* lowest weighted ones.
* @param maxGraphExpansions Maximum number of graph paths
* to expand from the analyzed form. Set this to -1 for
* no limit.
* @param maxEdits must be >= 0 and <= {@link org.apache.lucene.util.automaton.LevenshteinAutomata#MAXIMUM_SUPPORTED_DISTANCE} .
* @param transpositions <code>true</code> if transpositions should be treated as a primitive
* edit operation. If this is false, comparisons will implement the classic
* Levenshtein algorithm.
* @param nonFuzzyPrefix length of common (non-fuzzy) prefix (see default {@link #DEFAULT_NON_FUZZY_PREFIX}
* @param minFuzzyLength minimum length of lookup key before any edits are allowed (see default {@link #DEFAULT_MIN_FUZZY_LENGTH})
* @param sepLabel separation label
* @param payloadSep payload separator byte
* @param endByte end byte marker byte
*/
public XFuzzySuggester(Analyzer indexAnalyzer, Analyzer queryAnalyzer, int options, int maxSurfaceFormsPerAnalyzedForm, int maxGraphExpansions,
int maxEdits, boolean transpositions, int nonFuzzyPrefix, int minFuzzyLength, boolean unicodeAware,
FST<PairOutputs.Pair<Long, BytesRef>> fst, boolean hasPayloads, int maxAnalyzedPathsForOneInput,
int sepLabel, int payloadSep, int endByte, int holeCharacter) {
super(indexAnalyzer, queryAnalyzer, options, maxSurfaceFormsPerAnalyzedForm, maxGraphExpansions, true, fst, hasPayloads, maxAnalyzedPathsForOneInput, sepLabel, payloadSep, endByte, holeCharacter);
if (maxEdits < 0 || maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE) {
throw new IllegalArgumentException("maxEdits must be between 0 and " + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE);
}
if (nonFuzzyPrefix < 0) {
throw new IllegalArgumentException("nonFuzzyPrefix must not be >= 0 (got " + nonFuzzyPrefix + ")");
}
if (minFuzzyLength < 0) {
throw new IllegalArgumentException("minFuzzyLength must not be >= 0 (got " + minFuzzyLength + ")");
}
this.maxEdits = maxEdits;
this.transpositions = transpositions;
this.nonFuzzyPrefix = nonFuzzyPrefix;
this.minFuzzyLength = minFuzzyLength;
this.unicodeAware = unicodeAware;
}
@Override
protected List<FSTUtil.Path<PairOutputs.Pair<Long,BytesRef>>> getFullPrefixPaths(List<FSTUtil.Path<PairOutputs.Pair<Long,BytesRef>>> prefixPaths,
Automaton lookupAutomaton,
FST<PairOutputs.Pair<Long,BytesRef>> fst)
throws IOException {
// TODO: right now there's no penalty for fuzzy/edits,
// ie a completion whose prefix matched exactly what the
// user typed gets no boost over completions that
// required an edit, which get no boost over completions
// requiring two edits. I suspect a multiplicative
// factor is appropriate (eg, say a fuzzy match must be at
// least 2X better weight than the non-fuzzy match to
// "compete") ... in which case I think the wFST needs
// to be log weights or something ...
Automaton levA = convertAutomaton(toLevenshteinAutomata(lookupAutomaton));
/*
Writer w = new OutputStreamWriter(new FileOutputStream("out.dot"), "UTF-8");
w.write(levA.toDot());
w.close();
System.out.println("Wrote LevA to out.dot");
*/
return FSTUtil.intersectPrefixPaths(levA, fst);
}
@Override
protected Automaton convertAutomaton(Automaton a) {
if (unicodeAware) {
Automaton utf8automaton = new UTF32ToUTF8().convert(a);
BasicOperations.determinize(utf8automaton);
return utf8automaton;
} else {
return a;
}
}
@Override
public TokenStreamToAutomaton getTokenStreamToAutomaton() {
final TokenStreamToAutomaton tsta = super.getTokenStreamToAutomaton();
tsta.setUnicodeArcs(unicodeAware);
return tsta;
}
Automaton toLevenshteinAutomata(Automaton automaton) {
final Set<IntsRef> ref = SpecialOperations.getFiniteStrings(automaton, -1);
Automaton subs[] = new Automaton[ref.size()];
int upto = 0;
for (IntsRef path : ref) {
if (path.length <= nonFuzzyPrefix || path.length < minFuzzyLength) {
subs[upto] = BasicAutomata.makeString(path.ints, path.offset, path.length);
upto++;
} else {
Automaton prefix = BasicAutomata.makeString(path.ints, path.offset, nonFuzzyPrefix);
int ints[] = new int[path.length-nonFuzzyPrefix];
System.arraycopy(path.ints, path.offset+nonFuzzyPrefix, ints, 0, ints.length);
// TODO: maybe add alphaMin to LevenshteinAutomata,
// and pass 1 instead of 0? We probably don't want
// to allow the trailing dedup bytes to be
// edited... but then 0 byte is "in general" allowed
// on input (but not in UTF8).
LevenshteinAutomata lev = new LevenshteinAutomata(ints, unicodeAware ? Character.MAX_CODE_POINT : 255, transpositions);
Automaton levAutomaton = lev.toAutomaton(maxEdits);
Automaton combined = BasicOperations.concatenate(Arrays.asList(prefix, levAutomaton));
combined.setDeterministic(true); // its like the special case in concatenate itself, except we cloneExpanded already
subs[upto] = combined;
upto++;
}
}
if (subs.length == 0) {
// automaton is empty, there is no accepted paths through it
return BasicAutomata.makeEmpty(); // matches nothing
} else if (subs.length == 1) {
// no synonyms or anything: just a single path through the tokenstream
return subs[0];
} else {
// multiple paths: this is really scary! is it slow?
// maybe we should not do this and throw UOE?
Automaton a = BasicOperations.union(Arrays.asList(subs));
// TODO: we could call toLevenshteinAutomata() before det?
// this only happens if you have multiple paths anyway (e.g. synonyms)
BasicOperations.determinize(a);
return a;
}
}
} | 0true
| src_main_java_org_apache_lucene_search_suggest_analyzing_XFuzzySuggester.java |
1,250 | public abstract class AbstractIndicesAdminClient implements InternalIndicesAdminClient {
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> RequestBuilder prepareExecute(final IndicesAction<Request, Response, RequestBuilder> action) {
return action.newRequestBuilder(this);
}
@Override
public ActionFuture<IndicesExistsResponse> exists(final IndicesExistsRequest request) {
return execute(IndicesExistsAction.INSTANCE, request);
}
@Override
public void exists(final IndicesExistsRequest request, final ActionListener<IndicesExistsResponse> listener) {
execute(IndicesExistsAction.INSTANCE, request, listener);
}
@Override
public IndicesExistsRequestBuilder prepareExists(String... indices) {
return new IndicesExistsRequestBuilder(this, indices);
}
@Override
public ActionFuture<TypesExistsResponse> typesExists(TypesExistsRequest request) {
return execute(TypesExistsAction.INSTANCE, request);
}
@Override
public void typesExists(TypesExistsRequest request, ActionListener<TypesExistsResponse> listener) {
execute(TypesExistsAction.INSTANCE, request, listener);
}
@Override
public TypesExistsRequestBuilder prepareTypesExists(String... index) {
return new TypesExistsRequestBuilder(this, index);
}
@Override
public ActionFuture<IndicesAliasesResponse> aliases(final IndicesAliasesRequest request) {
return execute(IndicesAliasesAction.INSTANCE, request);
}
@Override
public void aliases(final IndicesAliasesRequest request, final ActionListener<IndicesAliasesResponse> listener) {
execute(IndicesAliasesAction.INSTANCE, request, listener);
}
@Override
public IndicesAliasesRequestBuilder prepareAliases() {
return new IndicesAliasesRequestBuilder(this);
}
@Override
public ActionFuture<GetAliasesResponse> getAliases(GetAliasesRequest request) {
return execute(GetAliasesAction.INSTANCE, request);
}
@Override
public void getAliases(GetAliasesRequest request, ActionListener<GetAliasesResponse> listener) {
execute(GetAliasesAction.INSTANCE, request, listener);
}
@Override
public GetAliasesRequestBuilder prepareGetAliases(String... aliases) {
return new GetAliasesRequestBuilder(this, aliases);
}
@Override
public ActionFuture<ClearIndicesCacheResponse> clearCache(final ClearIndicesCacheRequest request) {
return execute(ClearIndicesCacheAction.INSTANCE, request);
}
@Override
public void aliasesExist(GetAliasesRequest request, ActionListener<AliasesExistResponse> listener) {
execute(AliasesExistAction.INSTANCE, request, listener);
}
@Override
public ActionFuture<AliasesExistResponse> aliasesExist(GetAliasesRequest request) {
return execute(AliasesExistAction.INSTANCE, request);
}
@Override
public AliasesExistRequestBuilder prepareAliasesExist(String... aliases) {
return new AliasesExistRequestBuilder(this, aliases);
}
@Override
public void clearCache(final ClearIndicesCacheRequest request, final ActionListener<ClearIndicesCacheResponse> listener) {
execute(ClearIndicesCacheAction.INSTANCE, request, listener);
}
@Override
public ClearIndicesCacheRequestBuilder prepareClearCache(String... indices) {
return new ClearIndicesCacheRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<CreateIndexResponse> create(final CreateIndexRequest request) {
return execute(CreateIndexAction.INSTANCE, request);
}
@Override
public void create(final CreateIndexRequest request, final ActionListener<CreateIndexResponse> listener) {
execute(CreateIndexAction.INSTANCE, request, listener);
}
@Override
public CreateIndexRequestBuilder prepareCreate(String index) {
return new CreateIndexRequestBuilder(this, index);
}
@Override
public ActionFuture<DeleteIndexResponse> delete(final DeleteIndexRequest request) {
return execute(DeleteIndexAction.INSTANCE, request);
}
@Override
public void delete(final DeleteIndexRequest request, final ActionListener<DeleteIndexResponse> listener) {
execute(DeleteIndexAction.INSTANCE, request, listener);
}
@Override
public DeleteIndexRequestBuilder prepareDelete(String... indices) {
return new DeleteIndexRequestBuilder(this, indices);
}
@Override
public ActionFuture<CloseIndexResponse> close(final CloseIndexRequest request) {
return execute(CloseIndexAction.INSTANCE, request);
}
@Override
public void close(final CloseIndexRequest request, final ActionListener<CloseIndexResponse> listener) {
execute(CloseIndexAction.INSTANCE, request, listener);
}
@Override
public CloseIndexRequestBuilder prepareClose(String... indices) {
return new CloseIndexRequestBuilder(this, indices);
}
@Override
public ActionFuture<OpenIndexResponse> open(final OpenIndexRequest request) {
return execute(OpenIndexAction.INSTANCE, request);
}
@Override
public void open(final OpenIndexRequest request, final ActionListener<OpenIndexResponse> listener) {
execute(OpenIndexAction.INSTANCE, request, listener);
}
@Override
public OpenIndexRequestBuilder prepareOpen(String... indices) {
return new OpenIndexRequestBuilder(this, indices);
}
@Override
public ActionFuture<FlushResponse> flush(final FlushRequest request) {
return execute(FlushAction.INSTANCE, request);
}
@Override
public void flush(final FlushRequest request, final ActionListener<FlushResponse> listener) {
execute(FlushAction.INSTANCE, request, listener);
}
@Override
public FlushRequestBuilder prepareFlush(String... indices) {
return new FlushRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<GatewaySnapshotResponse> gatewaySnapshot(final GatewaySnapshotRequest request) {
return execute(GatewaySnapshotAction.INSTANCE, request);
}
@Override
public void gatewaySnapshot(final GatewaySnapshotRequest request, final ActionListener<GatewaySnapshotResponse> listener) {
execute(GatewaySnapshotAction.INSTANCE, request, listener);
}
@Override
public GatewaySnapshotRequestBuilder prepareGatewaySnapshot(String... indices) {
return new GatewaySnapshotRequestBuilder(this).setIndices(indices);
}
@Override
public void getMappings(GetMappingsRequest request, ActionListener<GetMappingsResponse> listener) {
execute(GetMappingsAction.INSTANCE, request, listener);
}
@Override
public void getFieldMappings(GetFieldMappingsRequest request, ActionListener<GetFieldMappingsResponse> listener) {
execute(GetFieldMappingsAction.INSTANCE, request, listener);
}
@Override
public GetMappingsRequestBuilder prepareGetMappings(String... indices) {
return new GetMappingsRequestBuilder(this, indices);
}
@Override
public ActionFuture<GetMappingsResponse> getMappings(GetMappingsRequest request) {
return execute(GetMappingsAction.INSTANCE, request);
}
@Override
public GetFieldMappingsRequestBuilder prepareGetFieldMappings(String... indices) {
return new GetFieldMappingsRequestBuilder(this, indices);
}
@Override
public ActionFuture<GetFieldMappingsResponse> getFieldMappings(GetFieldMappingsRequest request) {
return execute(GetFieldMappingsAction.INSTANCE, request);
}
@Override
public ActionFuture<PutMappingResponse> putMapping(final PutMappingRequest request) {
return execute(PutMappingAction.INSTANCE, request);
}
@Override
public void putMapping(final PutMappingRequest request, final ActionListener<PutMappingResponse> listener) {
execute(PutMappingAction.INSTANCE, request, listener);
}
@Override
public PutMappingRequestBuilder preparePutMapping(String... indices) {
return new PutMappingRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<DeleteMappingResponse> deleteMapping(final DeleteMappingRequest request) {
return execute(DeleteMappingAction.INSTANCE, request);
}
@Override
public void deleteMapping(final DeleteMappingRequest request, final ActionListener<DeleteMappingResponse> listener) {
execute(DeleteMappingAction.INSTANCE, request, listener);
}
@Override
public DeleteMappingRequestBuilder prepareDeleteMapping(String... indices) {
return new DeleteMappingRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<OptimizeResponse> optimize(final OptimizeRequest request) {
return execute(OptimizeAction.INSTANCE, request);
}
@Override
public void optimize(final OptimizeRequest request, final ActionListener<OptimizeResponse> listener) {
execute(OptimizeAction.INSTANCE, request, listener);
}
@Override
public OptimizeRequestBuilder prepareOptimize(String... indices) {
return new OptimizeRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<RefreshResponse> refresh(final RefreshRequest request) {
return execute(RefreshAction.INSTANCE, request);
}
@Override
public void refresh(final RefreshRequest request, final ActionListener<RefreshResponse> listener) {
execute(RefreshAction.INSTANCE, request, listener);
}
@Override
public RefreshRequestBuilder prepareRefresh(String... indices) {
return new RefreshRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<IndicesStatsResponse> stats(final IndicesStatsRequest request) {
return execute(IndicesStatsAction.INSTANCE, request);
}
@Override
public void stats(final IndicesStatsRequest request, final ActionListener<IndicesStatsResponse> listener) {
execute(IndicesStatsAction.INSTANCE, request, listener);
}
@Override
public IndicesStatsRequestBuilder prepareStats(String... indices) {
return new IndicesStatsRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<IndicesStatusResponse> status(final IndicesStatusRequest request) {
return execute(IndicesStatusAction.INSTANCE, request);
}
@Override
public void status(final IndicesStatusRequest request, final ActionListener<IndicesStatusResponse> listener) {
execute(IndicesStatusAction.INSTANCE, request, listener);
}
@Override
public IndicesStatusRequestBuilder prepareStatus(String... indices) {
return new IndicesStatusRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<IndicesSegmentResponse> segments(final IndicesSegmentsRequest request) {
return execute(IndicesSegmentsAction.INSTANCE, request);
}
@Override
public void segments(final IndicesSegmentsRequest request, final ActionListener<IndicesSegmentResponse> listener) {
execute(IndicesSegmentsAction.INSTANCE, request, listener);
}
@Override
public IndicesSegmentsRequestBuilder prepareSegments(String... indices) {
return new IndicesSegmentsRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<UpdateSettingsResponse> updateSettings(final UpdateSettingsRequest request) {
return execute(UpdateSettingsAction.INSTANCE, request);
}
@Override
public void updateSettings(final UpdateSettingsRequest request, final ActionListener<UpdateSettingsResponse> listener) {
execute(UpdateSettingsAction.INSTANCE, request, listener);
}
@Override
public UpdateSettingsRequestBuilder prepareUpdateSettings(String... indices) {
return new UpdateSettingsRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<AnalyzeResponse> analyze(final AnalyzeRequest request) {
return execute(AnalyzeAction.INSTANCE, request);
}
@Override
public void analyze(final AnalyzeRequest request, final ActionListener<AnalyzeResponse> listener) {
execute(AnalyzeAction.INSTANCE, request, listener);
}
@Override
public AnalyzeRequestBuilder prepareAnalyze(@Nullable String index, String text) {
return new AnalyzeRequestBuilder(this, index, text);
}
@Override
public AnalyzeRequestBuilder prepareAnalyze(String text) {
return new AnalyzeRequestBuilder(this, null, text);
}
@Override
public ActionFuture<PutIndexTemplateResponse> putTemplate(final PutIndexTemplateRequest request) {
return execute(PutIndexTemplateAction.INSTANCE, request);
}
@Override
public void putTemplate(final PutIndexTemplateRequest request, final ActionListener<PutIndexTemplateResponse> listener) {
execute(PutIndexTemplateAction.INSTANCE, request, listener);
}
@Override
public PutIndexTemplateRequestBuilder preparePutTemplate(String name) {
return new PutIndexTemplateRequestBuilder(this, name);
}
@Override
public ActionFuture<GetIndexTemplatesResponse> getTemplates(final GetIndexTemplatesRequest request) {
return execute(GetIndexTemplatesAction.INSTANCE, request);
}
@Override
public void getTemplates(final GetIndexTemplatesRequest request, final ActionListener<GetIndexTemplatesResponse> listener) {
execute(GetIndexTemplatesAction.INSTANCE, request, listener);
}
@Override
public GetIndexTemplatesRequestBuilder prepareGetTemplates(String... names) {
return new GetIndexTemplatesRequestBuilder(this, names);
}
@Override
public ActionFuture<DeleteIndexTemplateResponse> deleteTemplate(final DeleteIndexTemplateRequest request) {
return execute(DeleteIndexTemplateAction.INSTANCE, request);
}
@Override
public void deleteTemplate(final DeleteIndexTemplateRequest request, final ActionListener<DeleteIndexTemplateResponse> listener) {
execute(DeleteIndexTemplateAction.INSTANCE, request, listener);
}
@Override
public DeleteIndexTemplateRequestBuilder prepareDeleteTemplate(String name) {
return new DeleteIndexTemplateRequestBuilder(this, name);
}
@Override
public ActionFuture<ValidateQueryResponse> validateQuery(final ValidateQueryRequest request) {
return execute(ValidateQueryAction.INSTANCE, request);
}
@Override
public void validateQuery(final ValidateQueryRequest request, final ActionListener<ValidateQueryResponse> listener) {
execute(ValidateQueryAction.INSTANCE, request, listener);
}
@Override
public ValidateQueryRequestBuilder prepareValidateQuery(String... indices) {
return new ValidateQueryRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<PutWarmerResponse> putWarmer(PutWarmerRequest request) {
return execute(PutWarmerAction.INSTANCE, request);
}
@Override
public void putWarmer(PutWarmerRequest request, ActionListener<PutWarmerResponse> listener) {
execute(PutWarmerAction.INSTANCE, request, listener);
}
@Override
public PutWarmerRequestBuilder preparePutWarmer(String name) {
return new PutWarmerRequestBuilder(this, name);
}
@Override
public ActionFuture<DeleteWarmerResponse> deleteWarmer(DeleteWarmerRequest request) {
return execute(DeleteWarmerAction.INSTANCE, request);
}
@Override
public void deleteWarmer(DeleteWarmerRequest request, ActionListener<DeleteWarmerResponse> listener) {
execute(DeleteWarmerAction.INSTANCE, request, listener);
}
@Override
public DeleteWarmerRequestBuilder prepareDeleteWarmer() {
return new DeleteWarmerRequestBuilder(this);
}
@Override
public GetWarmersRequestBuilder prepareGetWarmers(String... indices) {
return new GetWarmersRequestBuilder(this, indices);
}
@Override
public ActionFuture<GetWarmersResponse> getWarmers(GetWarmersRequest request) {
return execute(GetWarmersAction.INSTANCE, request);
}
@Override
public void getWarmers(GetWarmersRequest request, ActionListener<GetWarmersResponse> listener) {
execute(GetWarmersAction.INSTANCE, request, listener);
}
@Override
public GetSettingsRequestBuilder prepareGetSettings(String... indices) {
return new GetSettingsRequestBuilder(this, indices);
}
@Override
public ActionFuture<GetSettingsResponse> getSettings(GetSettingsRequest request) {
return execute(GetSettingsAction.INSTANCE, request);
}
@Override
public void getSettings(GetSettingsRequest request, ActionListener<GetSettingsResponse> listener) {
execute(GetSettingsAction.INSTANCE, request, listener);
}
} | 0true
| src_main_java_org_elasticsearch_client_support_AbstractIndicesAdminClient.java |
399 | public class ORecordOperation implements OSerializableStream {
private static final long serialVersionUID = 1L;
public static final byte LOADED = 0;
public static final byte UPDATED = 1;
public static final byte DELETED = 2;
public static final byte CREATED = 3;
public byte type;
public OIdentifiable record;
public int dataSegmentId = 0; // DEFAULT ONE
public ORecordOperation() {
}
public ORecordOperation(final OIdentifiable iRecord, final byte iStatus) {
// CLONE RECORD AND CONTENT
this.record = iRecord;
this.type = iStatus;
}
@Override
public int hashCode() {
return record.getIdentity().hashCode();
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof ORecordOperation))
return false;
return record.equals(((ORecordOperation) obj).record);
}
@Override
public String toString() {
return new StringBuilder().append("ORecordOperation [record=").append(record).append(", type=").append(getName(type))
.append("]").toString();
}
public ORecordInternal<?> getRecord() {
return (ORecordInternal<?>) (record != null ? record.getRecord() : null);
}
public byte[] toStream() throws OSerializationException {
try {
final OMemoryStream stream = new OMemoryStream();
stream.set(type);
((ORecordId) record.getIdentity()).toStream(stream);
switch (type) {
case CREATED:
case UPDATED:
stream.set(((ORecordInternal<?>) record.getRecord()).getRecordType());
stream.set(((ORecordInternal<?>) record.getRecord()).toStream());
break;
}
return stream.toByteArray();
} catch (Exception e) {
throw new OSerializationException("Cannot serialize record operation", e);
}
}
public OSerializableStream fromStream(final byte[] iStream) throws OSerializationException {
try {
final OMemoryStream stream = new OMemoryStream(iStream);
type = stream.getAsByte();
final ORecordId rid = new ORecordId().fromStream(stream);
switch (type) {
case CREATED:
case UPDATED:
record = Orient.instance().getRecordFactoryManager().newInstance(stream.getAsByte());
((ORecordInternal<?>) record).fill(rid, OVersionFactory.instance().createVersion(), stream.getAsByteArray(), true);
break;
}
return this;
} catch (Exception e) {
throw new OSerializationException("Cannot deserialize record operation", e);
}
}
public static String getName(final int type) {
String operation = "?";
switch (type) {
case ORecordOperation.CREATED:
operation = "CREATE";
break;
case ORecordOperation.UPDATED:
operation = "UPDATE";
break;
case ORecordOperation.DELETED:
operation = "DELETE";
break;
case ORecordOperation.LOADED:
operation = "READ";
break;
}
return operation;
}
public static byte getId(String iName) {
iName = iName.toUpperCase();
if (iName.startsWith("CREAT"))
return ORecordOperation.CREATED;
else if (iName.startsWith("UPDAT"))
return ORecordOperation.UPDATED;
else if (iName.startsWith("DELET"))
return ORecordOperation.DELETED;
else if (iName.startsWith("READ"))
return ORecordOperation.LOADED;
return -1;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_record_ORecordOperation.java |
518 | public class OFetchException extends OException {
private static final long serialVersionUID = 7247597939953323863L;
public OFetchException(String message, Throwable cause) {
super(message, cause);
}
public OFetchException(String message) {
super(message);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_exception_OFetchException.java |
847 | 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;
}
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_AtomicReferencePortableHook.java |
1,161 | final class NewModuleWizardPage extends NewUnitWizardPage {
private String version="1.0.0";
NewModuleWizardPage() {
super("New Ceylon Module",
"Create a runnable Ceylon module with module and package descriptors.",
CEYLON_NEW_MODULE);
setUnitName("run");
}
String getVersion() {
return version;
}
@Override
String getCompilationUnitLabel() {
return "Runnable compilation unit: ";
}
@Override
String getPackageLabel() {
return "Module name: ";
}
@Override
String getSharedPackageLabel() {
return "Create module with shared root package"; // (visible to other modules)
}
@Override
void createControls(Composite composite) {
Text name = createPackageField(composite);
createVersionField(composite);
createSharedField(composite);
createNameField(composite);
createSeparator(composite);
createFolderField(composite);
name.forceFocus();
}
@Override
boolean isComplete() {
return super.isComplete() &&
!getPackageFragment().isDefaultPackage();
}
@Override
boolean packageNameIsLegal(String packageName) {
return !packageName.isEmpty() &&
super.packageNameIsLegal(packageName);
}
@Override
String getIllegalPackageNameMessage() {
return "Please enter a legal module name (a period-separated list of all-lowercase identifiers).";
}
@Override
String[] getFileNames() {
return new String[] { "module", "package", getUnitName() };
}
void createVersionField(Composite composite) {
Label versionLabel = new Label(composite, SWT.LEFT | SWT.WRAP);
versionLabel.setText("Module version:");
GridData lgd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
lgd.horizontalSpan = 1;
versionLabel.setLayoutData(lgd);
final Text versionName = new Text(composite, SWT.SINGLE | SWT.BORDER);
GridData ngd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
ngd.horizontalSpan = 2;
ngd.grabExcessHorizontalSpace = true;
versionName.setLayoutData(ngd);
versionName.setText(version);
versionName.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
version = versionName.getText();
setPageComplete(isComplete());
}
});
new Label(composite, SWT.NONE);
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_wizard_NewModuleWizardPage.java |
610 | Runnable recreateIndexesTask = new Runnable() {
@Override
public void run() {
try {
// START IT IN BACKGROUND
newDb.setProperty(ODatabase.OPTIONS.SECURITY.toString(), Boolean.FALSE);
newDb.open("admin", "nopass");
ODatabaseRecordThreadLocal.INSTANCE.set(newDb);
try {
// DROP AND RE-CREATE 'INDEX' DATA-SEGMENT AND CLUSTER IF ANY
final int dataId = newDb.getStorage().getDataSegmentIdByName(OMetadataDefault.DATASEGMENT_INDEX_NAME);
if (dataId > -1)
newDb.getStorage().dropDataSegment(OMetadataDefault.DATASEGMENT_INDEX_NAME);
final int clusterId = newDb.getStorage().getClusterIdByName(OMetadataDefault.CLUSTER_INDEX_NAME);
if (clusterId > -1)
newDb.dropCluster(clusterId, false);
newDb.addDataSegment(OMetadataDefault.DATASEGMENT_INDEX_NAME, null);
newDb.getStorage().addCluster(OClusterLocal.TYPE, OMetadataDefault.CLUSTER_INDEX_NAME, null,
OMetadataDefault.DATASEGMENT_INDEX_NAME, true);
} catch (IllegalArgumentException ex) {
// OLD DATABASE: CREATE SEPARATE DATASEGMENT AND LET THE INDEX CLUSTER TO POINT TO IT
OLogManager.instance().info(this, "Creating 'index' data-segment to store all the index content...");
newDb.addDataSegment(OMetadataDefault.DATASEGMENT_INDEX_NAME, null);
final OCluster indexCluster = newDb.getStorage().getClusterById(
newDb.getStorage().getClusterIdByName(OMetadataDefault.CLUSTER_INDEX_NAME));
try {
indexCluster.set(ATTRIBUTES.DATASEGMENT, OMetadataDefault.DATASEGMENT_INDEX_NAME);
OLogManager.instance().info(this,
"Data-segment 'index' create correctly. Indexes will store content into this data-segment");
} catch (IOException e) {
OLogManager.instance().error(this, "Error changing data segment for cluster 'index'", e);
}
}
final Collection<ODocument> idxs = doc.field(CONFIG_INDEXES);
if (idxs == null) {
OLogManager.instance().warn(this, "List of indexes is empty.");
return;
}
int ok = 0;
int errors = 0;
for (ODocument idx : idxs) {
try {
String indexType = idx.field(OIndexInternal.CONFIG_TYPE);
String algorithm = idx.field(OIndexInternal.ALGORITHM);
String valueContainerAlgorithm = idx.field(OIndexInternal.VALUE_CONTAINER_ALGORITHM);
if (indexType == null) {
OLogManager.instance().error(this, "Index type is null, will process other record.");
errors++;
continue;
}
final OIndexInternal<?> index = OIndexes.createIndex(newDb, indexType, algorithm, valueContainerAlgorithm);
OIndexInternal.IndexMetadata indexMetadata = index.loadMetadata(idx);
OIndexDefinition indexDefinition = indexMetadata.getIndexDefinition();
if (indexDefinition == null || !indexDefinition.isAutomatic()) {
OLogManager.instance().info(this, "Index %s is not automatic index and will be added as is.",
indexMetadata.getName());
if (index.loadFromConfiguration(idx)) {
addIndexInternal(index);
setDirty();
save();
ok++;
} else {
getDatabase().unregisterListener(index.getInternal());
index.delete();
errors++;
}
OLogManager.instance().info(this, "Index %s was added in DB index list.", index.getName());
} else {
String indexName = indexMetadata.getName();
Set<String> clusters = indexMetadata.getClustersToIndex();
String type = indexMetadata.getType();
if (indexName != null && indexDefinition != null && clusters != null && !clusters.isEmpty() && type != null) {
OLogManager.instance().info(this, "Start creation of index %s", indexName);
if (algorithm.equals(ODefaultIndexFactory.SBTREE_ALGORITHM) || indexType.endsWith("HASH_INDEX"))
index.deleteWithoutIndexLoad(indexName);
index.create(indexName, indexDefinition, defaultClusterName, clusters, false, new OIndexRebuildOutputListener(
index));
index.setRebuildingFlag();
addIndexInternal(index);
OLogManager.instance().info(this, "Index %s was successfully created and rebuild is going to be started.",
indexName);
index.rebuild(new OIndexRebuildOutputListener(index));
index.flush();
setDirty();
save();
ok++;
OLogManager.instance().info(this, "Rebuild of %s index was successfully finished.", indexName);
} else {
errors++;
OLogManager.instance().error(
this,
"Information about index was restored incorrectly, following data were loaded : "
+ "index name - %s, index definition %s, clusters %s, type %s.", indexName, indexDefinition, clusters,
type);
}
}
} catch (Exception e) {
OLogManager.instance().error(this, "Error during addition of index %s", e, idx);
errors++;
}
}
rebuildCompleted = true;
newDb.close();
OLogManager.instance().info(this, "%d indexes were restored successfully, %d errors", ok, errors);
} catch (Exception e) {
OLogManager.instance().error(this, "Error when attempt to restore indexes after crash was performed.", e);
}
}
}; | 1no label
| core_src_main_java_com_orientechnologies_orient_core_index_OIndexManagerShared.java |
1,157 | public class SimpleTimeBenchmark {
private static boolean USE_NANO_TIME = false;
private static long NUMBER_OF_ITERATIONS = 1000000;
private static int NUMBER_OF_THREADS = 100;
public static void main(String[] args) throws Exception {
StopWatch stopWatch = new StopWatch().start();
System.out.println("Running " + NUMBER_OF_ITERATIONS);
for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) {
System.currentTimeMillis();
}
System.out.println("Took " + stopWatch.stop().totalTime() + " TP Millis " + (NUMBER_OF_ITERATIONS / stopWatch.totalTime().millisFrac()));
System.out.println("Running using " + NUMBER_OF_THREADS + " threads with " + NUMBER_OF_ITERATIONS + " iterations");
final CountDownLatch latch = new CountDownLatch(NUMBER_OF_THREADS);
Thread[] threads = new Thread[NUMBER_OF_THREADS];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
if (USE_NANO_TIME) {
for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) {
System.nanoTime();
}
} else {
for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) {
System.currentTimeMillis();
}
}
latch.countDown();
}
});
}
stopWatch = new StopWatch().start();
for (Thread thread : threads) {
thread.start();
}
latch.await();
stopWatch.stop();
System.out.println("Took " + stopWatch.totalTime() + " TP Millis " + ((NUMBER_OF_ITERATIONS * NUMBER_OF_THREADS) / stopWatch.totalTime().millisFrac()));
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_time_SimpleTimeBenchmark.java |
1,360 | static class ShardRoutingEntry extends TransportRequest {
private ShardRouting shardRouting;
private String indexUUID = IndexMetaData.INDEX_UUID_NA_VALUE;
private String reason;
private ShardRoutingEntry() {
}
private ShardRoutingEntry(ShardRouting shardRouting, String indexUUID, String reason) {
this.shardRouting = shardRouting;
this.reason = reason;
this.indexUUID = indexUUID;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shardRouting = readShardRoutingEntry(in);
reason = in.readString();
indexUUID = in.readString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
shardRouting.writeTo(out);
out.writeString(reason);
out.writeString(indexUUID);
}
@Override
public String toString() {
return "" + shardRouting + ", indexUUID [" + indexUUID + "], reason [" + reason + "]";
}
} | 0true
| src_main_java_org_elasticsearch_cluster_action_shard_ShardStateAction.java |
3,265 | public class StringScriptDataComparator extends FieldComparator<BytesRef> {
public static IndexFieldData.XFieldComparatorSource comparatorSource(SearchScript script) {
return new InnerSource(script);
}
private static class InnerSource extends IndexFieldData.XFieldComparatorSource {
private final SearchScript script;
private InnerSource(SearchScript script) {
this.script = script;
}
@Override
public FieldComparator<?> newComparator(String fieldname, int numHits, int sortPos, boolean reversed) throws IOException {
return new StringScriptDataComparator(numHits, script);
}
@Override
public SortField.Type reducedType() {
return SortField.Type.STRING;
}
}
private final SearchScript script;
private BytesRef[] values; // TODO maybe we can preallocate or use a sentinel to prevent the conditionals in compare
private BytesRef bottom;
private final BytesRef spare = new BytesRef();
private int spareDoc = -1;
public StringScriptDataComparator(int numHits, SearchScript script) {
this.script = script;
values = new BytesRef[numHits];
}
@Override
public FieldComparator<BytesRef> setNextReader(AtomicReaderContext context) throws IOException {
script.setNextReader(context);
spareDoc = -1;
return this;
}
@Override
public void setScorer(Scorer scorer) {
script.setScorer(scorer);
}
@Override
public int compare(int slot1, int slot2) {
final BytesRef val1 = values[slot1];
final BytesRef val2 = values[slot2];
if (val1 == null) {
if (val2 == null) {
return 0;
}
return -1;
} else if (val2 == null) {
return 1;
}
return val1.compareTo(val2);
}
@Override
public int compareBottom(int doc) {
if (bottom == null) {
return -1;
}
setSpare(doc);
return bottom.compareTo(spare);
}
@Override
public int compareDocToValue(int doc, BytesRef val2) throws IOException {
script.setNextDocId(doc);
setSpare(doc);
return spare.compareTo(val2);
}
private void setSpare(int doc) {
if (spareDoc == doc) {
return;
}
script.setNextDocId(doc);
spare.copyChars(script.run().toString());
spareDoc = doc;
}
@Override
public void copy(int slot, int doc) {
setSpare(doc);
if (values[slot] == null) {
values[slot] = BytesRef.deepCopyOf(spare);
} else {
values[slot].copyBytes(spare);
}
}
@Override
public void setBottom(final int bottom) {
this.bottom = values[bottom];
}
@Override
public BytesRef value(int slot) {
return values[slot];
}
} | 1no label
| src_main_java_org_elasticsearch_index_fielddata_fieldcomparator_StringScriptDataComparator.java |
1,490 | public class BroadleafCheckoutController extends AbstractCheckoutController {
private static final Log LOG = LogFactory.getLog(BroadleafCheckoutController.class);
protected static String cartPageRedirect = "redirect:/cart";
protected static String checkoutView = "checkout/checkout";
protected static String checkoutPageRedirect = "redirect:/checkout";
protected static String multishipView = "checkout/multiship";
protected static String multishipAddAddressView = "checkout/multishipAddAddressForm";
protected static String multishipAddAddressSuccessView = "redirect:/checkout/multiship";
protected static String multishipSuccessView = "redirect:/checkout";
protected static String baseConfirmationView = "ajaxredirect:/confirmation";
/**
* Renders the default checkout page.
*
* @param request
* @param response
* @param model
* @return the return path
*/
public String checkout(HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
Order cart = CartState.getCart();
if (!(cart instanceof NullOrderImpl)) {
model.addAttribute("orderMultishipOptions", orderMultishipOptionService.getOrGenerateOrderMultishipOptions(cart));
}
populateModelWithShippingReferenceData(request, model);
return getCheckoutView();
}
/**
* Converts the order to singleship by collapsing all of the fulfillment groups into the
* default one
*
* @param request
* @param response
* @param model
* @return a redirect to /checkout
* @throws PricingException
*/
public String convertToSingleship(HttpServletRequest request, HttpServletResponse response, Model model) throws PricingException {
Order cart = CartState.getCart();
fulfillmentGroupService.collapseToOneFulfillmentGroup(cart, true);
return getCheckoutPageRedirect();
}
/**
* Attempts to attach the user's email to the order so that they may proceed anonymously
*
* @param request
* @param model
* @param errors
* @param emailAddress
* @return the return path
* @throws ServiceException
*/
public String saveGlobalOrderDetails(HttpServletRequest request, Model model,
OrderInfoForm orderInfoForm, BindingResult result) throws ServiceException {
Order cart = CartState.getCart();
orderInfoFormValidator.validate(orderInfoForm, result);
if (result.hasErrors()) {
// We need to clear the email on error in case they are trying to edit it
try {
cart.setEmailAddress(null);
orderService.save(cart, false);
} catch (PricingException pe) {
LOG.error("Error when saving the email address for order confirmation to the cart", pe);
}
populateModelWithShippingReferenceData(request, model);
return getCheckoutView();
}
try {
cart.setEmailAddress(orderInfoForm.getEmailAddress());
orderService.save(cart, false);
} catch (PricingException pe) {
LOG.error("Error when saving the email address for order confirmation to the cart", pe);
}
return getCheckoutPageRedirect();
}
/**
* Processes the request to save a single shipping address
*
* Note that the default Broadleaf implementation creates an order
* with a single fulfillment group. In the case of shipping to mutiple addresses,
* the multiship methods should be used.
*
* @param request
* @param response
* @param model
* @param shippingForm
* @return the return path
* @throws ServiceException
*/
public String saveSingleShip(HttpServletRequest request, HttpServletResponse response, Model model,
ShippingInfoForm shippingForm, BindingResult result) throws PricingException, ServiceException {
Order cart = CartState.getCart();
shippingInfoFormValidator.validate(shippingForm, result);
if (result.hasErrors()) {
putFulfillmentOptionsAndEstimationOnModel(model);
populateModelWithShippingReferenceData(request, model);
model.addAttribute("states", stateService.findStates());
model.addAttribute("countries", countryService.findCountries());
model.addAttribute("expirationMonths", populateExpirationMonths());
model.addAttribute("expirationYears", populateExpirationYears());
model.addAttribute("validShipping", false);
return getCheckoutView();
}
FulfillmentGroup fulfillmentGroup = cart.getFulfillmentGroups().get(0);
if ((shippingForm.getAddress().getPhonePrimary() != null) && (StringUtils.isEmpty(shippingForm.getAddress().getPhonePrimary().getPhoneNumber()))) {
shippingForm.getAddress().setPhonePrimary(null);
}
fulfillmentGroup.setAddress(shippingForm.getAddress());
fulfillmentGroup.setPersonalMessage(shippingForm.getPersonalMessage());
fulfillmentGroup.setDeliveryInstruction(shippingForm.getDeliveryMessage());
FulfillmentOption fulfillmentOption = fulfillmentOptionService.readFulfillmentOptionById(shippingForm.getFulfillmentOptionId());
fulfillmentGroup.setFulfillmentOption(fulfillmentOption);
cart = orderService.save(cart, true);
return isAjaxRequest(request) ? getCheckoutView() : getCheckoutPageRedirect();
}
public String savePaymentForm(HttpServletRequest request, HttpServletResponse response, Model model) throws PricingException {
//TODO: Implement
return isAjaxRequest(request) ? getCheckoutView() : getCheckoutPageRedirect();
}
/**
* Renders the multiship page. This page is used by the user when shipping items
* to different locations (or with different FulfillmentOptions) is desired.
*
* Note that the default Broadleaf implementation will require the user to input
* an Address and FulfillmentOption for each quantity of each DiscreteOrderItem.
*
* @param request
* @param response
* @param model
* @return the return path
*/
public String showMultiship(HttpServletRequest request, HttpServletResponse response, Model model) {
Customer customer = CustomerState.getCustomer();
Order cart = CartState.getCart();
model.addAttribute("orderMultishipOptions", orderMultishipOptionService.getOrGenerateOrderMultishipOptions(cart));
model.addAttribute("customerAddresses", customerAddressService.readActiveCustomerAddressesByCustomerId(customer.getId()));
model.addAttribute("fulfillmentOptions", fulfillmentOptionService.readAllFulfillmentOptions());
return getMultishipView();
}
/**
* Processes the given options for multiship. Validates that all options are
* selected before performing any actions.
*
* @see #showMultiship(HttpServletRequest, HttpServletResponse, Model)
*
* @param request
* @param response
* @param model
* @param orderMultishipOptionForm
* @return a redirect to the checkout page
* @throws PricingException
* @throws ServiceException
*/
public String saveMultiship(HttpServletRequest request, HttpServletResponse response, Model model,
OrderMultishipOptionForm orderMultishipOptionForm, BindingResult result) throws PricingException, ServiceException {
Order cart = CartState.getCart();
orderMultishipOptionService.saveOrderMultishipOptions(cart, orderMultishipOptionForm.getOptions());
cart = fulfillmentGroupService.matchFulfillmentGroupsToMultishipOptions(cart, true);
return getMultishipSuccessView();
}
/**
* Renders the add address form during the multiship process
*
* @param request
* @param response
* @param model
* @return the return path
*/
public String showMultishipAddAddress(HttpServletRequest request, HttpServletResponse response, Model model) {
model.addAttribute("states", stateService.findStates());
model.addAttribute("countries", countryService.findCountries());
return getMultishipAddAddressView();
}
/**
* Processes the requested add address from the multiship process.
* This method will create a CustomerAddress based on the requested Address
* and associate it with the current Customer in session.
*
* @param request
* @param response
* @param model
* @param addressForm
* @return the return path to the multiship page
* @throws ServiceException
*/
public String saveMultishipAddAddress(HttpServletRequest request, HttpServletResponse response, Model model,
ShippingInfoForm addressForm, BindingResult result) throws ServiceException {
multishipAddAddressFormValidator.validate(addressForm, result);
if (result.hasErrors()) {
return showMultishipAddAddress(request, response, model);
}
Address address = addressService.saveAddress(addressForm.getAddress());
CustomerAddress customerAddress = customerAddressService.create();
customerAddress.setAddressName(addressForm.getAddressName());
customerAddress.setAddress(address);
customerAddress.setCustomer(CustomerState.getCustomer());
customerAddressService.saveCustomerAddress(customerAddress);
//append current time to redirect to fix a problem with ajax caching in IE
return getMultishipAddAddressSuccessView() + "?_=" + System.currentTimeMillis();
}
public String saveMultiShipInstruction(HttpServletRequest request, HttpServletResponse response, Model model,
MultiShipInstructionForm instructionForm) throws ServiceException, PricingException {
Order cart = CartState.getCart();
FulfillmentGroup fulfillmentGroup = null;
for (FulfillmentGroup tempFulfillmentGroup : cart.getFulfillmentGroups()) {
if (tempFulfillmentGroup.getId().equals(instructionForm.getFulfillmentGroupId())) {
fulfillmentGroup = tempFulfillmentGroup;
}
}
fulfillmentGroup.setPersonalMessage(instructionForm.getPersonalMessage());
fulfillmentGroup.setDeliveryInstruction(instructionForm.getDeliveryMessage());
fulfillmentGroupService.save(fulfillmentGroup);
//append current time to redirect to fix a problem with ajax caching in IE
return getCheckoutPageRedirect()+ "?_=" + System.currentTimeMillis();
}
/**
* Processes the request to complete checkout
*
* If the paymentMethod is undefined or "creditCard" delegates to the "completeSecureCreditCardCheckout"
* method.
*
* Otherwise, returns an operation not supported.
*
* This method assumes that a credit card payment info
* will be either sent to a third party gateway or saved in a secure schema.
* If the transaction is successful, the order will be assigned an order number,
* its status change to SUBMITTED, and given a submit date. The method then
* returns the default confirmation path "/confirmation/{orderNumber}"
*
* If the transaction is unsuccessful, (e.g. the gateway declines payment)
* processFailedOrderCheckout() is called and reverses the state of the order.
*
* Note: this method removes any existing payment infos of type CREDIT_CARD
* and re-creates it with the information from the BillingInfoForm
*
* @param request
* @param response
* @param model
* @param billingForm
* @return the return path
* @throws ServiceException
*/
public String completeCheckout(HttpServletRequest request, HttpServletResponse response, Model model,
BillingInfoForm billingForm, BindingResult result) throws CheckoutException, PricingException, ServiceException {
if (billingForm.getPaymentMethod() == null || "credit_card".equals(billingForm.getPaymentMethod())) {
return completeSecureCreditCardCheckout(request, response, model, billingForm, result);
} else {
throw new IllegalArgumentException("Complete checkout called with payment Method " + billingForm.getPaymentMethod() + " which has not been implemented.");
}
}
/**
* Processes the request to complete checkout using a Credit Card
*
* This method assumes that a credit card payment info
* will be either sent to a third party gateway or saved in a secure schema.
* If the transaction is successful, the order will be assigned an order number,
* its status change to SUBMITTED, and given a submit date. The method then
* returns the default confirmation path "/confirmation/{orderNumber}"
*
* If the transaction is unsuccessful, (e.g. the gateway declines payment)
* processFailedOrderCheckout() is called and reverses the state of the order.
*
* Note: this method removes any existing payment infos of type CREDIT_CARD
* and re-creates it with the information from the BillingInfoForm
*
* @param request
* @param response
* @param model
* @param billingForm
* @return the return path
* @throws ServiceException
*/
public String completeSecureCreditCardCheckout(HttpServletRequest request, HttpServletResponse response, Model model,
BillingInfoForm billingForm, BindingResult result) throws PricingException, ServiceException {
Order cart = CartState.getCart();
if (cart != null) {
Map<PaymentInfo, Referenced> payments = new HashMap<PaymentInfo, Referenced>();
orderService.removePaymentsFromOrder(cart, PaymentInfoType.CREDIT_CARD);
if (billingForm.isUseShippingAddress()){
copyShippingAddressToBillingAddress(cart, billingForm);
}
billingInfoFormValidator.validate(billingForm, result);
if (result.hasErrors()) {
populateModelWithShippingReferenceData(request, model);
return getCheckoutView();
}
PaymentInfo ccInfo = creditCardPaymentInfoFactory.constructPaymentInfo(cart);
ccInfo.setAddress(billingForm.getAddress());
cart.getPaymentInfos().add(ccInfo);
CreditCardPaymentInfo ccReference = (CreditCardPaymentInfo) securePaymentInfoService.create(PaymentInfoType.CREDIT_CARD);
ccReference.setNameOnCard(billingForm.getCreditCardName());
ccReference.setReferenceNumber(ccInfo.getReferenceNumber());
ccReference.setPan(billingForm.getCreditCardNumber());
ccReference.setCvvCode(billingForm.getCreditCardCvvCode());
ccReference.setExpirationMonth(Integer.parseInt(billingForm.getCreditCardExpMonth()));
ccReference.setExpirationYear(Integer.parseInt(billingForm.getCreditCardExpYear()));
payments.put(ccInfo, ccReference);
CheckoutResponse checkoutResponse = null;
boolean checkoutError = false;
try {
checkoutResponse = checkoutService.performCheckout(cart, payments);
} catch (CheckoutException ex) {
checkoutError = true;
}
if (checkoutError || (checkoutResponse != null && !checkoutResponse.getPaymentResponse().getResponseItems().get(ccInfo).getTransactionSuccess())){
populateModelWithShippingReferenceData(request, model);
result.rejectValue("creditCardNumber", "payment.exception", null, null);
return getCheckoutView();
}
return getConfirmationView(cart.getOrderNumber());
}
return getCartPageRedirect();
}
/**
* This method will copy the shipping address of the first fulfillment group on the order
* to the billing address on the BillingInfoForm that is passed in.
*
* @param billingInfoForm
*/
protected void copyShippingAddressToBillingAddress(Order order, BillingInfoForm billingInfoForm) {
if (order.getFulfillmentGroups().get(0) != null) {
Address shipping = order.getFulfillmentGroups().get(0).getAddress();
if (shipping != null) {
Address billing = new AddressImpl();
billing.setFirstName(shipping.getFirstName());
billing.setLastName(shipping.getLastName());
billing.setAddressLine1(shipping.getAddressLine1());
billing.setAddressLine2(shipping.getAddressLine2());
billing.setCity(shipping.getCity());
billing.setState(shipping.getState());
billing.setPostalCode(shipping.getPostalCode());
billing.setCountry(shipping.getCountry());
billing.setPrimaryPhone(shipping.getPrimaryPhone());
billing.setEmailAddress(shipping.getEmailAddress());
billingInfoForm.setAddress(billing);
}
}
}
/**
* A helper method used to determine the validity of the fulfillment groups
*
* @param cart
* @return boolean indicating whether or not the fulfillment groups on the cart have addresses.
*/
protected boolean hasValidShippingAddresses(Order cart) {
if (cart.getFulfillmentGroups() == null) {
return false;
}
for (FulfillmentGroup fulfillmentGroup : cart.getFulfillmentGroups()) {
if (fulfillmentGroup.getAddress() == null || fulfillmentGroup.getFulfillmentOption() == null) {
return false;
}
}
return true;
}
/**
* A helper method used to determine the validity of order info
*
* @param cart
* @return boolean indicating whether or not the order has valid info
*/
protected boolean hasValidOrderInfo(Order cart) {
return StringUtils.isNotBlank(cart.getEmailAddress());
}
/**
* A helper method to retrieve all fulfillment options for the cart
*/
protected void putFulfillmentOptionsAndEstimationOnModel(Model model) {
List<FulfillmentOption> fulfillmentOptions = fulfillmentOptionService.readAllFulfillmentOptions();
Order cart = CartState.getCart();
if (!(cart instanceof NullOrderImpl) && cart.getFulfillmentGroups().size() > 0 && hasValidShippingAddresses(cart)) {
Set<FulfillmentOption> options = new HashSet<FulfillmentOption>();
options.addAll(fulfillmentOptions);
FulfillmentEstimationResponse estimateResponse = null;
try {
estimateResponse = fulfillmentPricingService.estimateCostForFulfillmentGroup(cart.getFulfillmentGroups().get(0), options);
} catch (FulfillmentPriceException e) {
}
model.addAttribute("estimateResponse", estimateResponse);
}
model.addAttribute("fulfillmentOptions", fulfillmentOptions);
}
/**
* A helper method used to construct a list of Credit Card Expiration Months
* Useful for expiration dropdown menus.
* Will use locale to determine language if a locale is available.
*
* @return List containing expiration months of the form "01 - January"
*/
protected List<String> populateExpirationMonths() {
DateFormatSymbols dateFormatter;
if(BroadleafRequestContext.hasLocale()){
Locale locale = BroadleafRequestContext.getBroadleafRequestContext().getJavaLocale();
dateFormatter = new DateFormatSymbols(locale);
} else {
dateFormatter = new DateFormatSymbols();
}
List<String> expirationMonths = new ArrayList<String>();
NumberFormat formatter = new DecimalFormat("00");
String[] months = dateFormatter.getMonths();
for (int i=1; i<months.length; i++) {
expirationMonths.add(formatter.format(i) + " - " + months[i-1]);
}
return expirationMonths;
}
/**
* A helper method used to construct a list of Credit Card Expiration Years
* Useful for expiration dropdown menus.
*
* @return List of the next ten years starting with the current year.
*/
protected List<String> populateExpirationYears() {
List<String> expirationYears = new ArrayList<String>();
DateTime dateTime = new DateTime();
for (int i=0; i<10; i++){
expirationYears.add(dateTime.plusYears(i).getYear()+"");
}
return expirationYears;
}
/**
* Initializes some custom binding operations for the checkout flow.
* More specifically, this method will attempt to bind state and country
* abbreviations to actual State and Country objects when the String
* representation of the abbreviation is submitted.
*
* @param request
* @param binder
* @throws Exception
*/
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(State.class, "address.state", new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
if (StringUtils.isNotEmpty(text)) {
State state = stateService.findStateByAbbreviation(text);
setValue(state);
} else {
setValue(null);
}
}
});
binder.registerCustomEditor(Country.class, "address.country", new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
Country country = countryService.findCountryByAbbreviation(text);
setValue(country);
}
});
binder.registerCustomEditor(Phone.class, "address.phonePrimary", new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
if (!StringUtils.isBlank(text)) {
Phone phone = new PhoneImpl();
phone.setPhoneNumber(text);
setValue(phone);
} else {
setValue(null);
}
}
});
}
protected void populateModelWithShippingReferenceData(HttpServletRequest request, Model model) {
String editOrderInfo = request.getParameter("edit-order-info");
boolean hasValidOrderInfo;
if (BooleanUtils.toBoolean(editOrderInfo)) {
hasValidOrderInfo = false;
} else {
hasValidOrderInfo = hasValidOrderInfo(CartState.getCart());
}
model.addAttribute("validOrderInfo", hasValidOrderInfo);
String editShipping = request.getParameter("edit-shipping");
boolean hasValidShipping;
if (BooleanUtils.toBoolean(editShipping)) {
hasValidShipping = false;
} else {
hasValidShipping = hasValidShippingAddresses(CartState.getCart());
}
model.addAttribute("validShipping", hasValidShipping);
putFulfillmentOptionsAndEstimationOnModel(model);
model.addAttribute("states", stateService.findStates());
model.addAttribute("countries", countryService.findCountries());
model.addAttribute("expirationMonths", populateExpirationMonths());
model.addAttribute("expirationYears", populateExpirationYears());
}
public String getCartPageRedirect() {
return cartPageRedirect;
}
public String getCheckoutView() {
return checkoutView;
}
public String getCheckoutPageRedirect() {
return checkoutPageRedirect;
}
public String getMultishipView() {
return multishipView;
}
public String getMultishipAddAddressView() {
return multishipAddAddressView;
}
public String getMultishipSuccessView() {
return multishipSuccessView;
}
public String getMultishipAddAddressSuccessView() {
return multishipAddAddressSuccessView;
}
public String getBaseConfirmationView() {
return baseConfirmationView;
}
protected String getConfirmationView(String orderNumber) {
return getBaseConfirmationView() + "/" + orderNumber;
}
} | 1no label
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_checkout_BroadleafCheckoutController.java |
243 | public class OCacheLevelTwoLocatorRemote implements OCacheLevelTwoLocator {
@Override
public OCache primaryCache(String storageName) {
return new OEmptyCache();
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_cache_OCacheLevelTwoLocatorRemote.java |
1,176 | public class OQueryOperatorContainsText extends OQueryTargetOperator {
private boolean ignoreCase = true;
public OQueryOperatorContainsText(final boolean iIgnoreCase) {
super("CONTAINSTEXT", 5, false);
ignoreCase = iIgnoreCase;
}
public OQueryOperatorContainsText() {
super("CONTAINSTEXT", 5, false);
}
@Override
public String getSyntax() {
return "<left> CONTAINSTEXT[( noignorecase ] )] <right>";
}
/**
* This is executed on non-indexed fields.
*/
@Override
public Object evaluateRecord(final OIdentifiable iRecord, ODocument iCurrentResult, final OSQLFilterCondition iCondition,
final Object iLeft, final Object iRight, OCommandContext iContext) {
if (iLeft == null || iRight == null)
return false;
return iLeft.toString().indexOf(iRight.toString()) > -1;
}
@SuppressWarnings({ "unchecked", "deprecation" })
@Override
public Collection<OIdentifiable> filterRecords(final ODatabaseComplex<?> iDatabase, final List<String> iTargetClasses,
final OSQLFilterCondition iCondition, final Object iLeft, final Object iRight) {
final String fieldName;
if (iCondition.getLeft() instanceof OSQLFilterItemField)
fieldName = iCondition.getLeft().toString();
else
fieldName = iCondition.getRight().toString();
final String fieldValue;
if (iCondition.getLeft() instanceof OSQLFilterItemField)
fieldValue = iCondition.getRight().toString();
else
fieldValue = iCondition.getLeft().toString();
final String className = iTargetClasses.get(0);
final OProperty prop = iDatabase.getMetadata().getSchema().getClass(className).getProperty(fieldName);
if (prop == null)
// NO PROPERTY DEFINED
return null;
OIndex<?> fullTextIndex = null;
for (final OIndex<?> indexDefinition : prop.getIndexes()) {
if (indexDefinition instanceof OIndexFullText) {
fullTextIndex = indexDefinition;
break;
}
}
if (fullTextIndex == null) {
return null;
}
return (Collection<OIdentifiable>) fullTextIndex.get(fieldValue);
}
public boolean isIgnoreCase() {
return ignoreCase;
}
@Override
public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) {
return OIndexReuseType.INDEX_METHOD;
}
@Override
public Object executeIndexQuery(OCommandContext iContext, OIndex<?> index, INDEX_OPERATION_TYPE iOperationType,
List<Object> keyParams, IndexResultListener resultListener, int fetchLimit) {
final OIndexDefinition indexDefinition = index.getDefinition();
if (indexDefinition.getParamCount() > 1)
return null;
final OIndex<?> internalIndex = index.getInternal();
final Object result;
if (internalIndex instanceof OIndexFullText) {
final Object indexResult = index.get(indexDefinition.createValue(keyParams));
if (indexResult instanceof Collection)
result = indexResult;
else if (indexResult == null)
result = Collections.emptyList();
else
result = Collections.singletonList((OIdentifiable) indexResult);
} else
return null;
updateProfiler(iContext, internalIndex, keyParams, indexDefinition);
if (iOperationType == INDEX_OPERATION_TYPE.COUNT)
return ((Collection<?>) result).size();
return result;
}
@Override
public ORID getBeginRidRange(Object iLeft, Object iRight) {
return null;
}
@Override
public ORID getEndRidRange(Object iLeft, Object iRight) {
return null;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorContainsText.java |
1,278 | public class ClusterChangedEvent {
private final String source;
private final ClusterState previousState;
private final ClusterState state;
private final DiscoveryNodes.Delta nodesDelta;
public ClusterChangedEvent(String source, ClusterState state, ClusterState previousState) {
this.source = source;
this.state = state;
this.previousState = previousState;
this.nodesDelta = state.nodes().delta(previousState.nodes());
}
/**
* The source that caused this cluster event to be raised.
*/
public String source() {
return this.source;
}
public ClusterState state() {
return this.state;
}
public ClusterState previousState() {
return this.previousState;
}
public boolean routingTableChanged() {
return state.routingTable() != previousState.routingTable();
}
public boolean indexRoutingTableChanged(String index) {
if (!state.routingTable().hasIndex(index) && !previousState.routingTable().hasIndex(index)) {
return false;
}
if (state.routingTable().hasIndex(index) && previousState.routingTable().hasIndex(index)) {
return state.routingTable().index(index) != previousState.routingTable().index(index);
}
return true;
}
/**
* Returns the indices created in this event
*/
public List<String> indicesCreated() {
if (previousState == null) {
return Arrays.asList(state.metaData().indices().keys().toArray(String.class));
}
if (!metaDataChanged()) {
return ImmutableList.of();
}
List<String> created = null;
for (ObjectCursor<String> cursor : state.metaData().indices().keys()) {
String index = cursor.value;
if (!previousState.metaData().hasIndex(index)) {
if (created == null) {
created = Lists.newArrayList();
}
created.add(index);
}
}
return created == null ? ImmutableList.<String>of() : created;
}
/**
* Returns the indices deleted in this event
*/
public List<String> indicesDeleted() {
if (previousState == null) {
return ImmutableList.of();
}
if (!metaDataChanged()) {
return ImmutableList.of();
}
List<String> deleted = null;
for (ObjectCursor<String> cursor : previousState.metaData().indices().keys()) {
String index = cursor.value;
if (!state.metaData().hasIndex(index)) {
if (deleted == null) {
deleted = Lists.newArrayList();
}
deleted.add(index);
}
}
return deleted == null ? ImmutableList.<String>of() : deleted;
}
public boolean metaDataChanged() {
return state.metaData() != previousState.metaData();
}
public boolean indexMetaDataChanged(IndexMetaData current) {
MetaData previousMetaData = previousState.metaData();
if (previousMetaData == null) {
return true;
}
IndexMetaData previousIndexMetaData = previousMetaData.index(current.index());
// no need to check on version, since disco modules will make sure to use the
// same instance if its a version match
if (previousIndexMetaData == current) {
return false;
}
return true;
}
public boolean blocksChanged() {
return state.blocks() != previousState.blocks();
}
public boolean localNodeMaster() {
return state.nodes().localNodeMaster();
}
public DiscoveryNodes.Delta nodesDelta() {
return this.nodesDelta;
}
public boolean nodesRemoved() {
return nodesDelta.removed();
}
public boolean nodesAdded() {
return nodesDelta.added();
}
public boolean nodesChanged() {
return nodesRemoved() || nodesAdded();
}
} | 0true
| src_main_java_org_elasticsearch_cluster_ClusterChangedEvent.java |
761 | public class ListReplicationOperation extends CollectionReplicationOperation {
public ListReplicationOperation() {
}
public ListReplicationOperation(Map<String, CollectionContainer> migrationData, int partitionId, int replicaIndex) {
super(migrationData, partitionId, replicaIndex);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
int mapSize = in.readInt();
migrationData = new HashMap<String, CollectionContainer>(mapSize);
for (int i = 0; i < mapSize; i++) {
String name = in.readUTF();
ListContainer container = new ListContainer();
container.readData(in);
migrationData.put(name, container);
}
}
@Override
public int getId() {
return CollectionDataSerializerHook.LIST_REPLICATION;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_list_ListReplicationOperation.java |
172 | public class BroadleafProcessURLFilter extends OncePerRequestFilter {
private final Log LOG = LogFactory.getLog(BroadleafProcessURLFilter.class);
// List of URLProcessors
private List<URLProcessor> urlProcessorList = new ArrayList<URLProcessor>();
// Cache-settings
// by default, expire cache every four hours (4 hours * 60 minutes * 60 seconds)
private int cacheExpirationSeconds = 4 * 60 * 60;
private int maxCacheElements = 10000;
private int maxCacheConcurrency = 3;
private Cache<String, URLProcessor> urlCache;
@Resource(name = "blSandBoxService")
private SandBoxService sandBoxService;
@Resource(name = "blLocaleService")
private LocaleService localeService;
protected Boolean sandBoxPreviewEnabled = true;
/**
* Parameter/Attribute name for the current language
*/
public static String LOCALE_VAR = "blLocale";
/**
* Parameter/Attribute name for the current language
*/
public static String LOCALE_CODE_PARAM = "blLocaleCode";
/**
* Parameter/Attribute name for the current language
*/
public static String REQUEST_DTO = "blRequestDTO";
/**
* Request attribute to store the current sandbox
*/
public static String SANDBOX_VAR = "blSandbox";
// Properties to manage URLs that will not be processed by this filter.
private static final String BLC_ADMIN_GWT = "org.broadleafcommerce.admin";
private static final String BLC_ADMIN_PREFIX = "blcadmin";
private static final String BLC_ADMIN_SERVICE = ".service";
private HashSet<String> ignoreSuffixes;
// Request Parameters and Attributes for Sandbox Mode properties - mostly date values.
private static String SANDBOX_ID_VAR = "blSandboxId";
private static String SANDBOX_DATE_TIME_VAR = "blSandboxDateTime";
private static final SimpleDateFormat CONTENT_DATE_FORMATTER = new SimpleDateFormat("yyyyMMddHHmm");
private static final SimpleDateFormat CONTENT_DATE_DISPLAY_FORMATTER = new SimpleDateFormat("MM/dd/yyyy");
private static final SimpleDateFormat CONTENT_DATE_DISPLAY_HOURS_FORMATTER = new SimpleDateFormat("h");
private static final SimpleDateFormat CONTENT_DATE_DISPLAY_MINUTES_FORMATTER = new SimpleDateFormat("mm");
private static final SimpleDateFormat CONTENT_DATE_PARSE_FORMAT = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
private static String SANDBOX_DATE_TIME_RIBBON_OVERRIDE_PARAM = "blSandboxDateTimeRibbonOverride";
private static final String SANDBOX_DISPLAY_DATE_TIME_DATE_PARAM = "blSandboxDisplayDateTimeDate";
private static final String SANDBOX_DISPLAY_DATE_TIME_HOURS_PARAM = "blSandboxDisplayDateTimeHours";
private static final String SANDBOX_DISPLAY_DATE_TIME_MINUTES_PARAM = "blSandboxDisplayDateTimeMinutes";
private static final String SANDBOX_DISPLAY_DATE_TIME_AMPM_PARAM = "blSandboxDisplayDateTimeAMPM";
/**
* (non-Javadoc)
*
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
if (!shouldProcessURL(request, request.getRequestURI())) {
if (LOG.isTraceEnabled()) {
LOG.trace("Process URL not processing URL " + request.getRequestURI());
}
filterChain.doFilter(request, response);
return;
}
final String requestURIWithoutContext;
if (request.getContextPath() != null) {
requestURIWithoutContext = request.getRequestURI().substring(request.getContextPath().length());
} else {
requestURIWithoutContext = request.getRequestURI();
}
if (LOG.isTraceEnabled()) {
LOG.trace("Process URL Filter Begin " + requestURIWithoutContext);
}
if (request.getAttribute(REQUEST_DTO) == null) {
request.setAttribute(REQUEST_DTO, new RequestDTOImpl(request));
}
Site site = determineSite(request);
SandBox currentSandbox = determineSandbox(request, site);
BroadleafRequestContext brc = new BroadleafRequestContext();
brc.setLocale(determineLocale(request, site));
brc.setSandbox(currentSandbox);
brc.setRequest(request);
brc.setResponse(response);
BroadleafRequestContext.setBroadleafRequestContext(brc);
try {
URLProcessor urlProcessor = null;
if (isProduction(currentSandbox)) {
try {
urlProcessor = lookupProcessorFromCache(requestURIWithoutContext);
} catch (ExecutionException e) {
LOG.error(e);
}
}
if (urlProcessor == null) {
urlProcessor = determineURLProcessor(requestURIWithoutContext);
}
if (urlProcessor instanceof NullURLProcessor) {
// Pass request down the filter chain
if (LOG.isTraceEnabled()) {
LOG.trace("URL not being processed by a Broadleaf URLProcessor " + requestURIWithoutContext);
}
StatusExposingServletResponse sesResponse = new StatusExposingServletResponse(response);
filterChain.doFilter(request, sesResponse);
if (sesResponse.getStatus() == sesResponse.SC_NOT_FOUND) {
if (LOG.isWarnEnabled()) {
LOG.warn("Page not found. Unable to render " + requestURIWithoutContext);
}
urlCache.invalidate(requestURIWithoutContext);
}
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("URL about to be processed by a Broadleaf URLProcessor " + requestURIWithoutContext);
}
urlProcessor.processURL(requestURIWithoutContext);
}
} finally {
// If the system-time was overridden, set it back to normal
SystemTime.resetLocalTimeSource();
}
}
/**
* Returns true if the passed in sandbox is null or is of type SandBoxType.PRODUCTION.
*
* @param sandbox
* @return
*/
private boolean isProduction(SandBox sandbox) {
return (sandbox == null) || (SandBoxType.PRODUCTION.equals(sandbox));
}
/**
* Builds a cache for each URL that determines how it should be processed.
*
* @return
*/
private URLProcessor lookupProcessorFromCache(String requestURIWithoutContextPath) throws ExecutionException {
if (urlCache == null) {
urlCache = CacheBuilder.newBuilder()
.maximumSize(maxCacheElements)
.concurrencyLevel(maxCacheConcurrency)
.expireAfterWrite(cacheExpirationSeconds, TimeUnit.SECONDS)
.build(new CacheLoader<String,URLProcessor>() {
public URLProcessor load(String key) throws IOException, ServletException {
if (LOG.isDebugEnabled()) {
LOG.debug("Loading URL processor into Cache");
}
return determineURLProcessor(key);
}
});
}
return urlCache.getIfPresent(requestURIWithoutContextPath);
}
private URLProcessor determineURLProcessor(String requestURI) {
for (URLProcessor processor: getUrlProcessorList()) {
if (processor.canProcessURL(requestURI)) {
if (LOG.isDebugEnabled()) {
LOG.debug("URLProcessor found for URI " + requestURI + " - " + processor.getClass().getName());
}
return processor;
}
}
// Indicates that this URL is not handled by a URLProcessor
return NullURLProcessor.getInstance();
}
/**
* Determines if the passed in URL should be processed by the content management system.
* <p/>
* By default, this method returns false for any BLC-Admin URLs and service calls and for all
* common image/digital mime-types (as determined by an internal call to {@code getIgnoreSuffixes}.
* <p/>
* This check is called with the {@code doFilterInternal} method to short-circuit the content
* processing which can be expensive for requests that do not require it.
*
* @param requestURI - the HttpServletRequest.getRequestURI
* @return true if the {@code HttpServletRequest} should be processed
*/
protected boolean shouldProcessURL(HttpServletRequest request, String requestURI) {
if (requestURI.contains(BLC_ADMIN_GWT) ||
requestURI.endsWith(BLC_ADMIN_SERVICE) ||
requestURI.contains(BLC_ADMIN_PREFIX)) {
if (LOG.isTraceEnabled()) {
LOG.trace("BroadleafProcessURLFilter ignoring admin request URI " + requestURI);
}
return false;
} else {
int pos = requestURI.lastIndexOf(".");
if (pos > 0) {
String suffix = requestURI.substring(pos);
if (getIgnoreSuffixes().contains(suffix.toLowerCase())) {
if (LOG.isTraceEnabled()) {
LOG.trace("BroadleafProcessURLFilter ignoring request due to suffix " + requestURI);
}
return false;
}
}
}
return true;
}
private SandBox determineSandbox(HttpServletRequest request, Site site) {
SandBox currentSandbox = null;
if (!sandBoxPreviewEnabled) {
if (LOG.isTraceEnabled()) {
LOG.trace("Sandbox preview disabled. Setting sandbox to production");
}
request.setAttribute(SANDBOX_VAR, currentSandbox);
} else {
Long sandboxId = null;
if (request.getParameter("blSandboxDateTimeRibbonProduction") == null) {
sandboxId = lookupSandboxId(request);
} else {
request.getSession().removeAttribute(SANDBOX_DATE_TIME_VAR);
request.getSession().removeAttribute(SANDBOX_ID_VAR);
}
if (sandboxId != null) {
currentSandbox = sandBoxService.retrieveSandboxById(sandboxId);
request.setAttribute(SANDBOX_VAR, currentSandbox);
if (currentSandbox != null && !SandBoxType.PRODUCTION.equals(currentSandbox.getSandBoxType())) {
setContentTime(request);
}
}
if (currentSandbox == null && site != null) {
currentSandbox = site.getProductionSandbox();
}
}
if (LOG.isTraceEnabled()) {
LOG.trace("Serving request using sandbox: " + currentSandbox);
}
Date currentSystemDateTime = SystemTime.asDate(true);
Calendar sandboxDateTimeCalendar = Calendar.getInstance();
sandboxDateTimeCalendar.setTime(currentSystemDateTime);
request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_DATE_PARAM, CONTENT_DATE_DISPLAY_FORMATTER.format(currentSystemDateTime));
request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_HOURS_PARAM, CONTENT_DATE_DISPLAY_HOURS_FORMATTER.format(currentSystemDateTime));
request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_MINUTES_PARAM, CONTENT_DATE_DISPLAY_MINUTES_FORMATTER.format(currentSystemDateTime));
request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_AMPM_PARAM, sandboxDateTimeCalendar.get(Calendar.AM_PM));
return currentSandbox;
}
/**
* If another filter has already set the language as a request attribute, that will be honored.
* Otherwise, the request parameter is checked followed by the session attribute.
*
* @param request
* @param site
* @return
*/
private Locale determineLocale(HttpServletRequest request, Site site) {
Locale locale = null;
// First check for request attribute
locale = (Locale) request.getAttribute(LOCALE_VAR);
// Second, check for a request parameter
if (locale == null && request.getParameter(LOCALE_CODE_PARAM) != null) {
String localeCode = request.getParameter(LOCALE_CODE_PARAM);
locale = localeService.findLocaleByCode(localeCode);
if (LOG.isTraceEnabled()) {
LOG.trace("Attempt to find locale by param " + localeCode + " resulted in " + locale);
}
}
// Third, check the session
if (locale == null) {
HttpSession session = request.getSession(true);
if (session != null) {
locale = (Locale) session.getAttribute(LOCALE_VAR);
}
if (LOG.isTraceEnabled()) {
LOG.trace("Attempt to find locale from session resulted in " + locale);
}
}
// Finally, use the default
if (locale == null) {
locale = localeService.findDefaultLocale();
if (LOG.isTraceEnabled()) {
LOG.trace("Locale set to default locale " + locale);
}
}
request.setAttribute(LOCALE_VAR, locale);
request.getSession().setAttribute(LOCALE_VAR, locale);
Map<String, Object> ruleMap = (Map<String, Object>) request.getAttribute("blRuleMap");
if (ruleMap == null) {
ruleMap = new HashMap<String, Object>();
request.setAttribute("blRuleMap", ruleMap);
}
ruleMap.put("locale", locale);
return locale;
}
private Long lookupSandboxId(HttpServletRequest request) {
String sandboxIdStr = request.getParameter(SANDBOX_ID_VAR);
Long sandboxId = null;
if (sandboxIdStr != null) {
try {
sandboxId = Long.valueOf(sandboxIdStr);
if (LOG.isTraceEnabled()) {
LOG.trace("SandboxId found on request " + sandboxId);
}
} catch (NumberFormatException nfe) {
LOG.warn("blcSandboxId parameter could not be converted into a Long", nfe);
}
}
if (sandboxId == null) {
// check the session
HttpSession session = request.getSession(false);
if (session != null) {
sandboxId = (Long) session.getAttribute(SANDBOX_ID_VAR);
if (LOG.isTraceEnabled()) {
if (sandboxId != null) {
LOG.trace("SandboxId found in session " + sandboxId);
}
}
}
} else {
HttpSession session = request.getSession();
session.setAttribute(SANDBOX_ID_VAR, sandboxId);
}
return sandboxId;
}
private void setContentTime(HttpServletRequest request) {
String sandboxDateTimeParam = request.getParameter(SANDBOX_DATE_TIME_VAR);
if (sandBoxPreviewEnabled) {
sandboxDateTimeParam = null;
}
Date overrideTime = null;
try {
if (request.getParameter(SANDBOX_DATE_TIME_RIBBON_OVERRIDE_PARAM) != null) {
overrideTime = readDateFromRequest(request);
} else if (sandboxDateTimeParam != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Setting date/time using " + sandboxDateTimeParam);
}
overrideTime = CONTENT_DATE_FORMATTER.parse(sandboxDateTimeParam);
}
} catch (ParseException e) {
LOG.debug(e);
}
if (overrideTime == null) {
HttpSession session = request.getSession(false);
if (session != null) {
overrideTime = (Date) session.getAttribute(SANDBOX_DATE_TIME_VAR);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Setting date-time for sandbox mode to " + overrideTime + " for sandboxDateTimeParam = " + sandboxDateTimeParam);
}
HttpSession session = request.getSession();
session.setAttribute(SANDBOX_DATE_TIME_VAR, overrideTime);
}
if (overrideTime != null) {
FixedTimeSource ft = new FixedTimeSource(overrideTime.getTime());
SystemTime.setLocalTimeSource(ft);
} else {
SystemTime.resetLocalTimeSource();
}
}
private Date readDateFromRequest(HttpServletRequest request) throws ParseException {
String date = request.getParameter(SANDBOX_DISPLAY_DATE_TIME_DATE_PARAM);
String minutes = request.getParameter(SANDBOX_DISPLAY_DATE_TIME_MINUTES_PARAM);
String hours = request.getParameter(SANDBOX_DISPLAY_DATE_TIME_HOURS_PARAM);
String ampm = request.getParameter(SANDBOX_DISPLAY_DATE_TIME_AMPM_PARAM);
if (StringUtils.isEmpty(minutes)) {
minutes = Integer.toString(SystemTime.asCalendar().get(Calendar.MINUTE));
}
if (StringUtils.isEmpty(hours)) {
hours = Integer.toString(SystemTime.asCalendar().get(Calendar.HOUR_OF_DAY));
}
String dateString = date + " " + hours + ":" + minutes + " " + ampm;
if (LOG.isDebugEnabled()) {
LOG.debug("Setting date/time using " + dateString);
}
Date parsedDate = CONTENT_DATE_PARSE_FORMAT.parse(dateString);
return parsedDate;
}
private Site determineSite(ServletRequest request) {
/* TODO: Multi-tennant: Need to add code that determines the site to support
SiteService.retrieveAllSites();
For each site, check the identifier type (e.g. hostname, url, param)
to determine the current site.
*/
return null;
}
/**
* Returns a set of suffixes that can be ignored by content processing. The following
* are returned:
* <p/>
* <B>List of suffixes ignored:</B>
*
* ".aif", ".aiff", ".asf", ".avi", ".bin", ".bmp", ".doc", ".eps", ".gif", ".hqx", ".jpg", ".jpeg", ".mid", ".midi", ".mov", ".mp3", ".mpg", ".mpeg", ".p65", ".pdf", ".pic", ".pict", ".png", ".ppt", ".psd", ".qxd", ".ram", ".ra", ".rm", ".sea", ".sit", ".stk", ".swf", ".tif", ".tiff", ".txt", ".rtf", ".vob", ".wav", ".wmf", ".xls", ".zip";
*
* @return set of suffixes to ignore.
*/
protected Set getIgnoreSuffixes() {
if (ignoreSuffixes == null || ignoreSuffixes.isEmpty()) {
String[] ignoreSuffixList = {".aif", ".aiff", ".asf", ".avi", ".bin", ".bmp", ".css", ".doc", ".eps", ".gif", ".hqx", ".js", ".jpg", ".jpeg", ".mid", ".midi", ".mov", ".mp3", ".mpg", ".mpeg", ".p65", ".pdf", ".pic", ".pict", ".png", ".ppt", ".psd", ".qxd", ".ram", ".ra", ".rm", ".sea", ".sit", ".stk", ".swf", ".tif", ".tiff", ".txt", ".rtf", ".vob", ".wav", ".wmf", ".xls", ".zip"};
ignoreSuffixes = new HashSet<String>(Arrays.asList(ignoreSuffixList));
}
return ignoreSuffixes;
}
public int getMaxCacheElements() {
return maxCacheElements;
}
public void setMaxCacheElements(int maxCacheElements) {
this.maxCacheElements = maxCacheElements;
}
public int getCacheExpirationSeconds() {
return cacheExpirationSeconds;
}
public void setCacheExpirationSeconds(int cacheExpirationSeconds) {
this.cacheExpirationSeconds = cacheExpirationSeconds;
}
public int getMaxCacheConcurrency() {
return maxCacheConcurrency;
}
public void setMaxCacheConcurrency(int maxCacheConcurrency) {
this.maxCacheConcurrency = maxCacheConcurrency;
}
public List<URLProcessor> getUrlProcessorList() {
return urlProcessorList;
}
public void setUrlProcessorList(List<URLProcessor> urlProcessorList) {
this.urlProcessorList = urlProcessorList;
}
public Boolean getSandBoxPreviewEnabled() {
return sandBoxPreviewEnabled;
}
public void setSandBoxPreviewEnabled(Boolean sandBoxPreviewEnabled) {
this.sandBoxPreviewEnabled = sandBoxPreviewEnabled;
}
} | 1no label
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_web_BroadleafProcessURLFilter.java |
593 | public class EmailStatusHandler implements StatusHandler {
@Resource(name="blEmailService")
protected EmailService emailService;
protected EmailInfo emailInfo;
protected EmailTarget emailTarget;
public void handleStatus(String serviceName, ServiceStatusType status) {
String message = serviceName + " is reporting a status of " + status.getType();
EmailInfo copy = emailInfo.clone();
copy.setMessageBody(message);
copy.setSubject(message);
emailService.sendBasicEmail(copy, emailTarget, null);
}
public EmailInfo getEmailInfo() {
return emailInfo;
}
public void setEmailInfo(EmailInfo emailInfo) {
this.emailInfo = emailInfo;
}
public EmailTarget getEmailTarget() {
return emailTarget;
}
public void setEmailTarget(EmailTarget emailTarget) {
this.emailTarget = emailTarget;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_vendor_service_monitor_handler_EmailStatusHandler.java |
4,201 | public class RateLimitingInputStream extends InputStream {
private final InputStream delegate;
private final RateLimiter rateLimiter;
private final Listener listener;
public interface Listener {
void onPause(long nanos);
}
public RateLimitingInputStream(InputStream delegate, RateLimiter rateLimiter, Listener listener) {
this.delegate = delegate;
this.rateLimiter = rateLimiter;
this.listener = listener;
}
@Override
public int read() throws IOException {
int b = delegate.read();
long pause = rateLimiter.pause(1);
if (pause > 0) {
listener.onPause(pause);
}
return b;
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int n = delegate.read(b, off, len);
if (n > 0) {
listener.onPause(rateLimiter.pause(n));
}
return n;
}
@Override
public long skip(long n) throws IOException {
return delegate.skip(n);
}
@Override
public int available() throws IOException {
return delegate.available();
}
@Override
public void close() throws IOException {
delegate.close();
}
@Override
public void mark(int readlimit) {
delegate.mark(readlimit);
}
@Override
public void reset() throws IOException {
delegate.reset();
}
@Override
public boolean markSupported() {
return delegate.markSupported();
}
} | 1no label
| src_main_java_org_elasticsearch_index_snapshots_blobstore_RateLimitingInputStream.java |