Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
2,484 | public static final Params EMPTY_PARAMS = new Params() {
@Override
public String param(String key) {
return null;
}
@Override
public String param(String key, String defaultValue) {
return defaultValue;
}
@Override
public boolean paramAsBoolean(String key, boolean defaultValue) {
return defaultValue;
}
@Override
public Boolean paramAsBoolean(String key, Boolean defaultValue) {
return defaultValue;
}
@Override @Deprecated
public Boolean paramAsBooleanOptional(String key, Boolean defaultValue) {
return paramAsBoolean(key, defaultValue);
}
}; | 0true
| src_main_java_org_elasticsearch_common_xcontent_ToXContent.java |
2,824 | private static class LocalPartitionListener implements PartitionListener {
final Address thisAddress;
private InternalPartitionServiceImpl partitionService;
private LocalPartitionListener(InternalPartitionServiceImpl partitionService, Address thisAddress) {
this.thisAddress = thisAddress;
this.partitionService = partitionService;
}
@Override
public void replicaChanged(PartitionReplicaChangeEvent event) {
int replicaIndex = event.getReplicaIndex();
Address newAddress = event.getNewAddress();
if (replicaIndex > 0) {
// backup replica owner changed!
int partitionId = event.getPartitionId();
if (thisAddress.equals(event.getOldAddress())) {
InternalPartitionImpl partition = partitionService.partitions[partitionId];
if (!partition.isOwnerOrBackup(thisAddress)) {
partitionService.clearPartitionReplica(partitionId, replicaIndex);
}
} else if (thisAddress.equals(newAddress)) {
partitionService.clearPartitionReplica(partitionId, replicaIndex);
partitionService.forcePartitionReplicaSync(partitionId, replicaIndex);
}
}
Node node = partitionService.node;
if (replicaIndex == 0 && newAddress == null && node.isActive() && node.joined()) {
logOwnerOfPartitionIsRemoved(event);
}
if (partitionService.node.isMaster()) {
partitionService.stateVersion.incrementAndGet();
}
}
private void logOwnerOfPartitionIsRemoved(PartitionReplicaChangeEvent event) {
String warning = "Owner of partition is being removed! "
+ "Possible data loss for partition[" + event.getPartitionId() + "]. " + event;
partitionService.logger.warning(warning);
partitionService.systemLogService.logWarningPartition(warning);
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_partition_impl_InternalPartitionServiceImpl.java |
882 | public class OQueryBlock extends OAbstractBlock {
public static final String NAME = "query";
@Override
public Object processBlock(final OComposableProcessor iManager, final OCommandContext iContext, final ODocument iConfig,
ODocument iOutput, final boolean iReadOnly) {
if (!(iConfig instanceof ODocument))
throw new OTransactionException("QueryBlock: expected document as content");
String command = parse(iContext, (ODocument) iConfig);
command = (String) resolveValue(iContext, command, true);
debug(iContext, "Executing: " + (iReadOnly ? "query" : "command") + ": " + command.replace("%", "%%") + "...");
final OCommandRequestText cmd = new OSQLSynchQuery<OIdentifiable>(command.toString());
cmd.getContext().setParent(iContext);
// CREATE THE RIGHT COMMAND BASED ON IDEMPOTENCY
// final OCommandRequestText cmd = iReadOnly ? new OSQLSynchQuery<OIdentifiable>(command.toString()) : new OCommandSQL(
// command.toString());
final String returnVariable = getFieldOfClass(iContext, iConfig, "return", String.class);
if (returnVariable != null) {
final List<?> result = cmd.execute();
debug(iContext, "Returned %d records", result.size());
return result;
}
return cmd;
}
@Override
public String getName() {
return NAME;
}
protected String parse(final OCommandContext iContext, final ODocument iContent) {
final Object code = getField(iContext, iContent, "code");
if (code != null)
// CODE MODE
return code.toString();
// SINGLE FIELDS MODE
final StringBuilder command = new StringBuilder();
command.append("select ");
generateProjections(iContext, iContent, command);
generateTarget(iContext, iContent, command);
generateLet(iContext, iContent, command);
generateLimit(iContext, iContent, command);
generateFilter(iContext, iContent, command);
generateGroupBy(iContext, iContent, command);
generateOrderBy(iContext, iContent, command);
generateLimit(iContext, iContent, command);
return command.toString();
}
@SuppressWarnings("unchecked")
private void generateProjections(final OCommandContext iContext, ODocument iInput, final StringBuilder iCommandText) {
final Object fields = getField(iContext, iInput, "fields");
if (fields instanceof String)
iCommandText.append(fields.toString());
else {
final List<ODocument> fieldList = (List<ODocument>) fields;
if (fieldList != null) {
boolean first = true;
for (Object field : fieldList) {
if (first)
first = false;
else
iCommandText.append(", ");
if (field instanceof ODocument) {
final ODocument fieldDoc = (ODocument) field;
for (String f : fieldDoc.fieldNames()) {
iCommandText.append(f);
iCommandText.append(" as ");
iCommandText.append(fieldDoc.field(f));
}
} else
iCommandText.append(field.toString());
}
}
}
}
private void generateTarget(final OCommandContext iContext, ODocument iInput, final StringBuilder iCommandText) {
final String target = getField(iContext, iInput, "target");
if (target != null) {
iCommandText.append(" from ");
iCommandText.append(target);
}
}
private void generateLet(final OCommandContext iContext, ODocument iInput, final StringBuilder iCommandText) {
final String let = getField(iContext, iInput, "let");
if (let != null) {
iCommandText.append(" let ");
iCommandText.append(let);
}
}
private void generateFilter(final OCommandContext iContext, ODocument iInput, final StringBuilder iCommandText) {
final String filter = getField(iContext, iInput, "filter");
if (filter != null) {
iCommandText.append(" where ");
iCommandText.append(filter);
}
}
private void generateGroupBy(final OCommandContext iContext, ODocument iInput, final StringBuilder iCommandText) {
final String groupBy = getField(iContext, iInput, "groupBy");
if (groupBy != null) {
iCommandText.append(" group by ");
iCommandText.append(groupBy);
}
}
private void generateOrderBy(final OCommandContext iContext, ODocument iInput, final StringBuilder iCommandText) {
final String orderBy = getField(iContext, iInput, "orderBy");
if (orderBy != null) {
iCommandText.append(" order by ");
iCommandText.append(orderBy);
}
}
private void generateLimit(final OCommandContext iContext, ODocument iInput, final StringBuilder iCommandText) {
final Integer limit = getField(iContext, iInput, "limit");
if (limit != null) {
iCommandText.append(" limit ");
iCommandText.append(limit);
}
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_processor_block_OQueryBlock.java |
294 | class RestorePreviousSelectionAction extends Action {
private CeylonEditor editor;
private List<IRegion> previous = new ArrayList<IRegion>();
private boolean restoring;
public RestorePreviousSelectionAction() {
this(null);
}
@Override
public boolean isEnabled() {
return super.isEnabled() && editor!=null;
}
public RestorePreviousSelectionAction(CeylonEditor editor) {
super("Select Enclosing");
setActionDefinitionId(RESTORE_PREVIOUS);
setEditor(editor);
}
private void setEditor(ITextEditor editor) {
if (editor instanceof CeylonEditor) {
this.editor = (CeylonEditor) editor;
this.editor.getSelectionProvider()
.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
if (!restoring) {
IRegion r = RestorePreviousSelectionAction.this.editor.getSelection();
if (r.getLength()==0) {
previous.clear();
}
previous.add(r);//new Region(r.getOffset(), r.getLength()));
if (previous.size()>20) {
previous.remove(0);
}
setEnabled(previous.size()>1);
}
}
});
}
else {
this.editor= null;
}
setEnabled(false);
}
@Override
public void run() {
if (previous.size()>0) {
previous.remove(previous.size()-1);
}
if (previous.size()>0) {
IRegion r = previous.get(previous.size()-1);
restoring=true;
editor.selectAndReveal(r.getOffset(), r.getLength());
restoring=false;
setEnabled(previous.size()>1);
}
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_RestorePreviousSelectionAction.java |
402 | public class ORecordTrackedSet extends AbstractCollection<OIdentifiable> implements Set<OIdentifiable>, ORecordElement {
protected final ORecord<?> sourceRecord;
protected Map<Object, Object> map = new HashMap<Object, Object>();
private STATUS status = STATUS.NOT_LOADED;
protected final static Object ENTRY_REMOVAL = new Object();
public ORecordTrackedSet(final ORecord<?> iSourceRecord) {
this.sourceRecord = iSourceRecord;
if (iSourceRecord != null)
iSourceRecord.setDirty();
}
public Iterator<OIdentifiable> iterator() {
return new ORecordTrackedIterator(sourceRecord, map.keySet().iterator());
}
public boolean add(final OIdentifiable e) {
if (map.containsKey(e))
return false;
map.put(e, ENTRY_REMOVAL);
setDirty();
if (e instanceof ODocument)
((ODocument) e).addOwner(this);
return true;
}
@Override
public boolean contains(Object o) {
return map.containsKey(o);
}
public boolean remove(Object o) {
final Object old = map.remove(o);
if (old != null) {
if (o instanceof ODocument)
((ODocument) o).removeOwner(this);
setDirty();
return true;
}
return false;
}
public void clear() {
setDirty();
map.clear();
}
public boolean removeAll(final Collection<?> c) {
boolean changed = false;
for (Object item : c) {
if (map.remove(item) != null)
changed = true;
}
if (changed)
setDirty();
return changed;
}
public boolean addAll(final Collection<? extends OIdentifiable> c) {
if (c == null || c.size() == 0)
return false;
for (OIdentifiable o : c)
add(o);
setDirty();
return true;
}
public boolean retainAll(final Collection<?> c) {
if (c == null || c.size() == 0)
return false;
if (super.removeAll(c)) {
setDirty();
return true;
}
return false;
}
@Override
public int size() {
return map.size();
}
@SuppressWarnings("unchecked")
public ORecordTrackedSet setDirty() {
if (status != STATUS.UNMARSHALLING && sourceRecord != null && !sourceRecord.isDirty())
sourceRecord.setDirty();
return this;
}
public void onBeforeIdentityChanged(final ORID iRID) {
map.remove(iRID);
setDirty();
}
public void onAfterIdentityChanged(final ORecord<?> iRecord) {
map.put(iRecord, ENTRY_REMOVAL);
}
public STATUS getInternalStatus() {
return status;
}
public void setInternalStatus(final STATUS iStatus) {
status = iStatus;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_record_ORecordTrackedSet.java |
2,773 | public class SSLSocketChannelWrapper extends DefaultSocketChannelWrapper {
private static final boolean DEBUG = false;
private final ByteBuffer in;
private final ByteBuffer emptyBuffer;
private final ByteBuffer netOutBuffer;
// "reliable" write transport
private final ByteBuffer netInBuffer;
// "reliable" read transport
private final SSLEngine sslEngine;
private volatile boolean handshakeCompleted;
private SSLEngineResult sslEngineResult;
public SSLSocketChannelWrapper(SSLContext sslContext, SocketChannel sc, boolean client) throws Exception {
super(sc);
sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(client);
sslEngine.setEnableSessionCreation(true);
SSLSession session = sslEngine.getSession();
in = ByteBuffer.allocate(64 * 1024);
emptyBuffer = ByteBuffer.allocate(0);
int netBufferMax = session.getPacketBufferSize();
netOutBuffer = ByteBuffer.allocate(netBufferMax);
netInBuffer = ByteBuffer.allocate(netBufferMax);
}
private void handshake() throws IOException {
if (handshakeCompleted) {
return;
}
if (DEBUG) {
log("Starting handshake...");
}
synchronized (this) {
if (handshakeCompleted) {
if (DEBUG) {
log("Handshake already completed...");
}
return;
}
int counter = 0;
if (DEBUG) {
log("Begin handshake");
}
sslEngine.beginHandshake();
writeInternal(emptyBuffer);
while (counter++ < 250 && sslEngineResult.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.FINISHED) {
if (DEBUG) {
log("Handshake status: " + sslEngineResult.getHandshakeStatus());
}
if (sslEngineResult.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
if (DEBUG) {
log("Begin UNWRAP");
}
netInBuffer.clear();
while (socketChannel.read(netInBuffer) < 1) {
try {
if (DEBUG) {
log("Spinning on channel read...");
}
Thread.sleep(50);
} catch (InterruptedException e) {
throw new IOException(e);
}
}
netInBuffer.flip();
unwrap(netInBuffer);
if (DEBUG) {
log("Done UNWRAP: " + sslEngineResult.getHandshakeStatus());
}
if (sslEngineResult.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.FINISHED) {
emptyBuffer.clear();
writeInternal(emptyBuffer);
if (DEBUG) {
log("Done WRAP after UNWRAP: " + sslEngineResult.getHandshakeStatus());
}
}
} else if (sslEngineResult.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
if (DEBUG) {
log("Begin WRAP");
}
emptyBuffer.clear();
writeInternal(emptyBuffer);
if (DEBUG) {
log("Done WRAP: " + sslEngineResult.getHandshakeStatus());
}
} else {
try {
if (DEBUG) {
log("Sleeping... Status: " + sslEngineResult.getHandshakeStatus());
}
Thread.sleep(500);
} catch (InterruptedException e) {
throw new IOException(e);
}
}
}
if (sslEngineResult.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.FINISHED) {
throw new SSLHandshakeException("SSL handshake failed after " + counter
+ " trials! -> " + sslEngineResult.getHandshakeStatus());
}
if (DEBUG) {
log("Handshake completed!");
}
in.clear();
in.flip();
handshakeCompleted = true;
}
}
private void log(String log) {
if (DEBUG) {
System.err.println(getClass().getSimpleName() + "[" + socketChannel.socket().getLocalSocketAddress() + "]: " + log);
}
}
private ByteBuffer unwrap(ByteBuffer b) throws SSLException {
in.clear();
while (b.hasRemaining()) {
sslEngineResult = sslEngine.unwrap(b, in);
if (sslEngineResult.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
if (DEBUG) {
log("Handshake NEED TASK");
}
Runnable task;
while ((task = sslEngine.getDelegatedTask()) != null) {
if (DEBUG) {
log("Running task: " + task);
}
task.run();
}
} else if (sslEngineResult.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.FINISHED
|| sslEngineResult.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) {
return in;
}
}
return in;
}
public int write(ByteBuffer input) throws IOException {
if (!handshakeCompleted) {
handshake();
}
return writeInternal(input);
}
private int writeInternal(ByteBuffer input) throws IOException {
sslEngineResult = sslEngine.wrap(input, netOutBuffer);
netOutBuffer.flip();
int written = socketChannel.write(netOutBuffer);
if (netOutBuffer.hasRemaining()) {
netOutBuffer.compact();
} else {
netOutBuffer.clear();
}
return written;
}
public int read(ByteBuffer output) throws IOException {
if (!handshakeCompleted) {
handshake();
}
int readBytesCount = 0;
int limit;
if (in.hasRemaining()) {
limit = Math.min(in.remaining(), output.remaining());
for (int i = 0; i < limit; i++) {
output.put(in.get());
readBytesCount++;
}
return readBytesCount;
}
if (netInBuffer.hasRemaining()) {
unwrap(netInBuffer);
in.flip();
limit = Math.min(in.remaining(), output.remaining());
for (int i = 0; i < limit; i++) {
output.put(in.get());
readBytesCount++;
}
if (sslEngineResult.getStatus() != SSLEngineResult.Status.BUFFER_UNDERFLOW) {
netInBuffer.clear();
netInBuffer.flip();
return readBytesCount;
}
}
if (netInBuffer.hasRemaining()) {
netInBuffer.compact();
} else {
netInBuffer.clear();
}
if (socketChannel.read(netInBuffer) == -1) {
netInBuffer.clear();
netInBuffer.flip();
return -1;
}
netInBuffer.flip();
unwrap(netInBuffer);
in.flip();
limit = Math.min(in.remaining(), output.remaining());
for (int i = 0; i < limit; i++) {
output.put(in.get());
readBytesCount++;
}
return readBytesCount;
}
public void close() throws IOException {
sslEngine.closeOutbound();
try {
writeInternal(emptyBuffer);
} catch (Exception ignored) {
}
socketChannel.close();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("SSLSocketChannelWrapper{");
sb.append("socketChannel=").append(socketChannel);
sb.append('}');
return sb.toString();
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_nio_ssl_SSLSocketChannelWrapper.java |
231 | private static final class DummyInformationProvider
implements IInformationProvider, IInformationProviderExtension {
// private CeylonParseController parseController;
// DummyInformationProvider(CeylonParseController parseController) {
// this.parseController = parseController;
// }
@Override
public IRegion getSubject(ITextViewer textViewer, int offset) {
return new Region(offset, 0); // Could be anything, since it's ignored below in getInformation2()...
}
@Override
public String getInformation(ITextViewer textViewer, IRegion subject) {
// shouldn't be called, given IInformationProviderExtension???
throw new UnsupportedOperationException();
}
@Override
public Object getInformation2(ITextViewer textViewer, IRegion subject) {
return new Object();
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonSourceViewerConfiguration.java |
206 | public interface FieldQueryExtension {
Query query(QueryParseContext parseContext, String queryText);
} | 0true
| src_main_java_org_apache_lucene_queryparser_classic_FieldQueryExtension.java |
3,208 | constructors[VECTOR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new VectorClock();
}
}; | 1no label
| hazelcast_src_main_java_com_hazelcast_replicatedmap_operation_ReplicatedMapDataSerializerHook.java |
796 | public class ODatabaseFunctionFactory implements OSQLFunctionFactory {
@Override
public boolean hasFunction(final String iName) {
final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.get();
return db.getMetadata().getFunctionLibrary().getFunction(iName) != null;
}
@Override
public Set<String> getFunctionNames() {
final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.get();
return db.getMetadata().getFunctionLibrary().getFunctionNames();
}
@Override
public OSQLFunction createFunction(final String name) throws OCommandExecutionException {
final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.get();
final OFunction f = db.getMetadata().getFunctionLibrary().getFunction(name);
return new ODatabaseFunction(f);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_metadata_function_ODatabaseFunctionFactory.java |
324 | public class OStorageMemoryLinearHashingClusterConfiguration extends OAbstractStorageClusterConfiguration {
public OStorageMemoryLinearHashingClusterConfiguration(final String name, final int id, final int iDataSegmentId) {
super(name, id, iDataSegmentId);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_config_OStorageMemoryLinearHashingClusterConfiguration.java |
437 | public final class PartitionServiceProxy implements PartitionService {
private final ClientPartitionService partitionService;
private final Random random = new Random();
public PartitionServiceProxy(ClientPartitionService partitionService) {
this.partitionService = partitionService;
}
@Override
public String randomPartitionKey() {
return Integer.toString(random.nextInt(partitionService.getPartitionCount()));
}
@Override
public Set<Partition> getPartitions() {
final int partitionCount = partitionService.getPartitionCount();
Set<Partition> partitions = new LinkedHashSet<Partition>(partitionCount);
for (int i = 0; i < partitionCount; i++) {
final Partition partition = partitionService.getPartition(i);
partitions.add(partition);
}
return partitions;
}
@Override
public Partition getPartition(Object key) {
final int partitionId = partitionService.getPartitionId(key);
return partitionService.getPartition(partitionId);
}
@Override
public String addMigrationListener(MigrationListener migrationListener) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeMigrationListener(String registrationId) {
throw new UnsupportedOperationException();
}
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_proxy_PartitionServiceProxy.java |
927 | new ConstructorFunction<ObjectNamespace, LockStoreImpl>() {
public LockStoreImpl createNew(ObjectNamespace namespace) {
final ConstructorFunction<ObjectNamespace, LockStoreInfo> ctor =
lockService.getConstructor(namespace.getServiceName());
if (ctor != null) {
LockStoreInfo info = ctor.createNew(namespace);
if (info != null) {
return new LockStoreImpl(
lockService, namespace, info.getBackupCount(), info.getAsyncBackupCount());
}
}
throw new IllegalArgumentException("No LockStore constructor is registered!");
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockStoreContainer.java |
1,090 | public class OrderTest extends OrderBaseTest {
private Long orderId = null;
private int numOrderItems = 0;
private Long bundleOrderItemId;
@Resource(name = "blOrderItemService")
private OrderItemService orderItemService;
@Resource
private SkuDao skuDao;
@Resource(name = "blFulfillmentGroupService")
protected FulfillmentGroupService fulfillmentGroupService;
@Resource(name = "blAddItemWorkflow")
protected SequenceProcessor addItemWorkflow;
@Test(groups = { "createCartForCustomer" }, dependsOnGroups = { "readCustomer", "createPhone" })
@Transactional
@Rollback(false)
public void createCartForCustomer() {
String userName = "customer1";
Customer customer = customerService.readCustomerByUsername(userName);
Order order = orderService.createNewCartForCustomer(customer);
assert order != null;
assert order.getId() != null;
this.orderId = order.getId();
}
@Test(groups = { "findCurrentCartForCustomer" }, dependsOnGroups = { "readCustomer", "createPhone", "createCartForCustomer" })
@Transactional
@Rollback(false)
public void findCurrentCartForCustomer() {
String userName = "customer1";
Customer customer = customerService.readCustomerByUsername(userName);
Order order = orderService.findCartForCustomer(customer);
assert order != null;
assert order.getId() != null;
this.orderId = order.getId();
}
@Test(groups = { "addItemToOrder" }, dependsOnGroups = { "findCurrentCartForCustomer", "createSku", "testCatalog" })
@Rollback(false)
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void addItemToOrder() throws AddToCartException {
numOrderItems++;
Sku sku = skuDao.readFirstSku();
Order order = orderService.findOrderById(orderId);
assert order != null;
assert sku.getId() != null;
OrderItemRequestDTO itemRequest = new OrderItemRequestDTO();
itemRequest.setQuantity(1);
itemRequest.setSkuId(sku.getId());
order = orderService.addItem(orderId, itemRequest, true);
DiscreteOrderItem item = (DiscreteOrderItem) orderService.findLastMatchingItem(order, sku.getId(), null);
assert item != null;
assert item.getQuantity() == numOrderItems;
assert item.getSku() != null;
assert item.getSku().equals(sku);
assert order.getFulfillmentGroups().size() == 1;
FulfillmentGroup fg = order.getFulfillmentGroups().get(0);
assert fg.getFulfillmentGroupItems().size() == 1;
FulfillmentGroupItem fgItem = fg.getFulfillmentGroupItems().get(0);
assert fgItem.getOrderItem().equals(item);
assert fgItem.getQuantity() == item.getQuantity();
}
@Test(groups = { "addAnotherItemToOrder" }, dependsOnGroups = { "addItemToOrder" })
@Rollback(false)
@Transactional
public void addAnotherItemToOrder() throws AddToCartException {
Sku sku = skuDao.readFirstSku();
Order order = orderService.findOrderById(orderId);
assert order != null;
assert sku.getId() != null;
orderService.setAutomaticallyMergeLikeItems(true);
OrderItemRequestDTO itemRequest = new OrderItemRequestDTO();
itemRequest.setQuantity(1);
itemRequest.setSkuId(sku.getId());
// Note that we are not incrementing the numOrderItems count because it should have gotten merged
order = orderService.addItem(orderId, itemRequest, true);
DiscreteOrderItem item = (DiscreteOrderItem) orderService.findLastMatchingItem(order, sku.getId(), null);
assert item.getSku() != null;
assert item.getSku().equals(sku);
assert item.getQuantity() == 2; // item-was merged with prior item.
order = orderService.findOrderById(orderId);
assert(order.getOrderItems().size()==1);
assert(order.getOrderItems().get(0).getQuantity()==2);
assert order.getFulfillmentGroups().size() == 1;
FulfillmentGroup fg = order.getFulfillmentGroups().get(0);
assert fg.getFulfillmentGroupItems().size() == 1;
FulfillmentGroupItem fgItem = fg.getFulfillmentGroupItems().get(0);
assert fgItem.getOrderItem().equals(item);
assert fgItem.getQuantity() == item.getQuantity();
/*
This test is not supported currently, as the order service may only do like item merging
// re-price the order without automatically merging.
orderService.setAutomaticallyMergeLikeItems(false);
numOrderItems++;
itemRequest = new OrderItemRequestDTO();
itemRequest.setQuantity(1);
itemRequest.setSkuId(sku.getId());
order = orderService.addItem(orderId, itemRequest, true);
DiscreteOrderItem item2 = (DiscreteOrderItem) orderService.findLastMatchingItem(order, sku.getId(), null);
assert item2.getSku() != null;
assert item2.getSku().equals(sku);
assert item2.getQuantity() == 1; // item-was not auto-merged with prior items.
order = orderService.findOrderById(orderId);
assert(order.getOrderItems().size()==2);
assert(order.getOrderItems().get(0).getQuantity()==2);
assert(order.getOrderItems().get(1).getQuantity()==1);
assert order.getFulfillmentGroups().size() == 1;
fg = order.getFulfillmentGroups().get(0);
assert fg.getFulfillmentGroupItems().size() == 2;
for (FulfillmentGroupItem fgi : fg.getFulfillmentGroupItems()) {
assert fgi.getQuantity() == fgi.getOrderItem().getQuantity();
}*/
}
@Test(groups = { "testIllegalAddScenarios" }, dependsOnGroups = { "addItemToOrder" })
@Transactional
public void testIllegalAddScenarios() throws AddToCartException {
Order order = orderService.findOrderById(orderId);
assert order != null;
Product activeProduct = addTestProduct("mug", "cups", true);
Product inactiveProduct = addTestProduct("cup", "cups", false);
// Inactive skus should not be added
OrderItemRequestDTO itemRequest = new OrderItemRequestDTO().setQuantity(1).setSkuId(inactiveProduct.getDefaultSku().getId());
boolean addSuccessful = true;
try {
order = orderService.addItem(orderId, itemRequest, true);
} catch (AddToCartException e) {
addSuccessful = false;
}
assert !addSuccessful;
// Products that have SKUs marked as inactive should not be added either
itemRequest = new OrderItemRequestDTO().setQuantity(1).setProductId(inactiveProduct.getId());
addSuccessful = true;
try {
order = orderService.addItem(orderId, itemRequest, true);
} catch (AddToCartException e) {
addSuccessful = false;
}
assert !addSuccessful;
// Negative quantities are not allowed
itemRequest = new OrderItemRequestDTO().setQuantity(-1).setSkuId(activeProduct.getDefaultSku().getId());
addSuccessful = true;
try {
order = orderService.addItem(orderId, itemRequest, true);
} catch (AddToCartException e) {
addSuccessful = false;
assert e.getCause() instanceof IllegalArgumentException;
}
assert !addSuccessful;
// Order must exist
itemRequest = new OrderItemRequestDTO().setQuantity(1).setSkuId(activeProduct.getDefaultSku().getId());
addSuccessful = true;
try {
order = orderService.addItem(-1L, itemRequest, true);
} catch (AddToCartException e) {
addSuccessful = false;
assert e.getCause() instanceof IllegalArgumentException;
}
assert !addSuccessful;
// If a product is provided, it must exist
itemRequest = new OrderItemRequestDTO().setQuantity(1).setProductId(-1L);
addSuccessful = true;
try {
order = orderService.addItem(orderId, itemRequest, true);
} catch (AddToCartException e) {
addSuccessful = false;
assert e.getCause() instanceof IllegalArgumentException;
}
assert !addSuccessful;
// The SKU must exist
itemRequest = new OrderItemRequestDTO().setQuantity(1).setSkuId(-1L);
addSuccessful = true;
try {
order = orderService.addItem(orderId, itemRequest, true);
} catch (AddToCartException e) {
addSuccessful = false;
assert e.getCause() instanceof IllegalArgumentException;
}
assert !addSuccessful;
}
@Test(groups = { "testIllegalUpdateScenarios" }, dependsOnGroups = { "addItemToOrder" })
@Transactional
public void testIllegalUpdateScenarios() throws UpdateCartException, AddToCartException, RemoveFromCartException {
Order order = orderService.findOrderById(orderId);
assert order != null;
Product activeProduct = addTestProduct("mug", "cups", true);
Product inactiveProduct = addTestProduct("cup", "cups", false);
// Inactive skus should not be added
OrderItemRequestDTO itemRequest = new OrderItemRequestDTO().setQuantity(1).setSkuId(activeProduct.getDefaultSku().getId());
boolean addSuccessful = true;
try {
order = orderService.addItem(orderId, itemRequest, true);
} catch (AddToCartException e) {
addSuccessful = false;
}
assert addSuccessful;
// should not be able to update to negative quantity
OrderItem item = orderService.findLastMatchingItem(order, activeProduct.getDefaultSku().getId(), activeProduct.getId());
itemRequest = new OrderItemRequestDTO().setQuantity(-3).setOrderItemId(item.getId());
boolean updateSuccessful = true;
try {
orderService.updateItemQuantity(orderId, itemRequest, true);
} catch (UpdateCartException e) {
updateSuccessful = false;
}
assert !updateSuccessful;
//shouldn't be able to update the quantity of a DOI inside of a bundle
ProductBundle bundle = addProductBundle();
itemRequest = new OrderItemRequestDTO().setQuantity(1).setProductId(bundle.getId()).setSkuId(bundle.getDefaultSku().getId());
addSuccessful = true;
try {
order = orderService.addItem(orderId, itemRequest, true);
} catch (AddToCartException e) {
addSuccessful = false;
}
assert addSuccessful;
BundleOrderItem bundleItem = (BundleOrderItem) orderService.findLastMatchingItem(order,
bundle.getDefaultSku().getId(),
bundle.getId());
//should just be a single DOI inside the bundle
DiscreteOrderItem doi = bundleItem.getDiscreteOrderItems().get(0);
itemRequest = new OrderItemRequestDTO().setQuantity(4).setOrderItemId(doi.getId());
try {
orderService.updateItemQuantity(orderId, itemRequest, true);
} catch (UpdateCartException e) {
updateSuccessful = false;
}
assert !updateSuccessful;
}
@Test(groups = { "addBundleToOrder" }, dependsOnGroups = { "addAnotherItemToOrder" })
@Rollback(false)
@Transactional
public void addBundleToOrder() throws AddToCartException {
numOrderItems++;
Sku sku = skuDao.readFirstSku();
Order order = orderService.findOrderById(orderId);
assert order != null;
assert sku.getId() != null;
ProductBundle bundleItem = addProductBundle();
OrderItemRequestDTO orderItemRequestDTO = new OrderItemRequestDTO();
orderItemRequestDTO.setProductId(bundleItem.getId());
orderItemRequestDTO.setSkuId(bundleItem.getDefaultSku().getId());
orderItemRequestDTO.setQuantity(1);
order = orderService.addItem(order.getId(), orderItemRequestDTO, true);
BundleOrderItem item = (BundleOrderItem) orderService.findLastMatchingItem(order, bundleItem.getDefaultSku().getId(), null);
bundleOrderItemId = item.getId();
assert item != null;
assert item.getQuantity() == 1;
}
@Test(groups = { "removeBundleFromOrder" }, dependsOnGroups = { "addBundleToOrder" })
@Rollback(false)
@Transactional
public void removeBundleFromOrder() throws RemoveFromCartException {
Order order = orderService.findOrderById(orderId);
List<OrderItem> orderItems = order.getOrderItems();
assert orderItems.size() == numOrderItems;
int startingSize = orderItems.size();
BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItemService.readOrderItemById(bundleOrderItemId);
assert bundleOrderItem != null;
assert bundleOrderItem.getDiscreteOrderItems() != null;
assert bundleOrderItem.getDiscreteOrderItems().size() == 1;
order = orderService.removeItem(order.getId(), bundleOrderItem.getId(), true);
List<OrderItem> items = order.getOrderItems();
assert items != null;
assert items.size() == startingSize - 1;
}
@Test(groups = { "getItemsForOrder" }, dependsOnGroups = { "removeBundleFromOrder" })
@Transactional
public void getItemsForOrder() {
Order order = orderService.findOrderById(orderId);
List<OrderItem> orderItems = order.getOrderItems();
assert orderItems != null;
assert orderItems.size() == numOrderItems - 1;
}
@Test(groups = { "testManyToOneFGItemToOrderItem" }, dependsOnGroups = { "getItemsForOrder" })
@Transactional
public void testManyToOneFGItemToOrderItem() throws UpdateCartException, RemoveFromCartException, PricingException {
// Grab the order and the first OrderItem
Order order = orderService.findOrderById(orderId);
List<OrderItem> orderItems = order.getOrderItems();
assert orderItems.size() > 0;
OrderItem item = orderItems.get(0);
// Set the quantity of the first OrderItem to 10
OrderItemRequestDTO orderItemRequestDTO = new OrderItemRequestDTO();
orderItemRequestDTO.setOrderItemId(item.getId());
orderItemRequestDTO.setQuantity(10);
order = orderService.updateItemQuantity(order.getId(), orderItemRequestDTO, true);
// Assert that the quantity has changed
OrderItem updatedItem = orderItemService.readOrderItemById(item.getId());
assert updatedItem != null;
assert updatedItem.getQuantity() == 10;
// Assert that the appropriate fulfillment group item has changed
assert order.getFulfillmentGroups().size() == 1;
FulfillmentGroup fg = order.getFulfillmentGroups().get(0);
assert fg.getFulfillmentGroupItems().size() == 1;
FulfillmentGroupItem fgItem = null;
for (FulfillmentGroupItem fgi : fg.getFulfillmentGroupItems()) {
if (fgi.getOrderItem().equals(updatedItem)) {
fgItem = fgi;
}
}
assert fgItem != null;
/*
TODO because of the merging that takes place in the offer service, these tests do not
work unless multiship options are incorporated
// Split one of the fulfillment group items to simulate a OneToMany relationship between
// OrderItems and FulfillmentGroupItems
FulfillmentGroup secondFg = fulfillmentGroupService.createEmptyFulfillmentGroup();
secondFg.setOrder(order);
secondFg = fulfillmentGroupService.save(secondFg);
fgItem.setQuantity(5);
FulfillmentGroupItem clonedFgItem = fgItem.clone();
clonedFgItem.setFulfillmentGroup(secondFg);
secondFg.addFulfillmentGroupItem(clonedFgItem);
order.getFulfillmentGroups().add(secondFg);
order = orderService.save(order, false);
// Set the quantity of the first OrderItem to 15
orderItemRequestDTO = new OrderItemRequestDTO();
orderItemRequestDTO.setOrderItemId(item.getId());
orderItemRequestDTO.setQuantity(15);
order = orderService.updateItemQuantity(order.getId(), orderItemRequestDTO, true);
// Assert that the quantity has changed
updatedItem = orderItemService.readOrderItemById(item.getId());
assert updatedItem != null;
assert updatedItem.getQuantity() == 15;
// Assert that the appropriate fulfillment group item has changed
assert order.getFulfillmentGroups().size() == 2;
int fgItemQuantity = 0;
for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) {
for (FulfillmentGroupItem fgi : fulfillmentGroup.getFulfillmentGroupItems()) {
if (fgi.getOrderItem().equals(updatedItem)) {
fgItemQuantity += fgi.getQuantity();
}
}
}
assert fgItemQuantity == 15;
// Set the quantity of the first OrderItem to 3
orderItemRequestDTO = new OrderItemRequestDTO();
orderItemRequestDTO.setOrderItemId(item.getId());
orderItemRequestDTO.setQuantity(3);
order = orderService.updateItemQuantity(order.getId(), orderItemRequestDTO, true);
// Assert that the quantity has changed
updatedItem = orderItemService.readOrderItemById(item.getId());
assert updatedItem != null;
assert updatedItem.getQuantity() == 3;
// Assert that the appropriate fulfillment group item has changed
assert order.getFulfillmentGroups().size() == 2;
boolean fgItemFound = false;
for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) {
for (FulfillmentGroupItem fgi : fulfillmentGroup.getFulfillmentGroupItems()) {
if (fgi.getOrderItem().equals(updatedItem)) {
assert fgItemFound == false;
assert fgi.getQuantity() == 3;
fgItemFound = true;
}
}
}
assert fgItemFound;
*/
}
@Test(groups = { "updateItemsInOrder" }, dependsOnGroups = { "getItemsForOrder" })
@Transactional
public void updateItemsInOrder() throws UpdateCartException, RemoveFromCartException {
// Grab the order and the first OrderItem
Order order = orderService.findOrderById(orderId);
List<OrderItem> orderItems = order.getOrderItems();
assert orderItems.size() > 0;
OrderItem item = orderItems.get(0);
// Set the quantity of the first OrderItem to 10
OrderItemRequestDTO orderItemRequestDTO = new OrderItemRequestDTO();
orderItemRequestDTO.setOrderItemId(item.getId());
orderItemRequestDTO.setQuantity(10);
order = orderService.updateItemQuantity(order.getId(), orderItemRequestDTO, true);
// Assert that the quantity has changed
OrderItem updatedItem = orderItemService.readOrderItemById(item.getId());
assert updatedItem != null;
assert updatedItem.getQuantity() == 10;
// Assert that the appropriate fulfillment group item has changed
assert order.getFulfillmentGroups().size() == 1;
FulfillmentGroup fg = order.getFulfillmentGroups().get(0);
assert fg.getFulfillmentGroupItems().size() == 1;
boolean fgItemUpdated = false;
for (FulfillmentGroupItem fgi : fg.getFulfillmentGroupItems()) {
if (fgi.getOrderItem().equals(updatedItem)) {
assert fgi.getQuantity() == 10;
fgItemUpdated = true;
}
}
assert fgItemUpdated;
// Set the quantity of the first OrderItem to 5
orderItemRequestDTO = new OrderItemRequestDTO();
orderItemRequestDTO.setOrderItemId(item.getId());
orderItemRequestDTO.setQuantity(5);
order = orderService.updateItemQuantity(order.getId(), orderItemRequestDTO, true);
// Assert that the quantity has changed - going to a smaller quantity is also ok
updatedItem = orderItemService.readOrderItemById(item.getId());
assert updatedItem != null;
assert updatedItem.getQuantity() == 5;
// Assert that the appropriate fulfillment group item has changed
assert order.getFulfillmentGroups().size() == 1;
fg = order.getFulfillmentGroups().get(0);
assert fg.getFulfillmentGroupItems().size() == 1;
fgItemUpdated = false;
for (FulfillmentGroupItem fgi : fg.getFulfillmentGroupItems()) {
if (fgi.getOrderItem().equals(updatedItem)) {
assert fgi.getQuantity() == 5;
fgItemUpdated = true;
}
}
assert fgItemUpdated;
// Setting the quantity to 0 should in fact remove the item completely
int startingSize = order.getOrderItems().size();
orderItemRequestDTO = new OrderItemRequestDTO();
orderItemRequestDTO.setOrderItemId(item.getId());
orderItemRequestDTO.setQuantity(0);
order = orderService.updateItemQuantity(order.getId(), orderItemRequestDTO, true);
// Assert that the item has been removed
updatedItem = orderItemService.readOrderItemById(item.getId());
assert updatedItem == null;
assert order.getOrderItems().size() == startingSize - 1;
// Assert that the appropriate fulfillment group item has been removed
assert order.getFulfillmentGroups().size() == 0;
/*
TODO Since we commented out some tests above, there is no longer an additional item
in the cart, hence the fulfillment group is removed
fg = order.getFulfillmentGroups().get(0);
assert fg.getFulfillmentGroupItems().size() == startingSize - 1;
boolean fgItemRemoved = true;
for (FulfillmentGroupItem fgi : fg.getFulfillmentGroupItems()) {
if (fgi.getOrderItem().equals(updatedItem)) {
fgItemRemoved = false;
}
}
assert fgItemRemoved;*/
}
@Test(groups = { "removeItemFromOrder" }, dependsOnGroups = { "getItemsForOrder" })
@Transactional
public void removeItemFromOrder() throws RemoveFromCartException {
// Grab the order and the first OrderItem
Order order = orderService.findOrderById(orderId);
List<OrderItem> orderItems = order.getOrderItems();
assert orderItems.size() > 0;
int startingSize = orderItems.size();
OrderItem item = orderItems.get(0);
Long itemId = item.getId();
assert item != null;
// Remove the item
order = orderService.removeItem(order.getId(), item.getId(), true);
List<OrderItem> items = order.getOrderItems();
OrderItem updatedItem = orderItemService.readOrderItemById(item.getId());
// Assert that the item has been removed
assert items != null;
assert items.size() == startingSize - 1;
assert updatedItem == null;
}
@Test(groups = { "checkOrderItems" }, dependsOnGroups = { "removeItemFromOrder" })
@Transactional
public void checkOrderItems() throws PricingException {
Order order = orderService.findOrderById(orderId);
// The removal from the removeBundleFromOrder() has actually persisted.
// However, the previous two transactions were rolled back and thus the items still exist.
assert order.getOrderItems().size() == 1;
// As mentioned, the bundleOrderItem however has gone away
BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItemService.readOrderItemById(bundleOrderItemId);
assert bundleOrderItem == null;
}
@Test(groups = { "getOrdersForCustomer" }, dependsOnGroups = { "readCustomer", "findCurrentCartForCustomer" })
@Transactional
public void getOrdersForCustomer() {
String username = "customer1";
Customer customer = customerService.readCustomerByUsername(username);
List<Order> orders = orderService.findOrdersForCustomer(customer);
assert orders != null;
assert orders.size() > 0;
}
@Test(groups = { "findCartForAnonymousCustomer" }, dependsOnGroups = { "getOrdersForCustomer" })
public void findCartForAnonymousCustomer() {
Customer customer = customerService.createCustomerFromId(null);
Order order = orderService.findCartForCustomer(customer);
assert order == null;
order = orderService.createNewCartForCustomer(customer);
Long orderId = order.getId();
Order newOrder = orderService.findOrderById(orderId);
assert newOrder != null;
assert newOrder.getCustomer() != null;
}
@Test(groups = { "findOrderByOrderNumber" }, dependsOnGroups = { "findCartForAnonymousCustomer" })
@Transactional
public void findOrderByOrderNumber() throws PricingException {
Customer customer = customerService.createCustomerFromId(null);
Order order = orderService.createNewCartForCustomer(customer);
order.setOrderNumber("3456");
order = orderService.save(order, false);
Long orderId = order.getId();
Order newOrder = orderService.findOrderByOrderNumber("3456");
assert newOrder.getId().equals(orderId);
Order nullOrder = orderService.findOrderByOrderNumber(null);
assert nullOrder == null;
nullOrder = orderService.findOrderByOrderNumber("");
assert nullOrder == null;
}
@Test(groups = { "findNamedOrderForCustomer" }, dependsOnGroups = { "findOrderByOrderNumber" })
@Transactional
public void findNamedOrderForCustomer() throws PricingException {
Customer customer = customerService.createCustomerFromId(null);
Order order = orderService.createNewCartForCustomer(customer);
order.setStatus(OrderStatus.NAMED);
order.setName("COOL ORDER");
order = orderService.save(order, false);
Long orderId = order.getId();
Order newOrder = orderService.findNamedOrderForCustomer("COOL ORDER", customer);
assert newOrder.getId().equals(orderId);
}
@Test(groups = { "testReadOrdersForCustomer" }, dependsOnGroups = { "findNamedOrderForCustomer" })
@Transactional
public void testReadOrdersForCustomer() throws PricingException {
Customer customer = customerService.createCustomerFromId(null);
Order order = orderService.createNewCartForCustomer(customer);
order.setStatus(OrderStatus.IN_PROCESS);
order = orderService.save(order, false);
List<Order> newOrders = orderService.findOrdersForCustomer(customer, OrderStatus.IN_PROCESS);
boolean containsOrder = false;
if (newOrders.contains(order)) {
containsOrder = true;
}
assert containsOrder == true;
containsOrder = false;
newOrders = orderService.findOrdersForCustomer(customer, null);
if (newOrders.contains(order)) {
containsOrder = true;
}
assert containsOrder == true;
}
@Test(groups = { "testOrderProperties" }, dependsOnGroups = { "testReadOrdersForCustomer" })
public void testOrderProperties() throws PricingException {
Customer customer = customerService.createCustomerFromId(null);
Order order = orderService.createNewCartForCustomer(customer);
assert order.getSubTotal() == null;
assert order.getTotal() == null;
assert order.getRemainingTotal() == null;
Calendar testCalendar = Calendar.getInstance();
order.setSubmitDate(testCalendar.getTime());
assert order.getSubmitDate().equals(testCalendar.getTime());
}
@Test(groups = { "testNamedOrderForCustomer" }, dependsOnGroups = { "testOrderProperties" })
public void testNamedOrderForCustomer() throws PricingException {
Customer customer = customerService.createCustomerFromId(null);
customer = customerService.saveCustomer(customer);
Order order = orderService.createNamedOrderForCustomer("Birthday Order", customer);
Long orderId = order.getId();
assert order != null;
assert order.getName().equals("Birthday Order");
assert order.getCustomer().equals(customer);
orderService.cancelOrder(order);
assert orderService.findOrderById(orderId) == null;
}
@Test(groups = { "addPaymentToOrder" }, dataProvider = "basicPaymentInfo", dataProviderClass = PaymentInfoDataProvider.class, dependsOnGroups = { "checkOrderItems" })
@Rollback(false)
@Transactional
public void addPaymentToOrder(PaymentInfo paymentInfo) {
Order order = orderService.findOrderById(orderId);
orderService.addPaymentToOrder(order, paymentInfo, null);
order = orderService.findOrderById(orderId);
PaymentInfo payment = order.getPaymentInfos().get(order.getPaymentInfos().indexOf(paymentInfo));
assert payment != null;
assert payment.getOrder() != null;
assert payment.getOrder().equals(order);
}
@Test(groups = { "testOrderPaymentInfos" }, dataProvider = "basicPaymentInfo", dataProviderClass = PaymentInfoDataProvider.class)
@Transactional
public void testOrderPaymentInfos(PaymentInfo info) throws PricingException {
Customer customer = customerService.saveCustomer(createNamedCustomer());
Order order = orderService.createNewCartForCustomer(customer);
orderService.addPaymentToOrder(order, info, null);
boolean foundInfo = false;
assert order.getPaymentInfos() != null;
for (PaymentInfo testInfo : order.getPaymentInfos()) {
if (testInfo.equals(info)) {
foundInfo = true;
}
}
assert foundInfo == true;
assert orderService.findPaymentInfosForOrder(order) != null;
}
@Test
public void findCartForNullCustomerId() {
assert orderService.findCartForCustomer(new CustomerImpl()) == null;
}
@Test(groups = { "testSubmitOrder" }, dependsOnGroups = { "findNamedOrderForCustomer" })
public void testSubmitOrder() throws PricingException {
Customer customer = customerService.createCustomerFromId(null);
Order order = orderService.createNewCartForCustomer(customer);
order.setStatus(OrderStatus.IN_PROCESS);
order = orderService.save(order, false);
Long orderId = order.getId();
Order confirmedOrder = orderService.confirmOrder(order);
confirmedOrder = orderService.findOrderById(confirmedOrder.getId());
Long confirmedOrderId = confirmedOrder.getId();
assert orderId.equals(confirmedOrderId);
assert confirmedOrder.getStatus().equals(OrderStatus.SUBMITTED);
}
} | 0true
| integration_src_test_java_org_broadleafcommerce_core_order_service_OrderTest.java |
3,403 | public class UidAndRoutingFieldsVisitor extends FieldsVisitor {
private String routing;
@Override
public Status needsField(FieldInfo fieldInfo) throws IOException {
if (RoutingFieldMapper.NAME.equals(fieldInfo.name)) {
return Status.YES;
} else if (UidFieldMapper.NAME.equals(fieldInfo.name)) {
return Status.YES;
}
return uid != null && routing != null ? Status.STOP : Status.NO;
}
@Override
public void stringField(FieldInfo fieldInfo, String value) throws IOException {
if (RoutingFieldMapper.NAME.equals(fieldInfo.name)) {
routing = value;
} else {
super.stringField(fieldInfo, value);
}
}
public String routing() {
return routing;
}
} | 0true
| src_main_java_org_elasticsearch_index_fieldvisitor_UidAndRoutingFieldsVisitor.java |
2,753 | public class HttpInfo implements Streamable, Serializable, ToXContent {
private BoundTransportAddress address;
private long maxContentLength;
HttpInfo() {
}
public HttpInfo(BoundTransportAddress address, long maxContentLength) {
this.address = address;
this.maxContentLength = maxContentLength;
}
static final class Fields {
static final XContentBuilderString HTTP = new XContentBuilderString("http");
static final XContentBuilderString BOUND_ADDRESS = new XContentBuilderString("bound_address");
static final XContentBuilderString PUBLISH_ADDRESS = new XContentBuilderString("publish_address");
static final XContentBuilderString MAX_CONTENT_LENGTH = new XContentBuilderString("max_content_length");
static final XContentBuilderString MAX_CONTENT_LENGTH_IN_BYTES = new XContentBuilderString("max_content_length_in_bytes");
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.HTTP);
builder.field(Fields.BOUND_ADDRESS, address.boundAddress().toString());
builder.field(Fields.PUBLISH_ADDRESS, address.publishAddress().toString());
builder.byteSizeField(Fields.MAX_CONTENT_LENGTH_IN_BYTES, Fields.MAX_CONTENT_LENGTH, maxContentLength);
builder.endObject();
return builder;
}
public static HttpInfo readHttpInfo(StreamInput in) throws IOException {
HttpInfo info = new HttpInfo();
info.readFrom(in);
return info;
}
@Override
public void readFrom(StreamInput in) throws IOException {
address = BoundTransportAddress.readBoundTransportAddress(in);
maxContentLength = in.readLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
address.writeTo(out);
out.writeLong(maxContentLength);
}
public BoundTransportAddress address() {
return address;
}
public BoundTransportAddress getAddress() {
return address();
}
public ByteSizeValue maxContentLength() {
return new ByteSizeValue(maxContentLength);
}
public ByteSizeValue getMaxContentLength() {
return maxContentLength();
}
} | 0true
| src_main_java_org_elasticsearch_http_HttpInfo.java |
3,402 | public class SingleFieldsVisitor extends FieldsVisitor {
private String field;
public SingleFieldsVisitor(String field) {
this.field = field;
}
@Override
public Status needsField(FieldInfo fieldInfo) throws IOException {
// TODO we can potentially skip if we processed a field, the question is if it works for multi valued fields
if (fieldInfo.name.equals(field)) {
return Status.YES;
} else {
return Status.NO;
}
}
public void reset(String field) {
this.field = field;
super.reset();
}
public void postProcess(FieldMapper mapper) {
if (fieldsValues == null) {
return;
}
List<Object> fieldValues = fieldsValues.get(mapper.names().indexName());
if (fieldValues == null) {
return;
}
for (int i = 0; i < fieldValues.size(); i++) {
fieldValues.set(i, mapper.valueForSearch(fieldValues.get(i)));
}
}
} | 0true
| src_main_java_org_elasticsearch_index_fieldvisitor_SingleFieldsVisitor.java |
1,180 | @Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_PAYMENT_LOG")
public class PaymentLogImpl implements PaymentLog {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "PaymentLogId")
@GenericGenerator(
name="PaymentLogId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="PaymentLogImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.payment.domain.PaymentLogImpl")
}
)
@Column(name = "PAYMENT_LOG_ID")
protected Long id;
@Column(name = "USER_NAME", nullable=false)
@Index(name="PAYMENTLOG_USER_INDEX", columnNames={"USER_NAME"})
@AdminPresentation(friendlyName = "PaymentLogImpl_User_Name", order = 1, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected String userName;
@Column(name = "TRANSACTION_TIMESTAMP", nullable=false)
@Temporal(TemporalType.TIMESTAMP)
@AdminPresentation(friendlyName = "PaymentLogImpl_Transaction_Time", order = 3, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected Date transactionTimestamp;
@Column(name = "ORDER_PAYMENT_ID")
@Index(name="PAYMENTLOG_ORDERPAYMENT_INDEX", columnNames={"ORDER_PAYMENT_ID"})
@AdminPresentation(excluded = true, readOnly = true)
protected Long paymentInfoId;
@ManyToOne(targetEntity = CustomerImpl.class)
@JoinColumn(name = "CUSTOMER_ID")
@Index(name="PAYMENTLOG_CUSTOMER_INDEX", columnNames={"CUSTOMER_ID"})
protected Customer customer;
@Column(name = "PAYMENT_INFO_REFERENCE_NUMBER")
@Index(name="PAYMENTLOG_REFERENCE_INDEX", columnNames={"PAYMENT_INFO_REFERENCE_NUMBER"})
@AdminPresentation(friendlyName = "PaymentLogImpl_Payment_Ref_Number", order = 4, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected String paymentInfoReferenceNumber;
@Column(name = "TRANSACTION_TYPE", nullable=false)
@Index(name="PAYMENTLOG_TRANTYPE_INDEX", columnNames={"TRANSACTION_TYPE"})
@AdminPresentation(friendlyName = "PaymentLogImpl_Transaction_Type", order = 5, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected String transactionType;
@Column(name = "TRANSACTION_SUCCESS")
@AdminPresentation(friendlyName = "PaymentLogImpl_Transaction_Successfule", order = 6, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected Boolean transactionSuccess = false;
@Column(name = "EXCEPTION_MESSAGE")
@AdminPresentation(friendlyName = "PaymentLogImpl_Exception_Message", order = 7, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected String exceptionMessage;
@Column(name = "LOG_TYPE", nullable=false)
@Index(name="PAYMENTLOG_LOGTYPE_INDEX", columnNames={"LOG_TYPE"})
@AdminPresentation(friendlyName = "PaymentLogImpl_Type", order = 8, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected String logType;
@Column(name = "AMOUNT_PAID", precision=19, scale=5)
@AdminPresentation(friendlyName = "PaymentLogImpl_Amount", order = 2, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected BigDecimal amountPaid;
@ManyToOne(targetEntity = BroadleafCurrencyImpl.class)
@JoinColumn(name = "CURRENCY_CODE")
@AdminPresentation(friendlyName = "PaymentLogImpl_currency", order = 2, group = "PaymentLogImpl_Payment_Log", readOnly = true)
protected BroadleafCurrency currency;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getUserName() {
return userName;
}
@Override
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public Date getTransactionTimestamp() {
return transactionTimestamp;
}
@Override
public void setTransactionTimestamp(Date transactionTimestamp) {
this.transactionTimestamp = transactionTimestamp;
}
@Override
public Long getPaymentInfoId() {
return paymentInfoId;
}
@Override
public void setPaymentInfoId(Long paymentInfoId) {
this.paymentInfoId = paymentInfoId;
}
@Override
public Customer getCustomer() {
return customer;
}
@Override
public void setCustomer(Customer customer) {
this.customer = customer;
}
@Override
public String getPaymentInfoReferenceNumber() {
return paymentInfoReferenceNumber;
}
@Override
public void setPaymentInfoReferenceNumber(String paymentInfoReferenceNumber) {
this.paymentInfoReferenceNumber = paymentInfoReferenceNumber;
}
@Override
public TransactionType getTransactionType() {
return TransactionType.getInstance(transactionType);
}
@Override
public void setTransactionType(TransactionType transactionType) {
this.transactionType = transactionType.getType();
}
@Override
public PaymentLogEventType getLogType() {
return PaymentLogEventType.getInstance(logType);
}
@Override
public void setLogType(PaymentLogEventType logType) {
this.logType = logType.getType();
}
@Override
public Boolean getTransactionSuccess() {
if (transactionSuccess == null) {
return Boolean.FALSE;
} else {
return transactionSuccess;
}
}
@Override
public void setTransactionSuccess(Boolean transactionSuccess) {
this.transactionSuccess = transactionSuccess;
}
@Override
public String getExceptionMessage() {
return exceptionMessage;
}
@Override
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
@Override
public Money getAmountPaid() {
return BroadleafCurrencyUtils.getMoney(amountPaid, currency);
}
@Override
public void setAmountPaid(Money amountPaid) {
this.amountPaid = Money.toAmount(amountPaid);
}
@Override
public BroadleafCurrency getCurrency() {
return currency;
}
@Override
public void setCurrency(BroadleafCurrency currency) {
this.currency = currency;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((customer == null) ? 0 : customer.hashCode());
result = prime * result + ((paymentInfoId == null) ? 0 : paymentInfoId.hashCode());
result = prime * result + ((paymentInfoReferenceNumber == null) ? 0 : paymentInfoReferenceNumber.hashCode());
result = prime * result + ((transactionTimestamp == null) ? 0 : transactionTimestamp.hashCode());
result = prime * result + ((userName == null) ? 0 : userName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PaymentLogImpl other = (PaymentLogImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (customer == null) {
if (other.customer != null) {
return false;
}
} else if (!customer.equals(other.customer)) {
return false;
}
if (paymentInfoId == null) {
if (other.paymentInfoId != null) {
return false;
}
} else if (!paymentInfoId.equals(other.paymentInfoId)) {
return false;
}
if (paymentInfoReferenceNumber == null) {
if (other.paymentInfoReferenceNumber != null) {
return false;
}
} else if (!paymentInfoReferenceNumber.equals(other.paymentInfoReferenceNumber)) {
return false;
}
if (transactionTimestamp == null) {
if (other.transactionTimestamp != null) {
return false;
}
} else if (!transactionTimestamp.equals(other.transactionTimestamp)) {
return false;
}
if (userName == null) {
if (other.userName != null) {
return false;
}
} else if (!userName.equals(other.userName)) {
return false;
}
return true;
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_domain_PaymentLogImpl.java |
3,460 | public class HazelcastClientBeanDefinitionParser extends AbstractHazelcastBeanDefinitionParser {
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
final SpringXmlBuilder springXmlBuilder = new SpringXmlBuilder(parserContext);
springXmlBuilder.handleClient(element);
return springXmlBuilder.getBeanDefinition();
}
private class SpringXmlBuilder extends SpringXmlBuilderHelper {
private final ParserContext parserContext;
private BeanDefinitionBuilder builder;
private ManagedMap nearCacheConfigMap;//= new HashMap<String, NearCacheConfig>();
public SpringXmlBuilder(ParserContext parserContext) {
this.parserContext = parserContext;
this.builder = BeanDefinitionBuilder.rootBeanDefinition(HazelcastClient.class);
this.builder.setFactoryMethod("newHazelcastClient");
this.builder.setDestroyMethodName("shutdown");
this.nearCacheConfigMap = new ManagedMap();
this.configBuilder = BeanDefinitionBuilder.rootBeanDefinition(ClientConfig.class);
configBuilder.addPropertyValue("nearCacheConfigMap", nearCacheConfigMap);
BeanDefinitionBuilder managedContextBeanBuilder = createBeanBuilder(SpringManagedContext.class);
this.configBuilder.addPropertyValue("managedContext", managedContextBeanBuilder.getBeanDefinition());
}
public AbstractBeanDefinition getBeanDefinition() {
return builder.getBeanDefinition();
}
public void handleClient(Element element) {
handleCommonBeanAttributes(element, builder, parserContext);
final NamedNodeMap attrs = element.getAttributes();
if (attrs != null) {
for (int a = 0; a < attrs.getLength(); a++) {
final org.w3c.dom.Node att = attrs.item(a);
final String name = att.getNodeName();
final String value = att.getNodeValue();
if ("executor-pool-size".equals(name)) {
configBuilder.addPropertyValue("executorPoolSize", value);
} else if ("credentials-ref".equals(name)) {
configBuilder.addPropertyReference("credentials", value);
}
}
}
for (org.w3c.dom.Node node : new IterableNodeList(element, Node.ELEMENT_NODE)) {
final String nodeName = cleanNodeName(node.getNodeName());
if ("group".equals(nodeName)) {
createAndFillBeanBuilder(node, GroupConfig.class, "groupConfig", configBuilder);
} else if ("properties".equals(nodeName)) {
handleProperties(node, configBuilder);
} else if ("network".equals(nodeName)) {
handleNetwork(node);
} else if ("listeners".equals(nodeName)) {
final List listeners = parseListeners(node, ListenerConfig.class);
configBuilder.addPropertyValue("listenerConfigs", listeners);
} else if ("serialization".equals(nodeName)) {
handleSerialization(node);
} else if ("proxy-factories".equals(nodeName)) {
final List list = parseProxyFactories(node, ProxyFactoryConfig.class);
configBuilder.addPropertyValue("proxyFactoryConfigs", list);
} else if ("load-balancer".equals(nodeName)) {
handleLoadBalancer(node);
} else if ("near-cache".equals(nodeName)) {
handleNearCache(node);
}
}
builder.addConstructorArgValue(configBuilder.getBeanDefinition());
}
private void handleNetwork(Node node) {
List<String> members = new ArrayList<String>(10);
fillAttributeValues(node, configBuilder);
for (org.w3c.dom.Node child : new IterableNodeList(node, Node.ELEMENT_NODE)) {
final String nodeName = cleanNodeName(child);
if ("member".equals(nodeName)) {
members.add(getTextContent(child));
} else if ("socket-options".equals(nodeName)) {
createAndFillBeanBuilder(child, SocketOptions.class, "socketOptions", configBuilder);
} else if ("socket-interceptor".equals(nodeName)) {
handleSocketInterceptorConfig(node, configBuilder);
} else if ("ssl".equals(nodeName)) {
handleSSLConfig(node, configBuilder);
}
}
configBuilder.addPropertyValue("addresses", members);
}
private void handleSSLConfig(final Node node, final BeanDefinitionBuilder networkConfigBuilder) {
BeanDefinitionBuilder sslConfigBuilder = createBeanBuilder(SSLConfig.class);
final String implAttribute = "factory-implementation";
fillAttributeValues(node, sslConfigBuilder, implAttribute);
Node implNode = node.getAttributes().getNamedItem(implAttribute);
String implementation = implNode != null ? getTextContent(implNode) : null;
if (implementation != null) {
sslConfigBuilder.addPropertyReference(xmlToJavaName(implAttribute), implementation);
}
for (org.w3c.dom.Node child : new IterableNodeList(node, Node.ELEMENT_NODE)) {
final String name = cleanNodeName(child);
if ("properties".equals(name)) {
handleProperties(child, sslConfigBuilder);
}
}
networkConfigBuilder.addPropertyValue("SSLConfig", sslConfigBuilder.getBeanDefinition());
}
private void handleLoadBalancer(Node node) {
final String type = getAttribute(node, "type");
if ("random".equals(type)) {
configBuilder.addPropertyValue("loadBalancer", new RandomLB());
} else if ("round-robin".equals(type)) {
configBuilder.addPropertyValue("loadBalancer", new RoundRobinLB());
}
}
private void handleNearCache(Node node) {
createAndFillListedBean(node, NearCacheConfig.class, "name", nearCacheConfigMap, "name");
}
}
} | 1no label
| hazelcast-spring_src_main_java_com_hazelcast_spring_HazelcastClientBeanDefinitionParser.java |
1,622 | public interface DynamicEntityDao {
public abstract Class<?>[] getAllPolymorphicEntitiesFromCeiling(Class<?> ceilingClass);
public abstract Class<?>[] getAllPolymorphicEntitiesFromCeiling(Class<?> ceilingClass, boolean includeUnqualifiedPolymorphicEntities);
public ClassTree getClassTreeFromCeiling(Class<?> ceilingClass);
public ClassTree getClassTree(Class<?>[] polymorphicClasses);
public abstract Map<String, FieldMetadata> getPropertiesForPrimitiveClass(String propertyName, String friendlyPropertyName, Class<?> targetClass, Class<?> parentClass, MergedPropertyType mergedPropertyType);
public abstract Map<String, FieldMetadata> getMergedProperties(String ceilingEntityFullyQualifiedClassname, Class<?>[] entities, ForeignKey foreignField, String[] additionalNonPersistentProperties, ForeignKey[] additionalForeignFields, MergedPropertyType mergedPropertyType, Boolean populateManyToOneFields, String[] includeManyToOneFields, String[] excludeManyToOneFields, String configurationKey, String prefix);
public abstract Serializable persist(Serializable entity);
public abstract Serializable merge(Serializable entity);
public abstract Serializable retrieve(Class<?> entityClass, Object primaryKey);
public abstract void remove(Serializable entity);
public abstract void clear();
public void flush();
public void detach(Serializable entity);
public void refresh(Serializable entity);
public EntityManager getStandardEntityManager();
public void setStandardEntityManager(EntityManager entityManager);
/**
* Get the Hibernate PersistentClass instance associated with the fully-qualified
* class name. Will return null if no persistent class is associated with this name.
*
* @param targetClassName
* @return The PersistentClass instance
*/
public PersistentClass getPersistentClass(String targetClassName);
public Map<String, FieldMetadata> getSimpleMergedProperties(String entityName, PersistencePerspective persistencePerspective);
public FieldManager getFieldManager();
public EntityConfiguration getEntityConfiguration();
public void setEntityConfiguration(EntityConfiguration entityConfiguration);
public Map<String, Object> getIdMetadata(Class<?> entityClass);
public List<Type> getPropertyTypes(Class<?> entityClass);
public List<String> getPropertyNames(Class<?> entityClass);
public Criteria createCriteria(Class<?> entityClass);
public Field[] getAllFields(Class<?> targetClass);
public Metadata getMetadata();
public void setMetadata(Metadata metadata);
public FieldMetadataProvider getDefaultFieldMetadataProvider();
public SessionFactory getSessionFactory();
} | 0true
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_dao_DynamicEntityDao.java |
1,298 | @Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_CAT_SEARCH_FACET_EXCL_XREF")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
public class CategoryExcludedSearchFacetImpl implements CategoryExcludedSearchFacet, Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "CategoryExcludedSearchFacetId")
@GenericGenerator(
name="CategoryExcludedSearchFacetId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="CategoryExcludedSearchFacetImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.search.domain.CategoryExcludedSearchFacetImpl")
}
)
@Column(name = "CAT_EXCL_SEARCH_FACET_ID")
protected Long id;
@ManyToOne(targetEntity = CategoryImpl.class)
@JoinColumn(name = "CATEGORY_ID")
protected Category category;
@ManyToOne(targetEntity = SearchFacetImpl.class)
@JoinColumn(name = "SEARCH_FACET_ID")
protected SearchFacet searchFacet;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public Category getCategory() {
return category;
}
@Override
public void setCategory(Category category) {
this.category = category;
}
@Override
public SearchFacet getSearchFacet() {
return searchFacet;
}
@Override
public void setSearchFacet(SearchFacet searchFacet) {
this.searchFacet = searchFacet;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_domain_CategoryExcludedSearchFacetImpl.java |
2,180 | static class NotDeletedDocIdSetIterator extends FilteredDocIdSetIterator {
private final Bits match;
NotDeletedDocIdSetIterator(DocIdSetIterator innerIter, Bits match) {
super(innerIter);
this.match = match;
}
@Override
protected boolean match(int doc) {
return match.get(doc);
}
} | 0true
| src_main_java_org_elasticsearch_common_lucene_search_ApplyAcceptedDocsFilter.java |
3,687 | public static class Defaults extends AbstractFieldMapper.Defaults {
public static final String NAME = SourceFieldMapper.NAME;
public static final boolean ENABLED = true;
public static final long COMPRESS_THRESHOLD = -1;
public static final String FORMAT = null; // default format is to use the one provided
public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE);
static {
FIELD_TYPE.setIndexed(false);
FIELD_TYPE.setStored(true);
FIELD_TYPE.setOmitNorms(true);
FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_ONLY);
FIELD_TYPE.freeze();
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_internal_SourceFieldMapper.java |
1,299 | @Singleton
public static class MasterAwareService extends AbstractLifecycleComponent<MasterAwareService> implements LocalNodeMasterListener {
private final ClusterService clusterService;
private volatile boolean master;
@Inject
public MasterAwareService(Settings settings, ClusterService clusterService) {
super(settings);
clusterService.add(this);
this.clusterService = clusterService;
logger.info("initialized test service");
}
@Override
public void onMaster() {
logger.info("on master [" + clusterService.localNode() + "]");
master = true;
}
@Override
public void offMaster() {
logger.info("off master [" + clusterService.localNode() + "]");
master = false;
}
public boolean master() {
return master;
}
@Override
protected void doStart() throws ElasticsearchException {
}
@Override
protected void doStop() throws ElasticsearchException {
}
@Override
protected void doClose() throws ElasticsearchException {
}
@Override
public String executorName() {
return ThreadPool.Names.SAME;
}
} | 0true
| src_test_java_org_elasticsearch_cluster_ClusterServiceTests.java |
2,646 | zenPingA.setNodesProvider(new DiscoveryNodesProvider() {
@Override
public DiscoveryNodes nodes() {
return DiscoveryNodes.builder().put(nodeA).localNodeId("A").build();
}
@Override
public NodeService nodeService() {
return null;
}
}); | 0true
| src_test_java_org_elasticsearch_discovery_zen_ping_multicast_MulticastZenPingTests.java |
517 | MessageListener listener = new MessageListener() {
public void onMessage(Message message) {
latch.countDown();
}
}; | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_topic_ClientTopicTest.java |
214 | return new RecordIterator<KeyValueEntry>() {
private final Iterator<KeyValueEntry> entries = result.iterator();
@Override
public boolean hasNext() {
return entries.hasNext();
}
@Override
public KeyValueEntry next() {
return entries.next();
}
@Override
public void close() {
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}; | 0true
| titan-berkeleyje_src_main_java_com_thinkaurelius_titan_diskstorage_berkeleyje_BerkeleyJEKeyValueStore.java |
354 | @RunWith(HazelcastSerialClassRunner.class)
@Category(SlowTest.class)
public class ClientMapReduceTest
extends AbstractClientMapReduceJobTest {
private static final String MAP_NAME = "default";
@After
public void shutdown() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test(timeout = 60000, expected = ExecutionException.class)
public void testExceptionDistribution()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new ExceptionThrowingMapper()).submit();
try {
Map<String, List<Integer>> result = future.get();
fail();
} catch (Exception e) {
e.printStackTrace();
assertTrue(e.getCause() instanceof NullPointerException);
throw e;
}
}
@Test(timeout = 60000, expected = CancellationException.class)
public void testInProcessCancellation()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TimeConsumingMapper()).submit();
future.cancel(true);
try {
Map<String, List<Integer>> result = future.get();
fail();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
@Test(timeout = 60000)
public void testMapper()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TestMapper()).submit();
Map<String, List<Integer>> result = future.get();
assertEquals(100, result.size());
for (List<Integer> value : result.values()) {
assertEquals(1, value.size());
}
}
@Test(timeout = 60000)
public void testMapperReducer()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Map<String, Integer>> future = job.mapper(new GroupingTestMapper()).reducer(new TestReducerFactory())
.submit();
Map<String, Integer> result = future.get();
// Precalculate results
int[] expectedResults = new int[4];
for (int i = 0; i < 100; i++) {
int index = i % 4;
expectedResults[index] += i;
}
for (int i = 0; i < 4; i++) {
assertEquals(expectedResults[i], (int) result.get(String.valueOf(i)));
}
}
@Test(timeout = 60000)
public void testMapperCollator()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper()).submit(new GroupingTestCollator());
int result = future.get();
// Precalculate result
int expectedResult = 0;
for (int i = 0; i < 100; i++) {
expectedResult += i;
}
}
@Test(timeout = 60000)
public void testKeyedMapperCollator()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 10000; i++) {
m1.put(i, i);
}
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Integer> future = job.onKeys(50).mapper(new TestMapper()).submit(new GroupingTestCollator());
int result = future.get();
assertEquals(50, result);
}
@Test(timeout = 60000)
public void testKeyPredicateMapperCollator()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 10000; i++) {
m1.put(i, i);
}
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Integer> future = job.keyPredicate(new TestKeyPredicate()).mapper(new TestMapper())
.submit(new GroupingTestCollator());
int result = future.get();
assertEquals(50, result);
}
@Test(timeout = 60000)
public void testMapperReducerCollator()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper()).reducer(new TestReducerFactory())
.submit(new TestCollator());
int result = future.get();
// Precalculate result
int expectedResult = 0;
for (int i = 0; i < 100; i++) {
expectedResult += i;
}
for (int i = 0; i < 4; i++) {
assertEquals(expectedResult, result);
}
}
@Test(timeout = 60000)
public void testAsyncMapper()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
final Map<String, List<Integer>> listenerResults = new HashMap<String, List<Integer>>();
final Semaphore semaphore = new Semaphore(1);
semaphore.acquire();
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TestMapper()).submit();
future.andThen(new ExecutionCallback<Map<String, List<Integer>>>() {
@Override
public void onResponse(Map<String, List<Integer>> response) {
listenerResults.putAll(response);
semaphore.release();
}
@Override
public void onFailure(Throwable t) {
semaphore.release();
}
});
semaphore.acquire();
assertEquals(100, listenerResults.size());
for (List<Integer> value : listenerResults.values()) {
assertEquals(1, value.size());
}
}
@Test(timeout = 60000)
public void testKeyedAsyncMapper()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
final Map<String, List<Integer>> listenerResults = new HashMap<String, List<Integer>>();
final Semaphore semaphore = new Semaphore(1);
semaphore.acquire();
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Map<String, List<Integer>>> future = job.onKeys(50).mapper(new TestMapper()).submit();
future.andThen(new ExecutionCallback<Map<String, List<Integer>>>() {
@Override
public void onResponse(Map<String, List<Integer>> response) {
listenerResults.putAll(response);
semaphore.release();
}
@Override
public void onFailure(Throwable t) {
semaphore.release();
}
});
semaphore.acquire();
assertEquals(1, listenerResults.size());
for (List<Integer> value : listenerResults.values()) {
assertEquals(1, value.size());
}
}
@Test(timeout = 60000)
public void testAsyncMapperReducer()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
final Map<String, Integer> listenerResults = new HashMap<String, Integer>();
final Semaphore semaphore = new Semaphore(1);
semaphore.acquire();
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Map<String, Integer>> future = job.mapper(new GroupingTestMapper()).reducer(new TestReducerFactory())
.submit();
future.andThen(new ExecutionCallback<Map<String, Integer>>() {
@Override
public void onResponse(Map<String, Integer> response) {
listenerResults.putAll(response);
semaphore.release();
}
@Override
public void onFailure(Throwable t) {
semaphore.release();
}
});
// Precalculate results
int[] expectedResults = new int[4];
for (int i = 0; i < 100; i++) {
int index = i % 4;
expectedResults[index] += i;
}
semaphore.acquire();
for (int i = 0; i < 4; i++) {
assertEquals(expectedResults[i], (int) listenerResults.get(String.valueOf(i)));
}
}
@Test(timeout = 60000)
public void testAsyncMapperCollator()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
final int[] result = new int[1];
final Semaphore semaphore = new Semaphore(1);
semaphore.acquire();
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper())//
.submit(new GroupingTestCollator());
future.andThen(new ExecutionCallback<Integer>() {
@Override
public void onResponse(Integer response) {
result[0] = response.intValue();
semaphore.release();
}
@Override
public void onFailure(Throwable t) {
semaphore.release();
}
});
// Precalculate result
int expectedResult = 0;
for (int i = 0; i < 100; i++) {
expectedResult += i;
}
semaphore.acquire();
for (int i = 0; i < 4; i++) {
assertEquals(expectedResult, result[0]);
}
}
@Test(timeout = 60000)
public void testAsyncMapperReducerCollator()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
final int[] result = new int[1];
final Semaphore semaphore = new Semaphore(1);
semaphore.acquire();
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Integer> future = job.mapper(new GroupingTestMapper()).reducer(new TestReducerFactory())
.submit(new TestCollator());
future.andThen(new ExecutionCallback<Integer>() {
@Override
public void onResponse(Integer response) {
result[0] = response.intValue();
semaphore.release();
}
@Override
public void onFailure(Throwable t) {
semaphore.release();
}
});
// Precalculate result
int expectedResult = 0;
for (int i = 0; i < 100; i++) {
expectedResult += i;
}
semaphore.acquire();
for (int i = 0; i < 4; i++) {
assertEquals(expectedResult, result[0]);
}
}
public static class ExceptionThrowingMapper
implements Mapper<Integer, Integer, String, Integer> {
@Override
public void map(Integer key, Integer value, Context<String, Integer> context) {
throw new NullPointerException("BUMM!");
}
}
public static class TimeConsumingMapper
implements Mapper<Integer, Integer, String, Integer> {
@Override
public void map(Integer key, Integer value, Context<String, Integer> collector) {
try {
Thread.sleep(1000);
} catch (Exception ignore) {
}
collector.emit(String.valueOf(key), value);
}
}
public static class TestKeyPredicate
implements KeyPredicate<Integer> {
@Override
public boolean evaluate(Integer key) {
return key == 50;
}
}
public static class TestMapper
implements Mapper<Integer, Integer, String, Integer> {
@Override
public void map(Integer key, Integer value, Context<String, Integer> collector) {
collector.emit(String.valueOf(key), value);
}
}
public static class GroupingTestMapper
implements Mapper<Integer, Integer, String, Integer> {
@Override
public void map(Integer key, Integer value, Context<String, Integer> collector) {
collector.emit(String.valueOf(key % 4), value);
}
}
public static class TestReducer
extends Reducer<String, Integer, Integer> {
private transient int sum = 0;
@Override
public void reduce(Integer value) {
sum += value;
}
@Override
public Integer finalizeReduce() {
return sum;
}
}
public static class TestReducerFactory
implements ReducerFactory<String, Integer, Integer> {
public TestReducerFactory() {
}
@Override
public Reducer<String, Integer, Integer> newReducer(String key) {
return new TestReducer();
}
}
public static class GroupingTestCollator
implements Collator<Map.Entry<String, List<Integer>>, Integer> {
@Override
public Integer collate(Iterable<Map.Entry<String, List<Integer>>> values) {
int sum = 0;
for (Map.Entry<String, List<Integer>> entry : values) {
for (Integer value : entry.getValue()) {
sum += value;
}
}
return sum;
}
}
public static class TestCollator
implements Collator<Map.Entry<String, Integer>, Integer> {
@Override
public Integer collate(Iterable<Map.Entry<String, Integer>> values) {
int sum = 0;
for (Map.Entry<String, Integer> entry : values) {
sum += entry.getValue();
}
return sum;
}
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_ClientMapReduceTest.java |
387 | public class SupportLevel extends Level {
public SupportLevel(int level, String levelStr, int syslogEquivalent) {
super(level, levelStr, syslogEquivalent);
}
public static final int SUPPORT_INT = ERROR_INT + 10;
public static final Level SUPPORT = new SupportLevel(SUPPORT_INT, "SUPPORT", 6);
public static Level toLevel(String sArg) {
if (sArg != null && sArg.toUpperCase().equals("SUPPORT")) {
return SUPPORT;
}
return toLevel(sArg, Level.DEBUG);
}
public static Level toLevel(int val) {
if (val == SUPPORT_INT) {
return SUPPORT;
}
return toLevel(val, Level.DEBUG);
}
public static Level toLevel(int val, Level defaultLevel) {
if (val == SUPPORT_INT) {
return SUPPORT;
}
return Level.toLevel(val, defaultLevel);
}
public static Level toLevel(String sArg, Level defaultLevel) {
if (sArg != null && sArg.toUpperCase().equals("SUPPORT")) {
return SUPPORT;
}
return Level.toLevel(sArg, defaultLevel);
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_logging_SupportLevel.java |
273 | titleLabel.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
titleLabel.setStyleRanges(styleTitle(titleLabel).getStyleRanges());
}
}); | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_PeekDefinitionPopup.java |
902 | @SuppressWarnings({ "unchecked", "serial" })
public abstract class ORecordSchemaAwareAbstract<T> extends ORecordAbstract<T> implements ORecordSchemaAware<T> {
protected OClass _clazz;
public ORecordSchemaAwareAbstract() {
}
/**
* Validates the record following the declared constraints defined in schema such as mandatory, notNull, min, max, regexp, etc. If
* the schema is not defined for the current class or there are not constraints then the validation is ignored.
*
* @see OProperty
* @throws OValidationException
* if the document breaks some validation constraints defined in the schema
*/
public void validate() throws OValidationException {
if (ODatabaseRecordThreadLocal.INSTANCE.isDefined() && !getDatabase().isValidationEnabled())
return;
checkForLoading();
checkForFields();
if (_clazz != null) {
if (_clazz.isStrictMode()) {
// CHECK IF ALL FIELDS ARE DEFINED
for (String f : fieldNames()) {
if (_clazz.getProperty(f) == null)
throw new OValidationException("Found additional field '" + f + "'. It cannot be added because the schema class '"
+ _clazz.getName() + "' is defined as STRICT");
}
}
for (OProperty p : _clazz.properties()) {
validateField(this, p);
}
}
}
public OClass getSchemaClass() {
if (_clazz == null) {
// DESERIALIZE ONLY IF THE CLASS IS NOT SETTED: THIS PREVENT TO
// UNMARSHALL THE RECORD EVEN IF SETTED BY fromString()
checkForLoading();
checkForFields("@class");
}
return _clazz;
}
public String getClassName() {
if (_clazz != null)
return _clazz.getName();
// CLASS NOT FOUND: CHECK IF NEED LOADING AND UNMARSHALLING
checkForLoading();
checkForFields("@class");
return _clazz != null ? _clazz.getName() : null;
}
public void setClassName(final String iClassName) {
if (iClassName == null) {
_clazz = null;
return;
}
setClass(getDatabase().getMetadata().getSchema().getOrCreateClass(iClassName));
}
public void setClassNameIfExists(final String iClassName) {
if (iClassName == null) {
_clazz = null;
return;
}
setClass(getDatabase().getMetadata().getSchema().getClass(iClassName));
}
@Override
public ORecordSchemaAwareAbstract<T> reset() {
super.reset();
_clazz = null;
return this;
}
public byte[] toStream() {
return toStream(false);
}
public byte[] toStream(final boolean iOnlyDelta) {
if (_source == null)
_source = _recordFormat.toStream(this, iOnlyDelta);
invokeListenerEvent(ORecordListener.EVENT.MARSHALL);
return _source;
}
public void remove() {
throw new UnsupportedOperationException();
}
protected boolean checkForFields(final String... iFields) {
if (_status == ORecordElement.STATUS.LOADED && fields() == 0)
// POPULATE FIELDS LAZY
return deserializeFields(iFields);
return true;
}
public boolean deserializeFields(final String... iFields) {
if (_source == null)
return false;
_status = ORecordElement.STATUS.UNMARSHALLING;
_recordFormat.fromStream(_source, this, iFields);
_status = ORecordElement.STATUS.LOADED;
return true;
}
protected void setClass(final OClass iClass) {
if (iClass != null && iClass.isAbstract())
throw new OSchemaException("Cannot create a document of an abstract class");
_clazz = iClass;
}
protected void checkFieldAccess(final int iIndex) {
if (iIndex < 0 || iIndex >= fields())
throw new IndexOutOfBoundsException("Index " + iIndex + " is outside the range allowed: 0-" + fields());
}
public static void validateField(ORecordSchemaAwareAbstract<?> iRecord, OProperty p) throws OValidationException {
final Object fieldValue;
if (iRecord.containsField(p.getName())) {
if (iRecord instanceof ODocument)
// AVOID CONVERSIONS: FASTER!
fieldValue = ((ODocument) iRecord).rawField(p.getName());
else
fieldValue = iRecord.field(p.getName());
if (p.isNotNull() && fieldValue == null)
// NULLITY
throw new OValidationException("The field '" + p.getFullName() + "' cannot be null");
if (fieldValue != null && p.getRegexp() != null) {
// REGEXP
if (!fieldValue.toString().matches(p.getRegexp()))
throw new OValidationException("The field '" + p.getFullName() + "' does not match the regular expression '"
+ p.getRegexp() + "'. Field value is: " + fieldValue);
}
} else {
if (p.isMandatory())
throw new OValidationException("The field '" + p.getFullName() + "' is mandatory");
fieldValue = null;
}
final OType type = p.getType();
if (fieldValue != null && type != null) {
// CHECK TYPE
switch (type) {
case LINK:
validateLink(p, fieldValue);
break;
case LINKLIST:
if (!(fieldValue instanceof List))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as LINKLIST but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null)
for (Object item : ((List<?>) fieldValue))
validateLink(p, item);
break;
case LINKSET:
if (!(fieldValue instanceof Set))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as LINKSET but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null)
for (Object item : ((Set<?>) fieldValue))
validateLink(p, item);
break;
case LINKMAP:
if (!(fieldValue instanceof Map))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as LINKMAP but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null)
for (Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet())
validateLink(p, entry.getValue());
break;
case EMBEDDED:
validateEmbedded(p, fieldValue);
break;
case EMBEDDEDLIST:
if (!(fieldValue instanceof List))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as EMBEDDEDLIST but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null) {
for (Object item : ((List<?>) fieldValue))
validateEmbedded(p, item);
} else if (p.getLinkedType() != null) {
for (Object item : ((List<?>) fieldValue))
validateType(p, item);
}
break;
case EMBEDDEDSET:
if (!(fieldValue instanceof Set))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as EMBEDDEDSET but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null) {
for (Object item : ((Set<?>) fieldValue))
validateEmbedded(p, item);
} else if (p.getLinkedType() != null) {
for (Object item : ((Set<?>) fieldValue))
validateType(p, item);
}
break;
case EMBEDDEDMAP:
if (!(fieldValue instanceof Map))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as EMBEDDEDMAP but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null) {
for (Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet())
validateEmbedded(p, entry.getValue());
} else if (p.getLinkedType() != null) {
for (Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet())
validateType(p, entry.getValue());
}
break;
}
}
if (p.getMin() != null) {
// MIN
final String min = p.getMin();
if (p.getType().equals(OType.STRING) && (fieldValue != null && ((String) fieldValue).length() < Integer.parseInt(min)))
throw new OValidationException("The field '" + p.getFullName() + "' contains fewer characters than " + min + " requested");
else if (p.getType().equals(OType.BINARY) && (fieldValue != null && ((byte[]) fieldValue).length < Integer.parseInt(min)))
throw new OValidationException("The field '" + p.getFullName() + "' contains fewer bytes than " + min + " requested");
else if (p.getType().equals(OType.INTEGER) && (fieldValue != null && type.asInt(fieldValue) < Integer.parseInt(min)))
throw new OValidationException("The field '" + p.getFullName() + "' is less than " + min);
else if (p.getType().equals(OType.LONG) && (fieldValue != null && type.asLong(fieldValue) < Long.parseLong(min)))
throw new OValidationException("The field '" + p.getFullName() + "' is less than " + min);
else if (p.getType().equals(OType.FLOAT) && (fieldValue != null && type.asFloat(fieldValue) < Float.parseFloat(min)))
throw new OValidationException("The field '" + p.getFullName() + "' is less than " + min);
else if (p.getType().equals(OType.DOUBLE) && (fieldValue != null && type.asDouble(fieldValue) < Double.parseDouble(min)))
throw new OValidationException("The field '" + p.getFullName() + "' is less than " + min);
else if (p.getType().equals(OType.DATE)) {
try {
if (fieldValue != null
&& ((Date) fieldValue).before(iRecord.getDatabase().getStorage().getConfiguration().getDateFormatInstance()
.parse(min)))
throw new OValidationException("The field '" + p.getFullName() + "' contains the date " + fieldValue
+ " which precedes the first acceptable date (" + min + ")");
} catch (ParseException e) {
}
} else if (p.getType().equals(OType.DATETIME)) {
try {
if (fieldValue != null
&& ((Date) fieldValue).before(iRecord.getDatabase().getStorage().getConfiguration().getDateTimeFormatInstance()
.parse(min)))
throw new OValidationException("The field '" + p.getFullName() + "' contains the datetime " + fieldValue
+ " which precedes the first acceptable datetime (" + min + ")");
} catch (ParseException e) {
}
} else if ((p.getType().equals(OType.EMBEDDEDLIST) || p.getType().equals(OType.EMBEDDEDSET)
|| p.getType().equals(OType.LINKLIST) || p.getType().equals(OType.LINKSET))
&& (fieldValue != null && ((Collection<?>) fieldValue).size() < Integer.parseInt(min)))
throw new OValidationException("The field '" + p.getFullName() + "' contains fewer items than " + min + " requested");
}
if (p.getMax() != null) {
// MAX
final String max = p.getMax();
if (p.getType().equals(OType.STRING) && (fieldValue != null && ((String) fieldValue).length() > Integer.parseInt(max)))
throw new OValidationException("The field '" + p.getFullName() + "' contains more characters than " + max + " requested");
else if (p.getType().equals(OType.BINARY) && (fieldValue != null && ((byte[]) fieldValue).length > Integer.parseInt(max)))
throw new OValidationException("The field '" + p.getFullName() + "' contains more bytes than " + max + " requested");
else if (p.getType().equals(OType.INTEGER) && (fieldValue != null && type.asInt(fieldValue) > Integer.parseInt(max)))
throw new OValidationException("The field '" + p.getFullName() + "' is greater than " + max);
else if (p.getType().equals(OType.LONG) && (fieldValue != null && type.asLong(fieldValue) > Long.parseLong(max)))
throw new OValidationException("The field '" + p.getFullName() + "' is greater than " + max);
else if (p.getType().equals(OType.FLOAT) && (fieldValue != null && type.asFloat(fieldValue) > Float.parseFloat(max)))
throw new OValidationException("The field '" + p.getFullName() + "' is greater than " + max);
else if (p.getType().equals(OType.DOUBLE) && (fieldValue != null && type.asDouble(fieldValue) > Double.parseDouble(max)))
throw new OValidationException("The field '" + p.getFullName() + "' is greater than " + max);
else if (p.getType().equals(OType.DATE)) {
try {
if (fieldValue != null
&& ((Date) fieldValue).before(iRecord.getDatabase().getStorage().getConfiguration().getDateFormatInstance()
.parse(max)))
throw new OValidationException("The field '" + p.getFullName() + "' contains the date " + fieldValue
+ " which is after the last acceptable date (" + max + ")");
} catch (ParseException e) {
}
} else if (p.getType().equals(OType.DATETIME)) {
try {
if (fieldValue != null
&& ((Date) fieldValue).before(iRecord.getDatabase().getStorage().getConfiguration().getDateTimeFormatInstance()
.parse(max)))
throw new OValidationException("The field '" + p.getFullName() + "' contains the datetime " + fieldValue
+ " which is after the last acceptable datetime (" + max + ")");
} catch (ParseException e) {
}
} else if ((p.getType().equals(OType.EMBEDDEDLIST) || p.getType().equals(OType.EMBEDDEDSET)
|| p.getType().equals(OType.LINKLIST) || p.getType().equals(OType.LINKSET))
&& (fieldValue != null && ((Collection<?>) fieldValue).size() > Integer.parseInt(max)))
throw new OValidationException("The field '" + p.getFullName() + "' contains more items than " + max + " requested");
}
if (p.isReadonly() && iRecord instanceof ODocument && !iRecord.getRecordVersion().isTombstone()) {
for (String f : ((ODocument) iRecord).getDirtyFields())
if (f.equals(p.getName())) {
// check if the field is actually changed by equal.
// this is due to a limitation in the merge algorithm used server side marking all non simple fields as dirty
Object orgVal = ((ODocument) iRecord).getOriginalValue(f);
boolean simple = fieldValue != null ? OType.isSimpleType(fieldValue) : OType.isSimpleType(orgVal);
if ((simple) || (fieldValue != null && orgVal == null) || (fieldValue == null && orgVal != null)
|| (!fieldValue.equals(orgVal)))
throw new OValidationException("The field '" + p.getFullName()
+ "' is immutable and cannot be altered. Field value is: " + ((ODocument) iRecord).field(f));
}
}
}
protected static void validateType(final OProperty p, final Object value) {
if (value != null)
if (OType.convert(value, p.getLinkedType().getDefaultJavaType()) == null)
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType() + " of type '"
+ p.getLinkedType() + "' but the value is " + value);
}
protected static void validateLink(final OProperty p, final Object fieldValue) {
if (fieldValue == null)
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but contains a null record (probably a deleted record?)");
final ORecord<?> linkedRecord;
if (fieldValue instanceof OIdentifiable)
linkedRecord = ((OIdentifiable) fieldValue).getRecord();
else if (fieldValue instanceof String)
linkedRecord = new ORecordId((String) fieldValue).getRecord();
else
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but the value is not a record or a record-id");
if (linkedRecord != null && p.getLinkedClass() != null) {
if (!(linkedRecord instanceof ODocument))
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType() + " of type '"
+ p.getLinkedClass() + "' but the value is the record " + linkedRecord.getIdentity() + " that is not a document");
final ODocument doc = (ODocument) linkedRecord;
// AT THIS POINT CHECK THE CLASS ONLY IF != NULL BECAUSE IN CASE OF GRAPHS THE RECORD COULD BE PARTIAL
if (doc.getSchemaClass() != null && !p.getLinkedClass().isSuperClassOf(doc.getSchemaClass()))
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType() + " of type '"
+ p.getLinkedClass().getName() + "' but the value is the document " + linkedRecord.getIdentity() + " of class '"
+ doc.getSchemaClass() + "'");
}
}
protected static void validateEmbedded(final OProperty p, final Object fieldValue) {
if (fieldValue instanceof ORecordId)
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but the value is the RecordID " + fieldValue);
else if (fieldValue instanceof OIdentifiable) {
if (((OIdentifiable) fieldValue).getIdentity().isValid())
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but the value is a document with the valid RecordID " + fieldValue);
final OClass embeddedClass = p.getLinkedClass();
if (embeddedClass != null) {
final ORecord<?> rec = ((OIdentifiable) fieldValue).getRecord();
if (!(rec instanceof ODocument))
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " with linked class '" + embeddedClass + "' but the record was not a document");
final ODocument doc = (ODocument) rec;
if (doc.getSchemaClass() == null)
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " with linked class '" + embeddedClass + "' but the record has no class");
if (!(doc.getSchemaClass().isSubClassOf(embeddedClass)))
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " with linked class '" + embeddedClass + "' but the record is of class '" + doc.getSchemaClass().getName()
+ "' that is not a subclass of that");
}
} else
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but an incompatible type is used. Value: " + fieldValue);
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_record_ORecordSchemaAwareAbstract.java |
191 | public interface TransferQueue<E> extends BlockingQueue<E> {
/**
* Transfers the element to a waiting consumer immediately, if possible.
*
* <p>More precisely, transfers the specified element immediately
* if there exists a consumer already waiting to receive it (in
* {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
* otherwise returning {@code false} without enqueuing the element.
*
* @param e the element to transfer
* @return {@code true} if the element was transferred, else
* {@code false}
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this queue
*/
boolean tryTransfer(E e);
/**
* Transfers the element to a consumer, waiting if necessary to do so.
*
* <p>More precisely, transfers the specified element immediately
* if there exists a consumer already waiting to receive it (in
* {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
* else waits until the element is received by a consumer.
*
* @param e the element to transfer
* @throws InterruptedException if interrupted while waiting,
* in which case the element is not left enqueued
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this queue
*/
void transfer(E e) throws InterruptedException;
/**
* Transfers the element to a consumer if it is possible to do so
* before the timeout elapses.
*
* <p>More precisely, transfers the specified element immediately
* if there exists a consumer already waiting to receive it (in
* {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
* else waits until the element is received by a consumer,
* returning {@code false} if the specified wait time elapses
* before the element can be transferred.
*
* @param e the element to transfer
* @param timeout how long to wait before giving up, in units of
* {@code unit}
* @param unit a {@code TimeUnit} determining how to interpret the
* {@code timeout} parameter
* @return {@code true} if successful, or {@code false} if
* the specified waiting time elapses before completion,
* in which case the element is not left enqueued
* @throws InterruptedException if interrupted while waiting,
* in which case the element is not left enqueued
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this queue
*/
boolean tryTransfer(E e, long timeout, TimeUnit unit)
throws InterruptedException;
/**
* Returns {@code true} if there is at least one consumer waiting
* to receive an element via {@link #take} or
* timed {@link #poll(long,TimeUnit) poll}.
* The return value represents a momentary state of affairs.
*
* @return {@code true} if there is at least one waiting consumer
*/
boolean hasWaitingConsumer();
/**
* Returns an estimate of the number of consumers waiting to
* receive elements via {@link #take} or timed
* {@link #poll(long,TimeUnit) poll}. The return value is an
* approximation of a momentary state of affairs, that may be
* inaccurate if consumers have completed or given up waiting.
* The value may be useful for monitoring and heuristics, but
* not for synchronization control. Implementations of this
* method are likely to be noticeably slower than those for
* {@link #hasWaitingConsumer}.
*
* @return the number of consumers waiting to receive elements
*/
int getWaitingConsumerCount();
} | 0true
| src_main_java_jsr166y_TransferQueue.java |
941 | public class VerifyCustomerMaxOfferUsesActivity extends BaseActivity<CheckoutContext> {
@Resource(name="blOfferAuditService")
protected OfferAuditService offerAuditService;
@Resource(name = "blOfferService")
protected OfferService offerService;
@Override
public CheckoutContext execute(CheckoutContext context) throws Exception {
Order order = context.getSeedData().getOrder();
Set<Offer> appliedOffers = offerService.getUniqueOffersFromOrder(order);
for (Offer offer : appliedOffers) {
if (offer.isLimitedUsePerCustomer()) {
Long currentUses = offerAuditService.countUsesByCustomer(order.getCustomer().getId(), offer.getId());
if (currentUses >= offer.getMaxUsesPerCustomer()) {
throw new OfferMaxUseExceededException("The customer has used this offer more than the maximum allowed number of times.");
}
}
}
//TODO: allow lenient checking on offer code usage
for (OfferCode code : order.getAddedOfferCodes()) {
if (code.isLimitedUse()) {
Long currentCodeUses = offerAuditService.countOfferCodeUses(code.getId());
if (currentCodeUses >= code.getMaxUses()) {
throw new OfferMaxUseExceededException("Offer code " + code.getOfferCode() + " with id " + code.getId()
+ " has been than the maximum allowed number of times.");
}
}
}
return context;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_workflow_VerifyCustomerMaxOfferUsesActivity.java |
1,625 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class TimedMemberStateTest extends HazelcastTestSupport {
@Test
public void testSerialization() throws InterruptedException {
HazelcastInstance hz = createHazelcastInstance();
SerializationService serializationService = getNode(hz).getSerializationService();
TimedMemberStateFactory timedMemberStateFactory = new TimedMemberStateFactory(getHazelcastInstanceImpl(hz));
TimedMemberState state = timedMemberStateFactory.createTimedMemberState();
Data data = serializationService.toData(state);
TimedMemberState result = serializationService.toObject(data);
assertNotNull(result);
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_management_TimedMemberStateTest.java |
1,201 | public interface MultiMap<K, V> extends BaseMultiMap<K, V>, DistributedObject {
/**
* Returns the name of this multimap.
*
* @return the name of this multimap
*/
String getName();
/**
* Stores a key-value pair in the multimap.
* <p/>
* <p><b>Warning:</b></p>
* <p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
* </p>
*
* @param key the key to be stored
* @param value the value to be stored
* @return true if size of the multimap is increased, false if the multimap
* already contains the key-value pair.
*/
boolean put(K key, V value);
/**
* Returns the collection of values associated with the key.
* <p/>
* <p><b>Warning:</b></p>
* <p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
* </p>
* <p/>
* <p><b>Warning-2:</b></p>
* The collection is <b>NOT</b> backed by the map,
* so changes to the map are <b>NOT</b> reflected in the collection, and vice-versa.
*
* @param key the key whose associated values are to be returned
* @return the collection of the values associated with the key.
*/
Collection<V> get(K key);
/**
* Removes the given key value pair from the multimap.
* <p/>
* <p><b>Warning:</b></p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
*
* @param key the key of the entry to remove
* @param value the value of the entry to remove
* @return true if the size of the multimap changed after the remove operation, false otherwise.
*/
boolean remove(Object key, Object value);
/**
* Removes all the entries with the given key.
* <p/>
* <p><b>Warning:</b></p>
* <p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
* </p>
* <p/>
* <p><b>Warning-2:</b></p>
* The collection is <b>NOT</b> backed by the map,
* so changes to the map are <b>NOT</b> reflected in the collection, and vice-versa.
*
* @param key the key of the entries to remove
* @return the collection of removed values associated with the given key. Returned collection
* might be modifiable but it has no effect on the multimap
*/
Collection<V> remove(Object key);
/**
* Returns the locally owned set of keys.
* <p/>
* Each key in this map is owned and managed by a specific
* member in the cluster.
* <p/>
* Note that ownership of these keys might change over time
* so that key ownerships can be almost evenly distributed
* in the cluster.
* <p/>
* <p><b>Warning:</b></p>
* The set is <b>NOT</b> backed by the map,
* so changes to the map are <b>NOT</b> reflected in the set, and vice-versa.
*
* @return locally owned keys.
*/
Set<K> localKeySet();
/**
* Returns the set of keys in the multimap.
* <p/>
* <p><b>Warning:</b></p>
* The set is <b>NOT</b> backed by the map,
* so changes to the map are <b>NOT</b> reflected in the set, and vice-versa.
*
* @return the set of keys in the multimap. Returned set might be modifiable
* but it has no effect on the multimap
*/
Set<K> keySet();
/**
* Returns the collection of values in the multimap.
* <p/>
* <p><b>Warning:</b></p>
* The collection is <b>NOT</b> backed by the map,
* so changes to the map are <b>NOT</b> reflected in the collection, and vice-versa.
*
* @return the collection of values in the multimap. Returned collection might be modifiable
* but it has no effect on the multimap
*/
Collection<V> values();
/**
* Returns the set of key-value pairs in the multimap.
* <p/>
* <p><b>Warning:</b></p>
* The set is <b>NOT</b> backed by the map,
* so changes to the map are <b>NOT</b> reflected in the set, and vice-versa.
*
* @return the set of key-value pairs in the multimap. Returned set might be modifiable
* but it has no effect on the multimap
*/
Set<Map.Entry<K, V>> entrySet();
/**
* Returns whether the multimap contains an entry with the key.
* <p/>
* <p><b>Warning:</b></p>
* <p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
* </p>
*
* @param key the key whose existence is checked.
* @return true if the multimap contains an entry with the key, false otherwise.
*/
boolean containsKey(K key);
/**
* Returns whether the multimap contains an entry with the value.
* <p/>
*
* @param value the value whose existence is checked.
* @return true if the multimap contains an entry with the value, false otherwise.
*/
boolean containsValue(Object value);
/**
* Returns whether the multimap contains the given key-value pair.
* <p/>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
*
* @param key the key whose existence is checked.
* @param value the value whose existence is checked.
* @return true if the multimap contains the key-value pair, false otherwise.
*/
boolean containsEntry(K key, V value);
/**
* Returns the number of key-value pairs in the multimap.
*
* @return the number of key-value pairs in the multimap.
*/
int size();
/**
* Clears the multimap. Removes all key-value pairs.
*/
void clear();
/**
* Returns number of values matching to given key in the multimap.
* <p/>
* <p><b>Warning:</b></p>
* <p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
* </p>
*
* @param key the key whose values count are to be returned
* @return number of values matching to given key in the multimap.
*/
int valueCount(K key);
/**
* Adds a local entry listener for this multimap. Added listener will be only
* listening for the events (add/remove/update) of the locally owned entries.
* <p/>
* Note that entries in distributed multimap are partitioned across
* the cluster members; each member owns and manages the some portion of the
* entries. Owned entries are called local entries. This
* listener will be listening for the events of local entries. Let's say
* your cluster has member1 and member2. On member2 you added a local listener and from
* member1, you call <code>multimap.put(key2, value2)</code>.
* If the key2 is owned by member2 then the local listener will be
* notified for the add/update event. Also note that entries can migrate to
* other nodes for load balancing and/or membership change.
*
* @param listener entry listener
* @see #localKeySet()
*
* @return returns registration id.
*/
String addLocalEntryListener(EntryListener<K, V> listener);
/**
* Adds an entry listener for this multimap. Listener will get notified
* for all multimap add/remove/update/evict events.
*
* @param listener entry listener
* @param includeValue <tt>true</tt> if <tt>EntryEvent</tt> should
* contain the value.
*
* @return returns registration id.
*/
String addEntryListener(EntryListener<K, V> listener, boolean includeValue);
/**
* Removes the specified entry listener
* Returns silently if there is no such listener added before.
*
* @param registrationId Id of listener registration
*
* @return true if registration is removed, false otherwise
*/
boolean removeEntryListener(String registrationId);
/**
* Adds the specified entry listener for the specified key.
* The listener will get notified for all
* add/remove/update/evict events of the specified key only.
* <p/>
* <p><b>Warning:</b></p>
* <p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
* </p>
*
* @param listener entry listener
* @param key the key to listen
* @param includeValue <tt>true</tt> if <tt>EntryEvent</tt> should
* contain the value.
*
* @return returns registration id.
*/
String addEntryListener(EntryListener<K, V> listener, K key, boolean includeValue);
/**
* Acquires the lock for the specified key.
* <p>If the lock is not available then
* the current thread becomes disabled for thread scheduling
* purposes and lies dormant until the lock has been acquired.
* <p/>
* Scope of the lock is this multimap only.
* Acquired lock is only for the key in this multimap.
* <p/>
* Locks are re-entrant so if the key is locked N times then
* it should be unlocked N times before another thread can acquire it.
* <p/>
* <p><b>Warning:</b></p>
* <p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
* </p>
*
* @param key key to lock.
*/
void lock(K key);
/**
* Acquires the lock for the specified key for the specified lease time.
* <p>After lease time, lock will be released..
* <p/>
* <p>If the lock is not available then
* the current thread becomes disabled for thread scheduling
* purposes and lies dormant until the lock has been acquired.
* <p/>
* Scope of the lock is this map only.
* Acquired lock is only for the key in this map.
* <p/>
* Locks are re-entrant so if the key is locked N times then
* it should be unlocked N times before another thread can acquire it.
* <p/>
* <p><b>Warning:</b></p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
*
* @param key key to lock.
* @param leaseTime time to wait before releasing the lock.
* @param timeUnit unit of time to specify lease time.
*/
void lock(K key, long leaseTime, TimeUnit timeUnit);
/**
* Checks the lock for the specified key.
* <p>If the lock is acquired then returns true, else false.
* <p/>
* <p><b>Warning:</b></p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
*
* @param key key to lock to be checked.
* @return <tt>true</tt> if lock is acquired, <tt>false</tt> otherwise.
*/
boolean isLocked(K key);
/**
* Tries to acquire the lock for the specified key.
* <p>If the lock is not available then the current thread
* doesn't wait and returns false immediately.
* <p/>
* <p><b>Warning:</b></p>
* <p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
* </p>
*
* @param key key to lock.
* @return <tt>true</tt> if lock is acquired, <tt>false</tt> otherwise.
*/
boolean tryLock(K key);
/**
* Tries to acquire the lock for the specified key.
* <p>If the lock is not available then
* the current thread becomes disabled for thread scheduling
* purposes and lies dormant until one of two things happens:
* <ul>
* <li>The lock is acquired by the current thread; or
* <li>The specified waiting time elapses
* </ul>
* <p/>
* <p><b>Warning:</b></p>
* <p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
* </p>
*
* @param time the maximum time to wait for the lock
* @param timeunit the time unit of the <tt>time</tt> argument.
* @return <tt>true</tt> if the lock was acquired and <tt>false</tt>
* if the waiting time elapsed before the lock was acquired.
*/
boolean tryLock(K key, long time, TimeUnit timeunit) throws InterruptedException;
/**
* Releases the lock for the specified key. It never blocks and
* returns immediately.
* <p/>
* <p><b>Warning:</b></p>
* <p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
* </p>
*
* @param key key to lock.
*/
void unlock(K key);
/**
* Releases the lock for the specified key regardless of the lock owner.
* It always successfully unlocks the key, never blocks
* and returns immediately.
* <p/>
* <p><b>Warning:</b></p>
* This method uses <tt>hashCode</tt> and <tt>equals</tt> of binary form of
* the <tt>key</tt>, not the actual implementations of <tt>hashCode</tt> and <tt>equals</tt>
* defined in <tt>key</tt>'s class.
*
* @param key key to lock.
*/
void forceUnlock(K key);
/**
* Returns LocalMultiMapStats for this map.
* LocalMultiMapStats is the statistics for the local portion of this
* distributed multi map and contains information such as ownedEntryCount
* backupEntryCount, lastUpdateTime, lockedEntryCount.
* <p/>
* Since this stats are only for the local portion of this multi map, if you
* need the cluster-wide MultiMapStats then you need to get the LocalMapStats
* from all members of the cluster and combine them.
*
* @return this multimap's local statistics.
*/
LocalMultiMapStats getLocalMultiMapStats();
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_MultiMap.java |
331 | public abstract class BaseHandler implements MergeHandler, Comparable<Object> {
protected int priority;
protected String xpath;
protected MergeHandler[] children = {};
protected String name;
public int getPriority() {
return priority;
}
public String getXPath() {
return xpath;
}
public void setPriority(int priority) {
this.priority = priority;
}
public void setXPath(String xpath) {
this.xpath = xpath;
}
public int compareTo(Object arg0) {
return new Integer(getPriority()).compareTo(new Integer(((MergeHandler) arg0).getPriority()));
}
public MergeHandler[] getChildren() {
return children;
}
public void setChildren(MergeHandler[] children) {
this.children = children;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_BaseHandler.java |
2,659 | public class UnicastZenPingTests extends ElasticsearchTestCase {
@Test
public void testSimplePings() {
Settings settings = ImmutableSettings.EMPTY;
int startPort = 11000 + randomIntBetween(0, 1000);
int endPort = startPort + 10;
settings = ImmutableSettings.builder().put(settings).put("transport.tcp.port", startPort + "-" + endPort).build();
ThreadPool threadPool = new ThreadPool();
ClusterName clusterName = new ClusterName("test");
NetworkService networkService = new NetworkService(settings);
NettyTransport transportA = new NettyTransport(settings, threadPool, networkService, Version.CURRENT);
final TransportService transportServiceA = new TransportService(transportA, threadPool).start();
final DiscoveryNode nodeA = new DiscoveryNode("UZP_A", transportServiceA.boundAddress().publishAddress(), Version.CURRENT);
InetSocketTransportAddress addressA = (InetSocketTransportAddress) transportA.boundAddress().publishAddress();
NettyTransport transportB = new NettyTransport(settings, threadPool, networkService, Version.CURRENT);
final TransportService transportServiceB = new TransportService(transportB, threadPool).start();
final DiscoveryNode nodeB = new DiscoveryNode("UZP_B", transportServiceA.boundAddress().publishAddress(), Version.CURRENT);
InetSocketTransportAddress addressB = (InetSocketTransportAddress) transportB.boundAddress().publishAddress();
Settings hostsSettings = ImmutableSettings.settingsBuilder().putArray("discovery.zen.ping.unicast.hosts",
addressA.address().getAddress().getHostAddress() + ":" + addressA.address().getPort(),
addressB.address().getAddress().getHostAddress() + ":" + addressB.address().getPort())
.build();
UnicastZenPing zenPingA = new UnicastZenPing(hostsSettings, threadPool, transportServiceA, clusterName, Version.CURRENT, null);
zenPingA.setNodesProvider(new DiscoveryNodesProvider() {
@Override
public DiscoveryNodes nodes() {
return DiscoveryNodes.builder().put(nodeA).localNodeId("UZP_A").build();
}
@Override
public NodeService nodeService() {
return null;
}
});
zenPingA.start();
UnicastZenPing zenPingB = new UnicastZenPing(hostsSettings, threadPool, transportServiceB, clusterName, Version.CURRENT, null);
zenPingB.setNodesProvider(new DiscoveryNodesProvider() {
@Override
public DiscoveryNodes nodes() {
return DiscoveryNodes.builder().put(nodeB).localNodeId("UZP_B").build();
}
@Override
public NodeService nodeService() {
return null;
}
});
zenPingB.start();
try {
ZenPing.PingResponse[] pingResponses = zenPingA.pingAndWait(TimeValue.timeValueSeconds(1));
assertThat(pingResponses.length, equalTo(1));
assertThat(pingResponses[0].target().id(), equalTo("UZP_B"));
} finally {
zenPingA.close();
zenPingB.close();
transportServiceA.close();
transportServiceB.close();
threadPool.shutdown();
}
}
} | 0true
| src_test_java_org_elasticsearch_discovery_zen_ping_unicast_UnicastZenPingTests.java |
120 | public interface OVariableParserListener {
public Object resolve(String iVariable);
} | 0true
| commons_src_main_java_com_orientechnologies_common_parser_OVariableParserListener.java |
4,628 | public final class InternalNode implements Node {
private final Lifecycle lifecycle = new Lifecycle();
private final Injector injector;
private final Settings settings;
private final Environment environment;
private final PluginsService pluginsService;
private final Client client;
public InternalNode() throws ElasticsearchException {
this(ImmutableSettings.Builder.EMPTY_SETTINGS, true);
}
public InternalNode(Settings pSettings, boolean loadConfigSettings) throws ElasticsearchException {
Tuple<Settings, Environment> tuple = InternalSettingsPreparer.prepareSettings(pSettings, loadConfigSettings);
tuple = new Tuple<Settings, Environment>(TribeService.processSettings(tuple.v1()), tuple.v2());
Version version = Version.CURRENT;
ESLogger logger = Loggers.getLogger(Node.class, tuple.v1().get("name"));
logger.info("version[{}], pid[{}], build[{}/{}]", version, JvmInfo.jvmInfo().pid(), Build.CURRENT.hashShort(), Build.CURRENT.timestamp());
logger.info("initializing ...");
if (logger.isDebugEnabled()) {
Environment env = tuple.v2();
logger.debug("using home [{}], config [{}], data [{}], logs [{}], work [{}], plugins [{}]",
env.homeFile(), env.configFile(), Arrays.toString(env.dataFiles()), env.logsFile(),
env.workFile(), env.pluginsFile());
}
this.pluginsService = new PluginsService(tuple.v1(), tuple.v2());
this.settings = pluginsService.updatedSettings();
// create the environment based on the finalized (processed) view of the settings
this.environment = new Environment(this.settings());
CompressorFactory.configure(settings);
NodeEnvironment nodeEnvironment = new NodeEnvironment(this.settings, this.environment);
ModulesBuilder modules = new ModulesBuilder();
modules.add(new Version.Module(version));
modules.add(new CacheRecyclerModule(settings));
modules.add(new PageCacheRecyclerModule(settings));
modules.add(new PluginsModule(settings, pluginsService));
modules.add(new SettingsModule(settings));
modules.add(new NodeModule(this));
modules.add(new NetworkModule());
modules.add(new ScriptModule(settings));
modules.add(new EnvironmentModule(environment));
modules.add(new NodeEnvironmentModule(nodeEnvironment));
modules.add(new ClusterNameModule(settings));
modules.add(new ThreadPoolModule(settings));
modules.add(new DiscoveryModule(settings));
modules.add(new ClusterModule(settings));
modules.add(new RestModule(settings));
modules.add(new TransportModule(settings));
if (settings.getAsBoolean("http.enabled", true)) {
modules.add(new HttpServerModule(settings));
}
modules.add(new RiversModule(settings));
modules.add(new IndicesModule(settings));
modules.add(new SearchModule());
modules.add(new ActionModule(false));
modules.add(new MonitorModule(settings));
modules.add(new GatewayModule(settings));
modules.add(new NodeClientModule());
modules.add(new BulkUdpModule());
modules.add(new ShapeModule());
modules.add(new PercolatorModule());
modules.add(new ResourceWatcherModule());
modules.add(new RepositoriesModule());
modules.add(new TribeModule());
injector = modules.createInjector();
client = injector.getInstance(Client.class);
logger.info("initialized");
}
@Override
public Settings settings() {
return this.settings;
}
@Override
public Client client() {
return client;
}
public Node start() {
if (!lifecycle.moveToStarted()) {
return this;
}
ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
logger.info("starting ...");
// hack around dependency injection problem (for now...)
injector.getInstance(Discovery.class).setAllocationService(injector.getInstance(AllocationService.class));
for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
injector.getInstance(plugin).start();
}
injector.getInstance(IndicesService.class).start();
injector.getInstance(IndexingMemoryController.class).start();
injector.getInstance(IndicesClusterStateService.class).start();
injector.getInstance(IndicesTTLService.class).start();
injector.getInstance(RiversManager.class).start();
injector.getInstance(ClusterService.class).start();
injector.getInstance(RoutingService.class).start();
injector.getInstance(SearchService.class).start();
injector.getInstance(MonitorService.class).start();
injector.getInstance(RestController.class).start();
injector.getInstance(TransportService.class).start();
DiscoveryService discoService = injector.getInstance(DiscoveryService.class).start();
// gateway should start after disco, so it can try and recovery from gateway on "start"
injector.getInstance(GatewayService.class).start();
if (settings.getAsBoolean("http.enabled", true)) {
injector.getInstance(HttpServer.class).start();
}
injector.getInstance(BulkUdpService.class).start();
injector.getInstance(ResourceWatcherService.class).start();
injector.getInstance(TribeService.class).start();
logger.info("started");
return this;
}
@Override
public Node stop() {
if (!lifecycle.moveToStopped()) {
return this;
}
ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
logger.info("stopping ...");
injector.getInstance(TribeService.class).stop();
injector.getInstance(BulkUdpService.class).stop();
injector.getInstance(ResourceWatcherService.class).stop();
if (settings.getAsBoolean("http.enabled", true)) {
injector.getInstance(HttpServer.class).stop();
}
injector.getInstance(RiversManager.class).stop();
// stop any changes happening as a result of cluster state changes
injector.getInstance(IndicesClusterStateService.class).stop();
// we close indices first, so operations won't be allowed on it
injector.getInstance(IndexingMemoryController.class).stop();
injector.getInstance(IndicesTTLService.class).stop();
injector.getInstance(IndicesService.class).stop();
// sleep a bit to let operations finish with indices service
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// // ignore
// }
injector.getInstance(RoutingService.class).stop();
injector.getInstance(ClusterService.class).stop();
injector.getInstance(DiscoveryService.class).stop();
injector.getInstance(MonitorService.class).stop();
injector.getInstance(GatewayService.class).stop();
injector.getInstance(SearchService.class).stop();
injector.getInstance(RestController.class).stop();
injector.getInstance(TransportService.class).stop();
for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
injector.getInstance(plugin).stop();
}
logger.info("stopped");
return this;
}
public void close() {
if (lifecycle.started()) {
stop();
}
if (!lifecycle.moveToClosed()) {
return;
}
ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
logger.info("closing ...");
StopWatch stopWatch = new StopWatch("node_close");
stopWatch.start("tribe");
injector.getInstance(TribeService.class).close();
stopWatch.stop().start("bulk.udp");
injector.getInstance(BulkUdpService.class).close();
stopWatch.stop().start("http");
if (settings.getAsBoolean("http.enabled", true)) {
injector.getInstance(HttpServer.class).close();
}
stopWatch.stop().start("rivers");
injector.getInstance(RiversManager.class).close();
stopWatch.stop().start("client");
injector.getInstance(Client.class).close();
stopWatch.stop().start("indices_cluster");
injector.getInstance(IndicesClusterStateService.class).close();
stopWatch.stop().start("indices");
injector.getInstance(IndicesFilterCache.class).close();
injector.getInstance(IndicesFieldDataCache.class).close();
injector.getInstance(IndexingMemoryController.class).close();
injector.getInstance(IndicesTTLService.class).close();
injector.getInstance(IndicesService.class).close();
stopWatch.stop().start("routing");
injector.getInstance(RoutingService.class).close();
stopWatch.stop().start("cluster");
injector.getInstance(ClusterService.class).close();
stopWatch.stop().start("discovery");
injector.getInstance(DiscoveryService.class).close();
stopWatch.stop().start("monitor");
injector.getInstance(MonitorService.class).close();
stopWatch.stop().start("gateway");
injector.getInstance(GatewayService.class).close();
stopWatch.stop().start("search");
injector.getInstance(SearchService.class).close();
stopWatch.stop().start("rest");
injector.getInstance(RestController.class).close();
stopWatch.stop().start("transport");
injector.getInstance(TransportService.class).close();
stopWatch.stop().start("percolator_service");
injector.getInstance(PercolatorService.class).close();
for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
stopWatch.stop().start("plugin(" + plugin.getName() + ")");
injector.getInstance(plugin).close();
}
stopWatch.stop().start("script");
injector.getInstance(ScriptService.class).close();
stopWatch.stop().start("thread_pool");
injector.getInstance(ThreadPool.class).shutdown();
try {
injector.getInstance(ThreadPool.class).awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// ignore
}
stopWatch.stop().start("thread_pool_force_shutdown");
try {
injector.getInstance(ThreadPool.class).shutdownNow();
} catch (Exception e) {
// ignore
}
stopWatch.stop();
if (logger.isTraceEnabled()) {
logger.trace("Close times for each service:\n{}", stopWatch.prettyPrint());
}
injector.getInstance(NodeEnvironment.class).close();
injector.getInstance(CacheRecycler.class).close();
injector.getInstance(PageCacheRecycler.class).close();
Injectors.close(injector);
CachedStreams.clear();
logger.info("closed");
}
@Override
public boolean isClosed() {
return lifecycle.closed();
}
public Injector injector() {
return this.injector;
}
public static void main(String[] args) throws Exception {
final InternalNode node = new InternalNode();
node.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
node.close();
}
});
}
} | 1no label
| src_main_java_org_elasticsearch_node_internal_InternalNode.java |
1,272 | nodesService.execute(new TransportClientNodesService.NodeListenerCallback<Response>() {
@Override
public void doWithNode(DiscoveryNode node, ActionListener<Response> listener) throws ElasticsearchException {
proxy.execute(node, request, listener);
}
}, listener); | 0true
| src_main_java_org_elasticsearch_client_transport_support_InternalTransportClusterAdminClient.java |
3,707 | public static class Builder extends Mapper.Builder<Builder, VersionFieldMapper> {
DocValuesFormatProvider docValuesFormat;
public Builder() {
super(Defaults.NAME);
}
@Override
public VersionFieldMapper build(BuilderContext context) {
return new VersionFieldMapper(docValuesFormat);
}
public Builder docValuesFormat(DocValuesFormatProvider docValuesFormat) {
this.docValuesFormat = docValuesFormat;
return this;
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_internal_VersionFieldMapper.java |
2,172 | public class OrDocIdSet extends DocIdSet {
private final DocIdSet[] sets;
public OrDocIdSet(DocIdSet[] sets) {
this.sets = sets;
}
@Override
public boolean isCacheable() {
for (DocIdSet set : sets) {
if (!set.isCacheable()) {
return false;
}
}
return true;
}
@Override
public Bits bits() throws IOException {
Bits[] bits = new Bits[sets.length];
for (int i = 0; i < sets.length; i++) {
bits[i] = sets[i].bits();
if (bits[i] == null) {
return null;
}
}
return new OrBits(bits);
}
@Override
public DocIdSetIterator iterator() throws IOException {
return new IteratorBasedIterator(sets);
}
static class OrBits implements Bits {
private final Bits[] bits;
OrBits(Bits[] bits) {
this.bits = bits;
}
@Override
public boolean get(int index) {
for (Bits bit : bits) {
if (bit.get(index)) {
return true;
}
}
return false;
}
@Override
public int length() {
return bits[0].length();
}
}
static class IteratorBasedIterator extends DocIdSetIterator {
final class Item {
public final DocIdSetIterator iter;
public int doc;
public Item(DocIdSetIterator iter) {
this.iter = iter;
this.doc = -1;
}
}
private int _curDoc;
private final Item[] _heap;
private int _size;
private final long cost;
IteratorBasedIterator(DocIdSet[] sets) throws IOException {
_curDoc = -1;
_heap = new Item[sets.length];
_size = 0;
long cost = 0;
for (DocIdSet set : sets) {
DocIdSetIterator iterator = set.iterator();
if (iterator != null) {
_heap[_size++] = new Item(iterator);
cost += iterator.cost();
}
}
this.cost = cost;
if (_size == 0) _curDoc = DocIdSetIterator.NO_MORE_DOCS;
}
@Override
public final int docID() {
return _curDoc;
}
@Override
public final int nextDoc() throws IOException {
if (_curDoc == DocIdSetIterator.NO_MORE_DOCS) return DocIdSetIterator.NO_MORE_DOCS;
Item top = _heap[0];
while (true) {
DocIdSetIterator topIter = top.iter;
int docid;
if ((docid = topIter.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
top.doc = docid;
heapAdjust();
} else {
heapRemoveRoot();
if (_size == 0) return (_curDoc = DocIdSetIterator.NO_MORE_DOCS);
}
top = _heap[0];
int topDoc = top.doc;
if (topDoc > _curDoc) {
return (_curDoc = topDoc);
}
}
}
@Override
public final int advance(int target) throws IOException {
if (_curDoc == DocIdSetIterator.NO_MORE_DOCS) return DocIdSetIterator.NO_MORE_DOCS;
if (target <= _curDoc) target = _curDoc + 1;
Item top = _heap[0];
while (true) {
DocIdSetIterator topIter = top.iter;
int docid;
if ((docid = topIter.advance(target)) != DocIdSetIterator.NO_MORE_DOCS) {
top.doc = docid;
heapAdjust();
} else {
heapRemoveRoot();
if (_size == 0) return (_curDoc = DocIdSetIterator.NO_MORE_DOCS);
}
top = _heap[0];
int topDoc = top.doc;
if (topDoc >= target) {
return (_curDoc = topDoc);
}
}
}
// Organize subScorers into a min heap with scorers generating the earlest document on top.
/*
private final void heapify() {
int size = _size;
for (int i=(size>>1)-1; i>=0; i--)
heapAdjust(i);
}
*/
/* The subtree of subScorers at root is a min heap except possibly for its root element.
* Bubble the root down as required to make the subtree a heap.
*/
private final void heapAdjust() {
final Item[] heap = _heap;
final Item top = heap[0];
final int doc = top.doc;
final int size = _size;
int i = 0;
while (true) {
int lchild = (i << 1) + 1;
if (lchild >= size) break;
Item left = heap[lchild];
int ldoc = left.doc;
int rchild = lchild + 1;
if (rchild < size) {
Item right = heap[rchild];
int rdoc = right.doc;
if (rdoc <= ldoc) {
if (doc <= rdoc) break;
heap[i] = right;
i = rchild;
continue;
}
}
if (doc <= ldoc) break;
heap[i] = left;
i = lchild;
}
heap[i] = top;
}
// Remove the root Scorer from subScorers and re-establish it as a heap
private void heapRemoveRoot() {
_size--;
if (_size > 0) {
Item tmp = _heap[0];
_heap[0] = _heap[_size];
_heap[_size] = tmp; // keep the finished iterator at the end for debugging
heapAdjust();
}
}
@Override
public long cost() {
return cost;
}
}
} | 0true
| src_main_java_org_elasticsearch_common_lucene_docset_OrDocIdSet.java |
1,876 | public interface PreProcessModule {
void processModule(Module module);
} | 0true
| src_main_java_org_elasticsearch_common_inject_PreProcessModule.java |
1,261 | public class ODataHoleInfo implements Comparable<ODataHoleInfo> {
public int size;
public long dataOffset;
public int holeOffset;
public ODataHoleInfo() {
}
public ODataHoleInfo(final int iRecordSize, final long dataOffset, final int holeOffset) {
this.size = iRecordSize;
this.dataOffset = dataOffset;
this.holeOffset = holeOffset;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (dataOffset ^ (dataOffset >>> 32));
result = prime * result + holeOffset;
result = prime * result + size;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ODataHoleInfo other = (ODataHoleInfo) obj;
if (dataOffset != other.dataOffset)
return false;
if (holeOffset != other.holeOffset)
return false;
if (size != other.size)
return false;
return true;
}
@Override
public String toString() {
return holeOffset + ") " + dataOffset + " [" + size + "]";
}
public int compareTo(final ODataHoleInfo o) {
return size - o.size;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_ODataHoleInfo.java |
757 | public class ListGetOperation extends CollectionOperation {
private int index;
public ListGetOperation() {
}
public ListGetOperation(String name, int index) {
super(name);
this.index = index;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
final CollectionItem item = getOrCreateListContainer().get(index);
response = item.getValue();
}
@Override
public void afterRun() throws Exception {
}
@Override
public int getId() {
return CollectionDataSerializerHook.LIST_GET;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeInt(index);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
index = in.readInt();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_list_ListGetOperation.java |
2,608 | = new ConstructorFunction<Address, ConnectionMonitor>() {
public ConnectionMonitor createNew(Address endpoint) {
return new ConnectionMonitor(TcpIpConnectionManager.this, endpoint);
}
}; | 1no label
| hazelcast_src_main_java_com_hazelcast_nio_TcpIpConnectionManager.java |
5,324 | public class TermsParser implements Aggregator.Parser {
@Override
public String type() {
return StringTerms.TYPE.name();
}
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {
String field = null;
String script = null;
String scriptLang = null;
Map<String, Object> scriptParams = null;
Terms.ValueType valueType = null;
int requiredSize = 10;
int shardSize = -1;
String orderKey = "_count";
boolean orderAsc = false;
String format = null;
boolean assumeUnique = false;
String include = null;
int includeFlags = 0; // 0 means no flags
String exclude = null;
int excludeFlags = 0; // 0 means no flags
String executionHint = null;
long minDocCount = 1;
XContentParser.Token token;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.VALUE_STRING) {
if ("field".equals(currentFieldName)) {
field = parser.text();
} else if ("script".equals(currentFieldName)) {
script = parser.text();
} else if ("lang".equals(currentFieldName)) {
scriptLang = parser.text();
} else if ("value_type".equals(currentFieldName) || "valueType".equals(currentFieldName)) {
valueType = Terms.ValueType.resolveType(parser.text());
} else if ("format".equals(currentFieldName)) {
format = parser.text();
} else if ("include".equals(currentFieldName)) {
include = parser.text();
} else if ("exclude".equals(currentFieldName)) {
exclude = parser.text();
} else if ("execution_hint".equals(currentFieldName) || "executionHint".equals(currentFieldName)) {
executionHint = parser.text();
} else {
throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
}
} else if (token == XContentParser.Token.VALUE_BOOLEAN) {
if ("script_values_unique".equals(currentFieldName)) {
assumeUnique = parser.booleanValue();
} else {
throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
}
} else if (token == XContentParser.Token.VALUE_NUMBER) {
if ("size".equals(currentFieldName)) {
requiredSize = parser.intValue();
} else if ("shard_size".equals(currentFieldName) || "shardSize".equals(currentFieldName)) {
shardSize = parser.intValue();
} else if ("min_doc_count".equals(currentFieldName) || "minDocCount".equals(currentFieldName)) {
minDocCount = parser.intValue();
} else {
throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
}
} else if (token == XContentParser.Token.START_OBJECT) {
if ("params".equals(currentFieldName)) {
scriptParams = parser.map();
} else if ("order".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
orderKey = parser.currentName();
} else if (token == XContentParser.Token.VALUE_STRING) {
String dir = parser.text();
if ("asc".equalsIgnoreCase(dir)) {
orderAsc = true;
} else if ("desc".equalsIgnoreCase(dir)) {
orderAsc = false;
} else {
throw new SearchParseException(context, "Unknown terms order direction [" + dir + "] in terms aggregation [" + aggregationName + "]");
}
} else {
throw new SearchParseException(context, "Unexpected token " + token + " for [order] in [" + aggregationName + "].");
}
}
} else if ("include".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.VALUE_STRING) {
if ("pattern".equals(currentFieldName)) {
include = parser.text();
} else if ("flags".equals(currentFieldName)) {
includeFlags = Regex.flagsFromString(parser.text());
}
} else if (token == XContentParser.Token.VALUE_NUMBER) {
if ("flags".equals(currentFieldName)) {
includeFlags = parser.intValue();
}
}
}
} else if ("exclude".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.VALUE_STRING) {
if ("pattern".equals(currentFieldName)) {
exclude = parser.text();
} else if ("flags".equals(currentFieldName)) {
excludeFlags = Regex.flagsFromString(parser.text());
}
} else if (token == XContentParser.Token.VALUE_NUMBER) {
if ("flags".equals(currentFieldName)) {
excludeFlags = parser.intValue();
}
}
}
} else {
throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
}
} else {
throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "].");
}
}
if (shardSize == 0) {
shardSize = Integer.MAX_VALUE;
}
if (requiredSize == 0) {
requiredSize = Integer.MAX_VALUE;
}
// shard_size cannot be smaller than size as we need to at least fetch <size> entries from every shards in order to return <size>
if (shardSize < requiredSize) {
shardSize = requiredSize;
}
IncludeExclude includeExclude = null;
if (include != null || exclude != null) {
Pattern includePattern = include != null ? Pattern.compile(include, includeFlags) : null;
Pattern excludePattern = exclude != null ? Pattern.compile(exclude, excludeFlags) : null;
includeExclude = new IncludeExclude(includePattern, excludePattern);
}
InternalOrder order = resolveOrder(orderKey, orderAsc);
SearchScript searchScript = null;
if (script != null) {
searchScript = context.scriptService().search(context.lookup(), scriptLang, script, scriptParams);
}
if (field == null) {
Class<? extends ValuesSource> valueSourceType = script == null ?
ValuesSource.class : // unknown, will inherit whatever is in the context
valueType != null ? valueType.scriptValueType.getValuesSourceType() : // the user explicitly defined a value type
BytesValuesSource.class; // defaulting to bytes
ValuesSourceConfig<?> config = new ValuesSourceConfig(valueSourceType);
if (valueType != null) {
config.scriptValueType(valueType.scriptValueType);
}
config.script(searchScript);
if (!assumeUnique) {
config.ensureUnique(true);
}
return new TermsAggregatorFactory(aggregationName, config, order, requiredSize, shardSize, minDocCount, includeExclude, executionHint);
}
FieldMapper<?> mapper = context.smartNameFieldMapper(field);
if (mapper == null) {
ValuesSourceConfig<?> config = new ValuesSourceConfig<BytesValuesSource>(BytesValuesSource.class);
config.unmapped(true);
return new TermsAggregatorFactory(aggregationName, config, order, requiredSize, shardSize, minDocCount, includeExclude, executionHint);
}
IndexFieldData<?> indexFieldData = context.fieldData().getForField(mapper);
ValuesSourceConfig<?> config;
if (mapper instanceof DateFieldMapper) {
DateFieldMapper dateMapper = (DateFieldMapper) mapper;
ValueFormatter formatter = format == null ?
new ValueFormatter.DateTime(dateMapper.dateTimeFormatter()) :
new ValueFormatter.DateTime(format);
config = new ValuesSourceConfig<NumericValuesSource>(NumericValuesSource.class)
.formatter(formatter)
.parser(new ValueParser.DateMath(dateMapper.dateMathParser()));
} else if (mapper instanceof IpFieldMapper) {
config = new ValuesSourceConfig<NumericValuesSource>(NumericValuesSource.class)
.formatter(ValueFormatter.IPv4)
.parser(ValueParser.IPv4);
} else if (indexFieldData instanceof IndexNumericFieldData) {
config = new ValuesSourceConfig<NumericValuesSource>(NumericValuesSource.class);
if (format != null) {
config.formatter(new ValueFormatter.Number.Pattern(format));
}
} else {
config = new ValuesSourceConfig<BytesValuesSource>(BytesValuesSource.class);
// TODO: it will make sense to set false instead here if the aggregator factory uses
// ordinals instead of hash tables
config.needsHashes(true);
}
config.script(searchScript);
config.fieldContext(new FieldContext(field, indexFieldData));
// We need values to be unique to be able to run terms aggs efficiently
if (!assumeUnique) {
config.ensureUnique(true);
}
return new TermsAggregatorFactory(aggregationName, config, order, requiredSize, shardSize, minDocCount, includeExclude, executionHint);
}
static InternalOrder resolveOrder(String key, boolean asc) {
if ("_term".equals(key)) {
return asc ? InternalOrder.TERM_ASC : InternalOrder.TERM_DESC;
}
if ("_count".equals(key)) {
return asc ? InternalOrder.COUNT_ASC : InternalOrder.COUNT_DESC;
}
int i = key.indexOf('.');
if (i < 0) {
return new InternalOrder.Aggregation(key, asc);
}
return new InternalOrder.Aggregation(key.substring(0, i), key.substring(i+1), asc);
}
} | 1no label
| src_main_java_org_elasticsearch_search_aggregations_bucket_terms_TermsParser.java |
1,919 | InvocationHandler invocationHandler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] creationArgs) throws Throwable {
// pass methods from Object.class to the proxy
if (method.getDeclaringClass().equals(Object.class)) {
return method.invoke(this, creationArgs);
}
AssistedConstructor<?> constructor = factoryMethodToConstructor.get(method);
Object[] constructorArgs = gatherArgsForConstructor(constructor, creationArgs);
Object objectToReturn = constructor.newInstance(constructorArgs);
injector.injectMembers(objectToReturn);
return objectToReturn;
}
public Object[] gatherArgsForConstructor(
AssistedConstructor<?> constructor,
Object[] factoryArgs) {
int numParams = constructor.getAllParameters().size();
int argPosition = 0;
Object[] result = new Object[numParams];
for (int i = 0; i < numParams; i++) {
Parameter parameter = constructor.getAllParameters().get(i);
if (parameter.isProvidedByFactory()) {
result[i] = factoryArgs[argPosition];
argPosition++;
} else {
result[i] = parameter.getValue(injector);
}
}
return result;
}
}; | 0true
| src_main_java_org_elasticsearch_common_inject_assistedinject_FactoryProvider.java |
411 | public class ClientConditionProxy extends ClientProxy implements ICondition {
private final String conditionId;
private final ClientLockProxy lockProxy;
private volatile Data key;
private final InternalLockNamespace namespace;
public ClientConditionProxy(String instanceName, ClientLockProxy clientLockProxy, String name, ClientContext ctx) {
super(instanceName, LockService.SERVICE_NAME, clientLockProxy.getName());
this.setContext(ctx);
this.lockProxy = clientLockProxy;
this.namespace = new InternalLockNamespace(lockProxy.getName());
this.conditionId = name;
this.key = toData(lockProxy.getName());
}
@Override
public void await() throws InterruptedException {
await(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
@Override
public void awaitUninterruptibly() {
try {
await(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO: @mm - what if interrupted?
ExceptionUtil.sneakyThrow(e);
}
}
@Override
public long awaitNanos(long nanosTimeout) throws InterruptedException {
long start = System.nanoTime();
await(nanosTimeout, TimeUnit.NANOSECONDS);
long end = System.nanoTime();
return (end - start);
}
@Override
public boolean await(long time, TimeUnit unit) throws InterruptedException {
long threadId = ThreadUtil.getThreadId();
beforeAwait(threadId);
return doAwait(time, unit, threadId);
}
private void beforeAwait(long threadId) {
BeforeAwaitRequest request = new BeforeAwaitRequest(namespace, threadId, conditionId, key);
invoke(request);
}
private boolean doAwait(long time, TimeUnit unit, long threadId) throws InterruptedException {
final long timeoutInMillis = unit.toMillis(time);
AwaitRequest awaitRequest = new AwaitRequest(namespace, lockProxy.getName(), timeoutInMillis, threadId, conditionId);
final Boolean result = invoke(awaitRequest);
return result;
}
@Override
public boolean awaitUntil(Date deadline) throws InterruptedException {
long until = deadline.getTime();
final long timeToDeadline = until - Clock.currentTimeMillis();
return await(timeToDeadline, TimeUnit.MILLISECONDS);
}
@Override
public void signal() {
signal(false);
}
@Override
public void signalAll() {
signal(true);
}
private void signal(boolean all) {
SignalRequest request = new SignalRequest(namespace, lockProxy.getName(), ThreadUtil.getThreadId(), conditionId, all);
invoke(request);
}
@Override
protected void onDestroy() {
}
protected <T> T invoke(ClientRequest req) {
return super.invoke(req, key);
}
} | 1no label
| hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientConditionProxy.java |
3,652 | public static class Builder extends AbstractFieldMapper.Builder<Builder, AllFieldMapper> {
private boolean enabled = Defaults.ENABLED;
// an internal flag, automatically set if we encounter boosting
boolean autoBoost = false;
public Builder() {
super(Defaults.NAME, new FieldType(Defaults.FIELD_TYPE));
builder = this;
indexName = Defaults.INDEX_NAME;
}
public Builder enabled(boolean enabled) {
this.enabled = enabled;
return this;
}
@Override
public AllFieldMapper build(BuilderContext context) {
// In case the mapping overrides these
fieldType.setIndexed(true);
fieldType.setTokenized(true);
return new AllFieldMapper(name, fieldType, indexAnalyzer, searchAnalyzer, enabled, autoBoost, postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, context.indexSettings());
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_internal_AllFieldMapper.java |
3,519 | public static class Aggregator extends ObjectMapperListener {
public final List<ObjectMapper> mappers = new ArrayList<ObjectMapper>();
@Override
public void objectMapper(ObjectMapper objectMapper) {
mappers.add(objectMapper);
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_ObjectMapperListener.java |
284 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ClientStaticLBTest {
@AfterClass
public static void destroy() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testStaticLB_withMembers() {
TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);
HazelcastInstance server = factory.newHazelcastInstance();
Member member = server.getCluster().getLocalMember();
StaticLB lb = new StaticLB(member);
Member nextMember = lb.next();
assertEquals(member, nextMember);
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_loadBalancer_ClientStaticLBTest.java |
633 | public class OIndexTxAwareMultiValue extends OIndexTxAware<Collection<OIdentifiable>> {
public OIndexTxAwareMultiValue(final ODatabaseRecord iDatabase, final OIndex<Collection<OIdentifiable>> iDelegate) {
super(iDatabase, iDelegate);
}
@Override
public Collection<OIdentifiable> get(final Object key) {
final OTransactionIndexChanges indexChanges = database.getTransaction().getIndexChanges(delegate.getName());
if (indexChanges == null)
return super.get(key);
final Set<OIdentifiable> result = new TreeSet<OIdentifiable>();
if (!indexChanges.cleared) {
// BEGIN FROM THE UNDERLYING RESULT SET
final Collection<OIdentifiable> subResult = super.get(key);
if (subResult != null)
for (OIdentifiable oid : subResult)
if (oid != null)
result.add(oid);
}
return filterIndexChanges(indexChanges, key, result);
}
@Override
public boolean contains(final Object iKey) {
final OTransactionIndexChanges indexChanges = database.getTransaction().getIndexChanges(delegate.getName());
Set<OIdentifiable> result = new TreeSet<OIdentifiable>();
if (indexChanges == null || !indexChanges.cleared) {
// BEGIN FROM THE UNDERLYING RESULT SET
final Collection<OIdentifiable> subResult = super.get(iKey);
if (subResult != null)
for (OIdentifiable oid : subResult)
if (oid != null)
result.add(oid);
}
filterIndexChanges(indexChanges, iKey, result);
return !result.isEmpty();
}
@Override
public Collection<OIdentifiable> getValues(final Collection<?> iKeys) {
final Collection<?> keys = new ArrayList<Object>(iKeys);
final Set<OIdentifiable> result = new TreeSet<OIdentifiable>();
final Set<Object> keysToRemove = new TreeSet<Object>();
final OTransactionIndexChanges indexChanges = database.getTransaction().getIndexChanges(delegate.getName());
if (indexChanges == null) {
result.addAll(super.getValues(keys));
return result;
}
for (final Object key : keys) {
final Set<OIdentifiable> keyResult;
if (!indexChanges.cleared)
if (indexChanges.containsChangesPerKey(key))
// BEGIN FROM THE UNDERLYING RESULT SET
keyResult = new TreeSet<OIdentifiable>(super.get(key));
else
continue;
else
// BEGIN FROM EMPTY RESULT SET
keyResult = new TreeSet<OIdentifiable>();
keysToRemove.add(key);
filterIndexChanges(indexChanges, key, keyResult);
result.addAll(keyResult);
}
keys.removeAll(keysToRemove);
if (!keys.isEmpty())
result.addAll(super.getValues(keys));
return result;
}
@Override
public Collection<ODocument> getEntries(final Collection<?> iKeys) {
final Collection<?> keys = new ArrayList<Object>(iKeys);
final Set<ODocument> result = new ODocumentFieldsHashSet();
final Set<Object> keysToRemove = new HashSet<Object>();
final OTransactionIndexChanges indexChanges = database.getTransaction().getIndexChanges(delegate.getName());
if (indexChanges == null) {
return super.getEntries(keys);
}
for (final Object key : keys) {
final Set<OIdentifiable> keyResult;
if (!indexChanges.cleared)
if (indexChanges.containsChangesPerKey(key))
// BEGIN FROM THE UNDERLYING RESULT SET
keyResult = new TreeSet<OIdentifiable>(super.get(key));
else
continue;
else
// BEGIN FROM EMPTY RESULT SET
keyResult = new TreeSet<OIdentifiable>();
keysToRemove.add(key);
filterIndexChanges(indexChanges, key, keyResult);
for (final OIdentifiable id : keyResult) {
final ODocument document = new ODocument();
document.field("key", key);
document.field("rid", id.getIdentity());
document.unsetDirty();
result.add(document);
}
}
keys.removeAll(keysToRemove);
if (!keys.isEmpty())
result.addAll(super.getEntries(keys));
return result;
}
protected Collection<OIdentifiable> filterIndexChanges(final OTransactionIndexChanges indexChanges, final Object key,
final Collection<OIdentifiable> keyResult) {
if (indexChanges == null)
return keyResult;
if (indexChanges.containsChangesPerKey(key)) {
final OTransactionIndexChangesPerKey value = indexChanges.getChangesPerKey(key);
if (value != null) {
for (final OTransactionIndexEntry entry : value.entries) {
if (entry.operation == OPERATION.REMOVE) {
if (entry.value == null) {
// REMOVE THE ENTIRE KEY, SO RESULT SET IS EMPTY
keyResult.clear();
break;
} else
// REMOVE ONLY THIS RID
keyResult.remove(entry.value);
} else if (entry.operation == OPERATION.PUT) {
// ADD ALSO THIS RID
keyResult.add(entry.value);
}
}
}
}
return keyResult;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_OIndexTxAwareMultiValue.java |
18 | static class ByteEntry implements Comparable<ByteEntry> {
final ByteBuffer key;
final ByteBuffer value;
ByteEntry(ByteBuffer key, ByteBuffer value) {
this.value = value;
this.key = key;
}
@Override
public int compareTo(ByteEntry byteEntry) {
return key.compareTo(byteEntry.key);
}
} | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
904 | public interface PromotionRounding {
/**
* It is sometimes problematic to offer percentage-off offers with regards to rounding. For example,
* consider an item that costs 9.99 and has a 50% promotion. To be precise, the offer value is 4.995,
* but this may be a strange value to display to the user depending on the currency being used.
*/
boolean isRoundOfferValues();
/**
* Returns the rounding mode to use for rounding operations.
* @return
*/
RoundingMode getRoundingMode();
/**
* Returns the scale to use when rounding.
* @return
*/
int getRoundingScale();
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotionRounding.java |
460 | public interface ResourceMinificationService {
/**
* Given the source byte[], will return a byte[] that represents the YUI-compressor minified version
* of the byte[]. The behavior of this method is controlled via the following properties:
*
* <ul>
* <li>minify.enabled - whether or not to actually perform minification</li>
* <li>minify.linebreak - if set to a value other than -1, will enforce a linebreak at that value</li>
* <li>minify.munge - if true, will replace variable names with shorter versions</li>
* <li>minify.verbose - if true, will display extra logging information to the console</li>
* <li>minify.preserveAllSemiColons - if true, will never remove semi-colons, even if two in a row exist</li>
* <li>minify.disableOptimizations - if true, will disable some micro-optimizations that are performed</li>
* </ul>
*
* @param filename
* @param bytes
* @return the minified bytes
*/
public byte[] minify(String filename, byte[] bytes);
} | 0true
| common_src_main_java_org_broadleafcommerce_common_resource_service_ResourceMinificationService.java |
107 | public class OIOException extends OException {
private static final long serialVersionUID = -3003977236203691448L;
public OIOException(String string) {
super(string);
}
public OIOException(String message, Throwable cause) {
super(message, cause);
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_io_OIOException.java |
573 | public interface ValueAssignable<T extends Serializable> extends Serializable {
/**
* The value
*
* @return The value
*/
T getValue();
/**
* The value
*
* @param value The value
*/
void setValue(T value);
/**
* The name
*
* @return The name
*/
String getName();
/**
* The name
*
* @param name The name
*/
void setName(String name);
} | 0true
| common_src_main_java_org_broadleafcommerce_common_value_ValueAssignable.java |
1,196 | public interface MessageListener<E> extends EventListener {
/**
* Invoked when a message is received for the added topic. Note that topic guarantees message ordering.
* Therefore there is only one thread invoking onMessage. The user shouldn't keep the thread busy and preferably
* dispatch it via an Executor. This will increase the performance of the topic.
*
* @param message received message
*/
void onMessage(Message<E> message);
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_MessageListener.java |
2,594 | private class FDConnectionListener implements TransportConnectionListener {
@Override
public void onNodeConnected(DiscoveryNode node) {
}
@Override
public void onNodeDisconnected(DiscoveryNode node) {
handleTransportDisconnect(node);
}
} | 0true
| src_main_java_org_elasticsearch_discovery_zen_fd_MasterFaultDetection.java |
2,013 | @RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class TestWriteBehindException extends HazelcastTestSupport {
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
@Test
public void testWriteBehindStoreWithException() throws InterruptedException {
final MapStore mapStore = new MapStore();
mapStore.setLoadAllKeys(false);
Config config = MapStoreTest.newConfig(mapStore, 5);
config.setProperty("hazelcast.local.localAddress", "127.0.0.1");
HazelcastInstance instance = createHazelcastInstance(config);
IMap<Integer, String> map = instance.getMap("map");
IMap<Integer, String> map2 = instance.getMap("map2");
IMap<Integer, String> map3 = instance.getMap("map3");
for (int i = 0; i < 10; i++) {
map.put(i, "value-" + i);
}
for (int i = 0; i < 10; i++) {
map2.put(i + 10, "value-" + i);
}
for (int i = 0; i < 10; i++) {
map3.put(i + 20, "value-" + i);
}
assertOpenEventually(latch1);
Thread.sleep(2000);
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(29, mapStore.store.size());
}
});
for (int i = 0; i < 30; i++) {
map.delete(i);
}
assertOpenEventually(latch2);
Thread.sleep(2000);
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(1, mapStore.store.size());
}
});
}
class MapStore extends MapStoreTest.SimpleMapStore<Integer, String> {
MapStore() {
}
MapStore(Map<Integer, String> store) {
super(store);
}
public void storeAll(final Map<Integer, String> map) {
latch1.countDown();
for (Map.Entry<Integer, String> entry : map.entrySet()) {
store(entry.getKey(), entry.getValue());
}
}
@Override
public void delete(Integer key) {
if (key.equals(6)) {
throw new RuntimeException("delete db rejected value");
}
super.delete(key);
}
@Override
public void deleteAll(Collection<Integer> keys) {
latch2.countDown();
for (Integer key : keys) {
delete(key);
}
}
@Override
public void store(Integer key, String value) {
if (key.equals(5)) {
throw new RuntimeException("db rejected value");
}
super.store(key, value);
}
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_map_mapstore_TestWriteBehindException.java |
1,468 | public final class HazelcastCollectionRegion<Cache extends RegionCache> extends AbstractTransactionalDataRegion<Cache>
implements CollectionRegion {
public HazelcastCollectionRegion(final HazelcastInstance instance,
final String regionName, final Properties props,
final CacheDataDescription metadata, final Cache cache) {
super(instance, regionName, props, metadata, cache);
}
public CollectionRegionAccessStrategy buildAccessStrategy(final AccessType accessType) throws CacheException {
if (null == accessType) {
throw new CacheException(
"Got null AccessType while attempting to build CollectionRegionAccessStrategy. This can't happen!");
}
if (AccessType.READ_ONLY.equals(accessType)) {
return new CollectionRegionAccessStrategyAdapter(
new ReadOnlyAccessDelegate<HazelcastCollectionRegion>(this, props));
}
if (AccessType.NONSTRICT_READ_WRITE.equals(accessType)) {
return new CollectionRegionAccessStrategyAdapter(
new NonStrictReadWriteAccessDelegate<HazelcastCollectionRegion>(this, props));
}
if (AccessType.READ_WRITE.equals(accessType)) {
return new CollectionRegionAccessStrategyAdapter(
new ReadWriteAccessDelegate<HazelcastCollectionRegion>(this, props));
}
if (AccessType.TRANSACTIONAL.equals(accessType)) {
throw new CacheException("Transactional access is not currently supported by Hazelcast.");
}
throw new CacheException("Got unknown AccessType " + accessType
+ " while attempting to build CollectionRegionAccessStrategy.");
}
} | 0true
| hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_region_HazelcastCollectionRegion.java |
4 | public interface Action<A> { void accept(A a); } | 0true
| src_main_java_jsr166e_CompletableFuture.java |
217 | protected class SelectNextSubWordAction extends NextSubWordAction {
/**
* Creates a new select next sub-word action.
*/
public SelectNextSubWordAction() {
super(ST.SELECT_WORD_NEXT);
}
@Override
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonEditor.java |
960 | public abstract class AbstractCompressionTest {
protected void testCompression(String name) {
long seed = System.currentTimeMillis();
System.out.println("Compression seed " + seed);
Random random = new Random(seed);
final int iterationsCount = 1000;
for (int i = 0; i < iterationsCount; i++) {
int contentSize = random.nextInt(10 * 1024 - 100) + 100;
byte[] content = new byte[contentSize];
random.nextBytes(content);
OCompression compression = OCompressionFactory.INSTANCE.getCompression(name);
byte[] compressedContent = compression.compress(content);
Assert.assertEquals(content, compression.uncompress(compressedContent));
}
}
} | 0true
| core_src_test_java_com_orientechnologies_orient_core_serialization_compression_impl_AbstractCompressionTest.java |
1,672 | runnable = new Runnable() { public void run() { map.remove(null, "value"); } }; | 0true
| hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java |
1,583 | public interface LogListener {
void log(LogEvent logEvent);
} | 0true
| hazelcast_src_main_java_com_hazelcast_logging_LogListener.java |
2,933 | public class MultiResultSet extends AbstractSet<QueryableEntry> {
private Set<Object> index;
private final List<ConcurrentMap<Data, QueryableEntry>> resultSets
= new ArrayList<ConcurrentMap<Data, QueryableEntry>>();
public MultiResultSet() {
}
public void addResultSet(ConcurrentMap<Data, QueryableEntry> resultSet) {
resultSets.add(resultSet);
}
@Override
public boolean contains(Object o) {
QueryableEntry entry = (QueryableEntry) o;
if (index != null) {
return checkFromIndex(entry);
} else {
//todo: what is the point of this condition? Is it some kind of optimization?
if (resultSets.size() > 3) {
index = new HashSet<Object>();
for (ConcurrentMap<Data, QueryableEntry> result : resultSets) {
for (QueryableEntry queryableEntry : result.values()) {
index.add(queryableEntry.getIndexKey());
}
}
return checkFromIndex(entry);
} else {
for (ConcurrentMap<Data, QueryableEntry> resultSet : resultSets) {
if (resultSet.containsKey(entry.getIndexKey())) {
return true;
}
}
return false;
}
}
}
private boolean checkFromIndex(QueryableEntry entry) {
return index.contains(entry.getIndexKey());
}
@Override
public Iterator<QueryableEntry> iterator() {
return new It();
}
class It implements Iterator<QueryableEntry> {
int currentIndex;
Iterator<QueryableEntry> currentIterator;
@Override
public boolean hasNext() {
if (resultSets.size() == 0) {
return false;
}
if (currentIterator != null && currentIterator.hasNext()) {
return true;
}
while (currentIndex < resultSets.size()) {
currentIterator = resultSets.get(currentIndex++).values().iterator();
if (currentIterator.hasNext()) {
return true;
}
}
return false;
}
@Override
public QueryableEntry next() {
if (resultSets.size() == 0) {
return null;
}
return currentIterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
@Override
public boolean add(QueryableEntry obj) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
int size = 0;
for (ConcurrentMap<Data, QueryableEntry> resultSet : resultSets) {
size += resultSet.size();
}
return size;
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_query_impl_MultiResultSet.java |
35 | @Service("blSkuFieldService")
public class SkuFieldServiceImpl extends AbstractRuleBuilderFieldService {
@Override
public void init() {
fields.add(new FieldData.Builder()
.label("rule_skuName")
.name("name")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuFulfillmentType")
.name("fulfillmentType")
.operators("blcOperators_Enumeration")
.options("blcOptions_FulfillmentType")
.type(SupportedFieldType.BROADLEAF_ENUMERATION)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuInventoryType")
.name("inventoryType")
.operators("blcOperators_Enumeration")
.options("blcOptions_InventoryType")
.type(SupportedFieldType.BROADLEAF_ENUMERATION)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuDescription")
.name("description")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuLongDescription")
.name("longDescription")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuTaxable")
.name("taxable")
.operators("blcOperators_Boolean")
.options("[]")
.type(SupportedFieldType.BOOLEAN)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuAvailable")
.name("available")
.operators("blcOperators_Boolean")
.options("[]")
.type(SupportedFieldType.BOOLEAN)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuStartDate")
.name("activeStartDate")
.operators("blcOperators_Date")
.options("[]")
.type(SupportedFieldType.DATE)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuEndDate")
.name("activeEndDate")
.operators("blcOperators_Date")
.options("[]")
.type(SupportedFieldType.DATE)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuProductUrl")
.name("product.url")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuProductIsFeatured")
.name("product.isFeaturedProduct")
.operators("blcOperators_Boolean")
.options("[]")
.type(SupportedFieldType.BOOLEAN)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuProductManufacturer")
.name("product.manufacturer")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_skuProductModel")
.name("product.model")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
}
@Override
public String getName() {
return RuleIdentifier.SKU;
}
@Override
public String getDtoClassName() {
return "org.broadleafcommerce.core.catalog.domain.SkuImpl";
}
} | 0true
| admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_web_rulebuilder_service_SkuFieldServiceImpl.java |
1,547 | Arrays.sort(nodes, new Comparator<RoutingNode>() {
@Override
public int compare(RoutingNode o1, RoutingNode o2) {
return nodeCounts.get(o1.nodeId()) - nodeCounts.get(o2.nodeId());
}
}); | 0true
| src_main_java_org_elasticsearch_cluster_routing_allocation_allocator_EvenShardsCountAllocator.java |
1,449 | final ByteArrayOutputStream bytes = new ByteArrayOutputStream() {
public synchronized byte[] toByteArray() {
return buf;
}
}; | 0true
| graphdb_src_main_java_com_orientechnologies_orient_graph_gremlin_OGremlinHelper.java |
1,576 | public abstract class ODistributedAbstractPlugin extends OServerPluginAbstract implements ODistributedServerManager,
ODatabaseLifecycleListener {
public static final String REPLICATOR_USER = "replicator";
protected static final String MASTER_AUTO = "$auto";
protected static final String PAR_DEF_DISTRIB_DB_CONFIG = "configuration.db.default";
protected static final String FILE_DISTRIBUTED_DB_CONFIG = "distributed-config.json";
protected OServer serverInstance;
protected Map<String, ODocument> cachedDatabaseConfiguration = new HashMap<String, ODocument>();
protected boolean enabled = true;
protected String nodeName = null;
protected Class<? extends OReplicationConflictResolver> confictResolverClass;
protected File defaultDatabaseConfigFile;
protected Map<String, ODistributedPartitioningStrategy> strategies = new HashMap<String, ODistributedPartitioningStrategy>();
@SuppressWarnings("unchecked")
@Override
public void config(OServer oServer, OServerParameterConfiguration[] iParams) {
serverInstance = oServer;
oServer.setVariable("ODistributedAbstractPlugin", this);
for (OServerParameterConfiguration param : iParams) {
if (param.name.equalsIgnoreCase("enabled")) {
if (!Boolean.parseBoolean(OSystemVariableResolver.resolveSystemVariables(param.value))) {
// DISABLE IT
enabled = false;
return;
}
} else if (param.name.equalsIgnoreCase("nodeName"))
nodeName = param.value;
else if (param.name.startsWith(PAR_DEF_DISTRIB_DB_CONFIG)) {
defaultDatabaseConfigFile = new File(OSystemVariableResolver.resolveSystemVariables(param.value));
if (!defaultDatabaseConfigFile.exists())
throw new OConfigurationException("Cannot find distributed database config file: " + defaultDatabaseConfigFile);
} else if (param.name.equalsIgnoreCase("conflict.resolver.impl"))
try {
confictResolverClass = (Class<? extends OReplicationConflictResolver>) Class.forName(param.value);
} catch (ClassNotFoundException e) {
OLogManager.instance().error(this, "Cannot find the conflict resolver implementation '%s'", e, param.value);
}
else if (param.name.startsWith("sharding.strategy.")) {
try {
strategies.put(param.name.substring("sharding.strategy.".length()),
(ODistributedPartitioningStrategy) Class.forName(param.value).newInstance());
} catch (Exception e) {
OLogManager.instance().error(this, "Cannot create sharding strategy instance '%s'", e, param.value);
e.printStackTrace();
}
}
}
if (serverInstance.getUser(REPLICATOR_USER) == null)
// CREATE THE REPLICATOR USER
try {
serverInstance.addUser(REPLICATOR_USER, null, "database.passthrough");
serverInstance.saveConfiguration();
} catch (IOException e) {
throw new OConfigurationException("Error on creating 'replicator' user", e);
}
}
@Override
public void startup() {
if (!enabled)
return;
Orient.instance().addDbLifecycleListener(this);
}
@Override
public void shutdown() {
if (!enabled)
return;
Orient.instance().removeDbLifecycleListener(this);
}
/**
* Auto register myself as hook.
*/
@Override
public void onOpen(final ODatabase iDatabase) {
final String dbDirectory = serverInstance.getDatabaseDirectory();
if (!iDatabase.getURL().substring(iDatabase.getURL().indexOf(":") + 1).startsWith(dbDirectory))
// NOT OWN DB, SKIPT IT
return;
synchronized (cachedDatabaseConfiguration) {
final ODistributedConfiguration cfg = getDatabaseConfiguration(iDatabase.getName());
if (cfg == null)
return;
if (cfg.isReplicationActive(null)) {
if (iDatabase instanceof ODatabaseComplex<?> && !(iDatabase.getStorage() instanceof ODistributedStorage))
((ODatabaseComplex<?>) iDatabase).replaceStorage(new ODistributedStorage(serverInstance,
(OStorageEmbedded) ((ODatabaseComplex<?>) iDatabase).getStorage()));
}
}
}
/**
* Remove myself as hook.
*/
@Override
public void onClose(final ODatabase iDatabase) {
}
@Override
public void sendShutdown() {
super.sendShutdown();
}
@Override
public String getName() {
return "cluster";
}
public String getLocalNodeId() {
return nodeName;
}
public ODistributedPartitioningStrategy getReplicationStrategy(String iStrategy) {
if (iStrategy.startsWith("$"))
iStrategy = iStrategy.substring(1);
final ODistributedPartitioningStrategy strategy = strategies.get(iStrategy);
if (strategy == null)
throw new ODistributedException("Configured strategy '" + iStrategy + "' is not configured");
return strategy;
}
public ODistributedPartitioningStrategy getPartitioningStrategy(final String iStrategyName) {
return strategies.get(iStrategyName);
}
protected ODocument loadDatabaseConfiguration(final String iDatabaseName, final File file) {
if (!file.exists() || file.length() == 0)
return null;
ODistributedServerLog.info(this, getLocalNodeName(), null, DIRECTION.NONE, "loaded database configuration from disk: %s", file);
FileInputStream f = null;
try {
f = new FileInputStream(file);
final byte[] buffer = new byte[(int) file.length()];
f.read(buffer);
final ODocument doc = (ODocument) new ODocument().fromJSON(new String(buffer), "noMap");
updateCachedDatabaseConfiguration(iDatabaseName, doc);
return doc;
} catch (Exception e) {
} finally {
if (f != null)
try {
f.close();
} catch (IOException e) {
}
}
return null;
}
public void updateCachedDatabaseConfiguration(final String iDatabaseName, final ODocument cfg) {
synchronized (cachedDatabaseConfiguration) {
cachedDatabaseConfiguration.put(iDatabaseName, cfg);
OLogManager.instance().info(this, "updated distributed configuration for database: %s:\n----------\n%s\n----------",
iDatabaseName, cfg.toJSON("prettyPrint"));
}
}
public ODistributedConfiguration getDatabaseConfiguration(final String iDatabaseName) {
synchronized (cachedDatabaseConfiguration) {
ODocument cfg = cachedDatabaseConfiguration.get(iDatabaseName);
if (cfg == null) {
cfg = cachedDatabaseConfiguration.get("*");
if (cfg == null) {
cfg = loadDatabaseConfiguration(iDatabaseName, defaultDatabaseConfigFile);
if (cfg == null)
throw new OConfigurationException("Cannot load default distributed database config file: " + defaultDatabaseConfigFile);
}
}
return new ODistributedConfiguration(cfg);
}
}
protected void saveDatabaseConfiguration(final String iDatabaseName, final ODocument cfg) {
synchronized (cachedDatabaseConfiguration) {
final ODocument oldCfg = cachedDatabaseConfiguration.get(iDatabaseName);
if (oldCfg != null && Arrays.equals(oldCfg.toStream(), cfg.toStream()))
// NO CHANGE, SKIP IT
return;
}
// INCREMENT VERSION
Integer oldVersion = cfg.field("version");
if (oldVersion == null)
oldVersion = 0;
cfg.field("version", oldVersion.intValue() + 1);
updateCachedDatabaseConfiguration(iDatabaseName, cfg);
FileOutputStream f = null;
try {
File file = getDistributedConfigFile(iDatabaseName);
OLogManager.instance().config(this, "Saving distributed configuration file for database '%s' in: %s", iDatabaseName, file);
f = new FileOutputStream(file);
f.write(cfg.toJSON().getBytes());
} catch (Exception e) {
OLogManager.instance().error(this, "Error on saving distributed configuration file", e);
} finally {
if (f != null)
try {
f.close();
} catch (IOException e) {
}
}
}
public File getDistributedConfigFile(final String iDatabaseName) {
return new File(serverInstance.getDatabaseDirectory() + iDatabaseName + "/" + FILE_DISTRIBUTED_DB_CONFIG);
}
public OServer getServerInstance() {
return serverInstance;
}
} | 1no label
| server_src_main_java_com_orientechnologies_orient_server_distributed_ODistributedAbstractPlugin.java |
1,094 | public class QueueConfig {
public final static int DEFAULT_MAX_SIZE = 0;
public final static int DEFAULT_SYNC_BACKUP_COUNT = 1;
public final static int DEFAULT_ASYNC_BACKUP_COUNT = 0;
public final static int DEFAULT_EMPTY_QUEUE_TTL = -1;
private String name;
private List<ItemListenerConfig> listenerConfigs;
private int backupCount = DEFAULT_SYNC_BACKUP_COUNT;
private int asyncBackupCount = DEFAULT_ASYNC_BACKUP_COUNT;
private int maxSize = DEFAULT_MAX_SIZE;
private int emptyQueueTtl = DEFAULT_EMPTY_QUEUE_TTL;
private QueueStoreConfig queueStoreConfig;
private boolean statisticsEnabled = true;
private QueueConfigReadOnly readOnly;
public QueueConfig() {
}
public QueueConfig(QueueConfig config) {
this();
this.name = config.name;
this.backupCount = config.backupCount;
this.asyncBackupCount = config.asyncBackupCount;
this.maxSize = config.maxSize;
this.emptyQueueTtl = config.emptyQueueTtl;
this.statisticsEnabled = config.statisticsEnabled;
this.queueStoreConfig = config.queueStoreConfig != null ? new QueueStoreConfig(config.queueStoreConfig) : null;
this.listenerConfigs = new ArrayList<ItemListenerConfig>(config.getItemListenerConfigs());
}
public QueueConfigReadOnly getAsReadOnly(){
if (readOnly == null){
readOnly = new QueueConfigReadOnly(this);
}
return readOnly;
}
public int getEmptyQueueTtl() {
return emptyQueueTtl;
}
public QueueConfig setEmptyQueueTtl(int emptyQueueTtl) {
this.emptyQueueTtl = emptyQueueTtl;
return this;
}
public int getMaxSize() {
return maxSize == 0 ? Integer.MAX_VALUE : maxSize;
}
public QueueConfig setMaxSize(int maxSize) {
if (maxSize < 0) {
throw new IllegalArgumentException("Size of the queue can not be a negative value!");
}
this.maxSize = maxSize;
return this;
}
public int getTotalBackupCount() {
return backupCount + asyncBackupCount;
}
public int getBackupCount() {
return backupCount;
}
public QueueConfig setBackupCount(int backupCount) {
this.backupCount = backupCount;
return this;
}
public int getAsyncBackupCount() {
return asyncBackupCount;
}
public QueueConfig setAsyncBackupCount(int asyncBackupCount) {
this.asyncBackupCount = asyncBackupCount;
return this;
}
public QueueStoreConfig getQueueStoreConfig() {
return queueStoreConfig;
}
public QueueConfig setQueueStoreConfig(QueueStoreConfig queueStoreConfig) {
this.queueStoreConfig = queueStoreConfig;
return this;
}
public boolean isStatisticsEnabled() {
return statisticsEnabled;
}
public QueueConfig setStatisticsEnabled(boolean statisticsEnabled) {
this.statisticsEnabled = statisticsEnabled;
return this;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
* @return this queue config
*/
public QueueConfig setName(String name) {
this.name = name;
return this;
}
public QueueConfig addItemListenerConfig(ItemListenerConfig listenerConfig) {
getItemListenerConfigs().add(listenerConfig);
return this;
}
public List<ItemListenerConfig> getItemListenerConfigs() {
if (listenerConfigs == null) {
listenerConfigs = new ArrayList<ItemListenerConfig>();
}
return listenerConfigs;
}
public QueueConfig setItemListenerConfigs(List<ItemListenerConfig> listenerConfigs) {
this.listenerConfigs = listenerConfigs;
return this;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("QueueConfig{");
sb.append("name='").append(name).append('\'');
sb.append(", listenerConfigs=").append(listenerConfigs);
sb.append(", backupCount=").append(backupCount);
sb.append(", asyncBackupCount=").append(asyncBackupCount);
sb.append(", maxSize=").append(maxSize);
sb.append(", emptyQueueTtl=").append(emptyQueueTtl);
sb.append(", queueStoreConfig=").append(queueStoreConfig);
sb.append(", statisticsEnabled=").append(statisticsEnabled);
sb.append('}');
return sb.toString();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_config_QueueConfig.java |
470 | public class ExternalModuleNode implements ModuleNode {
private RepositoryNode repositoryNode;
private List<IPackageFragmentRoot> binaryArchives = new ArrayList<>();
protected String moduleSignature;
public ExternalModuleNode(RepositoryNode repositoryNode, String moduleSignature) {
this.moduleSignature = moduleSignature;
this.repositoryNode = repositoryNode;
}
public List<IPackageFragmentRoot> getBinaryArchives() {
return binaryArchives;
}
public CeylonArchiveFileStore getSourceArchive() {
JDTModule module = getModule();
if (module.isCeylonArchive()) {
String sourcePathString = module.getSourceArchivePath();
if (sourcePathString != null) {
IFolder sourceArchive = getExternalSourceArchiveManager().getSourceArchive(Path.fromOSString(sourcePathString));
if (sourceArchive != null && sourceArchive.exists()) {
return ((CeylonArchiveFileStore) ((Resource)sourceArchive).getStore());
}
}
}
return null;
}
public RepositoryNode getRepositoryNode() {
return repositoryNode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((moduleSignature == null) ? 0 : moduleSignature
.hashCode());
result = prime
* result
+ ((repositoryNode == null) ? 0 : repositoryNode.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ExternalModuleNode other = (ExternalModuleNode) obj;
if (moduleSignature == null) {
if (other.moduleSignature != null)
return false;
} else if (!moduleSignature.equals(other.moduleSignature))
return false;
if (repositoryNode == null) {
if (other.repositoryNode != null)
return false;
} else if (!repositoryNode.equals(other.repositoryNode))
return false;
return true;
}
@Override
public JDTModule getModule() {
for (JDTModule module : CeylonBuilder.getProjectExternalModules(repositoryNode.project)) {
if (module.getSignature().equals(moduleSignature)) {
return module;
}
}
return null;
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_navigator_ExternalModuleNode.java |
602 | public class OIndexFullText extends OIndexMultiValues {
private static final String CONFIG_STOP_WORDS = "stopWords";
private static final String CONFIG_SEPARATOR_CHARS = "separatorChars";
private static final String CONFIG_IGNORE_CHARS = "ignoreChars";
private static String DEF_SEPARATOR_CHARS = " \r\n\t:;,.|+*/\\=!?[]()";
private static String DEF_IGNORE_CHARS = "'\"";
private static String DEF_STOP_WORDS = "the in a at as and or for his her " + "him this that what which while "
+ "up with be was is";
private final String separatorChars = DEF_SEPARATOR_CHARS;
private final String ignoreChars = DEF_IGNORE_CHARS;
private final Set<String> stopWords;
public OIndexFullText(String typeId, String algorithm, OIndexEngine<Set<OIdentifiable>> indexEngine,
String valueContainerAlgorithm) {
super(typeId, algorithm, indexEngine, valueContainerAlgorithm);
stopWords = new HashSet<String>(OStringSerializerHelper.split(DEF_STOP_WORDS, ' '));
}
/**
* Indexes a value and save the index. Splits the value in single words and index each one. Save of the index is responsibility of
* the caller.
*/
@Override
public OIndexFullText put(Object key, final OIdentifiable iSingleValue) {
checkForRebuild();
if (key == null)
return this;
key = getCollatingValue(key);
modificationLock.requestModificationLock();
try {
final List<String> words = splitIntoWords(key.toString());
// FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT
for (final String word : words) {
acquireExclusiveLock();
try {
Set<OIdentifiable> refs;
// SEARCH FOR THE WORD
refs = indexEngine.get(word);
if (refs == null) {
// WORD NOT EXISTS: CREATE THE KEYWORD CONTAINER THE FIRST TIME THE WORD IS FOUND
if (ODefaultIndexFactory.SBTREEBONSAI_VALUE_CONTAINER.equals(valueContainerAlgorithm)) {
refs = new OIndexRIDContainer(getName());
} else {
refs = new OMVRBTreeRIDSet();
((OMVRBTreeRIDSet) refs).setAutoConvertToRecord(false);
}
}
// ADD THE CURRENT DOCUMENT AS REF FOR THAT WORD
refs.add(iSingleValue);
// SAVE THE INDEX ENTRY
indexEngine.put(word, refs);
} finally {
releaseExclusiveLock();
}
}
return this;
} finally {
modificationLock.releaseModificationLock();
}
}
@Override
protected void putInSnapshot(Object key, OIdentifiable value, Map<Object, Object> snapshot) {
if (key == null)
return;
key = getCollatingValue(key);
final List<String> words = splitIntoWords(key.toString());
// FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT
for (final String word : words) {
Set<OIdentifiable> refs;
final Object snapshotValue = snapshot.get(word);
if (snapshotValue == null)
refs = indexEngine.get(word);
else if (snapshotValue.equals(RemovedValue.INSTANCE))
refs = null;
else
refs = (Set<OIdentifiable>) snapshotValue;
if (refs == null) {
// WORD NOT EXISTS: CREATE THE KEYWORD CONTAINER THE FIRST TIME THE WORD IS FOUND
if (ODefaultIndexFactory.SBTREEBONSAI_VALUE_CONTAINER.equals(valueContainerAlgorithm)) {
refs = new OIndexRIDContainer(getName());
} else {
refs = new OMVRBTreeRIDSet();
((OMVRBTreeRIDSet) refs).setAutoConvertToRecord(false);
}
snapshot.put(word, refs);
}
// ADD THE CURRENT DOCUMENT AS REF FOR THAT WORD
refs.add(value.getIdentity());
}
}
/**
* Splits passed in key on several words and remove records with keys equals to any item of split result and values equals to
* passed in value.
*
* @param key
* Key to remove.
* @param value
* Value to remove.
* @return <code>true</code> if at least one record is removed.
*/
@Override
public boolean remove(Object key, final OIdentifiable value) {
checkForRebuild();
key = getCollatingValue(key);
modificationLock.requestModificationLock();
try {
final List<String> words = splitIntoWords(key.toString());
boolean removed = false;
for (final String word : words) {
acquireExclusiveLock();
try {
final Set<OIdentifiable> recs = indexEngine.get(word);
if (recs != null && !recs.isEmpty()) {
if (recs.remove(value)) {
if (recs.isEmpty())
indexEngine.remove(word);
else
indexEngine.put(word, recs);
removed = true;
}
}
} finally {
releaseExclusiveLock();
}
}
return removed;
} finally {
modificationLock.releaseModificationLock();
}
}
@Override
protected void removeFromSnapshot(Object key, OIdentifiable value, Map<Object, Object> snapshot) {
key = getCollatingValue(key);
final List<String> words = splitIntoWords(key.toString());
for (final String word : words) {
final Set<OIdentifiable> recs;
final Object snapshotValue = snapshot.get(word);
if (snapshotValue == null)
recs = indexEngine.get(word);
else if (snapshotValue.equals(RemovedValue.INSTANCE))
recs = null;
else
recs = (Set<OIdentifiable>) snapshotValue;
if (recs != null && !recs.isEmpty()) {
if (recs.remove(value)) {
if (recs.isEmpty())
snapshot.put(word, RemovedValue.INSTANCE);
else
snapshot.put(word, recs);
}
}
}
}
@Override
public OIndexInternal<?> create(String name, OIndexDefinition indexDefinition, String clusterIndexName,
Set<String> clustersToIndex, boolean rebuild, OProgressListener progressListener, OStreamSerializer valueSerializer) {
if (indexDefinition.getFields().size() > 1) {
throw new OIndexException(type + " indexes cannot be used as composite ones.");
}
return super.create(name, indexDefinition, clusterIndexName, clustersToIndex, rebuild, progressListener, valueSerializer);
}
@Override
public OIndexMultiValues create(String name, OIndexDefinition indexDefinition, String clusterIndexName,
Set<String> clustersToIndex, boolean rebuild, OProgressListener progressListener) {
if (indexDefinition.getFields().size() > 1) {
throw new OIndexException(type + " indexes cannot be used as composite ones.");
}
return super.create(name, indexDefinition, clusterIndexName, clustersToIndex, rebuild, progressListener);
}
@Override
public ODocument updateConfiguration() {
super.updateConfiguration();
configuration.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
try {
configuration.field(CONFIG_SEPARATOR_CHARS, separatorChars);
configuration.field(CONFIG_IGNORE_CHARS, ignoreChars);
configuration.field(CONFIG_STOP_WORDS, stopWords);
} finally {
configuration.setInternalStatus(ORecordElement.STATUS.LOADED);
}
return configuration;
}
private List<String> splitIntoWords(final String iKey) {
final List<String> result = new ArrayList<String>();
final List<String> words = (List<String>) OStringSerializerHelper.split(new ArrayList<String>(), iKey, 0, -1, separatorChars);
final StringBuilder buffer = new StringBuilder();
// FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT
char c;
boolean ignore;
for (String word : words) {
buffer.setLength(0);
for (int i = 0; i < word.length(); ++i) {
c = word.charAt(i);
ignore = false;
for (int k = 0; k < ignoreChars.length(); ++k)
if (c == ignoreChars.charAt(k)) {
ignore = true;
break;
}
if (!ignore)
buffer.append(c);
}
word = buffer.toString();
// CHECK IF IT'S A STOP WORD
if (stopWords.contains(word))
continue;
result.add(word);
}
return result;
}
public boolean canBeUsedInEqualityOperators() {
return false;
}
public boolean supportsOrderedIterations() {
return false;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_index_OIndexFullText.java |
2,851 | public class DelimitedPayloadTokenFilterFactory extends AbstractTokenFilterFactory {
static final char DEFAULT_DELIMITER = '|';
static final PayloadEncoder DEFAULT_ENCODER = new FloatEncoder();
static final String ENCODING = "encoding";
static final String DELIMITER = "delimiter";
char delimiter;
PayloadEncoder encoder;
@Inject
public DelimitedPayloadTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name,
@Assisted Settings settings) {
super(index, indexSettings, name, settings);
String delimiterConf = settings.get(DELIMITER);
if (delimiterConf != null) {
delimiter = delimiterConf.charAt(0);
} else {
delimiter = DEFAULT_DELIMITER;
}
if (settings.get(ENCODING) != null) {
if (settings.get(ENCODING).equals("float")) {
encoder = new FloatEncoder();
} else if (settings.get(ENCODING).equals("int")) {
encoder = new IntegerEncoder();
} else if (settings.get(ENCODING).equals("identity")) {
encoder = new IdentityEncoder();
}
} else {
encoder = DEFAULT_ENCODER;
}
}
@Override
public TokenStream create(TokenStream tokenStream) {
DelimitedPayloadTokenFilter filter = new DelimitedPayloadTokenFilter(tokenStream, delimiter, encoder);
return filter;
}
} | 0true
| src_main_java_org_elasticsearch_index_analysis_DelimitedPayloadTokenFilterFactory.java |
3,441 | public abstract class BlobStoreIndexShardGateway extends AbstractIndexShardComponent implements IndexShardGateway {
protected final ThreadPool threadPool;
protected final InternalIndexShard indexShard;
protected final Store store;
protected final ByteSizeValue chunkSize;
protected final BlobStore blobStore;
protected final BlobPath shardPath;
protected final ImmutableBlobContainer blobContainer;
private volatile RecoveryStatus recoveryStatus;
private volatile SnapshotStatus lastSnapshotStatus;
private volatile SnapshotStatus currentSnapshotStatus;
protected BlobStoreIndexShardGateway(ShardId shardId, @IndexSettings Settings indexSettings, ThreadPool threadPool, IndexGateway indexGateway,
IndexShard indexShard, Store store) {
super(shardId, indexSettings);
this.threadPool = threadPool;
this.indexShard = (InternalIndexShard) indexShard;
this.store = store;
BlobStoreIndexGateway blobStoreIndexGateway = (BlobStoreIndexGateway) indexGateway;
this.chunkSize = blobStoreIndexGateway.chunkSize(); // can be null -> no chunking
this.blobStore = blobStoreIndexGateway.blobStore();
this.shardPath = blobStoreIndexGateway.shardPath(shardId.id());
this.blobContainer = blobStore.immutableBlobContainer(shardPath);
this.recoveryStatus = new RecoveryStatus();
}
@Override
public RecoveryStatus recoveryStatus() {
return this.recoveryStatus;
}
@Override
public String toString() {
return type() + "://" + blobStore + "/" + shardPath;
}
@Override
public boolean requiresSnapshot() {
return true;
}
@Override
public boolean requiresSnapshotScheduling() {
return true;
}
@Override
public SnapshotLock obtainSnapshotLock() throws Exception {
return NO_SNAPSHOT_LOCK;
}
@Override
public void close() throws ElasticsearchException {
}
@Override
public SnapshotStatus lastSnapshotStatus() {
return this.lastSnapshotStatus;
}
@Override
public SnapshotStatus currentSnapshotStatus() {
SnapshotStatus snapshotStatus = this.currentSnapshotStatus;
if (snapshotStatus == null) {
return snapshotStatus;
}
if (snapshotStatus.stage() != SnapshotStatus.Stage.DONE || snapshotStatus.stage() != SnapshotStatus.Stage.FAILURE) {
snapshotStatus.time(System.currentTimeMillis() - snapshotStatus.startTime());
}
return snapshotStatus;
}
@Override
public SnapshotStatus snapshot(final Snapshot snapshot) throws IndexShardGatewaySnapshotFailedException {
currentSnapshotStatus = new SnapshotStatus();
currentSnapshotStatus.startTime(System.currentTimeMillis());
try {
doSnapshot(snapshot);
currentSnapshotStatus.time(System.currentTimeMillis() - currentSnapshotStatus.startTime());
currentSnapshotStatus.updateStage(SnapshotStatus.Stage.DONE);
} catch (Exception e) {
currentSnapshotStatus.time(System.currentTimeMillis() - currentSnapshotStatus.startTime());
currentSnapshotStatus.updateStage(SnapshotStatus.Stage.FAILURE);
currentSnapshotStatus.failed(e);
if (e instanceof IndexShardGatewaySnapshotFailedException) {
throw (IndexShardGatewaySnapshotFailedException) e;
} else {
throw new IndexShardGatewaySnapshotFailedException(shardId, e.getMessage(), e);
}
} finally {
this.lastSnapshotStatus = currentSnapshotStatus;
this.currentSnapshotStatus = null;
}
return this.lastSnapshotStatus;
}
private void doSnapshot(final Snapshot snapshot) throws IndexShardGatewaySnapshotFailedException {
ImmutableMap<String, BlobMetaData> blobs;
try {
blobs = blobContainer.listBlobs();
} catch (IOException e) {
throw new IndexShardGatewaySnapshotFailedException(shardId, "failed to list blobs", e);
}
long generation = findLatestFileNameGeneration(blobs);
CommitPoints commitPoints = buildCommitPoints(blobs);
currentSnapshotStatus.index().startTime(System.currentTimeMillis());
currentSnapshotStatus.updateStage(SnapshotStatus.Stage.INDEX);
final SnapshotIndexCommit snapshotIndexCommit = snapshot.indexCommit();
final Translog.Snapshot translogSnapshot = snapshot.translogSnapshot();
final CountDownLatch indexLatch = new CountDownLatch(snapshotIndexCommit.getFiles().length);
final CopyOnWriteArrayList<Throwable> failures = new CopyOnWriteArrayList<Throwable>();
final List<CommitPoint.FileInfo> indexCommitPointFiles = Lists.newArrayList();
int indexNumberOfFiles = 0;
long indexTotalFilesSize = 0;
for (final String fileName : snapshotIndexCommit.getFiles()) {
StoreFileMetaData md;
try {
md = store.metaData(fileName);
} catch (IOException e) {
throw new IndexShardGatewaySnapshotFailedException(shardId, "Failed to get store file metadata", e);
}
boolean snapshotRequired = false;
if (snapshot.indexChanged() && fileName.equals(snapshotIndexCommit.getSegmentsFileName())) {
snapshotRequired = true; // we want to always snapshot the segment file if the index changed
}
CommitPoint.FileInfo fileInfo = commitPoints.findPhysicalIndexFile(fileName);
if (fileInfo == null || !fileInfo.isSame(md) || !commitPointFileExistsInBlobs(fileInfo, blobs)) {
// commit point file does not exists in any commit point, or has different length, or does not fully exists in the listed blobs
snapshotRequired = true;
}
if (snapshotRequired) {
indexNumberOfFiles++;
indexTotalFilesSize += md.length();
// create a new FileInfo
try {
CommitPoint.FileInfo snapshotFileInfo = new CommitPoint.FileInfo(fileNameFromGeneration(++generation), fileName, md.length(), md.checksum());
indexCommitPointFiles.add(snapshotFileInfo);
snapshotFile(snapshotIndexCommit.getDirectory(), snapshotFileInfo, indexLatch, failures);
} catch (IOException e) {
failures.add(e);
indexLatch.countDown();
}
} else {
indexCommitPointFiles.add(fileInfo);
indexLatch.countDown();
}
}
currentSnapshotStatus.index().files(indexNumberOfFiles, indexTotalFilesSize);
try {
indexLatch.await();
} catch (InterruptedException e) {
failures.add(e);
}
if (!failures.isEmpty()) {
throw new IndexShardGatewaySnapshotFailedException(shardId(), "Failed to perform snapshot (index files)", failures.get(failures.size() - 1));
}
currentSnapshotStatus.index().time(System.currentTimeMillis() - currentSnapshotStatus.index().startTime());
currentSnapshotStatus.updateStage(SnapshotStatus.Stage.TRANSLOG);
currentSnapshotStatus.translog().startTime(System.currentTimeMillis());
// Note, we assume the snapshot is always started from "base 0". We need to seek forward if we want to lastTranslogPosition if we want the delta
List<CommitPoint.FileInfo> translogCommitPointFiles = Lists.newArrayList();
int expectedNumberOfOperations = 0;
boolean snapshotRequired = false;
if (snapshot.newTranslogCreated()) {
if (translogSnapshot.lengthInBytes() > 0) {
snapshotRequired = true;
expectedNumberOfOperations = translogSnapshot.estimatedTotalOperations();
}
} else {
// if we have a commit point, check that we have all the files listed in it in the blob store
if (!commitPoints.commits().isEmpty()) {
CommitPoint commitPoint = commitPoints.commits().get(0);
boolean allTranslogFilesExists = true;
for (CommitPoint.FileInfo fileInfo : commitPoint.translogFiles()) {
if (!commitPointFileExistsInBlobs(fileInfo, blobs)) {
allTranslogFilesExists = false;
break;
}
}
// if everything exists, we can seek forward in case there are new operations, otherwise, we copy over all again...
if (allTranslogFilesExists) {
translogCommitPointFiles.addAll(commitPoint.translogFiles());
if (snapshot.sameTranslogNewOperations()) {
translogSnapshot.seekForward(snapshot.lastTranslogLength());
if (translogSnapshot.lengthInBytes() > 0) {
snapshotRequired = true;
expectedNumberOfOperations = translogSnapshot.estimatedTotalOperations() - snapshot.lastTotalTranslogOperations();
}
} // else (no operations, nothing to snapshot)
} else {
// a full translog snapshot is required
if (translogSnapshot.lengthInBytes() > 0) {
expectedNumberOfOperations = translogSnapshot.estimatedTotalOperations();
snapshotRequired = true;
}
}
} else {
// no commit point, snapshot all the translog
if (translogSnapshot.lengthInBytes() > 0) {
expectedNumberOfOperations = translogSnapshot.estimatedTotalOperations();
snapshotRequired = true;
}
}
}
currentSnapshotStatus.translog().expectedNumberOfOperations(expectedNumberOfOperations);
if (snapshotRequired) {
CommitPoint.FileInfo addedTranslogFileInfo = new CommitPoint.FileInfo(fileNameFromGeneration(++generation), "translog-" + translogSnapshot.translogId(), translogSnapshot.lengthInBytes(), null /* no need for checksum in translog */);
translogCommitPointFiles.add(addedTranslogFileInfo);
try {
snapshotTranslog(translogSnapshot, addedTranslogFileInfo);
} catch (Exception e) {
throw new IndexShardGatewaySnapshotFailedException(shardId, "Failed to snapshot translog", e);
}
}
currentSnapshotStatus.translog().time(System.currentTimeMillis() - currentSnapshotStatus.translog().startTime());
// now create and write the commit point
currentSnapshotStatus.updateStage(SnapshotStatus.Stage.FINALIZE);
long version = 0;
if (!commitPoints.commits().isEmpty()) {
version = commitPoints.commits().iterator().next().version() + 1;
}
String commitPointName = "commit-" + Long.toString(version, Character.MAX_RADIX);
CommitPoint commitPoint = new CommitPoint(version, commitPointName, CommitPoint.Type.GENERATED, indexCommitPointFiles, translogCommitPointFiles);
try {
byte[] commitPointData = CommitPoints.toXContent(commitPoint);
blobContainer.writeBlob(commitPointName, new BytesStreamInput(commitPointData, false), commitPointData.length);
} catch (Exception e) {
throw new IndexShardGatewaySnapshotFailedException(shardId, "Failed to write commit point", e);
}
// delete all files that are not referenced by any commit point
// build a new CommitPoint, that includes this one and all the saved ones
List<CommitPoint> newCommitPointsList = Lists.newArrayList();
newCommitPointsList.add(commitPoint);
for (CommitPoint point : commitPoints) {
if (point.type() == CommitPoint.Type.SAVED) {
newCommitPointsList.add(point);
}
}
CommitPoints newCommitPoints = new CommitPoints(newCommitPointsList);
// first, go over and delete all the commit points
for (String blobName : blobs.keySet()) {
if (!blobName.startsWith("commit-")) {
continue;
}
long checkedVersion = Long.parseLong(blobName.substring("commit-".length()), Character.MAX_RADIX);
if (!newCommitPoints.hasVersion(checkedVersion)) {
try {
blobContainer.deleteBlob(blobName);
} catch (IOException e) {
// ignore
}
}
}
// now go over all the blobs, and if they don't exists in a commit point, delete them
for (String blobName : blobs.keySet()) {
String name = blobName;
if (!name.startsWith("__")) {
continue;
}
if (blobName.contains(".part")) {
name = blobName.substring(0, blobName.indexOf(".part"));
}
if (newCommitPoints.findNameFile(name) == null) {
try {
blobContainer.deleteBlob(blobName);
} catch (IOException e) {
// ignore, will delete it laters
}
}
}
}
@Override
public void recover(boolean indexShouldExists, RecoveryStatus recoveryStatus) throws IndexShardGatewayRecoveryException {
this.recoveryStatus = recoveryStatus;
final ImmutableMap<String, BlobMetaData> blobs;
try {
blobs = blobContainer.listBlobs();
} catch (IOException e) {
throw new IndexShardGatewayRecoveryException(shardId, "Failed to list content of gateway", e);
}
List<CommitPoint> commitPointsList = Lists.newArrayList();
boolean atLeastOneCommitPointExists = false;
for (String name : blobs.keySet()) {
if (name.startsWith("commit-")) {
atLeastOneCommitPointExists = true;
try {
commitPointsList.add(CommitPoints.fromXContent(blobContainer.readBlobFully(name)));
} catch (Exception e) {
logger.warn("failed to read commit point [{}]", e, name);
}
}
}
if (atLeastOneCommitPointExists && commitPointsList.isEmpty()) {
// no commit point managed to load, bail so we won't corrupt the index, will require manual intervention
throw new IndexShardGatewayRecoveryException(shardId, "Commit points exists but none could be loaded", null);
}
CommitPoints commitPoints = new CommitPoints(commitPointsList);
if (commitPoints.commits().isEmpty()) {
// no commit points, clean the store just so we won't recover wrong files
try {
indexShard.store().deleteContent();
} catch (IOException e) {
logger.warn("failed to clean store before starting shard", e);
}
recoveryStatus.index().startTime(System.currentTimeMillis());
recoveryStatus.index().time(System.currentTimeMillis() - recoveryStatus.index().startTime());
return;
}
for (CommitPoint commitPoint : commitPoints) {
if (!commitPointExistsInBlobs(commitPoint, blobs)) {
logger.warn("listed commit_point [{}]/[{}], but not all files exists, ignoring", commitPoint.name(), commitPoint.version());
continue;
}
try {
recoveryStatus.index().startTime(System.currentTimeMillis());
recoverIndex(commitPoint, blobs);
recoveryStatus.index().time(System.currentTimeMillis() - recoveryStatus.index().startTime());
recoverTranslog(commitPoint, blobs);
return;
} catch (Exception e) {
throw new IndexShardGatewayRecoveryException(shardId, "failed to recover commit_point [" + commitPoint.name() + "]/[" + commitPoint.version() + "]", e);
}
}
throw new IndexShardGatewayRecoveryException(shardId, "No commit point data is available in gateway", null);
}
private void recoverTranslog(CommitPoint commitPoint, ImmutableMap<String, BlobMetaData> blobs) throws IndexShardGatewayRecoveryException {
if (commitPoint.translogFiles().isEmpty()) {
// no translog files, bail
recoveryStatus.start().startTime(System.currentTimeMillis());
recoveryStatus.updateStage(RecoveryStatus.Stage.START);
indexShard.postRecovery("post recovery from gateway, no translog");
recoveryStatus.start().time(System.currentTimeMillis() - recoveryStatus.start().startTime());
recoveryStatus.start().checkIndexTime(indexShard.checkIndexTook());
return;
}
try {
recoveryStatus.start().startTime(System.currentTimeMillis());
recoveryStatus.updateStage(RecoveryStatus.Stage.START);
indexShard.performRecoveryPrepareForTranslog();
recoveryStatus.start().time(System.currentTimeMillis() - recoveryStatus.start().startTime());
recoveryStatus.start().checkIndexTime(indexShard.checkIndexTook());
recoveryStatus.updateStage(RecoveryStatus.Stage.TRANSLOG);
recoveryStatus.translog().startTime(System.currentTimeMillis());
final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(1);
final Iterator<CommitPoint.FileInfo> transIt = commitPoint.translogFiles().iterator();
blobContainer.readBlob(transIt.next().name(), new BlobContainer.ReadBlobListener() {
BytesStreamOutput bos = new BytesStreamOutput();
boolean ignore = false;
@Override
public synchronized void onPartial(byte[] data, int offset, int size) throws IOException {
if (ignore) {
return;
}
bos.write(data, offset, size);
// if we don't have enough to read the header size of the first translog, bail and wait for the next one
if (bos.size() < 4) {
return;
}
BytesStreamInput si = new BytesStreamInput(bos.bytes());
int position;
while (true) {
try {
position = si.position();
if (position + 4 > bos.size()) {
break;
}
int opSize = si.readInt();
int curPos = si.position();
if ((si.position() + opSize) > bos.size()) {
break;
}
Translog.Operation operation = TranslogStreams.readTranslogOperation(si);
if ((si.position() - curPos) != opSize) {
logger.warn("mismatch in size, expected [{}], got [{}]", opSize, si.position() - curPos);
}
recoveryStatus.translog().addTranslogOperations(1);
indexShard.performRecoveryOperation(operation);
if (si.position() >= bos.size()) {
position = si.position();
break;
}
} catch (Throwable e) {
logger.warn("failed to retrieve translog after [{}] operations, ignoring the rest, considered corrupted", e, recoveryStatus.translog().currentTranslogOperations());
ignore = true;
latch.countDown();
return;
}
}
BytesStreamOutput newBos = new BytesStreamOutput();
int leftOver = bos.size() - position;
if (leftOver > 0) {
newBos.write(bos.bytes().array(), position, leftOver);
}
bos = newBos;
}
@Override
public synchronized void onCompleted() {
if (ignore) {
return;
}
if (!transIt.hasNext()) {
latch.countDown();
return;
}
blobContainer.readBlob(transIt.next().name(), this);
}
@Override
public void onFailure(Throwable t) {
failure.set(t);
latch.countDown();
}
});
latch.await();
if (failure.get() != null) {
throw failure.get();
}
indexShard.performRecoveryFinalization(true);
recoveryStatus.translog().time(System.currentTimeMillis() - recoveryStatus.translog().startTime());
} catch (Throwable e) {
throw new IndexShardGatewayRecoveryException(shardId, "Failed to recover translog", e);
}
}
private void recoverIndex(CommitPoint commitPoint, ImmutableMap<String, BlobMetaData> blobs) throws Exception {
recoveryStatus.updateStage(RecoveryStatus.Stage.INDEX);
int numberOfFiles = 0;
long totalSize = 0;
int numberOfReusedFiles = 0;
long reusedTotalSize = 0;
List<CommitPoint.FileInfo> filesToRecover = Lists.newArrayList();
for (CommitPoint.FileInfo fileInfo : commitPoint.indexFiles()) {
String fileName = fileInfo.physicalName();
StoreFileMetaData md = null;
try {
md = store.metaData(fileName);
} catch (Exception e) {
// no file
}
// we don't compute checksum for segments, so always recover them
if (!fileName.startsWith("segments") && md != null && fileInfo.isSame(md)) {
numberOfFiles++;
totalSize += md.length();
numberOfReusedFiles++;
reusedTotalSize += md.length();
if (logger.isTraceEnabled()) {
logger.trace("not_recovering [{}], exists in local store and is same", fileInfo.physicalName());
}
} else {
if (logger.isTraceEnabled()) {
if (md == null) {
logger.trace("recovering [{}], does not exists in local store", fileInfo.physicalName());
} else {
logger.trace("recovering [{}], exists in local store but is different", fileInfo.physicalName());
}
}
numberOfFiles++;
totalSize += fileInfo.length();
filesToRecover.add(fileInfo);
}
}
recoveryStatus.index().files(numberOfFiles, totalSize, numberOfReusedFiles, reusedTotalSize);
if (filesToRecover.isEmpty()) {
logger.trace("no files to recover, all exists within the local store");
}
if (logger.isTraceEnabled()) {
logger.trace("recovering_files [{}] with total_size [{}], reusing_files [{}] with reused_size [{}]", numberOfFiles, new ByteSizeValue(totalSize), numberOfReusedFiles, new ByteSizeValue(reusedTotalSize));
}
final CountDownLatch latch = new CountDownLatch(filesToRecover.size());
final CopyOnWriteArrayList<Throwable> failures = new CopyOnWriteArrayList<Throwable>();
for (final CommitPoint.FileInfo fileToRecover : filesToRecover) {
recoverFile(fileToRecover, blobs, latch, failures);
}
try {
latch.await();
} catch (InterruptedException e) {
throw new IndexShardGatewayRecoveryException(shardId, "Interrupted while recovering index", e);
}
if (!failures.isEmpty()) {
throw new IndexShardGatewayRecoveryException(shardId, "Failed to recover index", failures.get(0));
}
// read the gateway data persisted
long version = -1;
try {
if (Lucene.indexExists(store.directory())) {
version = Lucene.readSegmentInfos(store.directory()).getVersion();
}
} catch (IOException e) {
throw new IndexShardGatewayRecoveryException(shardId(), "Failed to fetch index version after copying it over", e);
}
recoveryStatus.index().updateVersion(version);
/// now, go over and clean files that are in the store, but were not in the gateway
try {
for (String storeFile : store.directory().listAll()) {
if (!commitPoint.containPhysicalIndexFile(storeFile)) {
try {
store.directory().deleteFile(storeFile);
} catch (Exception e) {
// ignore
}
}
}
} catch (Exception e) {
// ignore
}
}
private void recoverFile(final CommitPoint.FileInfo fileInfo, final ImmutableMap<String, BlobMetaData> blobs, final CountDownLatch latch, final List<Throwable> failures) {
final IndexOutput indexOutput;
try {
// we create an output with no checksum, this is because the pure binary data of the file is not
// the checksum (because of seek). We will create the checksum file once copying is done
indexOutput = store.createOutputRaw(fileInfo.physicalName());
} catch (IOException e) {
failures.add(e);
latch.countDown();
return;
}
String firstFileToRecover = fileInfo.name();
if (!blobs.containsKey(fileInfo.name())) {
// chunking, append part0 to it
firstFileToRecover = fileInfo.name() + ".part0";
}
if (!blobs.containsKey(firstFileToRecover)) {
// no file, what to do, what to do?
logger.warn("no file [{}]/[{}] to recover, ignoring it", fileInfo.name(), fileInfo.physicalName());
latch.countDown();
return;
}
final AtomicInteger partIndex = new AtomicInteger();
blobContainer.readBlob(firstFileToRecover, new BlobContainer.ReadBlobListener() {
@Override
public synchronized void onPartial(byte[] data, int offset, int size) throws IOException {
recoveryStatus.index().addCurrentFilesSize(size);
indexOutput.writeBytes(data, offset, size);
}
@Override
public synchronized void onCompleted() {
int part = partIndex.incrementAndGet();
String partName = fileInfo.name() + ".part" + part;
if (blobs.containsKey(partName)) {
// continue with the new part
blobContainer.readBlob(partName, this);
return;
} else {
// we are done...
try {
indexOutput.close();
// write the checksum
if (fileInfo.checksum() != null) {
store.writeChecksum(fileInfo.physicalName(), fileInfo.checksum());
}
store.directory().sync(Collections.singleton(fileInfo.physicalName()));
} catch (IOException e) {
onFailure(e);
return;
}
}
latch.countDown();
}
@Override
public void onFailure(Throwable t) {
failures.add(t);
latch.countDown();
}
});
}
private void snapshotTranslog(Translog.Snapshot snapshot, CommitPoint.FileInfo fileInfo) throws IOException {
blobContainer.writeBlob(fileInfo.name(), snapshot.stream(), snapshot.lengthInBytes());
//
// long chunkBytes = Long.MAX_VALUE;
// if (chunkSize != null) {
// chunkBytes = chunkSize.bytes();
// }
//
// long totalLength = fileInfo.length();
// long numberOfChunks = totalLength / chunkBytes;
// if (totalLength % chunkBytes > 0) {
// numberOfChunks++;
// }
// if (numberOfChunks == 0) {
// numberOfChunks++;
// }
//
// if (numberOfChunks == 1) {
// blobContainer.writeBlob(fileInfo.name(), snapshot.stream(), snapshot.lengthInBytes());
// } else {
// InputStream translogStream = snapshot.stream();
// long totalLengthLeftToWrite = totalLength;
// for (int i = 0; i < numberOfChunks; i++) {
// long lengthToWrite = chunkBytes;
// if (totalLengthLeftToWrite < chunkBytes) {
// lengthToWrite = totalLengthLeftToWrite;
// }
// blobContainer.writeBlob(fileInfo.name() + ".part" + i, new LimitInputStream(translogStream, lengthToWrite), lengthToWrite);
// totalLengthLeftToWrite -= lengthToWrite;
// }
// }
}
private void snapshotFile(Directory dir, final CommitPoint.FileInfo fileInfo, final CountDownLatch latch, final List<Throwable> failures) throws IOException {
long chunkBytes = Long.MAX_VALUE;
if (chunkSize != null) {
chunkBytes = chunkSize.bytes();
}
long totalLength = fileInfo.length();
long numberOfChunks = totalLength / chunkBytes;
if (totalLength % chunkBytes > 0) {
numberOfChunks++;
}
if (numberOfChunks == 0) {
numberOfChunks++;
}
final long fNumberOfChunks = numberOfChunks;
final AtomicLong counter = new AtomicLong(numberOfChunks);
for (long i = 0; i < fNumberOfChunks; i++) {
final long partNumber = i;
IndexInput indexInput = null;
try {
// TODO: maybe use IOContext.READONCE?
indexInput = indexShard.store().openInputRaw(fileInfo.physicalName(), IOContext.READ);
indexInput.seek(partNumber * chunkBytes);
InputStreamIndexInput is = new ThreadSafeInputStreamIndexInput(indexInput, chunkBytes);
String blobName = fileInfo.name();
if (fNumberOfChunks > 1) {
// if we do chunks, then all of them are in the form of "[xxx].part[N]".
blobName += ".part" + partNumber;
}
final IndexInput fIndexInput = indexInput;
blobContainer.writeBlob(blobName, is, is.actualSizeToRead(), new ImmutableBlobContainer.WriterListener() {
@Override
public void onCompleted() {
try {
fIndexInput.close();
} catch (IOException e) {
// ignore
}
if (counter.decrementAndGet() == 0) {
latch.countDown();
}
}
@Override
public void onFailure(Throwable t) {
try {
fIndexInput.close();
} catch (IOException e) {
// ignore
}
failures.add(t);
if (counter.decrementAndGet() == 0) {
latch.countDown();
}
}
});
} catch (Exception e) {
if (indexInput != null) {
try {
indexInput.close();
} catch (IOException e1) {
// ignore
}
}
failures.add(e);
latch.countDown();
}
}
}
private boolean commitPointExistsInBlobs(CommitPoint commitPoint, ImmutableMap<String, BlobMetaData> blobs) {
for (CommitPoint.FileInfo fileInfo : Iterables.concat(commitPoint.indexFiles(), commitPoint.translogFiles())) {
if (!commitPointFileExistsInBlobs(fileInfo, blobs)) {
return false;
}
}
return true;
}
private boolean commitPointFileExistsInBlobs(CommitPoint.FileInfo fileInfo, ImmutableMap<String, BlobMetaData> blobs) {
BlobMetaData blobMetaData = blobs.get(fileInfo.name());
if (blobMetaData != null) {
if (blobMetaData.length() != fileInfo.length()) {
return false;
}
} else if (blobs.containsKey(fileInfo.name() + ".part0")) {
// multi part file sum up the size and check
int part = 0;
long totalSize = 0;
while (true) {
blobMetaData = blobs.get(fileInfo.name() + ".part" + part++);
if (blobMetaData == null) {
break;
}
totalSize += blobMetaData.length();
}
if (totalSize != fileInfo.length()) {
return false;
}
} else {
// no file, not exact and not multipart
return false;
}
return true;
}
private CommitPoints buildCommitPoints(ImmutableMap<String, BlobMetaData> blobs) {
List<CommitPoint> commitPoints = Lists.newArrayList();
for (String name : blobs.keySet()) {
if (name.startsWith("commit-")) {
try {
commitPoints.add(CommitPoints.fromXContent(blobContainer.readBlobFully(name)));
} catch (Exception e) {
logger.warn("failed to read commit point [{}]", e, name);
}
}
}
return new CommitPoints(commitPoints);
}
private String fileNameFromGeneration(long generation) {
return "__" + Long.toString(generation, Character.MAX_RADIX);
}
private long findLatestFileNameGeneration(ImmutableMap<String, BlobMetaData> blobs) {
long generation = -1;
for (String name : blobs.keySet()) {
if (!name.startsWith("__")) {
continue;
}
if (name.contains(".part")) {
name = name.substring(0, name.indexOf(".part"));
}
try {
long currentGen = Long.parseLong(name.substring(2) /*__*/, Character.MAX_RADIX);
if (currentGen > generation) {
generation = currentGen;
}
} catch (NumberFormatException e) {
logger.warn("file [{}] does not conform to the '__' schema");
}
}
return generation;
}
} | 0true
| src_main_java_org_elasticsearch_index_gateway_blobstore_BlobStoreIndexShardGateway.java |
909 | makeDbCall(iMyDb, new ODbRelatedCall<Object>() {
public Object call() {
if (iCurrent.getInternalStatus() == STATUS.NOT_LOADED)
iCurrent.reload();
return null;
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java |
351 | public class MergePersistenceUnitManager extends DefaultPersistenceUnitManager {
private static final Log LOG = LogFactory.getLog(MergePersistenceUnitManager.class);
protected HashMap<String, PersistenceUnitInfo> mergedPus = new HashMap<String, PersistenceUnitInfo>();
protected final boolean jpa2ApiPresent = ClassUtils.hasMethod(PersistenceUnitInfo.class, "getSharedCacheMode");
protected List<BroadleafClassTransformer> classTransformers = new ArrayList<BroadleafClassTransformer>();
@Resource(name="blMergedPersistenceXmlLocations")
protected Set<String> mergedPersistenceXmlLocations;
@Resource(name="blMergedDataSources")
protected Map<String, DataSource> mergedDataSources;
@Resource(name="blMergedClassTransformers")
protected Set<BroadleafClassTransformer> mergedClassTransformers;
@PostConstruct
public void configureMergedItems() {
String[] tempLocations;
try {
Field persistenceXmlLocations = DefaultPersistenceUnitManager.class.getDeclaredField("persistenceXmlLocations");
persistenceXmlLocations.setAccessible(true);
tempLocations = (String[]) persistenceXmlLocations.get(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
for (String legacyLocation : tempLocations) {
if (!legacyLocation.endsWith("/persistence.xml")) {
//do not add the default JPA persistence location by default
mergedPersistenceXmlLocations.add(legacyLocation);
}
}
setPersistenceXmlLocations(mergedPersistenceXmlLocations.toArray(new String[mergedPersistenceXmlLocations.size()]));
if (!mergedDataSources.isEmpty()) {
setDataSources(mergedDataSources);
}
}
@PostConstruct
public void configureClassTransformers() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
classTransformers.addAll(mergedClassTransformers);
}
protected PersistenceUnitInfo getMergedUnit(String persistenceUnitName, MutablePersistenceUnitInfo newPU) {
if (!mergedPus.containsKey(persistenceUnitName)) {
PersistenceUnitInfo puiToStore = newPU;
if (jpa2ApiPresent) {
puiToStore = (PersistenceUnitInfo) Proxy.newProxyInstance(SmartPersistenceUnitInfo.class.getClassLoader(),
new Class[] {SmartPersistenceUnitInfo.class}, new Jpa2PersistenceUnitInfoDecorator(newPU));
}
mergedPus.put(persistenceUnitName, puiToStore);
}
return mergedPus.get(persistenceUnitName);
}
@Override
@SuppressWarnings({"unchecked", "ToArrayCallWithZeroLengthArrayArgument"})
public void preparePersistenceUnitInfos() {
//Need to use reflection to try and execute the logic in the DefaultPersistenceUnitManager
//SpringSource added a block of code in version 3.1 to "protect" the user from having more than one PU with
//the same name. Of course, in our case, this happens before a merge occurs. They have added
//a block of code to throw an exception if more than one PU has the same name. We want to
//use the logic of the DefaultPersistenceUnitManager without the exception in the case of
//a duplicate name. This will require reflection in order to do what we need.
try {
Set<String> persistenceUnitInfoNames = null;
Map<String, PersistenceUnitInfo> persistenceUnitInfos = null;
ResourcePatternResolver resourcePatternResolver = null;
Field[] fields = getClass().getSuperclass().getDeclaredFields();
for (Field field : fields) {
if ("persistenceUnitInfoNames".equals(field.getName())) {
field.setAccessible(true);
persistenceUnitInfoNames = (Set<String>)field.get(this);
} else if ("persistenceUnitInfos".equals(field.getName())) {
field.setAccessible(true);
persistenceUnitInfos = (Map<String, PersistenceUnitInfo>)field.get(this);
} else if ("resourcePatternResolver".equals(field.getName())) {
field.setAccessible(true);
resourcePatternResolver = (ResourcePatternResolver)field.get(this);
}
}
persistenceUnitInfoNames.clear();
persistenceUnitInfos.clear();
Method readPersistenceUnitInfos =
getClass().
getSuperclass().
getDeclaredMethod("readPersistenceUnitInfos");
readPersistenceUnitInfos.setAccessible(true);
//In Spring 3.0 this returns an array
//In Spring 3.1 this returns a List
Object pInfosObject = readPersistenceUnitInfos.invoke(this);
Object[] puis;
if (pInfosObject.getClass().isArray()) {
puis = (Object[])pInfosObject;
} else {
puis = ((Collection)pInfosObject).toArray();
}
for (Object pui : puis) {
MutablePersistenceUnitInfo mPui = (MutablePersistenceUnitInfo)pui;
if (mPui.getPersistenceUnitRootUrl() == null) {
Method determineDefaultPersistenceUnitRootUrl =
getClass().
getSuperclass().
getDeclaredMethod("determineDefaultPersistenceUnitRootUrl");
determineDefaultPersistenceUnitRootUrl.setAccessible(true);
mPui.setPersistenceUnitRootUrl((URL)determineDefaultPersistenceUnitRootUrl.invoke(this));
}
ConfigurationOnlyState state = ConfigurationOnlyState.getState();
if ((state == null || !state.isConfigurationOnly()) && mPui.getNonJtaDataSource() == null) {
mPui.setNonJtaDataSource(getDefaultDataSource());
}
if (super.getLoadTimeWeaver() != null) {
Method puiInitMethod = mPui.getClass().getDeclaredMethod("init", LoadTimeWeaver.class);
puiInitMethod.setAccessible(true);
puiInitMethod.invoke(pui, getLoadTimeWeaver());
}
else {
Method puiInitMethod = mPui.getClass().getDeclaredMethod("init", ClassLoader.class);
puiInitMethod.setAccessible(true);
puiInitMethod.invoke(pui, resourcePatternResolver.getClassLoader());
}
postProcessPersistenceUnitInfo((MutablePersistenceUnitInfo)pui);
String name = mPui.getPersistenceUnitName();
persistenceUnitInfoNames.add(name);
PersistenceUnitInfo puiToStore = mPui;
if (jpa2ApiPresent) {
InvocationHandler jpa2PersistenceUnitInfoDecorator = null;
Class<?>[] classes = getClass().getSuperclass().getDeclaredClasses();
for (Class<?> clz : classes){
if ("org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager$Jpa2PersistenceUnitInfoDecorator"
.equals(clz.getName())) {
Constructor<?> constructor =
clz.getConstructor(Class.forName("org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo"));
constructor.setAccessible(true);
jpa2PersistenceUnitInfoDecorator = (InvocationHandler)constructor.newInstance(mPui);
break;
}
}
puiToStore = (PersistenceUnitInfo) Proxy.newProxyInstance(SmartPersistenceUnitInfo.class.getClassLoader(),
new Class[] {SmartPersistenceUnitInfo.class}, jpa2PersistenceUnitInfoDecorator);
}
persistenceUnitInfos.put(name, puiToStore);
}
} catch (Exception e) {
throw new RuntimeException("An error occured reflectively invoking methods on " +
"class: " + getClass().getSuperclass().getName(), e);
}
try {
List<String> managedClassNames = new ArrayList<String>();
for (PersistenceUnitInfo pui : mergedPus.values()) {
for (BroadleafClassTransformer transformer : classTransformers) {
try {
if (!(transformer instanceof NullClassTransformer) && pui.getPersistenceUnitName().equals("blPU")) {
pui.addTransformer(transformer);
}
} catch (IllegalStateException e) {
LOG.warn("A BroadleafClassTransformer is configured for this persistence unit, but Spring reported a problem (likely that a LoadTimeWeaver is not registered). As a result, the Broadleaf Commerce ClassTransformer ("+transformer.getClass().getName()+") is not being registered with the persistence unit.", e);
}
}
}
for (PersistenceUnitInfo pui : mergedPus.values()) {
for (String managedClassName : pui.getManagedClassNames()) {
if (!managedClassNames.contains(managedClassName)) {
// Force-load this class so that we are able to ensure our instrumentation happens globally.
Class.forName(managedClassName, true, getClass().getClassLoader());
managedClassNames.add(managedClassName);
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo newPU) {
super.postProcessPersistenceUnitInfo(newPU);
ConfigurationOnlyState state = ConfigurationOnlyState.getState();
String persistenceUnitName = newPU.getPersistenceUnitName();
MutablePersistenceUnitInfo temp;
PersistenceUnitInfo pui = getMergedUnit(persistenceUnitName, newPU);
if (pui != null && Proxy.isProxyClass(pui.getClass())) {
// JPA 2.0 PersistenceUnitInfo decorator with a SpringPersistenceUnitInfo as target
Jpa2PersistenceUnitInfoDecorator dec = (Jpa2PersistenceUnitInfoDecorator) Proxy.getInvocationHandler(pui);
temp = (MutablePersistenceUnitInfo) dec.getTarget();
}
else {
// Must be a raw JPA 1.0 SpringPersistenceUnitInfo instance
temp = (MutablePersistenceUnitInfo) pui;
}
List<String> managedClassNames = newPU.getManagedClassNames();
for (String managedClassName : managedClassNames){
if (!temp.getManagedClassNames().contains(managedClassName)) {
temp.addManagedClassName(managedClassName);
}
}
List<String> mappingFileNames = newPU.getMappingFileNames();
for (String mappingFileName : mappingFileNames) {
if (!temp.getMappingFileNames().contains(mappingFileName)) {
temp.addMappingFileName(mappingFileName);
}
}
temp.setExcludeUnlistedClasses(newPU.excludeUnlistedClasses());
for (URL url : newPU.getJarFileUrls()) {
// Avoid duplicate class scanning by Ejb3Configuration. Do not re-add the URL to the list of jars for this
// persistence unit or duplicate the persistence unit root URL location (both types of locations are scanned)
if (!temp.getJarFileUrls().contains(url) && !temp.getPersistenceUnitRootUrl().equals(url)) {
temp.addJarFileUrl(url);
}
}
if (temp.getProperties() == null) {
temp.setProperties(newPU.getProperties());
} else {
Properties props = newPU.getProperties();
if (props != null) {
for (Object key : props.keySet()) {
temp.getProperties().put(key, props.get(key));
for (BroadleafClassTransformer transformer : classTransformers) {
try {
transformer.compileJPAProperties(props, key);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
}
if (state == null || !state.isConfigurationOnly()) {
if (newPU.getJtaDataSource() != null) {
temp.setJtaDataSource(newPU.getJtaDataSource());
}
if (newPU.getNonJtaDataSource() != null) {
temp.setNonJtaDataSource(newPU.getNonJtaDataSource());
}
} else {
temp.getProperties().setProperty("hibernate.hbm2ddl.auto", "none");
temp.getProperties().setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false");
}
temp.setTransactionType(newPU.getTransactionType());
if (newPU.getPersistenceProviderClassName() != null) {
temp.setPersistenceProviderClassName(newPU.getPersistenceProviderClassName());
}
if (newPU.getPersistenceProviderPackageName() != null) {
temp.setPersistenceProviderPackageName(newPU.getPersistenceProviderPackageName());
}
}
/* (non-Javadoc)
* @see org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager#obtainPersistenceUnitInfo(java.lang.String)
*/
@Override
public PersistenceUnitInfo obtainPersistenceUnitInfo(String persistenceUnitName) {
return mergedPus.get(persistenceUnitName);
}
/* (non-Javadoc)
* @see org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager#obtainDefaultPersistenceUnitInfo()
*/
@Override
public PersistenceUnitInfo obtainDefaultPersistenceUnitInfo() {
throw new IllegalStateException("Default Persistence Unit is not supported. The persistence unit name must be specified at the entity manager factory.");
}
public List<BroadleafClassTransformer> getClassTransformers() {
return classTransformers;
}
public void setClassTransformers(List<BroadleafClassTransformer> classTransformers) {
this.classTransformers = classTransformers;
}
} | 1no label
| common_src_main_java_org_broadleafcommerce_common_extensibility_jpa_MergePersistenceUnitManager.java |
1,072 | public enum MaxSizePolicy {
PER_NODE, PER_PARTITION, USED_HEAP_PERCENTAGE, USED_HEAP_SIZE
} | 0true
| hazelcast_src_main_java_com_hazelcast_config_MaxSizeConfig.java |
199 | public static class LogPositionCache
{
private final LruCache<Long, TxPosition> txStartPositionCache =
new LruCache<Long, TxPosition>( "Tx start position cache", 10000 );
private final LruCache<Long /*log version*/, Long /*last committed tx*/> logHeaderCache =
new LruCache<Long, Long>( "Log header cache", 1000 );
public void clear()
{
logHeaderCache.clear();
txStartPositionCache.clear();
}
public TxPosition positionOf( long txId )
{
return txStartPositionCache.get( txId );
}
public void putHeader( long logVersion, long previousLogLastCommittedTx )
{
logHeaderCache.put( logVersion, previousLogLastCommittedTx );
}
public Long getHeader( long logVersion )
{
return logHeaderCache.get( logVersion );
}
public void putStartPosition( long txId, TxPosition position )
{
txStartPositionCache.put( txId, position );
}
public TxPosition getStartPosition( long txId )
{
return txStartPositionCache.get( txId );
}
public synchronized TxPosition cacheStartPosition( long txId, LogEntry.Start startEntry, long logVersion )
{
if ( startEntry.getStartPosition() == -1 )
{
throw new RuntimeException( "StartEntry.position is " + startEntry.getStartPosition() );
}
TxPosition result = new TxPosition( logVersion, startEntry.getMasterId(), startEntry.getIdentifier(),
startEntry.getStartPosition(), startEntry.getChecksum() );
putStartPosition( txId, result );
return result;
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogExtractor.java |
99 | public class Precision extends AbstractDecimal {
public static final int DECIMALS = 6;
public static final Precision MIN_VALUE = new Precision(minDoubleValue(DECIMALS));
public static final Precision MAX_VALUE = new Precision(maxDoubleValue(DECIMALS));
private Precision() {}
public Precision(double value) {
super(value, DECIMALS);
}
private Precision(long format) {
super(format, DECIMALS);
}
public static class PrecisionSerializer extends AbstractDecimalSerializer<Precision> {
public PrecisionSerializer() {
super(DECIMALS, Precision.class);
}
@Override
protected Precision construct(long format, int decimals) {
assert decimals==DECIMALS;
return new Precision(format);
}
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Precision.java |
1,113 | public class SocketInterceptorConfig {
private boolean enabled = false;
private String className = null;
private Object implementation = null;
private Properties properties = new Properties();
/**
* Returns the name of the {@link com.hazelcast.nio.SocketInterceptor} implementation class
*
* @return name of the class
*/
public String getClassName() {
return className;
}
/**
* Sets the name for the {@link com.hazelcast.nio.SocketInterceptor} implementation class
*
* @param className the name of the {@link com.hazelcast.nio.SocketInterceptor} implementation class to set
* @return this SocketInterceptorConfig instance
*/
public SocketInterceptorConfig setClassName(String className) {
this.className = className;
return this;
}
/**
* Sets the {@link com.hazelcast.nio.SocketInterceptor} implementation object
*
* @param implementation implementation object
* @return this SocketInterceptorConfig instance
*/
public SocketInterceptorConfig setImplementation(Object implementation) {
this.implementation = implementation;
return this;
}
/**
* Returns the {@link com.hazelcast.nio.SocketInterceptor} implementation object
*
* @return SocketInterceptor implementation object
*/
public Object getImplementation() {
return implementation;
}
/**
* Returns if this configuration is enabled
*
* @return true if enabled, false otherwise
*/
public boolean isEnabled() {
return enabled;
}
/**
* Enables and disables this configuration
*
* @param enabled
*/
public SocketInterceptorConfig setEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Sets a property.
*
* @param name the name of the property to set.
* @param value the value of the property to set
* @return the updated SocketInterceptorConfig
* @throws NullPointerException if name or value is null.
*/
public SocketInterceptorConfig setProperty(String name, String value) {
properties.put(name, value);
return this;
}
/**
* Gets a property.
*
* @param name the name of the property to get.
* @return the value of the property, null if not found
* @throws NullPointerException if name is null.
*/
public String getProperty(String name) {
return properties.getProperty(name);
}
/**
* Gets all properties.
*
* @return the properties.
*/
public Properties getProperties() {
return properties;
}
/**
* Sets the properties.
*
* @param properties the properties to set.
* @return the updated SSLConfig.
* @throws IllegalArgumentException if properties is null.
*/
public SocketInterceptorConfig setProperties(Properties properties) {
if(properties == null){
throw new IllegalArgumentException("properties can't be null");
}
this.properties = properties;
return this;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("SocketInterceptorConfig");
sb.append("{className='").append(className).append('\'');
sb.append(", enabled=").append(enabled);
sb.append(", implementation=").append(implementation);
sb.append(", properties=").append(properties);
sb.append('}');
return sb.toString();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_config_SocketInterceptorConfig.java |
805 | public static enum INDEX_TYPE {
UNIQUE(true), NOTUNIQUE(true), FULLTEXT(true), DICTIONARY(false), PROXY(true), UNIQUE_HASH_INDEX(true), NOTUNIQUE_HASH_INDEX(
true), FULLTEXT_HASH_INDEX(true), DICTIONARY_HASH_INDEX(false);
private final boolean automaticIndexable;
INDEX_TYPE(boolean iValue) {
automaticIndexable = iValue;
}
public boolean isAutomaticIndexable() {
return automaticIndexable;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OClass.java |
163 | public abstract class PartitionClientRequest extends ClientRequest {
private static final int TRY_COUNT = 100;
protected void beforeProcess() {
}
protected void afterResponse() {
}
@Override
final void process() {
beforeProcess();
ClientEndpoint endpoint = getEndpoint();
Operation op = prepareOperation();
op.setCallerUuid(endpoint.getUuid());
InvocationBuilder builder = clientEngine.createInvocationBuilder(getServiceName(), op, getPartition())
.setReplicaIndex(getReplicaIndex())
.setTryCount(TRY_COUNT)
.setResultDeserialized(false)
.setCallback(new CallbackImpl(endpoint));
builder.invoke();
}
protected abstract Operation prepareOperation();
protected abstract int getPartition();
protected int getReplicaIndex() {
return 0;
}
protected Object filter(Object response) {
return response;
}
private class CallbackImpl implements Callback<Object> {
private final ClientEndpoint endpoint;
public CallbackImpl(ClientEndpoint endpoint) {
this.endpoint = endpoint;
}
@Override
public void notify(Object object) {
endpoint.sendResponse(filter(object), getCallId());
afterResponse();
}
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_client_PartitionClientRequest.java |
478 | class ColumnValueStore {
private static final double SIZE_THRESHOLD = 0.66;
private Data data;
public ColumnValueStore() {
data = new Data(new Entry[0], 0);
}
boolean isEmpty(StoreTransaction txh) {
Lock lock = getLock(txh);
lock.lock();
try {
return data.isEmpty();
} finally {
lock.unlock();
}
}
EntryList getSlice(KeySliceQuery query, StoreTransaction txh) {
Lock lock = getLock(txh);
lock.lock();
try {
Data datacp = data;
int start = datacp.getIndex(query.getSliceStart());
if (start < 0) start = (-start - 1);
int end = datacp.getIndex(query.getSliceEnd());
if (end < 0) end = (-end - 1);
if (start < end) {
MemoryEntryList result = new MemoryEntryList(end - start);
for (int i = start; i < end; i++) {
if (query.hasLimit() && result.size() >= query.getLimit()) break;
result.add(datacp.get(i));
}
return result;
} else {
return EntryList.EMPTY_LIST;
}
} finally {
lock.unlock();
}
}
private static class MemoryEntryList extends ArrayList<Entry> implements EntryList {
public MemoryEntryList(int size) {
super(size);
}
@Override
public Iterator<Entry> reuseIterator() {
return iterator();
}
@Override
public int getByteSize() {
int size = 48;
for (Entry e : this) {
size += 8 + 16 + 8 + 8 + e.length();
}
return size;
}
}
synchronized void mutate(List<Entry> additions, List<StaticBuffer> deletions, StoreTransaction txh) {
//Prepare data
Entry[] add;
if (!additions.isEmpty()) {
add = new Entry[additions.size()];
int pos = 0;
for (Entry e : additions) {
add[pos] = e;
pos++;
}
Arrays.sort(add);
} else add = new Entry[0];
//Filter out deletions that are also added
Entry[] del;
if (!deletions.isEmpty()) {
del = new Entry[deletions.size()];
int pos=0;
for (StaticBuffer deletion : deletions) {
Entry delEntry = StaticArrayEntry.of(deletion);
if (Arrays.binarySearch(add,delEntry) >= 0) continue;
del[pos++]=delEntry;
}
if (pos<deletions.size()) del = Arrays.copyOf(del,pos);
Arrays.sort(del);
} else del = new Entry[0];
Lock lock = getLock(txh);
lock.lock();
try {
Entry[] olddata = data.array;
int oldsize = data.size;
Entry[] newdata = new Entry[oldsize + add.length];
//Merge sort
int i = 0, iold = 0, iadd = 0, idel = 0;
while (iold < oldsize) {
Entry e = olddata[iold];
iold++;
//Compare with additions
if (iadd < add.length) {
int compare = e.compareTo(add[iadd]);
if (compare >= 0) {
e = add[iadd];
iadd++;
//Skip duplicates
while (iadd < add.length && e.equals(add[iadd])) iadd++;
}
if (compare > 0) iold--;
}
//Compare with deletions
if (idel < del.length) {
int compare = e.compareTo(del[idel]);
if (compare == 0) e = null;
if (compare >= 0) idel++;
}
if (e != null) {
newdata[i] = e;
i++;
}
}
while (iadd < add.length) {
newdata[i] = add[iadd];
i++;
iadd++;
}
if (i * 1.0 / newdata.length < SIZE_THRESHOLD) {
//shrink array to free space
Entry[] tmpdata = newdata;
newdata = new Entry[i];
System.arraycopy(tmpdata, 0, newdata, 0, i);
}
data = new Data(newdata, i);
} finally {
lock.unlock();
}
}
private ReentrantLock lock = null;
private Lock getLock(StoreTransaction txh) {
Boolean txOn = txh.getConfiguration().getCustomOption(STORAGE_TRANSACTIONAL);
if (null != txOn && txOn) {
if (lock == null) {
synchronized (this) {
if (lock == null) {
lock = new ReentrantLock();
}
}
}
return lock;
} else return NoLock.INSTANCE;
}
private static class Data {
final Entry[] array;
final int size;
Data(final Entry[] array, final int size) {
Preconditions.checkArgument(size >= 0 && size <= array.length);
assert isSorted();
this.array = array;
this.size = size;
}
boolean isEmpty() {
return size == 0;
}
int getIndex(StaticBuffer column) {
return Arrays.binarySearch(array, 0, size, StaticArrayEntry.of(column));
}
Entry get(int index) {
return array[index];
}
boolean isSorted() {
for (int i = 1; i < size; i++) {
if (!(array[i].compareTo(array[i - 1]) > 0)) return false;
}
return true;
}
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_inmemory_ColumnValueStore.java |
1,186 | public interface BroadleafPaymentModuleService {
/**
* Validates the response received from the payment module.
*
* When implemented it should throw an error with the message received from the payment module. This message
* will be bubbled up and displayed in the admin to the user.
*
* @param paymentSeed
* @return boolean
*/
public void validateResponse(PaymentSeed paymentSeed) throws Exception;
/**
* Used by the payment module to implement setting the transaction id into the database where approriate
* the payment module.
*
* @param transactionID
*/
public void manualPayment(PaymentSeed paymentSeed, String transactionID);
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_BroadleafPaymentModuleService.java |
3,171 | public class DuelFieldDataTests extends AbstractFieldDataTests {
@Override
protected FieldDataType getFieldDataType() {
return null;
}
public static int atLeast(Random random, int i) {
int min = i;
int max = min + (min / 2);
return min + random.nextInt(max - min);
}
@Test
public void testDuelAllTypesSingleValue() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("bytes").field("type", "string").field("index", "not_analyzed").startObject("fielddata").field("format", LuceneTestCase.defaultCodecSupportsSortedSet() ? "doc_values" : "fst").endObject().endObject()
.startObject("byte").field("type", "byte").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("short").field("type", "short").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("integer").field("type", "integer").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("long").field("type", "long").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("float").field("type", "float").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("double").field("type", "double").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = MapperTestUtils.newParser().parse(mapping);
Random random = getRandom();
int atLeast = atLeast(random, 1000);
for (int i = 0; i < atLeast; i++) {
String s = Integer.toString(randomByte());
XContentBuilder doc = XContentFactory.jsonBuilder().startObject();
for (String fieldName : Arrays.asList("bytes", "byte", "short", "integer", "long", "float", "double")) {
doc = doc.field(fieldName, s);
}
doc = doc.endObject();
final ParsedDocument d = mapper.parse("type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
AtomicReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<FieldDataType, DuelFieldDataTests.Type>();
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "fst")), Type.Bytes);
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "paged_bytes")), Type.Bytes);
typeMap.put(new FieldDataType("byte", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("short", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("int", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("long", ImmutableSettings.builder().put("format", "array")), Type.Long);
typeMap.put(new FieldDataType("double", ImmutableSettings.builder().put("format", "array")), Type.Double);
typeMap.put(new FieldDataType("float", ImmutableSettings.builder().put("format", "array")), Type.Float);
typeMap.put(new FieldDataType("byte", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("short", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("int", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("long", ImmutableSettings.builder().put("format", "doc_values")), Type.Long);
typeMap.put(new FieldDataType("double", ImmutableSettings.builder().put("format", "doc_values")), Type.Double);
typeMap.put(new FieldDataType("float", ImmutableSettings.builder().put("format", "doc_values")), Type.Float);
if (LuceneTestCase.defaultCodecSupportsSortedSet()) {
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "doc_values")), Type.Bytes);
}
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<Entry<FieldDataType, Type>>(typeMap.entrySet());
Preprocessor pre = new ToDoublePreprocessor();
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexFieldData<?> leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexFieldData<?> rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataBytes(random, context, leftFieldData, rightFieldData, pre);
duelFieldDataBytes(random, context, rightFieldData, leftFieldData, pre);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<AtomicReaderContext> leaves = composite.leaves();
for (AtomicReaderContext atomicReaderContext : leaves) {
duelFieldDataBytes(random, atomicReaderContext, leftFieldData, rightFieldData, pre);
}
}
}
@Test
public void testDuelIntegers() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("byte").field("type", "byte").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("short").field("type", "short").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("integer").field("type", "integer").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("long").field("type", "long").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = MapperTestUtils.newParser().parse(mapping);
Random random = getRandom();
int atLeast = atLeast(random, 1000);
final int maxNumValues = randomBoolean() ? 1 : randomIntBetween(2, 40);
byte[] values = new byte[maxNumValues];
for (int i = 0; i < atLeast; i++) {
final int numValues = randomInt(maxNumValues);
for (int j = 0; j < numValues; ++j) {
if (randomBoolean()) {
values[j] = 1; // test deduplication
} else {
values[j] = randomByte();
}
}
XContentBuilder doc = XContentFactory.jsonBuilder().startObject();
for (String fieldName : Arrays.asList("byte", "short", "integer", "long")) {
doc = doc.startArray(fieldName);
for (int j = 0; j < numValues; ++j) {
doc = doc.value(values[j]);
}
doc = doc.endArray();
}
doc = doc.endObject();
final ParsedDocument d = mapper.parse("type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
AtomicReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<FieldDataType, Type>();
typeMap.put(new FieldDataType("byte", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("short", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("int", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("long", ImmutableSettings.builder().put("format", "array")), Type.Long);
typeMap.put(new FieldDataType("byte", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("short", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("int", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("long", ImmutableSettings.builder().put("format", "doc_values")), Type.Long);
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<Entry<FieldDataType, Type>>(typeMap.entrySet());
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexNumericFieldData<?> leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexNumericFieldData<?> rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataLong(random, context, leftFieldData, rightFieldData);
duelFieldDataLong(random, context, rightFieldData, leftFieldData);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<AtomicReaderContext> leaves = composite.leaves();
for (AtomicReaderContext atomicReaderContext : leaves) {
duelFieldDataLong(random, atomicReaderContext, leftFieldData, rightFieldData);
}
}
}
@Test
public void testDuelDoubles() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("float").field("type", "float").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("double").field("type", "double").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = MapperTestUtils.newParser().parse(mapping);
Random random = getRandom();
int atLeast = atLeast(random, 1000);
final int maxNumValues = randomBoolean() ? 1 : randomIntBetween(2, 40);
float[] values = new float[maxNumValues];
for (int i = 0; i < atLeast; i++) {
final int numValues = randomInt(maxNumValues);
float def = randomBoolean() ? randomFloat() : Float.NaN;
for (int j = 0; j < numValues; ++j) {
if (randomBoolean()) {
values[j] = def;
} else {
values[j] = randomFloat();
}
}
XContentBuilder doc = XContentFactory.jsonBuilder().startObject().startArray("float");
for (int j = 0; j < numValues; ++j) {
doc = doc.value(values[j]);
}
doc = doc.endArray().startArray("double");
for (int j = 0; j < numValues; ++j) {
doc = doc.value(values[j]);
}
doc = doc.endArray().endObject();
final ParsedDocument d = mapper.parse("type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
AtomicReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<FieldDataType, Type>();
typeMap.put(new FieldDataType("double", ImmutableSettings.builder().put("format", "array")), Type.Double);
typeMap.put(new FieldDataType("float", ImmutableSettings.builder().put("format", "array")), Type.Float);
typeMap.put(new FieldDataType("double", ImmutableSettings.builder().put("format", "doc_values")), Type.Double);
typeMap.put(new FieldDataType("float", ImmutableSettings.builder().put("format", "doc_values")), Type.Float);
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<Entry<FieldDataType, Type>>(typeMap.entrySet());
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexNumericFieldData<?> leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexNumericFieldData<?> rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
assertOrder(left.getValue().order(), leftFieldData, context);
assertOrder(right.getValue().order(), rightFieldData, context);
duelFieldDataDouble(random, context, leftFieldData, rightFieldData);
duelFieldDataDouble(random, context, rightFieldData, leftFieldData);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<AtomicReaderContext> leaves = composite.leaves();
for (AtomicReaderContext atomicReaderContext : leaves) {
duelFieldDataDouble(random, atomicReaderContext, leftFieldData, rightFieldData);
}
}
}
@Test
public void testDuelStrings() throws Exception {
Random random = getRandom();
int atLeast = atLeast(random, 1000);
for (int i = 0; i < atLeast; i++) {
Document d = new Document();
d.add(new StringField("_id", "" + i, Field.Store.NO));
if (random.nextInt(15) != 0) {
int[] numbers = getNumbers(random, Integer.MAX_VALUE);
for (int j : numbers) {
final String s = English.longToEnglish(j);
d.add(new StringField("bytes", s, Field.Store.NO));
if (LuceneTestCase.defaultCodecSupportsSortedSet()) {
d.add(new SortedSetDocValuesField("bytes", new BytesRef(s)));
}
}
if (random.nextInt(10) == 0) {
d.add(new StringField("bytes", "", Field.Store.NO));
if (LuceneTestCase.defaultCodecSupportsSortedSet()) {
d.add(new SortedSetDocValuesField("bytes", new BytesRef()));
}
}
}
writer.addDocument(d);
if (random.nextInt(10) == 0) {
refreshReader();
}
}
AtomicReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<FieldDataType, DuelFieldDataTests.Type>();
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "fst")), Type.Bytes);
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "paged_bytes")), Type.Bytes);
if (LuceneTestCase.defaultCodecSupportsSortedSet()) {
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "doc_values")), Type.Bytes);
}
// TODO add filters
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<Entry<FieldDataType, Type>>(typeMap.entrySet());
Preprocessor pre = new Preprocessor();
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexFieldData<?> leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexFieldData<?> rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataBytes(random, context, leftFieldData, rightFieldData, pre);
duelFieldDataBytes(random, context, rightFieldData, leftFieldData, pre);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<AtomicReaderContext> leaves = composite.leaves();
for (AtomicReaderContext atomicReaderContext : leaves) {
assertOrder(AtomicFieldData.Order.BYTES, leftFieldData, atomicReaderContext);
assertOrder(AtomicFieldData.Order.BYTES, rightFieldData, atomicReaderContext);
duelFieldDataBytes(random, atomicReaderContext, leftFieldData, rightFieldData, pre);
}
perSegment.close();
}
}
public void testDuelGeoPoints() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("geopoint").field("type", "geo_point").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = MapperTestUtils.newParser().parse(mapping);
Random random = getRandom();
int atLeast = atLeast(random, 1000);
int maxValuesPerDoc = randomBoolean() ? 1 : randomIntBetween(2, 40);
// to test deduplication
double defaultLat = randomDouble() * 180 - 90;
double defaultLon = randomDouble() * 360 - 180;
for (int i = 0; i < atLeast; i++) {
final int numValues = randomInt(maxValuesPerDoc);
XContentBuilder doc = XContentFactory.jsonBuilder().startObject().startArray("geopoint");
for (int j = 0; j < numValues; ++j) {
if (randomBoolean()) {
doc.startObject().field("lat", defaultLat).field("lon", defaultLon).endObject();
} else {
doc.startObject().field("lat", randomDouble() * 180 - 90).field("lon", randomDouble() * 360 - 180).endObject();
}
}
doc = doc.endArray().endObject();
final ParsedDocument d = mapper.parse("type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
AtomicReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<FieldDataType, DuelFieldDataTests.Type>();
final Distance precision = new Distance(1, randomFrom(DistanceUnit.values()));
typeMap.put(new FieldDataType("geo_point", ImmutableSettings.builder().put("format", "array")), Type.GeoPoint);
typeMap.put(new FieldDataType("geo_point", ImmutableSettings.builder().put("format", "compressed").put("precision", precision)), Type.GeoPoint);
typeMap.put(new FieldDataType("geo_point", ImmutableSettings.builder().put("format", "doc_values")), Type.GeoPoint);
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<Entry<FieldDataType, Type>>(typeMap.entrySet());
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexGeoPointFieldData<?> leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexGeoPointFieldData<?> rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataGeoPoint(random, context, leftFieldData, rightFieldData, precision);
duelFieldDataGeoPoint(random, context, rightFieldData, leftFieldData, precision);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<AtomicReaderContext> leaves = composite.leaves();
for (AtomicReaderContext atomicReaderContext : leaves) {
duelFieldDataGeoPoint(random, atomicReaderContext, leftFieldData, rightFieldData, precision);
}
perSegment.close();
}
}
private void assertOrder(AtomicFieldData.Order order, IndexFieldData<?> data, AtomicReaderContext context) throws Exception {
AtomicFieldData<?> leftData = randomBoolean() ? data.load(context) : data.loadDirect(context);
assertThat(leftData.getBytesValues(randomBoolean()).getOrder(), is(order));
}
private int[] getNumbers(Random random, int margin) {
if (random.nextInt(20) == 0) {
int[] num = new int[1 + random.nextInt(10)];
for (int i = 0; i < num.length; i++) {
int v = (random.nextBoolean() ? -1 * random.nextInt(margin) : random.nextInt(margin));
num[i] = v;
}
return num;
}
return new int[]{(random.nextBoolean() ? -1 * random.nextInt(margin) : random.nextInt(margin))};
}
private static void duelFieldDataBytes(Random random, AtomicReaderContext context, IndexFieldData<?> left, IndexFieldData<?> right, Preprocessor pre) throws Exception {
AtomicFieldData<?> leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicFieldData<?> rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
assertThat(leftData.getNumDocs(), equalTo(rightData.getNumDocs()));
int numDocs = leftData.getNumDocs();
BytesValues leftBytesValues = leftData.getBytesValues(random.nextBoolean());
BytesValues rightBytesValues = rightData.getBytesValues(random.nextBoolean());
BytesRef leftSpare = new BytesRef();
BytesRef rightSpare = new BytesRef();
for (int i = 0; i < numDocs; i++) {
int numValues = 0;
assertThat((numValues = leftBytesValues.setDocument(i)), equalTo(rightBytesValues.setDocument(i)));
BytesRef previous = null;
for (int j = 0; j < numValues; j++) {
rightSpare.copyBytes(rightBytesValues.nextValue());
leftSpare.copyBytes(leftBytesValues.nextValue());
assertThat(rightSpare.hashCode(), equalTo(rightBytesValues.currentValueHash()));
assertThat(leftSpare.hashCode(), equalTo(leftBytesValues.currentValueHash()));
if (previous != null && leftBytesValues.getOrder() == rightBytesValues.getOrder()) { // we can only compare the
assertThat(pre.compare(previous, rightSpare), lessThan(0));
}
previous = BytesRef.deepCopyOf(rightSpare);
pre.toString(rightSpare);
pre.toString(leftSpare);
assertThat(pre.toString(leftSpare), equalTo(pre.toString(rightSpare)));
if (leftSpare.equals(rightSpare)) {
assertThat(leftBytesValues.currentValueHash(), equalTo(rightBytesValues.currentValueHash()));
}
}
}
}
private static void duelFieldDataDouble(Random random, AtomicReaderContext context, IndexNumericFieldData<?> left, IndexNumericFieldData<?> right) throws Exception {
AtomicNumericFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicNumericFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
assertThat(leftData.getNumDocs(), equalTo(rightData.getNumDocs()));
int numDocs = leftData.getNumDocs();
DoubleValues leftDoubleValues = leftData.getDoubleValues();
DoubleValues rightDoubleValues = rightData.getDoubleValues();
for (int i = 0; i < numDocs; i++) {
int numValues = 0;
assertThat((numValues = leftDoubleValues.setDocument(i)), equalTo(rightDoubleValues.setDocument(i)));
double previous = 0;
for (int j = 0; j < numValues; j++) {
double current = rightDoubleValues.nextValue();
if (Double.isNaN(current)) {
assertTrue(Double.isNaN(leftDoubleValues.nextValue()));
} else {
assertThat(leftDoubleValues.nextValue(), closeTo(current, 0.0001));
}
if (j > 0) {
assertThat(Double.compare(previous,current), lessThan(0));
}
previous = current;
}
}
}
private static void duelFieldDataLong(Random random, AtomicReaderContext context, IndexNumericFieldData<?> left, IndexNumericFieldData right) throws Exception {
AtomicNumericFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicNumericFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
assertThat(leftData.getNumDocs(), equalTo(rightData.getNumDocs()));
int numDocs = leftData.getNumDocs();
LongValues leftLongValues = leftData.getLongValues();
LongValues rightLongValues = rightData.getLongValues();
for (int i = 0; i < numDocs; i++) {
int numValues = 0;
long previous = 0;
assertThat((numValues = leftLongValues.setDocument(i)), equalTo(rightLongValues.setDocument(i)));
for (int j = 0; j < numValues; j++) {
long current;
assertThat(leftLongValues.nextValue(), equalTo(current = rightLongValues.nextValue()));
if (j > 0) {
assertThat(previous, lessThan(current));
}
previous = current;
}
}
}
private static void duelFieldDataGeoPoint(Random random, AtomicReaderContext context, IndexGeoPointFieldData<?> left, IndexGeoPointFieldData<?> right, Distance precision) throws Exception {
AtomicGeoPointFieldData<?> leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicGeoPointFieldData<?> rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
assertThat(leftData.getNumDocs(), equalTo(rightData.getNumDocs()));
int numDocs = leftData.getNumDocs();
GeoPointValues leftValues = leftData.getGeoPointValues();
GeoPointValues rightValues = rightData.getGeoPointValues();
for (int i = 0; i < numDocs; ++i) {
final int numValues = leftValues.setDocument(i);
assertEquals(numValues, rightValues.setDocument(i));
List<GeoPoint> leftPoints = Lists.newArrayList();
List<GeoPoint> rightPoints = Lists.newArrayList();
for (int j = 0; j < numValues; ++j) {
GeoPoint l = leftValues.nextValue();
leftPoints.add(new GeoPoint(l.getLat(), l.getLon()));
GeoPoint r = rightValues.nextValue();
rightPoints.add(new GeoPoint(r.getLat(), r.getLon()));
}
for (GeoPoint l : leftPoints) {
assertTrue("Couldn't find " + l + " among " + rightPoints, contains(l, rightPoints, precision));
}
for (GeoPoint r : rightPoints) {
assertTrue("Couldn't find " + r + " among " + leftPoints, contains(r, leftPoints, precision));
}
}
}
private static boolean contains(GeoPoint point, List<GeoPoint> set, Distance precision) {
for (GeoPoint r : set) {
final double distance = GeoDistance.PLANE.calculate(point.getLat(), point.getLon(), r.getLat(), r.getLon(), DistanceUnit.METERS);
if (new Distance(distance, DistanceUnit.METERS).compareTo(precision) <= 0) {
return true;
}
}
return false;
}
private static class Preprocessor {
public String toString(BytesRef ref) {
return ref.utf8ToString();
}
public int compare(BytesRef a, BytesRef b) {
return a.compareTo(b);
}
}
private static class ToDoublePreprocessor extends Preprocessor {
@Override
public String toString(BytesRef ref) {
assertTrue(ref.length > 0);
return Double.toString(Double.parseDouble(super.toString(ref)));
}
@Override
public int compare(BytesRef a, BytesRef b) {
Double _a = Double.parseDouble(super.toString(a));
return _a.compareTo(Double.parseDouble(super.toString(b)));
}
}
private static enum Type {
Float(AtomicFieldData.Order.NUMERIC), Double(AtomicFieldData.Order.NUMERIC), Integer(AtomicFieldData.Order.NUMERIC), Long(AtomicFieldData.Order.NUMERIC), Bytes(AtomicFieldData.Order.BYTES), GeoPoint(AtomicFieldData.Order.NONE);
private final AtomicFieldData.Order order;
Type(AtomicFieldData.Order order) {
this.order = order;
}
public AtomicFieldData.Order order() {
return order;
}
}
} | 0true
| src_test_java_org_elasticsearch_index_fielddata_DuelFieldDataTests.java |
799 | public class OFunctionLibraryImpl implements OFunctionLibrary {
protected Map<String, OFunction> functions = new ConcurrentHashMap<String, OFunction>();
static {
OCommandManager.instance().registerExecutor(OCommandFunction.class, OCommandExecutorFunction.class);
}
public OFunctionLibraryImpl() {
}
public void create() {
init();
}
public void load() {
functions.clear();
// LOAD ALL THE FUNCTIONS IN MEMORY
final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.get();
if (db.getMetadata().getSchema().existsClass("OFunction")) {
List<ODocument> result = db.query(new OSQLSynchQuery<ODocument>("select from OFunction order by name"));
for (ODocument d : result) {
d.reload();
functions.put(d.field("name").toString().toUpperCase(), new OFunction(d));
}
}
}
public Set<String> getFunctionNames() {
return Collections.unmodifiableSet(functions.keySet());
}
public OFunction getFunction(final String iName) {
OFunction f = functions.get(iName.toUpperCase());
if (f == null) {
// CHECK IF THE FUNCTION HAS BEEN JUST CREATED ON DB
final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.get();
if (db.getMetadata().getSchema().existsClass("OFunction")) {
List<ODocument> result = db.query(new OSQLSynchQuery<ODocument>("select from OFunction where name = ?"), iName);
for (ODocument d : result) {
f = new OFunction(d);
functions.put(d.field("name").toString().toUpperCase(), f);
}
}
}
return f;
}
public synchronized OFunction createFunction(final String iName) {
init();
final OFunction f = new OFunction().setName(iName);
functions.put(iName.toUpperCase(), f);
return f;
}
public void close() {
functions.clear();
}
protected void init() {
final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.get();
if (db.getMetadata().getSchema().existsClass("OFunction"))
return;
final OClass f = db.getMetadata().getSchema().createClass("OFunction");
f.createProperty("name", OType.STRING);
f.createProperty("code", OType.STRING);
f.createProperty("language", OType.STRING);
f.createProperty("idempotent", OType.BOOLEAN);
f.createProperty("parameters", OType.EMBEDDEDLIST, OType.STRING);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_metadata_function_OFunctionLibraryImpl.java |
3,170 | public static abstract class WithOrdinals extends DoubleValues {
protected final Docs ordinals;
protected WithOrdinals(Ordinals.Docs ordinals) {
super(ordinals.isMultiValued());
this.ordinals = ordinals;
}
/**
* Returns the associated ordinals instance.
* @return the associated ordinals instance.
*/
public Docs ordinals() {
return ordinals;
}
/**
* Returns the value for the given ordinal.
* @param ord the ordinal to lookup.
* @return a double value associated with the given ordinal.
*/
public abstract double getValueByOrd(long ord);
@Override
public int setDocument(int docId) {
this.docId = docId;
return ordinals.setDocument(docId);
}
@Override
public double nextValue() {
return getValueByOrd(ordinals.nextOrd());
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_DoubleValues.java |
2,064 | public class MapKeySetOperationFactory implements OperationFactory {
String name;
public MapKeySetOperationFactory() {
}
public MapKeySetOperationFactory(String name) {
this.name = name;
}
@Override
public Operation createOperation() {
return new MapKeySetOperation(name);
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(name);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
name = in.readUTF();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_operation_MapKeySetOperationFactory.java |
135 | public static final class ClientTestResource extends ExternalResource {
private final Config config;
private HazelcastInstance instance;
private SimpleClient client;
public ClientTestResource(Config config) {
this.config = config;
}
protected void before() throws Throwable {
instance = new TestHazelcastInstanceFactory(1).newHazelcastInstance(config);
client = newClient(TestUtil.getNode(instance));
client.auth();
}
protected void after() {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
instance.shutdown();
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_client_ClientTestSupport.java |
657 | public class PutIndexTemplateResponse extends AcknowledgedResponse {
PutIndexTemplateResponse() {
}
PutIndexTemplateResponse(boolean acknowledged) {
super(acknowledged);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
readAcknowledged(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
writeAcknowledged(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_template_put_PutIndexTemplateResponse.java |
2,649 | ping(new PingListener() {
@Override
public void onPing(PingResponse[] pings) {
response.set(pings);
latch.countDown();
}
}, timeout); | 0true
| src_main_java_org_elasticsearch_discovery_zen_ping_unicast_UnicastZenPing.java |
1,478 | return OSQLEngine.foreachRecord(new OCallable<Object, OIdentifiable>() {
@Override
public Object call(final OIdentifiable iArgument) {
return move(graph, iArgument, labels);
}
}, iCurrentResult, iContext); | 1no label
| graphdb_src_main_java_com_orientechnologies_orient_graph_sql_functions_OSQLFunctionMove.java |
531 | public class Mod43CheckDigitUtil {
private final static String CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%";
public static boolean isValidCheckedValue(String value) {
boolean valid = false;
if (value != null && !"".equals(value)) {
String code = value.substring(0, value.length() - 1);
char checkDigit = value.substring(value.length() - 1).charAt(0);
try {
if (generateCheckDigit(code) == checkDigit) {
valid = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return valid;
}
public static char generateCheckDigit(String data) {
// MOD 43 check digit - take the acsii value of each digit, sum them up, divide by 43. the remainder is the check digit (in ascii)
int sum = 0;
for (int i = 0; i < data.length(); ++i) {
sum += CHARSET.indexOf(data.charAt(i));
}
int remainder = sum % 43;
return CHARSET.charAt(remainder);
}
public static void main(String[] args) {
try {
System.out.println(generateCheckDigit("TEACH000012345"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(isValidCheckedValue("TEACH000012345B"));
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_util_Mod43CheckDigitUtil.java |
1,822 | class ExposedKeyFactory<T> implements InternalFactory<T>, BindingProcessor.CreationListener {
private final Key<T> key;
private final PrivateElements privateElements;
private BindingImpl<T> delegate;
public ExposedKeyFactory(Key<T> key, PrivateElements privateElements) {
this.key = key;
this.privateElements = privateElements;
}
public void notify(Errors errors) {
InjectorImpl privateInjector = (InjectorImpl) privateElements.getInjector();
BindingImpl<T> explicitBinding = privateInjector.state.getExplicitBinding(key);
// validate that the child injector has its own factory. If the getInternalFactory() returns
// this, then that child injector doesn't have a factory (and getExplicitBinding has returned
// its parent's binding instead
if (explicitBinding.getInternalFactory() == this) {
errors.withSource(explicitBinding.getSource()).exposedButNotBound(key);
return;
}
this.delegate = explicitBinding;
}
public T get(Errors errors, InternalContext context, Dependency<?> dependency)
throws ErrorsException {
return delegate.getInternalFactory().get(errors, context, dependency);
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_ExposedKeyFactory.java |
899 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class IdGeneratorTest extends HazelcastTestSupport {
private HazelcastInstance hz;
@Before
public void setUp() {
hz = createHazelcastInstance();
}
@Test
public void testInit() {
testInit(0, false, 0);
testInit(-1, false, 0);
testInit(1, true, 2);
testInit(10, true, 11);
}
private void testInit(int initialValue, boolean expected, long expectedValue) {
IdGenerator idGenerator = createIdGenerator();
boolean initialized = idGenerator.init(initialValue);
assertEquals(expected, initialized);
long newId = idGenerator.newId();
assertEquals(expectedValue, newId);
}
private IdGenerator createIdGenerator() {
return hz.getIdGenerator("id-" + UUID.randomUUID().toString());
}
@Test
public void testInitWhenAlreadyInitialized() {
IdGenerator idGenerator = createIdGenerator();
long first = idGenerator.newId();
boolean initialized = idGenerator.init(10);
assertFalse(initialized);
long actual = idGenerator.newId();
assertEquals(first + 1, actual);
}
@Test
public void testNewId_withExplicitInit() {
IdGenerator idGenerator =createIdGenerator();
assertTrue(idGenerator.init(10));
long result = idGenerator.newId();
assertEquals(11, result);
}
@Test
public void testNewId_withoutExplictInit() {
IdGenerator idGenerator = createIdGenerator();
long result = idGenerator.newId();
assertEquals(0, result);
}
@Test
public void testGeneratingMultipleBlocks() {
IdGenerator idGenerator = createIdGenerator();
long expected = 0;
for (int k = 0; k < 3 * IdGeneratorProxy.BLOCK_SIZE; k++) {
assertEquals(expected, idGenerator.newId());
expected++;
}
}
@Test
public void testDestroy() {
IdGenerator idGenerator = createIdGenerator();
String id = idGenerator.getName();
idGenerator.newId();
idGenerator.newId();
idGenerator.destroy();
IdGenerator newIdGenerator = hz.getIdGenerator(id);
long actual = newIdGenerator.newId();
assertEquals(0, actual);
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_concurrent_idgen_IdGeneratorTest.java |
3,328 | static class Empty extends FloatArrayAtomicFieldData {
Empty(int numDocs) {
super(numDocs);
}
@Override
public LongValues getLongValues() {
return LongValues.EMPTY;
}
@Override
public DoubleValues getDoubleValues() {
return DoubleValues.EMPTY;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public long getNumberUniqueValues() {
return 0;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getMemorySizeInBytes() {
return 0;
}
@Override
public BytesValues getBytesValues(boolean needsHashes) {
return BytesValues.EMPTY;
}
@Override
public ScriptDocValues getScriptValues() {
return ScriptDocValues.EMPTY;
}
} | 1no label
| src_main_java_org_elasticsearch_index_fielddata_plain_FloatArrayAtomicFieldData.java |
3,184 | public class FloatFieldDataTests extends AbstractNumericFieldDataTests {
@Override
protected FieldDataType getFieldDataType() {
return new FieldDataType("float");
}
protected String one() {
return "1.0";
}
protected String two() {
return "2.0";
}
protected String three() {
return "3.0";
}
protected String four() {
return "4.0";
}
protected void add2SingleValuedDocumentsAndDeleteOneOfThem() throws Exception {
Document d = new Document();
d.add(new StringField("_id", "1", Field.Store.NO));
d.add(new FloatField("value", 2.0f, Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "2", Field.Store.NO));
d.add(new FloatField("value", 4.0f, Field.Store.NO));
writer.addDocument(d);
writer.commit();
writer.deleteDocuments(new Term("_id", "1"));
}
@Override
protected void fillSingleValueAllSet() throws Exception {
Document d = new Document();
d.add(new StringField("_id", "1", Field.Store.NO));
d.add(new FloatField("value", 2.0f, Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "2", Field.Store.NO));
d.add(new FloatField("value", 1.0f, Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "3", Field.Store.NO));
d.add(new FloatField("value", 3.0f, Field.Store.NO));
writer.addDocument(d);
}
@Override
protected void fillSingleValueWithMissing() throws Exception {
Document d = new Document();
d.add(new StringField("_id", "1", Field.Store.NO));
d.add(new FloatField("value", 2.0f, Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "2", Field.Store.NO));
//d.add(new StringField("value", one(), Field.Store.NO)); // MISSING....
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "3", Field.Store.NO));
d.add(new FloatField("value", 3.0f, Field.Store.NO));
writer.addDocument(d);
}
@Override
protected void fillMultiValueAllSet() throws Exception {
Document d = new Document();
d.add(new StringField("_id", "1", Field.Store.NO));
d.add(new FloatField("value", 2.0f, Field.Store.NO));
d.add(new FloatField("value", 4.0f, Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "2", Field.Store.NO));
d.add(new FloatField("value", 1.0f, Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "3", Field.Store.NO));
d.add(new FloatField("value", 3.0f, Field.Store.NO));
writer.addDocument(d);
}
@Override
protected void fillMultiValueWithMissing() throws Exception {
Document d = new Document();
d.add(new StringField("_id", "1", Field.Store.NO));
d.add(new FloatField("value", 2.0f, Field.Store.NO));
d.add(new FloatField("value", 4.0f, Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "2", Field.Store.NO));
//d.add(new StringField("value", one(), Field.Store.NO)); // MISSING
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "3", Field.Store.NO));
d.add(new FloatField("value", 3.0f, Field.Store.NO));
writer.addDocument(d);
}
protected void fillExtendedMvSet() throws Exception {
Document d = new Document();
d.add(new StringField("_id", "1", Field.Store.NO));
d.add(new FloatField("value", 2, Field.Store.NO));
d.add(new FloatField("value", 4, Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "2", Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "3", Field.Store.NO));
d.add(new FloatField("value", 3, Field.Store.NO));
writer.addDocument(d);
writer.commit();
d = new Document();
d.add(new StringField("_id", "4", Field.Store.NO));
d.add(new FloatField("value", 4, Field.Store.NO));
d.add(new FloatField("value", 5, Field.Store.NO));
d.add(new FloatField("value", 6, Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "5", Field.Store.NO));
d.add(new FloatField("value", 6, Field.Store.NO));
d.add(new FloatField("value", 7, Field.Store.NO));
d.add(new FloatField("value", 8, Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "6", Field.Store.NO));
writer.addDocument(d);
d = new Document();
d.add(new StringField("_id", "7", Field.Store.NO));
d.add(new FloatField("value", 8, Field.Store.NO));
d.add(new FloatField("value", 9, Field.Store.NO));
d.add(new FloatField("value", 10, Field.Store.NO));
writer.addDocument(d);
writer.commit();
d = new Document();
d.add(new StringField("_id", "8", Field.Store.NO));
d.add(new FloatField("value", -8, Field.Store.NO));
d.add(new FloatField("value", -9, Field.Store.NO));
d.add(new FloatField("value", -10, Field.Store.NO));
writer.addDocument(d);
}
} | 0true
| src_test_java_org_elasticsearch_index_fielddata_FloatFieldDataTests.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.