Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
262 | ex.schedule(new Runnable() {
@Override
public void run() {
hzs.get(1).shutdown();
}
}, 1000, TimeUnit.MILLISECONDS); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_executor_ExecutionDelayTest.java |
590 | public class FinalizeJoinOperation extends MemberInfoUpdateOperation implements JoinOperation {
private PostJoinOperation postJoinOp;
public FinalizeJoinOperation() {
}
public FinalizeJoinOperation(Collection<MemberInfo> members, PostJoinOperation postJoinOp, long masterTime) {
super(members, masterTime, true);
this.postJoinOp = postJoinOp;
}
@Override
public void run() throws Exception {
if (isValid()) {
processMemberUpdate();
// Post join operations must be lock free; means no locks at all;
// no partition locks, no key-based locks, no service level locks!
final ClusterServiceImpl clusterService = getService();
final NodeEngineImpl nodeEngine = clusterService.getNodeEngine();
final Operation[] postJoinOperations = nodeEngine.getPostJoinOperations();
Collection<Future> calls = null;
if (postJoinOperations != null && postJoinOperations.length > 0) {
final Collection<MemberImpl> members = clusterService.getMemberList();
calls = new ArrayList<Future>(members.size());
for (MemberImpl member : members) {
if (!member.localMember()) {
Future f = nodeEngine.getOperationService().createInvocationBuilder(ClusterServiceImpl.SERVICE_NAME,
new PostJoinOperation(postJoinOperations), member.getAddress())
.setTryCount(10).setTryPauseMillis(100).invoke();
calls.add(f);
}
}
}
if (postJoinOp != null) {
postJoinOp.setNodeEngine(nodeEngine);
OperationAccessor.setCallerAddress(postJoinOp, getCallerAddress());
OperationAccessor.setConnection(postJoinOp, getConnection());
postJoinOp.setResponseHandler(ResponseHandlerFactory.createEmptyResponseHandler());
nodeEngine.getOperationService().runOperationOnCallingThread(postJoinOp);
}
if (calls != null) {
for (Future f : calls) {
try {
f.get(1, TimeUnit.SECONDS);
} catch (InterruptedException ignored) {
} catch (TimeoutException ignored) {
} catch (ExecutionException e) {
final ILogger logger = nodeEngine.getLogger(FinalizeJoinOperation.class);
if (logger.isFinestEnabled()) {
logger.finest("Error while executing post-join operations -> "
+ e.getClass().getSimpleName() + "[" + e.getMessage() + "]");
}
}
}
}
}
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
boolean hasPJOp = postJoinOp != null;
out.writeBoolean(hasPJOp);
if (hasPJOp) {
postJoinOp.writeData(out);
}
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
boolean hasPJOp = in.readBoolean();
if (hasPJOp) {
postJoinOp = new PostJoinOperation();
postJoinOp.readData(in);
}
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_cluster_FinalizeJoinOperation.java |
2,432 | public abstract class BaseFuture<V> implements Future<V> {
/**
* Synchronization control for AbstractFutures.
*/
private final Sync<V> sync = new Sync<V>();
/*
* Improve the documentation of when InterruptedException is thrown. Our
* behavior matches the JDK's, but the JDK's documentation is misleading.
*/
/**
* {@inheritDoc}
* <p/>
* <p>The default {@link BaseFuture} implementation throws {@code
* InterruptedException} if the current thread is interrupted before or during
* the call, even if the value is already available.
*
* @throws InterruptedException if the current thread was interrupted before
* or during the call (optional but recommended).
* @throws CancellationException {@inheritDoc}
*/
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException,
TimeoutException, ExecutionException {
return sync.get(unit.toNanos(timeout));
}
/*
* Improve the documentation of when InterruptedException is thrown. Our
* behavior matches the JDK's, but the JDK's documentation is misleading.
*/
/**
* {@inheritDoc}
* <p/>
* <p>The default {@link BaseFuture} implementation throws {@code
* InterruptedException} if the current thread is interrupted before or during
* the call, even if the value is already available.
*
* @throws InterruptedException if the current thread was interrupted before
* or during the call (optional but recommended).
* @throws CancellationException {@inheritDoc}
*/
@Override
public V get() throws InterruptedException, ExecutionException {
return sync.get();
}
@Override
public boolean isDone() {
return sync.isDone();
}
@Override
public boolean isCancelled() {
return sync.isCancelled();
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (!sync.cancel()) {
return false;
}
done();
if (mayInterruptIfRunning) {
interruptTask();
}
return true;
}
/**
* Subclasses can override this method to implement interruption of the
* future's computation. The method is invoked automatically by a successful
* call to {@link #cancel(boolean) cancel(true)}.
* <p/>
* <p>The default implementation does nothing.
*
* @since 10.0
*/
protected void interruptTask() {
}
/**
* Subclasses should invoke this method to set the result of the computation
* to {@code value}. This will set the state of the future to
* {@link BaseFuture.Sync#COMPLETED} and call {@link #done()} if the
* state was successfully changed.
*
* @param value the value that was the result of the task.
* @return true if the state was successfully changed.
*/
protected boolean set(@Nullable V value) {
boolean result = sync.set(value);
if (result) {
done();
}
return result;
}
/**
* Subclasses should invoke this method to set the result of the computation
* to an error, {@code throwable}. This will set the state of the future to
* {@link BaseFuture.Sync#COMPLETED} and call {@link #done()} if the
* state was successfully changed.
*
* @param throwable the exception that the task failed with.
* @return true if the state was successfully changed.
* @throws Error if the throwable was an {@link Error}.
*/
protected boolean setException(Throwable throwable) {
boolean result = sync.setException(checkNotNull(throwable));
if (result) {
done();
}
// If it's an Error, we want to make sure it reaches the top of the
// call stack, so we rethrow it.
// we want to notify the listeners we have with errors as well, as it breaks
// how we work in ES in terms of using assertions
// if (throwable instanceof Error) {
// throw (Error) throwable;
// }
return result;
}
@Beta
protected void done() {
}
/**
* <p>Following the contract of {@link AbstractQueuedSynchronizer} we create a
* private subclass to hold the synchronizer. This synchronizer is used to
* implement the blocking and waiting calls as well as to handle state changes
* in a thread-safe manner. The current state of the future is held in the
* Sync state, and the lock is released whenever the state changes to either
* {@link #COMPLETED} or {@link #CANCELLED}.
* <p/>
* <p>To avoid races between threads doing release and acquire, we transition
* to the final state in two steps. One thread will successfully CAS from
* RUNNING to COMPLETING, that thread will then set the result of the
* computation, and only then transition to COMPLETED or CANCELLED.
* <p/>
* <p>We don't use the integer argument passed between acquire methods so we
* pass around a -1 everywhere.
*/
static final class Sync<V> extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 0L;
/* Valid states. */
static final int RUNNING = 0;
static final int COMPLETING = 1;
static final int COMPLETED = 2;
static final int CANCELLED = 4;
private V value;
private Throwable exception;
/*
* Acquisition succeeds if the future is done, otherwise it fails.
*/
@Override
protected int tryAcquireShared(int ignored) {
if (isDone()) {
return 1;
}
return -1;
}
/*
* We always allow a release to go through, this means the state has been
* successfully changed and the result is available.
*/
@Override
protected boolean tryReleaseShared(int finalState) {
setState(finalState);
return true;
}
/**
* Blocks until the task is complete or the timeout expires. Throws a
* {@link TimeoutException} if the timer expires, otherwise behaves like
* {@link #get()}.
*/
V get(long nanos) throws TimeoutException, CancellationException,
ExecutionException, InterruptedException {
// Attempt to acquire the shared lock with a timeout.
if (!tryAcquireSharedNanos(-1, nanos)) {
throw new TimeoutException("Timeout waiting for task.");
}
return getValue();
}
/**
* Blocks until {@link #complete(Object, Throwable, int)} has been
* successfully called. Throws a {@link CancellationException} if the task
* was cancelled, or a {@link ExecutionException} if the task completed with
* an error.
*/
V get() throws CancellationException, ExecutionException,
InterruptedException {
// Acquire the shared lock allowing interruption.
acquireSharedInterruptibly(-1);
return getValue();
}
/**
* Implementation of the actual value retrieval. Will return the value
* on success, an exception on failure, a cancellation on cancellation, or
* an illegal state if the synchronizer is in an invalid state.
*/
private V getValue() throws CancellationException, ExecutionException {
int state = getState();
switch (state) {
case COMPLETED:
if (exception != null) {
throw new ExecutionException(exception);
} else {
return value;
}
case CANCELLED:
throw new CancellationException("Task was cancelled.");
default:
throw new IllegalStateException(
"Error, synchronizer in invalid state: " + state);
}
}
/**
* Checks if the state is {@link #COMPLETED} or {@link #CANCELLED}.
*/
boolean isDone() {
return (getState() & (COMPLETED | CANCELLED)) != 0;
}
/**
* Checks if the state is {@link #CANCELLED}.
*/
boolean isCancelled() {
return getState() == CANCELLED;
}
/**
* Transition to the COMPLETED state and set the value.
*/
boolean set(@Nullable V v) {
return complete(v, null, COMPLETED);
}
/**
* Transition to the COMPLETED state and set the exception.
*/
boolean setException(Throwable t) {
return complete(null, t, COMPLETED);
}
/**
* Transition to the CANCELLED state.
*/
boolean cancel() {
return complete(null, null, CANCELLED);
}
/**
* Implementation of completing a task. Either {@code v} or {@code t} will
* be set but not both. The {@code finalState} is the state to change to
* from {@link #RUNNING}. If the state is not in the RUNNING state we
* return {@code false} after waiting for the state to be set to a valid
* final state ({@link #COMPLETED} or {@link #CANCELLED}).
*
* @param v the value to set as the result of the computation.
* @param t the exception to set as the result of the computation.
* @param finalState the state to transition to.
*/
private boolean complete(@Nullable V v, @Nullable Throwable t,
int finalState) {
boolean doCompletion = compareAndSetState(RUNNING, COMPLETING);
if (doCompletion) {
// If this thread successfully transitioned to COMPLETING, set the value
// and exception and then release to the final state.
this.value = v;
this.exception = t;
releaseShared(finalState);
} else if (getState() == COMPLETING) {
// If some other thread is currently completing the future, block until
// they are done so we can guarantee completion.
acquireShared(-1);
}
return doCompletion;
}
}
} | 0true
| src_main_java_org_elasticsearch_common_util_concurrent_BaseFuture.java |
246 | public class StoreRecoverer
{
private final FileSystemAbstraction fs;
public StoreRecoverer()
{
this( new DefaultFileSystemAbstraction() );
}
public StoreRecoverer( FileSystemAbstraction fs )
{
this.fs = fs;
}
public boolean recoveryNeededAt( File dataDir, Map<String, String> params ) throws IOException
{
// We need config to determine where the logical log files are
params.put( GraphDatabaseSettings.store_dir.name(), dataDir.getPath() );
Config config = new Config( params, GraphDatabaseSettings.class );
File baseLogPath = config.get( GraphDatabaseSettings.logical_log );
XaLogicalLogFiles logFiles = new XaLogicalLogFiles( baseLogPath, fs );
File log;
switch ( logFiles.determineState() )
{
case CLEAN:
return false;
case NO_ACTIVE_FILE:
case DUAL_LOGS_LOG_1_ACTIVE:
case DUAL_LOGS_LOG_2_ACTIVE:
return true;
case LEGACY_WITHOUT_LOG_ROTATION:
log = baseLogPath;
break;
case LOG_1_ACTIVE:
log = logFiles.getLog1FileName();
break;
case LOG_2_ACTIVE:
log = logFiles.getLog2FileName();
break;
default:
return true;
}
StoreChannel logChannel = null;
try
{
logChannel = fs.open( log, "r" );
return new XaLogicalLogRecoveryCheck( logChannel ).recoveryRequired();
}
finally
{
if ( logChannel != null )
{
logChannel.close();
}
}
}
public void recover( File dataDir, Map<String, String> params ) throws IOException
{
// For now, just launch a full embedded database on top of the
// directory.
// In a perfect world, to be expanded to only do recovery, and to be
// used
// as a component of the database, rather than something that is bolted
// on outside it like this.
GraphDatabaseService db =
new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( dataDir.getCanonicalPath() )
.setConfig( params ).newGraphDatabase();
db.shutdown();
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_recovery_StoreRecoverer.java |
1,820 | constructors[PUT_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new PutBackupOperation();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_map_MapDataSerializerHook.java |
448 | public class ClusterStatsRequest extends NodesOperationRequest<ClusterStatsRequest> {
/**
* Get stats from nodes based on the nodes ids specified. If none are passed, stats
* based on all nodes will be returned.
*/
public ClusterStatsRequest(String... nodesIds) {
super(nodesIds);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsRequest.java |
29 | public class BerkeleyBlueprintsTest extends TitanBlueprintsTest {
private static final String DEFAULT_SUBDIR = "standard";
private static final Logger log =
LoggerFactory.getLogger(BerkeleyBlueprintsTest.class);
@Override
public Graph generateGraph() {
return generateGraph(DEFAULT_SUBDIR);
}
@Override
public void beforeOpeningGraph(String uid) {
String dir = BerkeleyStorageSetup.getHomeDir(uid);
log.debug("Cleaning directory {} before opening it for the first time", dir);
try {
BerkeleyJEStoreManager s = new BerkeleyJEStoreManager(BerkeleyStorageSetup.getBerkeleyJEConfiguration(dir));
s.clearStorage();
s.close();
File dirFile = new File(dir);
Assert.assertFalse(dirFile.exists() && dirFile.listFiles().length > 0);
} catch (BackendException e) {
throw new RuntimeException(e);
}
}
@Override
public TitanGraph openGraph(String uid) {
String dir = BerkeleyStorageSetup.getHomeDir(uid);
return TitanFactory.open(BerkeleyStorageSetup.getBerkeleyJEConfiguration(dir));
}
@Override
public void extraCleanUp(String uid) throws BackendException {
String dir = BerkeleyStorageSetup.getHomeDir(uid);
BerkeleyJEStoreManager s = new BerkeleyJEStoreManager(BerkeleyStorageSetup.getBerkeleyJEConfiguration(dir));
s.clearStorage();
s.close();
File dirFile = new File(dir);
Assert.assertFalse(dirFile.exists() && dirFile.listFiles().length > 0);
}
@Override
public boolean supportsMultipleGraphs() {
return true;
}
@Override
public void beforeSuite() {
//Nothing
}
@Override
public void afterSuite() {
synchronized (openGraphs) {
for (String dir : openGraphs.keySet()) {
File dirFile = new File(dir);
Assert.assertFalse(dirFile.exists() && dirFile.listFiles().length > 0);
}
}
}
} | 0true
| titan-berkeleyje_src_test_java_com_thinkaurelius_titan_blueprints_BerkeleyBlueprintsTest.java |
334 | public class NodesRestartAction extends ClusterAction<NodesRestartRequest, NodesRestartResponse, NodesRestartRequestBuilder> {
public static final NodesRestartAction INSTANCE = new NodesRestartAction();
public static final String NAME = "cluster/nodes/restart";
private NodesRestartAction() {
super(NAME);
}
@Override
public NodesRestartResponse newResponse() {
return new NodesRestartResponse();
}
@Override
public NodesRestartRequestBuilder newRequestBuilder(ClusterAdminClient client) {
return new NodesRestartRequestBuilder(client);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_node_restart_NodesRestartAction.java |
1,961 | public class MapTryPutRequest extends MapPutRequest {
private long timeout;
public MapTryPutRequest() {
}
public MapTryPutRequest(String name, Data key, Data value, long threadId, long timeout) {
super(name, key, value, threadId, -1);
this.timeout = timeout;
}
public int getClassId() {
return MapPortableHook.TRY_PUT;
}
@Override
protected Operation prepareOperation() {
TryPutOperation op = new TryPutOperation(name, key, value, timeout);
op.setThreadId(threadId);
return op;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeLong("timeout", timeout);
super.write(writer);
}
@Override
public void read(PortableReader reader) throws IOException {
timeout = reader.readLong("timeout");
super.read(reader);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_client_MapTryPutRequest.java |
1,297 | public interface CategoryExcludedSearchFacet {
/**
* Gets the internal id
*
* @return the internal id
*/
public Long getId();
/**
* Sets the internal id
*
* @param id
*/
public void setId(Long id);
/**
* Gets the associated category
*
* @return the associated category
*/
public Category getCategory();
/**
* Sets the associated category
*
* @param category
*/
public void setCategory(Category category);
/**
* Gets the associated search facet
*
* @return the associated search facet
*/
public SearchFacet getSearchFacet();
/**
* Sets the associated search facet
*
* @param searchFacet
*/
public void setSearchFacet(SearchFacet searchFacet);
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_domain_CategoryExcludedSearchFacet.java |
2,410 | public enum ByteUtils {
;
public static final int MAX_BYTES_VLONG = 9;
/** Zig-zag decode. */
public static long zigZagDecode(long n) {
return ((n >>> 1) ^ -(n & 1));
}
/** Zig-zag encode: this helps transforming small signed numbers into small positive numbers. */
public static long zigZagEncode(long n) {
return (n >> 63) ^ (n << 1);
}
/** Write a long in little-endian format. */
public static void writeLongLE(long l, byte[] arr, int offset) {
for (int i = 0; i < 8; ++i) {
arr[offset++] = (byte) l;
l >>>= 8;
}
assert l == 0;
}
/** Write a long in little-endian format. */
public static long readLongLE(byte[] arr, int offset) {
long l = arr[offset++] & 0xFFL;
for (int i = 1; i < 8; ++i) {
l |= (arr[offset++] & 0xFFL) << (8 * i);
}
return l;
}
/** Write an int in little-endian format. */
public static void writeIntLE(int l, byte[] arr, int offset) {
for (int i = 0; i < 4; ++i) {
arr[offset++] = (byte) l;
l >>>= 8;
}
assert l == 0;
}
/** Read an int in little-endian format. */
public static int readIntLE(byte[] arr, int offset) {
int l = arr[offset++] & 0xFF;
for (int i = 1; i < 4; ++i) {
l |= (arr[offset++] & 0xFF) << (8 * i);
}
return l;
}
/** Write a double in little-endian format. */
public static void writeDoubleLE(double d, byte[] arr, int offset) {
writeLongLE(Double.doubleToRawLongBits(d), arr, offset);
}
/** Read a double in little-endian format. */
public static double readDoubleLE(byte[] arr, int offset) {
return Double.longBitsToDouble(readLongLE(arr, offset));
}
/** Write a float in little-endian format. */
public static void writeFloatLE(float d, byte[] arr, int offset) {
writeIntLE(Float.floatToRawIntBits(d), arr, offset);
}
/** Read a float in little-endian format. */
public static float readFloatLE(byte[] arr, int offset) {
return Float.intBitsToFloat(readIntLE(arr, offset));
}
/** Same as DataOutput#writeVLong but accepts negative values (written on 9 bytes). */
public static void writeVLong(ByteArrayDataOutput out, long i) {
for (int k = 0; k < 8 && (i & ~0x7FL) != 0L; ++k) {
out.writeByte((byte)((i & 0x7FL) | 0x80L));
i >>>= 7;
}
out.writeByte((byte)i);
}
/** Same as DataOutput#readVLong but can read negative values (read on 9 bytes). */
public static long readVLong(ByteArrayDataInput in) {
// unwinded because of hotspot bugs, see Lucene's impl
byte b = in.readByte();
if (b >= 0) return b;
long i = b & 0x7FL;
b = in.readByte();
i |= (b & 0x7FL) << 7;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 14;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 21;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 28;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 35;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 42;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 49;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0xFFL) << 56;
return i;
}
} | 0true
| src_main_java_org_elasticsearch_common_util_ByteUtils.java |
1,833 | class InjectionRequestProcessor extends AbstractProcessor {
private final List<StaticInjection> staticInjections = Lists.newArrayList();
private final Initializer initializer;
InjectionRequestProcessor(Errors errors, Initializer initializer) {
super(errors);
this.initializer = initializer;
}
@Override
public Boolean visit(StaticInjectionRequest request) {
staticInjections.add(new StaticInjection(injector, request));
return true;
}
@Override
public Boolean visit(InjectionRequest request) {
Set<InjectionPoint> injectionPoints;
try {
injectionPoints = request.getInjectionPoints();
} catch (ConfigurationException e) {
errors.merge(e.getErrorMessages());
injectionPoints = e.getPartialValue();
}
initializer.requestInjection(
injector, request.getInstance(), request.getSource(), injectionPoints);
return true;
}
public void validate() {
for (StaticInjection staticInjection : staticInjections) {
staticInjection.validate();
}
}
public void injectMembers() {
for (StaticInjection staticInjection : staticInjections) {
staticInjection.injectMembers();
}
}
/**
* A requested static injection.
*/
private class StaticInjection {
final InjectorImpl injector;
final Object source;
final StaticInjectionRequest request;
ImmutableList<SingleMemberInjector> memberInjectors;
public StaticInjection(InjectorImpl injector, StaticInjectionRequest request) {
this.injector = injector;
this.source = request.getSource();
this.request = request;
}
void validate() {
Errors errorsForMember = errors.withSource(source);
Set<InjectionPoint> injectionPoints;
try {
injectionPoints = request.getInjectionPoints();
} catch (ConfigurationException e) {
errors.merge(e.getErrorMessages());
injectionPoints = e.getPartialValue();
}
memberInjectors = injector.membersInjectorStore.getInjectors(
injectionPoints, errorsForMember);
}
void injectMembers() {
try {
injector.callInContext(new ContextualCallable<Void>() {
public Void call(InternalContext context) {
for (SingleMemberInjector injector : memberInjectors) {
injector.inject(errors, context, null);
}
return null;
}
});
} catch (ErrorsException e) {
throw new AssertionError();
}
}
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_InjectionRequestProcessor.java |
890 | public interface ORecord<T> extends ORecordElement, OIdentifiable, Serializable {
/**
* Removes all the dependencies with other records. All the relationships remain in form of RecordID. If some links contain dirty
* records, the detach cannot be complete and this method returns false.
*
* @return True if the document has been successfully detached, otherwise false.
*/
public boolean detach();
/**
* Resets the record to be reused. The record is fresh like just created. Use this method to recycle records avoiding the creation
* of them stressing the JVM Garbage Collector.
*
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET reset();
/**
* Unloads current record. All information are lost but the record identity. At the next access the record will be auto-reloaded.
* Useful to free memory or to avoid to keep an old version of it.
*
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET unload();
/**
* All the fields are deleted but the record identity is maintained. Use this to remove all the document's fields.
*
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET clear();
/**
* Creates a copy of the record. All the record contents are copied.
*
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET copy();
/**
* Returns the record identity as <cluster-id>:<cluster-position>
*/
public ORID getIdentity();
/**
* Returns the data segment where the record will be created at first.
*
* @return Data segment name
*/
public String getDataSegmentName();
/**
* Sets the data segment name where to save the record the first time it's created.
*
* @param iName
* Data segment name
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET setDataSegmentName(String iName);
/**
* Returns the current version number of the record. When the record is created has version = 0. At every change the storage
* increment the version number. Version number is used by Optimistic transactions to check if the record is changed in the
* meanwhile of the transaction. In distributed environment you should prefer {@link #getRecordVersion()} instead of this method.
*
* @see OTransactionOptimistic
* @return The version number. 0 if it's a brand new record.
*/
public int getVersion();
/**
* The same as {@link #getVersion()} but returns {@link ORecordVersion} interface that can contain additional information about
* current version. In distributed environment you should prefer this method instead of {@link #getVersion()}.
*
* @return version of record
* @see ORecordVersion
*/
public ORecordVersion getRecordVersion();
/**
* Returns the database where the record belongs.
*
* @return
*/
public ODatabaseRecord getDatabase();
/**
* Checks if the record is dirty, namely if it was changed in memory.
*
* @return True if dirty, otherwise false
*/
public boolean isDirty();
/**
* Checks if the record is pinned.
*
* @return True if pinned, otherwise false
*/
public Boolean isPinned();
/**
* Suggests to the engine to keep the record in cache. Use it for the most read records.
*
* @see ORecord#unpin()
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET pin();
/**
* Suggests to the engine to not keep the record in cache.
*
* @see ORecord#pin()
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET unpin();
/**
* Loads the record content in memory. If the record is in cache will be returned a new instance, so pay attention to use the
* returned. If the record is dirty, then it returns to the original content. If the record does not exist a
* ORecordNotFoundException exception is thrown.
*
* @return The record loaded or itself if the record has been reloaded from the storage. Useful to call methods in chain.
*/
public <RET extends ORecord<T>> RET load() throws ORecordNotFoundException;
/**
* Loads the record content in memory. No cache is used. If the record is dirty, then it returns to the original content. If the
* record does not exist a ORecordNotFoundException exception is thrown.
*
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET reload() throws ORecordNotFoundException;
/**
* Saves in-memory changes to the database. Behavior depends by the current running transaction if any. If no transaction is
* running then changes apply immediately. If an Optimistic transaction is running then the record will be changed at commit time.
* The current transaction will continue to see the record as modified, while others not. If a Pessimistic transaction is running,
* then an exclusive lock is acquired against the record. Current transaction will continue to see the record as modified, while
* others cannot access to it since it's locked.
*
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET save();
/**
* Saves in-memory changes to the database defining a specific cluster where to save it. Behavior depends by the current running
* transaction if any. If no transaction is running then changes apply immediately. If an Optimistic transaction is running then
* the record will be changed at commit time. The current transaction will continue to see the record as modified, while others
* not. If a Pessimistic transaction is running, then an exclusive lock is acquired against the record. Current transaction will
* continue to see the record as modified, while others cannot access to it since it's locked.
*
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET save(String iCluster);
public <RET extends ORecord<T>> RET save(boolean forceCreate);
public <RET extends ORecord<T>> RET save(String iCluster, boolean forceCreate);
/**
* Deletes the record from the database. Behavior depends by the current running transaction if any. If no transaction is running
* then the record is deleted immediately. If an Optimistic transaction is running then the record will be deleted at commit time.
* The current transaction will continue to see the record as deleted, while others not. If a Pessimistic transaction is running,
* then an exclusive lock is acquired against the record. Current transaction will continue to see the record as deleted, while
* others cannot access to it since it's locked.
*
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET delete();
/**
* Fills the record parsing the content in JSON format.
*
* @param iJson
* Object content in JSON format
* @return The Object instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <RET extends ORecord<T>> RET fromJSON(String iJson);
/**
* Exports the record in JSON format.
*
* @return Object content in JSON format
*/
public String toJSON();
/**
* Exports the record in JSON format specifying additional formatting settings.
*
* @param iFormat
* Format settings separated by comma. Available settings are:
* <ul>
* <li><b>rid</b>: exports the record's id as property "@rid"</li>
* <li><b>version</b>: exports the record's version as property "@version"</li>
* <li><b>class</b>: exports the record's class as property "@class"</li>
* <li><b>attribSameRow</b>: exports all the record attributes in the same row</li>
* <li><b>indent:<level></b>: Indents the output if the <level> specified. Default is 0</li>
* </ul>
* Example: "rid,version,class,indent:6" exports record id, version and class properties along with record properties
* using an indenting level equals of 6.
* @return Object content in JSON format
*/
public String toJSON(String iFormat);
/**
* Returns the size in bytes of the record. The size can be computed only for not new records.
*
* @return the size in bytes
*/
public int getSize();
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_ORecord.java |
27 | static final class RunAfterEither extends Completion {
final CompletableFuture<?> src;
final CompletableFuture<?> snd;
final Runnable fn;
final CompletableFuture<Void> dst;
final Executor executor;
RunAfterEither(CompletableFuture<?> src,
CompletableFuture<?> snd,
Runnable fn,
CompletableFuture<Void> dst,
Executor executor) {
this.src = src; this.snd = snd;
this.fn = fn; this.dst = dst;
this.executor = executor;
}
public final void run() {
final CompletableFuture<?> a;
final CompletableFuture<?> b;
final Runnable fn;
final CompletableFuture<Void> dst;
Object r; Throwable ex;
if ((dst = this.dst) != null &&
(fn = this.fn) != null &&
(((a = this.src) != null && (r = a.result) != null) ||
((b = this.snd) != null && (r = b.result) != null)) &&
compareAndSet(0, 1)) {
if (r instanceof AltResult)
ex = ((AltResult)r).ex;
else
ex = null;
Executor e = executor;
if (ex == null) {
try {
if (e != null)
e.execute(new AsyncRun(fn, dst));
else
fn.run();
} catch (Throwable rex) {
ex = rex;
}
}
if (e == null || ex != null)
dst.internalComplete(null, ex);
}
}
private static final long serialVersionUID = 5232453952276885070L;
} | 0true
| src_main_java_jsr166e_CompletableFuture.java |
561 | final SortedSet<OIndex<?>> indexesToLock = new TreeSet<OIndex<?>>(new Comparator<OIndex<?>>() {
public int compare(OIndex<?> indexOne, OIndex<?> indexTwo) {
return indexOne.getName().compareTo(indexTwo.getName());
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_OClassIndexManager.java |
1,718 | public final class ImmutableOpenMap<KType, VType> implements Iterable<ObjectObjectCursor<KType, VType>> {
private final ObjectObjectOpenHashMap<KType, VType> map;
private ImmutableOpenMap(ObjectObjectOpenHashMap<KType, VType> map) {
this.map = map;
}
/**
* @return Returns the value associated with the given key or the default value
* for the key type, if the key is not associated with any value.
* <p/>
* <b>Important note:</b> For primitive type values, the value returned for a non-existing
* key may not be the default value of the primitive type (it may be any value previously
* assigned to that slot).
*/
public VType get(KType key) {
return map.get(key);
}
/**
* @return Returns the value associated with the given key or the provided default value if the
* key is not associated with any value.
*/
public VType getOrDefault(KType key, VType defaultValue) {
return map.getOrDefault(key, defaultValue);
}
/**
* Returns <code>true</code> if this container has an association to a value for
* the given key.
*/
public boolean containsKey(KType key) {
return map.containsKey(key);
}
/**
* @return Returns the current size (number of assigned keys) in the container.
*/
public int size() {
return map.size();
}
/**
* @return Return <code>true</code> if this hash map contains no assigned keys.
*/
public boolean isEmpty() {
return map.isEmpty();
}
/**
* Returns a cursor over the entries (key-value pairs) in this map. The iterator is
* implemented as a cursor and it returns <b>the same cursor instance</b> on every
* call to {@link Iterator#next()}. To read the current key and value use the cursor's
* public fields. An example is shown below.
* <pre>
* for (IntShortCursor c : intShortMap)
* {
* System.out.println("index=" + c.index
* + " key=" + c.key
* + " value=" + c.value);
* }
* </pre>
* <p/>
* <p>The <code>index</code> field inside the cursor gives the internal index inside
* the container's implementation. The interpretation of this index depends on
* to the container.
*/
@Override
public Iterator<ObjectObjectCursor<KType, VType>> iterator() {
return map.iterator();
}
/**
* Returns a specialized view of the keys of this associated container.
* The view additionally implements {@link ObjectLookupContainer}.
*/
public ObjectLookupContainer<KType> keys() {
return map.keys();
}
/**
* Returns a direct iterator over the keys.
*/
public UnmodifiableIterator<KType> keysIt() {
final Iterator<ObjectCursor<KType>> iterator = map.keys().iterator();
return new UnmodifiableIterator<KType>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public KType next() {
return iterator.next().value;
}
};
}
/**
* @return Returns a container with all values stored in this map.
*/
public ObjectContainer<VType> values() {
return map.values();
}
/**
* Returns a direct iterator over the keys.
*/
public UnmodifiableIterator<VType> valuesIt() {
final Iterator<ObjectCursor<VType>> iterator = map.values().iterator();
return new UnmodifiableIterator<VType>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public VType next() {
return iterator.next().value;
}
};
}
@Override
public String toString() {
return map.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ImmutableOpenMap that = (ImmutableOpenMap) o;
if (!map.equals(that.map)) return false;
return true;
}
@Override
public int hashCode() {
return map.hashCode();
}
@SuppressWarnings("unchecked")
private static final ImmutableOpenMap EMPTY = new ImmutableOpenMap(new ObjectObjectOpenHashMap());
@SuppressWarnings("unchecked")
public static <KType, VType> ImmutableOpenMap<KType, VType> of() {
return EMPTY;
}
public static <KType, VType> Builder<KType, VType> builder() {
return new Builder<KType, VType>();
}
public static <KType, VType> Builder<KType, VType> builder(int size) {
return new Builder<KType, VType>(size);
}
public static <KType, VType> Builder<KType, VType> builder(ImmutableOpenMap<KType, VType> map) {
return new Builder<KType, VType>(map);
}
public static class Builder<KType, VType> implements ObjectObjectMap<KType, VType> {
private ObjectObjectOpenHashMap<KType, VType> map;
public Builder() {
//noinspection unchecked
this(EMPTY);
}
public Builder(int size) {
this.map = new ObjectObjectOpenHashMap<KType, VType>(size);
}
public Builder(ImmutableOpenMap<KType, VType> map) {
this.map = map.map.clone();
}
/**
* Builds a new instance of the
*/
public ImmutableOpenMap<KType, VType> build() {
ObjectObjectOpenHashMap<KType, VType> map = this.map;
this.map = null; // nullify the map, so any operation post build will fail! (hackish, but safest)
return new ImmutableOpenMap<KType, VType>(map);
}
/**
* Puts all the entries in the map to the builder.
*/
public Builder<KType, VType> putAll(Map<KType, VType> map) {
for (Map.Entry<KType, VType> entry : map.entrySet()) {
this.map.put(entry.getKey(), entry.getValue());
}
return this;
}
/**
* A put operation that can be used in the fluent pattern.
*/
public Builder<KType, VType> fPut(KType key, VType value) {
map.put(key, value);
return this;
}
@Override
public VType put(KType key, VType value) {
return map.put(key, value);
}
@Override
public VType get(KType key) {
return map.get(key);
}
@Override
public VType getOrDefault(KType kType, VType vType) {
return map.getOrDefault(kType, vType);
}
@Override
public int putAll(ObjectObjectAssociativeContainer<? extends KType, ? extends VType> container) {
return map.putAll(container);
}
@Override
public int putAll(Iterable<? extends ObjectObjectCursor<? extends KType, ? extends VType>> iterable) {
return map.putAll(iterable);
}
/**
* Remove that can be used in the fluent pattern.
*/
public Builder<KType, VType> fRemove(KType key) {
map.remove(key);
return this;
}
@Override
public VType remove(KType key) {
return map.remove(key);
}
@Override
public Iterator<ObjectObjectCursor<KType, VType>> iterator() {
return map.iterator();
}
@Override
public boolean containsKey(KType key) {
return map.containsKey(key);
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public int removeAll(ObjectContainer<? extends KType> container) {
return map.removeAll(container);
}
@Override
public int removeAll(ObjectPredicate<? super KType> predicate) {
return map.removeAll(predicate);
}
@Override
public <T extends ObjectObjectProcedure<? super KType, ? super VType>> T forEach(T procedure) {
return map.forEach(procedure);
}
@Override
public void clear() {
map.clear();
}
@Override
public ObjectCollection<KType> keys() {
return map.keys();
}
@Override
public ObjectContainer<VType> values() {
return map.values();
}
@SuppressWarnings("unchecked")
public <K, V> Builder<K, V> cast() {
return (Builder) this;
}
}
} | 0true
| src_main_java_org_elasticsearch_common_collect_ImmutableOpenMap.java |
3,137 | public class InternalEngineTests extends ElasticsearchTestCase {
protected final ShardId shardId = new ShardId(new Index("index"), 1);
protected ThreadPool threadPool;
private Store store;
private Store storeReplica;
protected Engine engine;
protected Engine replicaEngine;
private IndexSettingsService engineSettingsService;
private IndexSettingsService replicaSettingsService;
private Settings defaultSettings;
@Before
public void setUp() throws Exception {
super.setUp();
defaultSettings = ImmutableSettings.builder()
.put(InternalEngine.INDEX_COMPOUND_ON_FLUSH, getRandom().nextBoolean())
.build(); // TODO randomize more settings
threadPool = new ThreadPool();
store = createStore();
store.deleteContent();
storeReplica = createStoreReplica();
storeReplica.deleteContent();
engineSettingsService = new IndexSettingsService(shardId.index(), EMPTY_SETTINGS);
engine = createEngine(engineSettingsService, store, createTranslog());
engine.start();
replicaSettingsService = new IndexSettingsService(shardId.index(), EMPTY_SETTINGS);
replicaEngine = createEngine(replicaSettingsService, storeReplica, createTranslogReplica());
replicaEngine.start();
}
@After
public void tearDown() throws Exception {
super.tearDown();
replicaEngine.close();
storeReplica.close();
engine.close();
store.close();
if (threadPool != null) {
threadPool.shutdownNow();
}
}
private Document testDocumentWithTextField() {
Document document = testDocument();
document.add(new TextField("value", "test", Field.Store.YES));
return document;
}
private Document testDocument() {
return new Document();
}
private ParsedDocument testParsedDocument(String uid, String id, String type, String routing, long timestamp, long ttl, Document document, Analyzer analyzer, BytesReference source, boolean mappingsModified) {
Field uidField = new Field("_uid", uid, UidFieldMapper.Defaults.FIELD_TYPE);
Field versionField = new NumericDocValuesField("_version", 0);
document.add(uidField);
document.add(versionField);
return new ParsedDocument(uidField, versionField, id, type, routing, timestamp, ttl, Arrays.asList(document), analyzer, source, mappingsModified);
}
protected Store createStore() throws IOException {
DirectoryService directoryService = new RamDirectoryService(shardId, EMPTY_SETTINGS);
return new Store(shardId, EMPTY_SETTINGS, null, null, directoryService, new LeastUsedDistributor(directoryService));
}
protected Store createStoreReplica() throws IOException {
DirectoryService directoryService = new RamDirectoryService(shardId, EMPTY_SETTINGS);
return new Store(shardId, EMPTY_SETTINGS, null, null, directoryService, new LeastUsedDistributor(directoryService));
}
protected Translog createTranslog() {
return new FsTranslog(shardId, EMPTY_SETTINGS, new File("work/fs-translog/primary"));
}
protected Translog createTranslogReplica() {
return new FsTranslog(shardId, EMPTY_SETTINGS, new File("work/fs-translog/replica"));
}
protected IndexDeletionPolicy createIndexDeletionPolicy() {
return new KeepOnlyLastDeletionPolicy(shardId, EMPTY_SETTINGS);
}
protected SnapshotDeletionPolicy createSnapshotDeletionPolicy() {
return new SnapshotDeletionPolicy(createIndexDeletionPolicy());
}
protected MergePolicyProvider<?> createMergePolicy() {
return new LogByteSizeMergePolicyProvider(store, new IndexSettingsService(new Index("test"), EMPTY_SETTINGS));
}
protected MergeSchedulerProvider<?> createMergeScheduler() {
return new SerialMergeSchedulerProvider(shardId, EMPTY_SETTINGS, threadPool);
}
protected Engine createEngine(IndexSettingsService indexSettingsService, Store store, Translog translog) {
return createEngine(indexSettingsService, store, translog, createMergeScheduler());
}
protected Engine createEngine(IndexSettingsService indexSettingsService, Store store, Translog translog, MergeSchedulerProvider<?> mergeSchedulerProvider) {
return new InternalEngine(shardId, defaultSettings, threadPool, indexSettingsService, new ShardIndexingService(shardId, EMPTY_SETTINGS, new ShardSlowLogIndexingService(shardId, EMPTY_SETTINGS, indexSettingsService)), null, store, createSnapshotDeletionPolicy(), translog, createMergePolicy(), mergeSchedulerProvider,
new AnalysisService(shardId.index()), new SimilarityService(shardId.index()), new CodecService(shardId.index()));
}
protected static final BytesReference B_1 = new BytesArray(new byte[]{1});
protected static final BytesReference B_2 = new BytesArray(new byte[]{2});
protected static final BytesReference B_3 = new BytesArray(new byte[]{3});
@Test
public void testSegments() throws Exception {
List<Segment> segments = engine.segments();
assertThat(segments.isEmpty(), equalTo(true));
assertThat(engine.segmentsStats().getCount(), equalTo(0l));
final boolean defaultCompound = defaultSettings.getAsBoolean(InternalEngine.INDEX_COMPOUND_ON_FLUSH, true);
// create a doc and refresh
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_1, false);
engine.create(new Engine.Create(null, newUid("1"), doc));
ParsedDocument doc2 = testParsedDocument("2", "2", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_2, false);
engine.create(new Engine.Create(null, newUid("2"), doc2));
engine.refresh(new Engine.Refresh("test").force(false));
segments = engine.segments();
assertThat(segments.size(), equalTo(1));
assertThat(engine.segmentsStats().getCount(), equalTo(1l));
assertThat(segments.get(0).isCommitted(), equalTo(false));
assertThat(segments.get(0).isSearch(), equalTo(true));
assertThat(segments.get(0).getNumDocs(), equalTo(2));
assertThat(segments.get(0).getDeletedDocs(), equalTo(0));
assertThat(segments.get(0).isCompound(), equalTo(defaultCompound));
engine.flush(new Engine.Flush());
segments = engine.segments();
assertThat(segments.size(), equalTo(1));
assertThat(engine.segmentsStats().getCount(), equalTo(1l));
assertThat(segments.get(0).isCommitted(), equalTo(true));
assertThat(segments.get(0).isSearch(), equalTo(true));
assertThat(segments.get(0).getNumDocs(), equalTo(2));
assertThat(segments.get(0).getDeletedDocs(), equalTo(0));
assertThat(segments.get(0).isCompound(), equalTo(defaultCompound));
engineSettingsService.refreshSettings(ImmutableSettings.builder().put(InternalEngine.INDEX_COMPOUND_ON_FLUSH, false).build());
ParsedDocument doc3 = testParsedDocument("3", "3", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_3, false);
engine.create(new Engine.Create(null, newUid("3"), doc3));
engine.refresh(new Engine.Refresh("test").force(false));
segments = engine.segments();
assertThat(segments.size(), equalTo(2));
assertThat(engine.segmentsStats().getCount(), equalTo(2l));
assertThat(segments.get(0).getGeneration() < segments.get(1).getGeneration(), equalTo(true));
assertThat(segments.get(0).isCommitted(), equalTo(true));
assertThat(segments.get(0).isSearch(), equalTo(true));
assertThat(segments.get(0).getNumDocs(), equalTo(2));
assertThat(segments.get(0).getDeletedDocs(), equalTo(0));
assertThat(segments.get(0).isCompound(), equalTo(defaultCompound));
assertThat(segments.get(1).isCommitted(), equalTo(false));
assertThat(segments.get(1).isSearch(), equalTo(true));
assertThat(segments.get(1).getNumDocs(), equalTo(1));
assertThat(segments.get(1).getDeletedDocs(), equalTo(0));
assertThat(segments.get(1).isCompound(), equalTo(false));
engine.delete(new Engine.Delete("test", "1", newUid("1")));
engine.refresh(new Engine.Refresh("test").force(false));
segments = engine.segments();
assertThat(segments.size(), equalTo(2));
assertThat(engine.segmentsStats().getCount(), equalTo(2l));
assertThat(segments.get(0).getGeneration() < segments.get(1).getGeneration(), equalTo(true));
assertThat(segments.get(0).isCommitted(), equalTo(true));
assertThat(segments.get(0).isSearch(), equalTo(true));
assertThat(segments.get(0).getNumDocs(), equalTo(1));
assertThat(segments.get(0).getDeletedDocs(), equalTo(1));
assertThat(segments.get(0).isCompound(), equalTo(defaultCompound));
assertThat(segments.get(1).isCommitted(), equalTo(false));
assertThat(segments.get(1).isSearch(), equalTo(true));
assertThat(segments.get(1).getNumDocs(), equalTo(1));
assertThat(segments.get(1).getDeletedDocs(), equalTo(0));
assertThat(segments.get(1).isCompound(), equalTo(false));
engineSettingsService.refreshSettings(ImmutableSettings.builder().put(InternalEngine.INDEX_COMPOUND_ON_FLUSH, true).build());
ParsedDocument doc4 = testParsedDocument("4", "4", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_3, false);
engine.create(new Engine.Create(null, newUid("4"), doc4));
engine.refresh(new Engine.Refresh("test").force(false));
segments = engine.segments();
assertThat(segments.size(), equalTo(3));
assertThat(engine.segmentsStats().getCount(), equalTo(3l));
assertThat(segments.get(0).getGeneration() < segments.get(1).getGeneration(), equalTo(true));
assertThat(segments.get(0).isCommitted(), equalTo(true));
assertThat(segments.get(0).isSearch(), equalTo(true));
assertThat(segments.get(0).getNumDocs(), equalTo(1));
assertThat(segments.get(0).getDeletedDocs(), equalTo(1));
assertThat(segments.get(0).isCompound(), equalTo(defaultCompound));
assertThat(segments.get(1).isCommitted(), equalTo(false));
assertThat(segments.get(1).isSearch(), equalTo(true));
assertThat(segments.get(1).getNumDocs(), equalTo(1));
assertThat(segments.get(1).getDeletedDocs(), equalTo(0));
assertThat(segments.get(1).isCompound(), equalTo(false));
assertThat(segments.get(2).isCommitted(), equalTo(false));
assertThat(segments.get(2).isSearch(), equalTo(true));
assertThat(segments.get(2).getNumDocs(), equalTo(1));
assertThat(segments.get(2).getDeletedDocs(), equalTo(0));
assertThat(segments.get(2).isCompound(), equalTo(true));
}
@Test
public void testSegmentsWithMergeFlag() throws Exception {
ConcurrentMergeSchedulerProvider mergeSchedulerProvider = new ConcurrentMergeSchedulerProvider(shardId, EMPTY_SETTINGS, threadPool);
final AtomicReference<CountDownLatch> waitTillMerge = new AtomicReference<CountDownLatch>();
final AtomicReference<CountDownLatch> waitForMerge = new AtomicReference<CountDownLatch>();
mergeSchedulerProvider.addListener(new MergeSchedulerProvider.Listener() {
@Override
public void beforeMerge(OnGoingMerge merge) {
try {
if (waitTillMerge.get() != null) {
waitTillMerge.get().countDown();
}
if (waitForMerge.get() != null) {
waitForMerge.get().await();
}
} catch (InterruptedException e) {
throw ExceptionsHelper.convertToRuntime(e);
}
}
@Override
public void afterMerge(OnGoingMerge merge) {
}
});
Engine engine = createEngine(engineSettingsService, store, createTranslog(), mergeSchedulerProvider);
engine.start();
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
engine.flush(new Engine.Flush());
assertThat(engine.segments().size(), equalTo(1));
index = new Engine.Index(null, newUid("2"), doc);
engine.index(index);
engine.flush(new Engine.Flush());
assertThat(engine.segments().size(), equalTo(2));
for (Segment segment : engine.segments()) {
assertThat(segment.getMergeId(), nullValue());
}
index = new Engine.Index(null, newUid("3"), doc);
engine.index(index);
engine.flush(new Engine.Flush());
assertThat(engine.segments().size(), equalTo(3));
for (Segment segment : engine.segments()) {
assertThat(segment.getMergeId(), nullValue());
}
waitTillMerge.set(new CountDownLatch(1));
waitForMerge.set(new CountDownLatch(1));
engine.optimize(new Engine.Optimize().maxNumSegments(1).waitForMerge(false));
waitTillMerge.get().await();
for (Segment segment : engine.segments()) {
assertThat(segment.getMergeId(), notNullValue());
}
waitForMerge.get().countDown();
index = new Engine.Index(null, newUid("4"), doc);
engine.index(index);
engine.flush(new Engine.Flush());
// now, optimize and wait for merges, see that we have no merge flag
engine.optimize(new Engine.Optimize().flush(true).maxNumSegments(1).waitForMerge(true));
for (Segment segment : engine.segments()) {
assertThat(segment.getMergeId(), nullValue());
}
engine.close();
}
@Test
public void testSimpleOperations() throws Exception {
Engine.Searcher searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0));
searchResult.release();
// create a document
Document document = testDocumentWithTextField();
document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, document, Lucene.STANDARD_ANALYZER, B_1, false);
engine.create(new Engine.Create(null, newUid("1"), doc));
// its not there...
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0));
searchResult.release();
// but, we can still get it (in realtime)
Engine.GetResult getResult = engine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
assertThat(getResult.source().source.toBytesArray(), equalTo(B_1.toBytesArray()));
assertThat(getResult.docIdAndVersion(), nullValue());
getResult.release();
// but, not there non realtime
getResult = engine.get(new Engine.Get(false, newUid("1")));
assertThat(getResult.exists(), equalTo(false));
getResult.release();
// refresh and it should be there
engine.refresh(new Engine.Refresh("test").force(false));
// now its there...
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 1));
searchResult.release();
// also in non realtime
getResult = engine.get(new Engine.Get(false, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
assertThat(getResult.docIdAndVersion(), notNullValue());
getResult.release();
// now do an update
document = testDocument();
document.add(new TextField("value", "test1", Field.Store.YES));
document.add(new Field(SourceFieldMapper.NAME, B_2.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, Lucene.STANDARD_ANALYZER, B_2, false);
engine.index(new Engine.Index(null, newUid("1"), doc));
// its not updated yet...
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 0));
searchResult.release();
// but, we can still get it (in realtime)
getResult = engine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
assertThat(getResult.source().source.toBytesArray(), equalTo(B_2.toBytesArray()));
assertThat(getResult.docIdAndVersion(), nullValue());
getResult.release();
// refresh and it should be updated
engine.refresh(new Engine.Refresh("test").force(false));
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 1));
searchResult.release();
// now delete
engine.delete(new Engine.Delete("test", "1", newUid("1")));
// its not deleted yet
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 1));
searchResult.release();
// but, get should not see it (in realtime)
getResult = engine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(false));
getResult.release();
// refresh and it should be deleted
engine.refresh(new Engine.Refresh("test").force(false));
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 0));
searchResult.release();
// add it back
document = testDocumentWithTextField();
document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, Lucene.STANDARD_ANALYZER, B_1, false);
engine.create(new Engine.Create(null, newUid("1"), doc));
// its not there...
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 0));
searchResult.release();
// refresh and it should be there
engine.refresh(new Engine.Refresh("test").force(false));
// now its there...
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 0));
searchResult.release();
// now flush
engine.flush(new Engine.Flush());
// and, verify get (in real time)
getResult = engine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
assertThat(getResult.source(), nullValue());
assertThat(getResult.docIdAndVersion(), notNullValue());
getResult.release();
// make sure we can still work with the engine
// now do an update
document = testDocument();
document.add(new TextField("value", "test1", Field.Store.YES));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, Lucene.STANDARD_ANALYZER, B_1, false);
engine.index(new Engine.Index(null, newUid("1"), doc));
// its not updated yet...
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 0));
searchResult.release();
// refresh and it should be updated
engine.refresh(new Engine.Refresh("test").force(false));
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 1));
searchResult.release();
engine.close();
}
@Test
public void testSearchResultRelease() throws Exception {
Engine.Searcher searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0));
searchResult.release();
// create a document
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_1, false);
engine.create(new Engine.Create(null, newUid("1"), doc));
// its not there...
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0));
searchResult.release();
// refresh and it should be there
engine.refresh(new Engine.Refresh("test").force(false));
// now its there...
searchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 1));
// don't release the search result yet...
// delete, refresh and do a new search, it should not be there
engine.delete(new Engine.Delete("test", "1", newUid("1")));
engine.refresh(new Engine.Refresh("test").force(false));
Engine.Searcher updateSearchResult = engine.acquireSearcher("test");
MatcherAssert.assertThat(updateSearchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0));
updateSearchResult.release();
// the non release search result should not see the deleted yet...
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1));
MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 1));
searchResult.release();
}
@Test
public void testSimpleSnapshot() throws Exception {
// create a document
ParsedDocument doc1 = testParsedDocument("1", "1", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_1, false);
engine.create(new Engine.Create(null, newUid("1"), doc1));
final ExecutorService executorService = Executors.newCachedThreadPool();
engine.snapshot(new Engine.SnapshotHandler<Void>() {
@Override
public Void snapshot(final SnapshotIndexCommit snapshotIndexCommit1, final Translog.Snapshot translogSnapshot1) {
MatcherAssert.assertThat(snapshotIndexCommit1, SnapshotIndexCommitExistsMatcher.snapshotIndexCommitExists());
assertThat(translogSnapshot1.hasNext(), equalTo(true));
Translog.Create create1 = (Translog.Create) translogSnapshot1.next();
assertThat(create1.source().toBytesArray(), equalTo(B_1.toBytesArray()));
assertThat(translogSnapshot1.hasNext(), equalTo(false));
Future<Object> future = executorService.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
engine.flush(new Engine.Flush());
ParsedDocument doc2 = testParsedDocument("2", "2", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_2, false);
engine.create(new Engine.Create(null, newUid("2"), doc2));
engine.flush(new Engine.Flush());
ParsedDocument doc3 = testParsedDocument("3", "3", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_3, false);
engine.create(new Engine.Create(null, newUid("3"), doc3));
return null;
}
});
try {
future.get();
} catch (Exception e) {
e.printStackTrace();
assertThat(e.getMessage(), false, equalTo(true));
}
MatcherAssert.assertThat(snapshotIndexCommit1, SnapshotIndexCommitExistsMatcher.snapshotIndexCommitExists());
engine.snapshot(new Engine.SnapshotHandler<Void>() {
@Override
public Void snapshot(SnapshotIndexCommit snapshotIndexCommit2, Translog.Snapshot translogSnapshot2) throws EngineException {
MatcherAssert.assertThat(snapshotIndexCommit1, SnapshotIndexCommitExistsMatcher.snapshotIndexCommitExists());
MatcherAssert.assertThat(snapshotIndexCommit2, SnapshotIndexCommitExistsMatcher.snapshotIndexCommitExists());
assertThat(snapshotIndexCommit2.getSegmentsFileName(), not(equalTo(snapshotIndexCommit1.getSegmentsFileName())));
assertThat(translogSnapshot2.hasNext(), equalTo(true));
Translog.Create create3 = (Translog.Create) translogSnapshot2.next();
assertThat(create3.source().toBytesArray(), equalTo(B_3.toBytesArray()));
assertThat(translogSnapshot2.hasNext(), equalTo(false));
return null;
}
});
return null;
}
});
engine.close();
}
@Test
public void testSimpleRecover() throws Exception {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_1, false);
engine.create(new Engine.Create(null, newUid("1"), doc));
engine.flush(new Engine.Flush());
engine.recover(new Engine.RecoveryHandler() {
@Override
public void phase1(SnapshotIndexCommit snapshot) throws EngineException {
try {
engine.flush(new Engine.Flush());
assertThat("flush is not allowed in phase 3", false, equalTo(true));
} catch (FlushNotAllowedEngineException e) {
// all is well
}
}
@Override
public void phase2(Translog.Snapshot snapshot) throws EngineException {
MatcherAssert.assertThat(snapshot, TranslogSizeMatcher.translogSize(0));
try {
engine.flush(new Engine.Flush());
assertThat("flush is not allowed in phase 3", false, equalTo(true));
} catch (FlushNotAllowedEngineException e) {
// all is well
}
}
@Override
public void phase3(Translog.Snapshot snapshot) throws EngineException {
MatcherAssert.assertThat(snapshot, TranslogSizeMatcher.translogSize(0));
try {
// we can do this here since we are on the same thread
engine.flush(new Engine.Flush());
assertThat("flush is not allowed in phase 3", false, equalTo(true));
} catch (FlushNotAllowedEngineException e) {
// all is well
}
}
});
engine.flush(new Engine.Flush());
engine.close();
}
@Test
public void testRecoverWithOperationsBetweenPhase1AndPhase2() throws Exception {
ParsedDocument doc1 = testParsedDocument("1", "1", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_1, false);
engine.create(new Engine.Create(null, newUid("1"), doc1));
engine.flush(new Engine.Flush());
ParsedDocument doc2 = testParsedDocument("2", "2", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_2, false);
engine.create(new Engine.Create(null, newUid("2"), doc2));
engine.recover(new Engine.RecoveryHandler() {
@Override
public void phase1(SnapshotIndexCommit snapshot) throws EngineException {
}
@Override
public void phase2(Translog.Snapshot snapshot) throws EngineException {
assertThat(snapshot.hasNext(), equalTo(true));
Translog.Create create = (Translog.Create) snapshot.next();
assertThat(create.source().toBytesArray(), equalTo(B_2));
assertThat(snapshot.hasNext(), equalTo(false));
}
@Override
public void phase3(Translog.Snapshot snapshot) throws EngineException {
MatcherAssert.assertThat(snapshot, TranslogSizeMatcher.translogSize(0));
}
});
engine.flush(new Engine.Flush());
engine.close();
}
@Test
public void testRecoverWithOperationsBetweenPhase1AndPhase2AndPhase3() throws Exception {
ParsedDocument doc1 = testParsedDocument("1", "1", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_1, false);
engine.create(new Engine.Create(null, newUid("1"), doc1));
engine.flush(new Engine.Flush());
ParsedDocument doc2 = testParsedDocument("2", "2", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_2, false);
engine.create(new Engine.Create(null, newUid("2"), doc2));
engine.recover(new Engine.RecoveryHandler() {
@Override
public void phase1(SnapshotIndexCommit snapshot) throws EngineException {
}
@Override
public void phase2(Translog.Snapshot snapshot) throws EngineException {
assertThat(snapshot.hasNext(), equalTo(true));
Translog.Create create = (Translog.Create) snapshot.next();
assertThat(snapshot.hasNext(), equalTo(false));
assertThat(create.source().toBytesArray(), equalTo(B_2));
// add for phase3
ParsedDocument doc3 = testParsedDocument("3", "3", "test", null, -1, -1, testDocumentWithTextField(), Lucene.STANDARD_ANALYZER, B_3, false);
engine.create(new Engine.Create(null, newUid("3"), doc3));
}
@Override
public void phase3(Translog.Snapshot snapshot) throws EngineException {
assertThat(snapshot.hasNext(), equalTo(true));
Translog.Create create = (Translog.Create) snapshot.next();
assertThat(snapshot.hasNext(), equalTo(false));
assertThat(create.source().toBytesArray(), equalTo(B_3));
}
});
engine.flush(new Engine.Flush());
engine.close();
}
@Test
public void testVersioningNewCreate() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Create create = new Engine.Create(null, newUid("1"), doc);
engine.create(create);
assertThat(create.version(), equalTo(1l));
create = new Engine.Create(null, newUid("1"), doc).version(create.version()).origin(REPLICA);
replicaEngine.create(create);
assertThat(create.version(), equalTo(1l));
}
@Test
public void testExternalVersioningNewCreate() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Create create = new Engine.Create(null, newUid("1"), doc).versionType(VersionType.EXTERNAL).version(12);
engine.create(create);
assertThat(create.version(), equalTo(12l));
create = new Engine.Create(null, newUid("1"), doc).version(create.version()).origin(REPLICA);
replicaEngine.create(create);
assertThat(create.version(), equalTo(12l));
}
@Test
public void testVersioningNewIndex() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(1l));
index = new Engine.Index(null, newUid("1"), doc).version(index.version()).origin(REPLICA);
replicaEngine.index(index);
assertThat(index.version(), equalTo(1l));
}
@Test
public void testExternalVersioningNewIndex() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc).versionType(VersionType.EXTERNAL).version(12);
engine.index(index);
assertThat(index.version(), equalTo(12l));
index = new Engine.Index(null, newUid("1"), doc).version(index.version()).origin(REPLICA);
replicaEngine.index(index);
assertThat(index.version(), equalTo(12l));
}
@Test
public void testVersioningIndexConflict() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(1l));
index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(2l));
index = new Engine.Index(null, newUid("1"), doc).version(1l);
try {
engine.index(index);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
// future versions should not work as well
index = new Engine.Index(null, newUid("1"), doc).version(3l);
try {
engine.index(index);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
}
@Test
public void testExternalVersioningIndexConflict() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc).versionType(VersionType.EXTERNAL).version(12);
engine.index(index);
assertThat(index.version(), equalTo(12l));
index = new Engine.Index(null, newUid("1"), doc).versionType(VersionType.EXTERNAL).version(14);
engine.index(index);
assertThat(index.version(), equalTo(14l));
index = new Engine.Index(null, newUid("1"), doc).versionType(VersionType.EXTERNAL).version(13l);
try {
engine.index(index);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
}
@Test
public void testVersioningIndexConflictWithFlush() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(1l));
index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(2l));
engine.flush(new Engine.Flush());
index = new Engine.Index(null, newUid("1"), doc).version(1l);
try {
engine.index(index);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
// future versions should not work as well
index = new Engine.Index(null, newUid("1"), doc).version(3l);
try {
engine.index(index);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
}
@Test
public void testExternalVersioningIndexConflictWithFlush() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc).versionType(VersionType.EXTERNAL).version(12);
engine.index(index);
assertThat(index.version(), equalTo(12l));
index = new Engine.Index(null, newUid("1"), doc).versionType(VersionType.EXTERNAL).version(14);
engine.index(index);
assertThat(index.version(), equalTo(14l));
engine.flush(new Engine.Flush());
index = new Engine.Index(null, newUid("1"), doc).versionType(VersionType.EXTERNAL).version(13);
try {
engine.index(index);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
}
@Test
public void testVersioningDeleteConflict() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(1l));
index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(2l));
Engine.Delete delete = new Engine.Delete("test", "1", newUid("1")).version(1l);
try {
engine.delete(delete);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
// future versions should not work as well
delete = new Engine.Delete("test", "1", newUid("1")).version(3l);
try {
engine.delete(delete);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
// now actually delete
delete = new Engine.Delete("test", "1", newUid("1")).version(2l);
engine.delete(delete);
assertThat(delete.version(), equalTo(3l));
// now check if we can index to a delete doc with version
index = new Engine.Index(null, newUid("1"), doc).version(2l);
try {
engine.index(index);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
// we shouldn't be able to create as well
Engine.Create create = new Engine.Create(null, newUid("1"), doc).version(2l);
try {
engine.create(create);
} catch (VersionConflictEngineException e) {
// all is well
}
}
@Test
public void testVersioningDeleteConflictWithFlush() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(1l));
index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(2l));
engine.flush(new Engine.Flush());
Engine.Delete delete = new Engine.Delete("test", "1", newUid("1")).version(1l);
try {
engine.delete(delete);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
// future versions should not work as well
delete = new Engine.Delete("test", "1", newUid("1")).version(3l);
try {
engine.delete(delete);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
engine.flush(new Engine.Flush());
// now actually delete
delete = new Engine.Delete("test", "1", newUid("1")).version(2l);
engine.delete(delete);
assertThat(delete.version(), equalTo(3l));
engine.flush(new Engine.Flush());
// now check if we can index to a delete doc with version
index = new Engine.Index(null, newUid("1"), doc).version(2l);
try {
engine.index(index);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
// we shouldn't be able to create as well
Engine.Create create = new Engine.Create(null, newUid("1"), doc).version(2l);
try {
engine.create(create);
} catch (VersionConflictEngineException e) {
// all is well
}
}
@Test
public void testVersioningCreateExistsException() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Create create = new Engine.Create(null, newUid("1"), doc);
engine.create(create);
assertThat(create.version(), equalTo(1l));
create = new Engine.Create(null, newUid("1"), doc);
try {
engine.create(create);
fail();
} catch (DocumentAlreadyExistsException e) {
// all is well
}
}
@Test
public void testVersioningCreateExistsExceptionWithFlush() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Create create = new Engine.Create(null, newUid("1"), doc);
engine.create(create);
assertThat(create.version(), equalTo(1l));
engine.flush(new Engine.Flush());
create = new Engine.Create(null, newUid("1"), doc);
try {
engine.create(create);
fail();
} catch (DocumentAlreadyExistsException e) {
// all is well
}
}
@Test
public void testVersioningReplicaConflict1() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(1l));
index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(2l));
// apply the second index to the replica, should work fine
index = new Engine.Index(null, newUid("1"), doc).version(2l).origin(REPLICA);
replicaEngine.index(index);
assertThat(index.version(), equalTo(2l));
// now, the old one should not work
index = new Engine.Index(null, newUid("1"), doc).version(1l).origin(REPLICA);
try {
replicaEngine.index(index);
fail();
} catch (VersionConflictEngineException e) {
// all is well
}
// second version on replica should fail as well
try {
index = new Engine.Index(null, newUid("1"), doc).version(2l).origin(REPLICA);
replicaEngine.index(index);
assertThat(index.version(), equalTo(2l));
} catch (VersionConflictEngineException e) {
// all is well
}
}
@Test
public void testVersioningReplicaConflict2() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(1l));
// apply the first index to the replica, should work fine
index = new Engine.Index(null, newUid("1"), doc).version(1l).origin(REPLICA);
replicaEngine.index(index);
assertThat(index.version(), equalTo(1l));
// index it again
index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertThat(index.version(), equalTo(2l));
// now delete it
Engine.Delete delete = new Engine.Delete("test", "1", newUid("1"));
engine.delete(delete);
assertThat(delete.version(), equalTo(3l));
// apply the delete on the replica (skipping the second index)
delete = new Engine.Delete("test", "1", newUid("1")).version(3l).origin(REPLICA);
replicaEngine.delete(delete);
assertThat(delete.version(), equalTo(3l));
// second time delete with same version should fail
try {
delete = new Engine.Delete("test", "1", newUid("1")).version(3l).origin(REPLICA);
replicaEngine.delete(delete);
assertThat(delete.version(), equalTo(3l));
} catch (VersionConflictEngineException e) {
// all is well
}
// now do the second index on the replica, it should fail
try {
index = new Engine.Index(null, newUid("1"), doc).version(2l).origin(REPLICA);
replicaEngine.index(index);
assertThat(index.version(), equalTo(2l));
} catch (VersionConflictEngineException e) {
// all is well
}
}
@Test
public void testBasicCreatedFlag() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertTrue(index.created());
index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertFalse(index.created());
engine.delete(new Engine.Delete(null, "1", newUid("1")));
index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertTrue(index.created());
}
@Test
public void testCreatedFlagAfterFlush() {
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false);
Engine.Index index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertTrue(index.created());
engine.delete(new Engine.Delete(null, "1", newUid("1")));
engine.flush(new Engine.Flush());
index = new Engine.Index(null, newUid("1"), doc);
engine.index(index);
assertTrue(index.created());
}
protected Term newUid(String id) {
return new Term("_uid", id);
}
} | 0true
| src_test_java_org_elasticsearch_index_engine_internal_InternalEngineTests.java |
1,660 | public final class Priority implements Comparable<Priority> {
public static Priority fromByte(byte b) {
switch (b) {
case 0:
return URGENT;
case 1:
return HIGH;
case 2:
return NORMAL;
case 3:
return LOW;
case 4:
return LANGUID;
default:
throw new ElasticsearchIllegalArgumentException("can't find priority for [" + b + "]");
}
}
public static Priority URGENT = new Priority((byte) 0);
public static Priority HIGH = new Priority((byte) 1);
public static Priority NORMAL = new Priority((byte) 2);
public static Priority LOW = new Priority((byte) 3);
public static Priority LANGUID = new Priority((byte) 4);
private final byte value;
private Priority(byte value) {
this.value = value;
}
public byte value() {
return this.value;
}
public int compareTo(Priority p) {
return this.value - p.value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Priority.class != o.getClass()) return false;
Priority priority = (Priority) o;
if (value != priority.value) return false;
return true;
}
@Override
public int hashCode() {
return (int) value;
}
@Override
public String toString() {
switch (value) {
case (byte) 0:
return "URGENT";
case (byte) 1:
return "HIGH";
case (byte) 2:
return "NORMAL";
case (byte) 3:
return "LOW";
default:
return "LANGUID";
}
}
} | 0true
| src_main_java_org_elasticsearch_common_Priority.java |
1,573 | public static enum Type {
YES,
NO,
THROTTLE
} | 0true
| src_main_java_org_elasticsearch_cluster_routing_allocation_decider_Decision.java |
1,518 | @SuppressWarnings("unchecked")
public class OObjectIteratorCluster<T> implements OObjectIteratorClusterInterface<T> {
private ODatabaseObject database;
private ORecordIteratorCluster<ODocument> underlying;
private String fetchPlan;
public OObjectIteratorCluster(final ODatabaseObject iDatabase, final ODatabaseRecordAbstract iUnderlyingDatabase,
final int iClusterId) {
database = iDatabase;
underlying = new ORecordIteratorCluster<ODocument>((ODatabaseRecord) iDatabase.getUnderlying(), iUnderlyingDatabase,
iClusterId, true);
}
public boolean hasNext() {
return underlying.hasNext();
}
public T next() {
return next(fetchPlan);
}
public T next(final String iFetchPlan) {
return (T) database.getUserObjectByRecord(underlying.next(), iFetchPlan);
}
public void remove() {
underlying.remove();
}
public Iterator<T> iterator() {
return this;
}
public String getFetchPlan() {
return fetchPlan;
}
public OObjectIteratorCluster<T> setFetchPlan(String fetchPlan) {
this.fetchPlan = fetchPlan;
return this;
}
} | 0true
| object_src_main_java_com_orientechnologies_orient_object_iterator_OObjectIteratorCluster.java |
300 | @RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientLockWithTerminationTest {
private HazelcastInstance node1;
private HazelcastInstance node2;
private HazelcastInstance client1;
private HazelcastInstance client2;
private String keyOwnedByNode1;
@Before
public void setup() throws InterruptedException {
node1 = Hazelcast.newHazelcastInstance();
node2 = Hazelcast.newHazelcastInstance();
client1 = HazelcastClient.newHazelcastClient();
client2 = HazelcastClient.newHazelcastClient();
keyOwnedByNode1 = HazelcastTestSupport.generateKeyOwnedBy(node1);
}
@After
public void tearDown() throws IOException {
Hazelcast.shutdownAll();
HazelcastClient.shutdownAll();
}
@Test
public void testLockOnClientCrash() throws InterruptedException {
ILock lock = client1.getLock(keyOwnedByNode1);
lock.lock();
client1.getLifecycleService().terminate();
lock = client2.getLock(keyOwnedByNode1);
boolean lockObtained = lock.tryLock();
assertTrue("Lock was Not Obtained, lock should be released on client crash", lockObtained);
}
@Test
@Category(ProblematicTest.class)
public void testLockOnClient_withNodeCrash() throws InterruptedException {
ILock lock = client1.getLock(keyOwnedByNode1);
lock.lock();
node1.getLifecycleService().terminate();
lock = client2.getLock(keyOwnedByNode1);
boolean lockObtained = lock.tryLock();
assertFalse("Lock was obtained by 2 different clients ", lockObtained);
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_lock_ClientLockWithTerminationTest.java |
33 | @Test
public class OMVRBTreeCompositeTest {
protected OMVRBTree<OCompositeKey, Double> tree;
@BeforeMethod
public void beforeMethod() throws Exception {
tree = new OMVRBTreeMemory<OCompositeKey, Double>(4, 0.5f, 2);
for (double i = 1; i < 4; i++) {
for (double j = 1; j < 10; j++) {
final OCompositeKey compositeKey = new OCompositeKey();
compositeKey.addKey(i);
compositeKey.addKey(j);
tree.put(compositeKey, i * 4 + j);
}
}
}
@Test
public void testGetEntrySameKeys() {
OMVRBTreeEntry<OCompositeKey, Double> result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(result.getKey(), compositeKey(1.0, 2.0));
result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(1.0, 2.0));
result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(1.0, 2.0));
}
@Test
public void testGetEntryPartialKeys() {
OMVRBTreeEntry<OCompositeKey, Double> result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(result.getKey().getKeys().get(0), 2.0);
result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(2.0, 1.0));
result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(result.getKey(), compositeKey(2.0, 9.0));
}
@Test
public void testSubMapInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 9);
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testSubMapNonInclusiveDescending() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 0);
assertTrue(navigableMap.isEmpty());
navigableMap = tree.subMap(compositeKey(1.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testSubMapInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 9);
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testSubMapNonInclusive() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 0);
assertTrue(navigableMap.isEmpty());
navigableMap = tree.subMap(compositeKey(1.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testSubMapInclusivePartialKey() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusivePartialKey() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 6);
for (double j = 4; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusivePartialKey() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), true);
assertEquals(navigableMap.size(), 14);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapNonInclusivePartial() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), false);
assertEquals(navigableMap.size(), 5);
for (double i = 5; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testSubMapInclusivePartialKeyDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapFromInclusivePartialKeyDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 6);
for (double j = 4; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, j)));
}
}
@Test
public void testSubMapToInclusivePartialKeyDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), true)
.descendingMap();
assertEquals(navigableMap.size(), 14);
for (double i = 2; i <= 3; i++) {
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 4)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
}
@Test
public void testSubMapNonInclusivePartialDescending() {
ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), false)
.descendingMap();
assertEquals(navigableMap.size(), 5);
for (double i = 5; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(2.0, i)));
}
}
@Test
public void testTailMapInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), true);
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), false);
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testTailMapInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), true).descendingMap();
assertEquals(navigableMap.size(), 18);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), false).descendingMap();
assertEquals(navigableMap.size(), 9);
for (double i = 1; i <= 9; i++) {
assertTrue(navigableMap.containsKey(compositeKey(3.0, i)));
}
}
@Test
public void testTailMapInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), true);
assertEquals(navigableMap.size(), 16);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), false);
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), true).descendingMap();
assertEquals(navigableMap.size(), 16);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j < 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testTailMapNonInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), false).descendingMap();
assertEquals(navigableMap.size(), 15);
for (double i = 2; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 2 && j <= 3)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), true);
assertEquals(navigableMap.size(), 27);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusivePartial() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), false);
assertEquals(navigableMap.size(), 18);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), true).descendingMap();
assertEquals(navigableMap.size(), 27);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusivePartialDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), false).descendingMap();
assertEquals(navigableMap.size(), 18);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), true);
assertEquals(navigableMap.size(), 20);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j > 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusive() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), false);
assertEquals(navigableMap.size(), 19);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j >= 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), true).descendingMap();
assertEquals(navigableMap.size(), 20);
for (double i = 1; i <= 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j > 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testHeadMapNonInclusiveDescending() {
final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), false).descendingMap();
assertEquals(navigableMap.size(), 19);
for (double i = 1; i < 3; i++)
for (double j = 1; j <= 9; j++) {
if (i == 3 && j >= 2)
continue;
assertTrue(navigableMap.containsKey(compositeKey(i, j)));
}
}
@Test
public void testGetCeilingEntryKeyExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 3.0);
entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(3.0, 9.0));
entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(3.0, 1.0));
}
@Test
public void testGetCeilingEntryKeyNotExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 2.0);
entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 9.0));
entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 1.0));
}
@Test
public void testGetFloorEntryKeyExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 2.0);
entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 9.0));
entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(2.0, 1.0));
}
@Test
public void testGetFloorEntryKeyNotExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.NONE);
assertEquals(entry.getKey().getKeys().get(0), 1.0);
entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(1.0, 9.0));
entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY);
assertEquals(entry.getKey(), compositeKey(1.0, 1.0));
}
@Test
public void testHigherEntryKeyExistPartial() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(2.0));
assertEquals(entry.getKey(), compositeKey(3.0, 1.0));
}
@Test
public void testHigherEntryKeyNotExist() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(1.3));
assertEquals(entry.getKey(), compositeKey(2.0, 1.0));
}
@Test
public void testHigherEntryNullResult() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(12.0));
assertNull(entry);
}
@Test
public void testLowerEntryNullResult() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(0.0));
assertNull(entry);
}
@Test
public void testLowerEntryKeyExist() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(2.0));
assertEquals(entry.getKey(), compositeKey(1.0, 9.0));
}
@Test
public void testLowerEntryKeyNotExist() {
OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(2.5));
assertEquals(entry.getKey(), compositeKey(2.0, 9.0));
}
private OCompositeKey compositeKey(Comparable<?>... params) {
return new OCompositeKey(Arrays.asList(params));
}
} | 0true
| core_src_test_java_com_orientechnologies_common_collection_OMVRBTreeCompositeTest.java |
1,478 | @Component("blChangePasswordValidator")
public class ChangePasswordValidator implements Validator {
public static final String DEFAULT_VALID_PASSWORD_REGEX = "[0-9A-Za-z]{4,15}";
private String validPasswordRegex = DEFAULT_VALID_PASSWORD_REGEX;
@Resource(name = "blCustomerService")
protected CustomerService customerService;
public void validate(PasswordChange passwordChange, Errors errors) {
String currentPassword = passwordChange.getCurrentPassword();
String password = passwordChange.getNewPassword();
String passwordConfirm = passwordChange.getNewPasswordConfirm();
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "currentPassword", "currentPassword.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "newPassword", "newPassword.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "newPasswordConfirm", "newPasswordConfirm.required");
if (!errors.hasErrors()) {
//validate current password
if (!customerService.isPasswordValid(currentPassword, CustomerState.getCustomer().getPassword(), CustomerState.getCustomer())) {
errors.rejectValue("currentPassword", "currentPassword.invalid");
}
//password and confirm password fields must be equal
if (!passwordConfirm.equals(password)) {
errors.rejectValue("newPasswordConfirm", "newPasswordConfirm.invalid");
}
//restrict password characteristics
if (!password.matches(validPasswordRegex)) {
errors.rejectValue("newPassword", "newPassword.invalid");
}
}
}
public String getValidPasswordRegex() {
return validPasswordRegex;
}
public void setValidPasswordRegex(String validPasswordRegex) {
this.validPasswordRegex = validPasswordRegex;
}
@Override
public boolean supports(Class<?> clazz) {
return false;
}
@Override
public void validate(Object target, Errors errors) {
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_account_validator_ChangePasswordValidator.java |
427 | public enum RequiredOverride {
REQUIRED,
NOT_REQUIRED,
IGNORED
} | 0true
| common_src_main_java_org_broadleafcommerce_common_presentation_RequiredOverride.java |
1,190 | @edu.umd.cs.findbugs.annotations.SuppressWarnings("SE_BAD_FIELD")
public class MemberLeftException extends ExecutionException implements DataSerializable, RetryableException {
private Member member;
public MemberLeftException() {
}
public MemberLeftException(Member member) {
this.member = member;
}
/**
* Returns the member which left the cluster
* @return member
*/
public Member getMember() {
return member;
}
public String getMessage() {
return member + " has left cluster!";
}
public void writeData(ObjectDataOutput out) throws IOException {
member.writeData(out);
}
public void readData(ObjectDataInput in) throws IOException {
member = new MemberImpl();
member.readData(in);
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_core_MemberLeftException.java |
1,406 | public static class Request {
final String index;
TimeValue timeout = TimeValue.timeValueSeconds(10);
TimeValue masterTimeout = MasterNodeOperationRequest.DEFAULT_MASTER_NODE_TIMEOUT;
public Request(String index) {
this.index = index;
}
public Request timeout(TimeValue timeout) {
this.timeout = timeout;
return this;
}
public Request masterTimeout(TimeValue masterTimeout) {
this.masterTimeout = masterTimeout;
return this;
}
} | 0true
| src_main_java_org_elasticsearch_cluster_metadata_MetaDataDeleteIndexService.java |
965 | public class OSnappyCompression implements OCompression {
public static final String NAME = "snappy";
public static final OSnappyCompression INSTANCE = new OSnappyCompression();
@Override
public byte[] compress(byte[] content) {
return Snappy.compress(content);
}
@Override
public byte[] uncompress(byte[] content) {
return Snappy.uncompress(content, 0, content.length);
}
@Override
public String name() {
return NAME;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_serialization_compression_impl_OSnappyCompression.java |
794 | private static class AddOneFunction implements IFunction<Long, Long> {
@Override
public Long apply(Long input) {
return input+1;
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_concurrent_atomiclong_AtomicLongTest.java |
335 | public interface WriteConfiguration extends ReadConfiguration {
public<O> void set(String key, O value);
public void remove(String key);
public WriteConfiguration copy();
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_WriteConfiguration.java |
399 | public class CreateSnapshotRequest extends MasterNodeOperationRequest<CreateSnapshotRequest> {
private String snapshot;
private String repository;
private String[] indices = EMPTY_ARRAY;
private IndicesOptions indicesOptions = IndicesOptions.strict();
private boolean partial = false;
private Settings settings = EMPTY_SETTINGS;
private boolean includeGlobalState = true;
private boolean waitForCompletion;
CreateSnapshotRequest() {
}
/**
* Constructs a new put repository request with the provided snapshot and repository names
*
* @param repository repository name
* @param snapshot snapshot name
*/
public CreateSnapshotRequest(String repository, String snapshot) {
this.snapshot = snapshot;
this.repository = repository;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (snapshot == null) {
validationException = addValidationError("snapshot is missing", validationException);
}
if (repository == null) {
validationException = addValidationError("repository is missing", validationException);
}
if (indices == null) {
validationException = addValidationError("indices is null", validationException);
}
for (String index : indices) {
if (index == null) {
validationException = addValidationError("index is null", validationException);
break;
}
}
if (indicesOptions == null) {
validationException = addValidationError("indicesOptions is null", validationException);
}
if (settings == null) {
validationException = addValidationError("settings is null", validationException);
}
return validationException;
}
/**
* Sets the snapshot name
*
* @param snapshot snapshot name
*/
public CreateSnapshotRequest snapshot(String snapshot) {
this.snapshot = snapshot;
return this;
}
/**
* The snapshot name
*
* @return snapshot name
*/
public String snapshot() {
return this.snapshot;
}
/**
* Sets repository name
*
* @param repository name
* @return this request
*/
public CreateSnapshotRequest repository(String repository) {
this.repository = repository;
return this;
}
/**
* Returns repository name
*
* @return repository name
*/
public String repository() {
return this.repository;
}
/**
* Sets a list of indices that should be included into the snapshot
* <p/>
* The list of indices supports multi-index syntax. For example: "+test*" ,"-test42" will index all indices with
* prefix "test" except index "test42". Aliases are supported. An empty list or {"_all"} will snapshot all open
* indices in the cluster.
*
* @param indices
* @return this request
*/
public CreateSnapshotRequest indices(String... indices) {
this.indices = indices;
return this;
}
/**
* Sets a list of indices that should be included into the snapshot
* <p/>
* The list of indices supports multi-index syntax. For example: "+test*" ,"-test42" will index all indices with
* prefix "test" except index "test42". Aliases are supported. An empty list or {"_all"} will snapshot all open
* indices in the cluster.
*
* @param indices
* @return this request
*/
public CreateSnapshotRequest indices(List<String> indices) {
this.indices = indices.toArray(new String[indices.size()]);
return this;
}
/**
* Returns a list of indices that should be included into the snapshot
*
* @return list of indices
*/
public String[] indices() {
return indices;
}
/**
* Specifies the indices options. Like what type of requested indices to ignore. For example indices that don't exist.
*
* @return the desired behaviour regarding indices options
*/
public IndicesOptions indicesOptions() {
return indicesOptions;
}
/**
* Specifies the indices options. Like what type of requested indices to ignore. For example indices that don't exist.
*
* @param indicesOptions the desired behaviour regarding indices options
* @return this request
*/
public CreateSnapshotRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
/**
* Returns true if indices with unavailable shards should be be partially snapshotted.
*
* @return the desired behaviour regarding indices options
*/
public boolean partial() {
return partial;
}
/**
* Set to true to allow indices with unavailable shards to be partially snapshotted.
*
* @param partial true if indices with unavailable shards should be be partially snapshotted.
* @return this request
*/
public CreateSnapshotRequest partial(boolean partial) {
this.partial = partial;
return this;
}
/**
* If set to true the request should wait for the snapshot completion before returning.
*
* @param waitForCompletion true if
* @return this request
*/
public CreateSnapshotRequest waitForCompletion(boolean waitForCompletion) {
this.waitForCompletion = waitForCompletion;
return this;
}
/**
* Returns true if the request should wait for the snapshot completion before returning
*
* @return true if the request should wait for completion
*/
public boolean waitForCompletion() {
return waitForCompletion;
}
/**
* Sets repository-specific snapshot settings.
* <p/>
* See repository documentation for more information.
*
* @param settings repository-specific snapshot settings
* @return this request
*/
public CreateSnapshotRequest settings(Settings settings) {
this.settings = settings;
return this;
}
/**
* Sets repository-specific snapshot settings.
* <p/>
* See repository documentation for more information.
*
* @param settings repository-specific snapshot settings
* @return this request
*/
public CreateSnapshotRequest settings(Settings.Builder settings) {
this.settings = settings.build();
return this;
}
/**
* Sets repository-specific snapshot settings in JSON, YAML or properties format
* <p/>
* See repository documentation for more information.
*
* @param source repository-specific snapshot settings
* @return this request
*/
public CreateSnapshotRequest settings(String source) {
this.settings = ImmutableSettings.settingsBuilder().loadFromSource(source).build();
return this;
}
/**
* Sets repository-specific snapshot settings.
* <p/>
* See repository documentation for more information.
*
* @param source repository-specific snapshot settings
* @return this request
*/
public CreateSnapshotRequest settings(Map<String, Object> source) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.map(source);
settings(builder.string());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
}
return this;
}
/**
* Returns repository-specific snapshot settings
*
* @return repository-specific snapshot settings
*/
public Settings settings() {
return this.settings;
}
/**
* Set to true if global state should be stored as part of the snapshot
*
* @param includeGlobalState true if global state should be stored
* @return this request
*/
public CreateSnapshotRequest includeGlobalState(boolean includeGlobalState) {
this.includeGlobalState = includeGlobalState;
return this;
}
/**
* Returns true if global state should be stored as part of the snapshot
*
* @return true if global state should be stored as part of the snapshot
*/
public boolean includeGlobalState() {
return includeGlobalState;
}
/**
* Parses snapshot definition.
*
* @param source snapshot definition
* @return this request
*/
public CreateSnapshotRequest source(XContentBuilder source) {
return source(source.bytes());
}
/**
* Parses snapshot definition.
*
* @param source snapshot definition
* @return this request
*/
public CreateSnapshotRequest source(Map source) {
boolean ignoreUnavailable = IndicesOptions.lenient().ignoreUnavailable();
boolean allowNoIndices = IndicesOptions.lenient().allowNoIndices();
boolean expandWildcardsOpen = IndicesOptions.lenient().expandWildcardsOpen();
boolean expandWildcardsClosed = IndicesOptions.lenient().expandWildcardsClosed();
for (Map.Entry<String, Object> entry : ((Map<String, Object>) source).entrySet()) {
String name = entry.getKey();
if (name.equals("indices")) {
if (entry.getValue() instanceof String) {
indices(Strings.splitStringByCommaToArray((String) entry.getValue()));
} else if (entry.getValue() instanceof ArrayList) {
indices((ArrayList<String>) entry.getValue());
} else {
throw new ElasticsearchIllegalArgumentException("malformed indices section, should be an array of strings");
}
} else if (name.equals("ignore_unavailable") || name.equals("ignoreUnavailable")) {
ignoreUnavailable = nodeBooleanValue(entry.getValue());
} else if (name.equals("allow_no_indices") || name.equals("allowNoIndices")) {
allowNoIndices = nodeBooleanValue(entry.getValue());
} else if (name.equals("expand_wildcards_open") || name.equals("expandWildcardsOpen")) {
expandWildcardsOpen = nodeBooleanValue(entry.getValue());
} else if (name.equals("expand_wildcards_closed") || name.equals("expandWildcardsClosed")) {
expandWildcardsClosed = nodeBooleanValue(entry.getValue());
} else if (name.equals("partial")) {
partial(nodeBooleanValue(entry.getValue()));
} else if (name.equals("settings")) {
if (!(entry.getValue() instanceof Map)) {
throw new ElasticsearchIllegalArgumentException("malformed settings section, should indices an inner object");
}
settings((Map<String, Object>) entry.getValue());
} else if (name.equals("include_global_state")) {
includeGlobalState = nodeBooleanValue(entry.getValue());
}
}
indicesOptions(IndicesOptions.fromOptions(ignoreUnavailable, allowNoIndices, expandWildcardsOpen, expandWildcardsClosed));
return this;
}
/**
* Parses snapshot definition. JSON, YAML and properties formats are supported
*
* @param source snapshot definition
* @return this request
*/
public CreateSnapshotRequest source(String source) {
if (hasLength(source)) {
try {
return source(XContentFactory.xContent(source).createParser(source).mapOrderedAndClose());
} catch (Exception e) {
throw new ElasticsearchIllegalArgumentException("failed to parse repository source [" + source + "]", e);
}
}
return this;
}
/**
* Parses snapshot definition. JSON, YAML and properties formats are supported
*
* @param source snapshot definition
* @return this request
*/
public CreateSnapshotRequest source(byte[] source) {
return source(source, 0, source.length);
}
/**
* Parses snapshot definition. JSON, YAML and properties formats are supported
*
* @param source snapshot definition
* @param offset offset
* @param length length
* @return this request
*/
public CreateSnapshotRequest source(byte[] source, int offset, int length) {
if (length > 0) {
try {
return source(XContentFactory.xContent(source, offset, length).createParser(source, offset, length).mapOrderedAndClose());
} catch (IOException e) {
throw new ElasticsearchIllegalArgumentException("failed to parse repository source", e);
}
}
return this;
}
/**
* Parses snapshot definition. JSON, YAML and properties formats are supported
*
* @param source snapshot definition
* @return this request
*/
public CreateSnapshotRequest source(BytesReference source) {
try {
return source(XContentFactory.xContent(source).createParser(source).mapOrderedAndClose());
} catch (IOException e) {
throw new ElasticsearchIllegalArgumentException("failed to parse snapshot source", e);
}
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
snapshot = in.readString();
repository = in.readString();
indices = in.readStringArray();
indicesOptions = IndicesOptions.readIndicesOptions(in);
settings = readSettingsFromStream(in);
includeGlobalState = in.readBoolean();
waitForCompletion = in.readBoolean();
partial = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(snapshot);
out.writeString(repository);
out.writeStringArray(indices);
indicesOptions.writeIndicesOptions(out);
writeSettingsToStream(settings, out);
out.writeBoolean(includeGlobalState);
out.writeBoolean(waitForCompletion);
out.writeBoolean(partial);
}
} | 1no label
| src_main_java_org_elasticsearch_action_admin_cluster_snapshots_create_CreateSnapshotRequest.java |
2,376 | public class Percent implements Streamable, Serializable {
private double value;
public Percent(double value) {
this.value = value;
}
public double value() {
return value;
}
public String toString() {
return format(value);
}
public static String format(double value) {
String p = String.valueOf(value * 100.0);
int ix = p.indexOf(".") + 1;
return p.substring(0, ix) + p.substring(ix, ix + 1) + "%";
}
@Override
public void readFrom(StreamInput in) throws IOException {
value = in.readDouble();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeDouble(value);
}
} | 0true
| src_main_java_org_elasticsearch_common_unit_Percent.java |
162 | @Test
public class StringSerializerTest {
private int FIELD_SIZE;
private String OBJECT;
private OStringSerializer stringSerializer;
byte[] stream;
@BeforeClass
public void beforeClass() {
stringSerializer = new OStringSerializer();
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < random.nextInt(20) + 5; i++) {
sb.append((char) random.nextInt());
}
OBJECT = sb.toString();
FIELD_SIZE = OBJECT.length() * 2 + 4 + 7;
stream = new byte[FIELD_SIZE];
}
public void testFieldSize() {
Assert.assertEquals(stringSerializer.getObjectSize(OBJECT), FIELD_SIZE - 7);
}
public void testSerialize() {
stringSerializer.serialize(OBJECT, stream, 7);
Assert.assertEquals(stringSerializer.deserialize(stream, 7), OBJECT);
}
public void testSerializeNative() {
stringSerializer.serializeNative(OBJECT, stream, 7);
Assert.assertEquals(stringSerializer.deserializeNative(stream, 7), OBJECT);
}
public void testNativeDirectMemoryCompatibility() {
stringSerializer.serializeNative(OBJECT, stream, 7);
ODirectMemoryPointer pointer = new ODirectMemoryPointer(stream);
try {
Assert.assertEquals(stringSerializer.deserializeFromDirectMemory(pointer, 7), OBJECT);
} finally {
pointer.free();
}
}
} | 0true
| commons_src_test_java_com_orientechnologies_common_serialization_types_StringSerializerTest.java |
1,136 | public class PriceOrderIfNecessaryActivity extends BaseActivity<CartOperationContext> {
@Resource(name = "blOrderService")
protected OrderService orderService;
@Override
public CartOperationContext execute(CartOperationContext context) throws Exception {
CartOperationRequest request = context.getSeedData();
Order order = request.getOrder();
order = orderService.save(order, request.isPriceOrder());
request.setOrder(order);
return context;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_workflow_PriceOrderIfNecessaryActivity.java |
552 | public class UrlUtil {
public static String generateUrlKey(String toConvert) {
if (toConvert.matches(".*?\\W.*?")) {
//remove all non-word characters
String result = toConvert.replaceAll("\\W","");
//uncapitalizes the first letter of the url key
return StringUtils.uncapitalize(result);
} else {
return StringUtils.uncapitalize(toConvert);
}
}
/**
* If the url does not include "//" then the system will ensure that the
* application context is added to the start of the URL.
*
* @param url
* @return
*/
public static String fixRedirectUrl(String contextPath, String url) {
if (url.indexOf("//") < 0) {
if (contextPath != null && (!"".equals(contextPath))) {
if (!url.startsWith("/")) {
url = "/" + url;
}
if (!url.startsWith(contextPath)) {
url = contextPath + url;
}
}
}
return url;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_util_UrlUtil.java |
1,204 | longLongMap = build(type, limit, smartSize, availableProcessors, new Recycler.C<LongLongOpenHashMap>() {
@Override
public LongLongOpenHashMap newInstance(int sizing) {
return new LongLongOpenHashMap(size(sizing));
}
@Override
public void clear(LongLongOpenHashMap value) {
value.clear();
}
}); | 0true
| src_main_java_org_elasticsearch_cache_recycler_CacheRecycler.java |
530 | final PortableFactory factory = new PortableFactory() {
public Portable create(int classId) {
switch (classId) {
case CREATE:
return new CreateTransactionRequest();
case COMMIT:
return new CommitTransactionRequest();
case ROLLBACK:
return new RollbackTransactionRequest();
case PREPARE:
return new PrepareTransactionRequest();
case RECOVER_ALL:
return new RecoverAllTransactionsRequest();
case RECOVER:
return new RecoverTransactionRequest();
default:
return null;
}
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_client_txn_ClientTxnPortableHook.java |
1,191 | public interface PaymentContext {
/**
* @deprecated
* @see #getTransactionAmount()
*/
public Money getOriginalPaymentAmount();
/**
* @deprecated
* @see #getRemainingTransactionAmount()
*/
public Money getRemainingPaymentAmount();
/**
* The amount that the system should attempt to process. For example, when submitting an order, this would be the order.getTotal.
* If refunding $10, this would be 10.
*
* @return
*/
public Money getTransactionAmount();
/**
* Sets the transaction amount
*
* @param amount
*/
public void setTransactionAmount(Money amount);
/**
* Returns the remaining transaction amount that needs to be processed. When using multiple forms of payment, each payment module will
* attempt to perform the operation if they are able to up to this amount.
*
* @return
*/
public Money getRemainingTransactionAmount();
/**
* Sets the remaining transaction amount.
*
* @param amount
*/
public void setRemainingTransactionAmount(Money amount);
public PaymentInfo getPaymentInfo();
public Referenced getReferencedPaymentInfo();
public String getTransactionId();
public void setTransactionId(String transactionId);
public String getUserName() ;
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_PaymentContext.java |
149 | public class OByteSerializer implements OBinarySerializer<Byte> {
/**
* size of byte value in bytes
*/
public static final int BYTE_SIZE = 1;
public static OByteSerializer INSTANCE = new OByteSerializer();
public static final byte ID = 2;
public int getObjectSize(Byte object, Object... hints) {
return BYTE_SIZE;
}
public void serialize(Byte object, byte[] stream, int startPosition, Object... hints) {
stream[startPosition] = object;
}
public Byte deserialize(byte[] stream, int startPosition) {
return stream[startPosition];
}
public int getObjectSize(byte[] stream, int startPosition) {
return BYTE_SIZE;
}
public byte getId() {
return ID;
}
public int getObjectSizeNative(byte[] stream, int startPosition) {
return getObjectSize(stream, startPosition);
}
public void serializeNative(Byte object, byte[] stream, int startPosition, Object... hints) {
serialize(object, stream, startPosition);
}
public Byte deserializeNative(byte[] stream, int startPosition) {
return deserialize(stream, startPosition);
}
@Override
public void serializeInDirectMemory(Byte object, ODirectMemoryPointer pointer, long offset, Object... hints) {
pointer.setByte(offset, object);
}
@Override
public Byte deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) {
return pointer.getByte(offset);
}
@Override
public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) {
return BYTE_SIZE;
}
public boolean isFixedLength() {
return true;
}
public int getFixedLength() {
return BYTE_SIZE;
}
@Override
public Byte preprocess(Byte value, Object... hints) {
return value;
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_serialization_types_OByteSerializer.java |
79 | EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
return true;
}
@Override
public boolean isValidCondition(Object condition) {
return true;
}
@Override
public boolean evaluate(Object value, Object condition) {
if (condition==null) {
return value==null;
} else {
return condition.equals(value);
}
}
@Override
public String toString() {
return "=";
}
@Override
public TitanPredicate negate() {
return NOT_EQUAL;
}
}, | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java |
1,519 | public final class OutOfMemoryErrorDispatcher {
private static final int MAX_REGISTERED_INSTANCES = 50;
private static final HazelcastInstance[] EMPTY_INSTANCES = new HazelcastInstance[0];
private static final AtomicReference<HazelcastInstance[]> INSTANCES_REF =
new AtomicReference<HazelcastInstance[]>(EMPTY_INSTANCES);
private static volatile OutOfMemoryHandler handler = new DefaultOutOfMemoryHandler();
private static volatile OutOfMemoryHandler clientHandler;
private OutOfMemoryErrorDispatcher() {
}
//for testing only
static HazelcastInstance[] current() {
return INSTANCES_REF.get();
}
public static void setHandler(OutOfMemoryHandler outOfMemoryHandler) {
handler = outOfMemoryHandler;
}
public static void setClientHandler(OutOfMemoryHandler outOfMemoryHandler) {
clientHandler = outOfMemoryHandler;
}
public static void register(HazelcastInstance instance) {
isNotNull(instance, "instance");
for (;;) {
HazelcastInstance[] oldInstances = INSTANCES_REF.get();
if (oldInstances.length == MAX_REGISTERED_INSTANCES) {
return;
}
HazelcastInstance[] newInstances = new HazelcastInstance[oldInstances.length + 1];
arraycopy(oldInstances, 0, newInstances, 0, oldInstances.length);
newInstances[oldInstances.length] = instance;
if (INSTANCES_REF.compareAndSet(oldInstances, newInstances)) {
return;
}
}
}
public static void deregister(HazelcastInstance instance) {
isNotNull(instance, "instance");
for (;;) {
HazelcastInstance[] oldInstances = INSTANCES_REF.get();
int indexOf = indexOf(oldInstances, instance);
if (indexOf == -1) {
return;
}
HazelcastInstance[] newInstances;
if (oldInstances.length == 1) {
newInstances = EMPTY_INSTANCES;
} else {
newInstances = new HazelcastInstance[oldInstances.length - 1];
arraycopy(oldInstances, 0, newInstances, 0, indexOf);
if (indexOf < newInstances.length) {
arraycopy(oldInstances, indexOf + 1, newInstances, indexOf, newInstances.length - indexOf);
}
}
if (INSTANCES_REF.compareAndSet(oldInstances, newInstances)) {
return;
}
}
}
private static int indexOf(HazelcastInstance[] instances, HazelcastInstance instance) {
for (int k = 0; k < instances.length; k++) {
if (instance == instances[k]) {
return k;
}
}
return -1;
}
static void clear() {
INSTANCES_REF.set(EMPTY_INSTANCES);
}
public static void inspectOutputMemoryError(Throwable throwable) {
if (throwable == null) {
return;
}
if (throwable instanceof OutOfMemoryError) {
onOutOfMemory((OutOfMemoryError) throwable);
}
}
/**
* Signals the OutOfMemoryErrorDispatcher that an OutOfMemoryError happened.
* <p/>
* If there are any registered instances, they are automatically unregistered. This is done to prevent creating
* new objects during the deregistration process while the system is suffering from a shortage of memory.
*
* @param outOfMemoryError the out of memory error
*/
public static void onOutOfMemory(OutOfMemoryError outOfMemoryError) {
isNotNull(outOfMemoryError, "outOfMemoryError");
HazelcastInstance[] instances = removeRegisteredInstances();
if (instances.length == 0) {
return;
}
OutOfMemoryHandler h = clientHandler;
if (h != null) {
try {
h.onOutOfMemory(outOfMemoryError, instances);
} catch (Throwable ignored) {
}
}
h = handler;
if (h != null) {
try {
h.onOutOfMemory(outOfMemoryError, instances);
} catch (Throwable ignored) {
}
}
}
private static HazelcastInstance[] removeRegisteredInstances() {
for (;;) {
HazelcastInstance[] instances = INSTANCES_REF.get();
if (INSTANCES_REF.compareAndSet(instances, EMPTY_INSTANCES)) {
return instances;
}
}
}
private static class DefaultOutOfMemoryHandler extends OutOfMemoryHandler {
@Override
public void onOutOfMemory(OutOfMemoryError oom, HazelcastInstance[] hazelcastInstances) {
for (HazelcastInstance instance : hazelcastInstances) {
if (instance instanceof HazelcastInstanceImpl) {
Helper.tryCloseConnections(instance);
Helper.tryStopThreads(instance);
Helper.tryShutdown(instance);
}
}
System.err.println(oom);
}
}
public static final class Helper {
private Helper() {
}
public static void tryCloseConnections(HazelcastInstance hazelcastInstance) {
if (hazelcastInstance == null) {
return;
}
HazelcastInstanceImpl factory = (HazelcastInstanceImpl) hazelcastInstance;
closeSockets(factory);
}
private static void closeSockets(HazelcastInstanceImpl factory) {
if (factory.node.connectionManager != null) {
try {
factory.node.connectionManager.shutdown();
} catch (Throwable ignored) {
}
}
}
public static void tryShutdown(HazelcastInstance hazelcastInstance) {
if (hazelcastInstance == null) {
return;
}
HazelcastInstanceImpl factory = (HazelcastInstanceImpl) hazelcastInstance;
closeSockets(factory);
try {
factory.node.shutdown(true);
} catch (Throwable ignored) {
}
}
public static void inactivate(HazelcastInstance hazelcastInstance) {
if (hazelcastInstance == null) {
return;
}
final HazelcastInstanceImpl factory = (HazelcastInstanceImpl) hazelcastInstance;
factory.node.inactivate();
}
public static void tryStopThreads(HazelcastInstance hazelcastInstance) {
if (hazelcastInstance == null) {
return;
}
HazelcastInstanceImpl factory = (HazelcastInstanceImpl) hazelcastInstance;
try {
factory.node.threadGroup.interrupt();
} catch (Throwable ignored) {
}
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_instance_OutOfMemoryErrorDispatcher.java |
2,007 | @Retention(RUNTIME)
@BindingAnnotation
@interface Element {
String setName();
int uniqueId();
} | 0true
| src_main_java_org_elasticsearch_common_inject_multibindings_Element.java |
1,320 | assertThat(awaitBusy(new Predicate<Object>() {
public boolean apply(Object obj) {
ClusterState state = client().admin().cluster().prepareState().setLocal(true).execute().actionGet().getState();
return state.blocks().hasGlobalBlock(Discovery.NO_MASTER_BLOCK);
}
}), equalTo(true)); | 0true
| src_test_java_org_elasticsearch_cluster_MinimumMasterNodesTests.java |
1,331 | public interface TimeoutClusterStateUpdateTask extends ProcessedClusterStateUpdateTask {
/**
* If the cluster state update task wasn't processed by the provided timeout, call
* {@link #onFailure(String, Throwable)}
*/
TimeValue timeout();
} | 0true
| src_main_java_org_elasticsearch_cluster_TimeoutClusterStateUpdateTask.java |
3,651 | public class AllFieldMapper extends AbstractFieldMapper<Void> implements InternalMapper, RootMapper {
public interface IncludeInAll extends Mapper {
void includeInAll(Boolean includeInAll);
void includeInAllIfNotSet(Boolean includeInAll);
void unsetIncludeInAll();
}
public static final String NAME = "_all";
public static final String CONTENT_TYPE = "_all";
public static class Defaults extends AbstractFieldMapper.Defaults {
public static final String NAME = AllFieldMapper.NAME;
public static final String INDEX_NAME = AllFieldMapper.NAME;
public static final boolean ENABLED = true;
public static final FieldType FIELD_TYPE = new FieldType();
static {
FIELD_TYPE.setIndexed(true);
FIELD_TYPE.setTokenized(true);
FIELD_TYPE.freeze();
}
}
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());
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
AllFieldMapper.Builder builder = all();
parseField(builder, builder.name, node, parserContext);
for (Map.Entry<String, Object> entry : node.entrySet()) {
String fieldName = Strings.toUnderscoreCase(entry.getKey());
Object fieldNode = entry.getValue();
if (fieldName.equals("enabled")) {
builder.enabled(nodeBooleanValue(fieldNode));
} else if (fieldName.equals("auto_boost")) {
builder.autoBoost = nodeBooleanValue(fieldNode);
}
}
return builder;
}
}
private boolean enabled;
// The autoBoost flag is automatically set based on indexed docs on the mappings
// if a doc is indexed with a specific boost value and part of _all, it is automatically
// set to true. This allows to optimize (automatically, which we like) for the common case
// where fields don't usually have boost associated with them, and we don't need to use the
// special SpanTermQuery to look at payloads
private volatile boolean autoBoost;
public AllFieldMapper() {
this(Defaults.NAME, new FieldType(Defaults.FIELD_TYPE), null, null, Defaults.ENABLED, false, null, null, null, null, null, ImmutableSettings.EMPTY);
}
protected AllFieldMapper(String name, FieldType fieldType, NamedAnalyzer indexAnalyzer, NamedAnalyzer searchAnalyzer,
boolean enabled, boolean autoBoost, PostingsFormatProvider postingsProvider,
DocValuesFormatProvider docValuesProvider, SimilarityProvider similarity, Loading normsLoading,
@Nullable Settings fieldDataSettings, Settings indexSettings) {
super(new Names(name, name, name, name), 1.0f, fieldType, null, indexAnalyzer, searchAnalyzer, postingsProvider, docValuesProvider,
similarity, normsLoading, fieldDataSettings, indexSettings);
this.enabled = enabled;
this.autoBoost = autoBoost;
}
public boolean enabled() {
return this.enabled;
}
@Override
public FieldType defaultFieldType() {
return Defaults.FIELD_TYPE;
}
@Override
public FieldDataType defaultFieldDataType() {
return new FieldDataType("string");
}
@Override
public Query queryStringTermQuery(Term term) {
if (!autoBoost) {
return new TermQuery(term);
}
if (fieldType.indexOptions() == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) {
return new AllTermQuery(term);
}
return new TermQuery(term);
}
@Override
public Query termQuery(Object value, QueryParseContext context) {
return queryStringTermQuery(names().createIndexNameTerm(indexedValueForSearch(value)));
}
@Override
public void preParse(ParseContext context) throws IOException {
}
@Override
public void postParse(ParseContext context) throws IOException {
super.parse(context);
}
@Override
public void parse(ParseContext context) throws IOException {
// we parse in post parse
}
@Override
public void validate(ParseContext context) throws MapperParsingException {
}
@Override
public boolean includeInObject() {
return true;
}
@Override
protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException {
if (!enabled) {
return;
}
// reset the entries
context.allEntries().reset();
// if the autoBoost flag is not set, and we indexed a doc with custom boost, make
// sure to update the flag, and notify mappings on change
if (!autoBoost && context.allEntries().customBoost()) {
autoBoost = true;
context.setMappingsModified();
}
Analyzer analyzer = findAnalyzer(context);
fields.add(new AllField(names.indexName(), context.allEntries(), analyzer, fieldType));
}
private Analyzer findAnalyzer(ParseContext context) {
Analyzer analyzer = indexAnalyzer;
if (analyzer == null) {
analyzer = context.analyzer();
if (analyzer == null) {
analyzer = context.docMapper().indexAnalyzer();
if (analyzer == null) {
// This should not happen, should we log warn it?
analyzer = Lucene.STANDARD_ANALYZER;
}
}
}
return analyzer;
}
@Override
public Void value(Object value) {
return null;
}
@Override
public Object valueForSearch(Object value) {
return null;
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
boolean includeDefaults = params.paramAsBoolean("include_defaults", false);
if (!includeDefaults) {
// simulate the generation to make sure we don't add unnecessary content if all is default
// if all are defaults, no need to write it at all - generating is twice is ok though
BytesStreamOutput bytesStreamOutput = new BytesStreamOutput(0);
XContentBuilder b = new XContentBuilder(builder.contentType().xContent(), bytesStreamOutput);
long pos = bytesStreamOutput.position();
innerToXContent(b, false);
b.flush();
if (pos == bytesStreamOutput.position()) {
return builder;
}
}
builder.startObject(CONTENT_TYPE);
innerToXContent(builder, includeDefaults);
builder.endObject();
return builder;
}
private void innerToXContent(XContentBuilder builder, boolean includeDefaults) throws IOException {
if (includeDefaults || enabled != Defaults.ENABLED) {
builder.field("enabled", enabled);
}
if (includeDefaults || autoBoost != false) {
builder.field("auto_boost", autoBoost);
}
if (includeDefaults || fieldType.stored() != Defaults.FIELD_TYPE.stored()) {
builder.field("store", fieldType.stored());
}
if (includeDefaults || fieldType.storeTermVectors() != Defaults.FIELD_TYPE.storeTermVectors()) {
builder.field("store_term_vectors", fieldType.storeTermVectors());
}
if (includeDefaults || fieldType.storeTermVectorOffsets() != Defaults.FIELD_TYPE.storeTermVectorOffsets()) {
builder.field("store_term_vector_offsets", fieldType.storeTermVectorOffsets());
}
if (includeDefaults || fieldType.storeTermVectorPositions() != Defaults.FIELD_TYPE.storeTermVectorPositions()) {
builder.field("store_term_vector_positions", fieldType.storeTermVectorPositions());
}
if (includeDefaults || fieldType.storeTermVectorPayloads() != Defaults.FIELD_TYPE.storeTermVectorPayloads()) {
builder.field("store_term_vector_payloads", fieldType.storeTermVectorPayloads());
}
if (includeDefaults || fieldType.omitNorms() != Defaults.FIELD_TYPE.omitNorms()) {
builder.field("omit_norms", fieldType.omitNorms());
}
if (indexAnalyzer == null && searchAnalyzer == null) {
if (includeDefaults) {
builder.field("analyzer", "default");
}
} else if (indexAnalyzer == null) {
// searchAnalyzer != null
if (includeDefaults || !searchAnalyzer.name().startsWith("_")) {
builder.field("search_analyzer", searchAnalyzer.name());
}
} else if (searchAnalyzer == null) {
// indexAnalyzer != null
if (includeDefaults || !indexAnalyzer.name().startsWith("_")) {
builder.field("index_analyzer", indexAnalyzer.name());
}
} else if (indexAnalyzer.name().equals(searchAnalyzer.name())) {
// indexAnalyzer == searchAnalyzer
if (includeDefaults || !indexAnalyzer.name().startsWith("_")) {
builder.field("analyzer", indexAnalyzer.name());
}
} else {
// both are there but different
if (includeDefaults || !indexAnalyzer.name().startsWith("_")) {
builder.field("index_analyzer", indexAnalyzer.name());
}
if (includeDefaults || !searchAnalyzer.name().startsWith("_")) {
builder.field("search_analyzer", searchAnalyzer.name());
}
}
if (similarity() != null) {
builder.field("similarity", similarity().name());
} else if (includeDefaults) {
builder.field("similarity", SimilarityLookupService.DEFAULT_SIMILARITY);
}
if (customFieldDataSettings != null) {
builder.field("fielddata", (Map) customFieldDataSettings.getAsMap());
} else if (includeDefaults) {
builder.field("fielddata", (Map) fieldDataType.getSettings().getAsMap());
}
}
@Override
public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
// do nothing here, no merging, but also no exception
}
@Override
public boolean hasDocValues() {
return false;
}
} | 1no label
| src_main_java_org_elasticsearch_index_mapper_internal_AllFieldMapper.java |
394 | public class ClientNearCache<K> {
public static final Object NULL_OBJECT = new Object();
public static final int EVICTION_PERCENTAGE = 20;
public static final int TTL_CLEANUP_INTERVAL_MILLS = 5000;
String registrationId;
final ClientNearCacheType cacheType;
final int maxSize;
volatile long lastCleanup;
final long maxIdleMillis;
final long timeToLiveMillis;
final boolean invalidateOnChange;
final EvictionPolicy evictionPolicy;
final InMemoryFormat inMemoryFormat;
final String mapName;
final ClientContext context;
final AtomicBoolean canCleanUp;
final AtomicBoolean canEvict;
final ConcurrentMap<K, CacheRecord<K>> cache;
final NearCacheStatsImpl clientNearCacheStats;
private final Comparator<CacheRecord<K>> comparator = new Comparator<CacheRecord<K>>() {
public int compare(CacheRecord<K> o1, CacheRecord<K> o2) {
if (EvictionPolicy.LRU.equals(evictionPolicy)) {
return ((Long) o1.lastAccessTime).compareTo((o2.lastAccessTime));
} else if (EvictionPolicy.LFU.equals(evictionPolicy)) {
return ((Integer) o1.hit.get()).compareTo((o2.hit.get()));
}
return 0;
}
};
public ClientNearCache(String mapName, ClientNearCacheType cacheType,
ClientContext context, NearCacheConfig nearCacheConfig) {
this.mapName = mapName;
this.cacheType = cacheType;
this.context = context;
maxSize = nearCacheConfig.getMaxSize();
maxIdleMillis = nearCacheConfig.getMaxIdleSeconds() * 1000;
inMemoryFormat = nearCacheConfig.getInMemoryFormat();
timeToLiveMillis = nearCacheConfig.getTimeToLiveSeconds() * 1000;
invalidateOnChange = nearCacheConfig.isInvalidateOnChange();
evictionPolicy = EvictionPolicy.valueOf(nearCacheConfig.getEvictionPolicy());
cache = new ConcurrentHashMap<K, CacheRecord<K>>();
canCleanUp = new AtomicBoolean(true);
canEvict = new AtomicBoolean(true);
lastCleanup = Clock.currentTimeMillis();
clientNearCacheStats = new NearCacheStatsImpl();
if (invalidateOnChange) {
addInvalidateListener();
}
}
private void addInvalidateListener() {
try {
ClientRequest request;
EventHandler handler;
if (cacheType == ClientNearCacheType.Map) {
request = new MapAddEntryListenerRequest(mapName, false);
handler = new EventHandler<PortableEntryEvent>() {
public void handle(PortableEntryEvent event) {
cache.remove(event.getKey());
}
@Override
public void onListenerRegister() {
cache.clear();
}
};
} else {
throw new IllegalStateException("Near cache is not available for this type of data structure");
}
//TODO callback
registrationId = ListenerUtil.listen(context, request, null, handler);
} catch (Exception e) {
Logger.getLogger(ClientNearCache.class).
severe("-----------------\n Near Cache is not initialized!!! \n-----------------", e);
}
}
static enum EvictionPolicy {
NONE, LRU, LFU
}
public void put(K key, Object object) {
fireTtlCleanup();
if (evictionPolicy == EvictionPolicy.NONE && cache.size() >= maxSize) {
return;
}
if (evictionPolicy != EvictionPolicy.NONE && cache.size() >= maxSize) {
fireEvictCache();
}
Object value;
if (object == null) {
value = NULL_OBJECT;
} else {
value = inMemoryFormat.equals(InMemoryFormat.BINARY) ? context.getSerializationService().toData(object) : object;
}
cache.put(key, new CacheRecord<K>(key, value));
}
private void fireEvictCache() {
if (canEvict.compareAndSet(true, false)) {
try {
context.getExecutionService().execute(new Runnable() {
public void run() {
try {
TreeSet<CacheRecord<K>> records = new TreeSet<CacheRecord<K>>(comparator);
records.addAll(cache.values());
int evictSize = cache.size() * EVICTION_PERCENTAGE / 100;
int i = 0;
for (CacheRecord<K> record : records) {
cache.remove(record.key);
if (++i > evictSize) {
break;
}
}
} finally {
canEvict.set(true);
}
}
});
} catch (RejectedExecutionException e) {
canEvict.set(true);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
}
private void fireTtlCleanup() {
if (Clock.currentTimeMillis() < (lastCleanup + TTL_CLEANUP_INTERVAL_MILLS)) {
return;
}
if (canCleanUp.compareAndSet(true, false)) {
try {
context.getExecutionService().execute(new Runnable() {
public void run() {
try {
lastCleanup = Clock.currentTimeMillis();
for (Map.Entry<K, CacheRecord<K>> entry : cache.entrySet()) {
if (entry.getValue().expired()) {
cache.remove(entry.getKey());
}
}
} finally {
canCleanUp.set(true);
}
}
});
} catch (RejectedExecutionException e) {
canCleanUp.set(true);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
}
public void invalidate(K key) {
cache.remove(key);
}
public Object get(K key) {
fireTtlCleanup();
CacheRecord<K> record = cache.get(key);
if (record != null) {
if (record.expired()) {
cache.remove(key);
clientNearCacheStats.incrementMisses();
return null;
}
if (record.value.equals(NULL_OBJECT)) {
clientNearCacheStats.incrementMisses();
return NULL_OBJECT;
}
record.access();
return inMemoryFormat.equals(InMemoryFormat.BINARY) ? context.getSerializationService().
toObject((Data) record.value) : record.value;
} else {
clientNearCacheStats.incrementMisses();
return null;
}
}
public NearCacheStatsImpl getNearCacheStats() {
return createNearCacheStats();
}
private NearCacheStatsImpl createNearCacheStats() {
long ownedEntryCount = cache.values().size();
long ownedEntryMemory = 0;
for (CacheRecord record : cache.values()) {
ownedEntryMemory += record.getCost();
}
clientNearCacheStats.setOwnedEntryCount(ownedEntryCount);
clientNearCacheStats.setOwnedEntryMemoryCost(ownedEntryMemory);
return clientNearCacheStats;
}
public void destroy() {
if (registrationId != null) {
BaseClientRemoveListenerRequest request;
if (cacheType == ClientNearCacheType.Map) {
request = new MapRemoveEntryListenerRequest(mapName, registrationId);
} else {
throw new IllegalStateException("Near cache is not available for this type of data structure");
}
ListenerUtil.stopListening(context, request, registrationId);
}
cache.clear();
}
class CacheRecord<K> {
final K key;
final Object value;
volatile long lastAccessTime;
final long creationTime;
final AtomicInteger hit;
CacheRecord(K key, Object value) {
this.key = key;
this.value = value;
long time = Clock.currentTimeMillis();
this.lastAccessTime = time;
this.creationTime = time;
this.hit = new AtomicInteger(0);
}
void access() {
hit.incrementAndGet();
clientNearCacheStats.incrementHits();
lastAccessTime = Clock.currentTimeMillis();
}
public long getCost() {
// todo find object size if not a Data instance.
if (!(value instanceof Data)) {
return 0;
}
if (!(key instanceof Data)) {
return 0;
}
// value is Data
return ((Data) key).getHeapCost()
+ ((Data) value).getHeapCost()
+ 2 * (Long.SIZE / Byte.SIZE)
// sizeof atomic integer
+ (Integer.SIZE / Byte.SIZE)
// object references (key, value, hit)
+ 3 * (Integer.SIZE / Byte.SIZE);
}
boolean expired() {
long time = Clock.currentTimeMillis();
return (maxIdleMillis > 0 && time > lastAccessTime + maxIdleMillis)
|| (timeToLiveMillis > 0 && time > creationTime + timeToLiveMillis);
}
}
} | 1no label
| hazelcast-client_src_main_java_com_hazelcast_client_nearcache_ClientNearCache.java |
5,095 | class ClearScrollContextsRequest extends TransportRequest {
ClearScrollContextsRequest() {
}
ClearScrollContextsRequest(TransportRequest request) {
super(request);
}
} | 1no label
| src_main_java_org_elasticsearch_search_action_SearchServiceTransportAction.java |
1,628 | public class ThreadDumpOperation extends Operation {
private boolean dumpDeadlocks;
private String result;
public ThreadDumpOperation() {
this(false);
}
public ThreadDumpOperation(boolean dumpDeadlocks) {
this.dumpDeadlocks = dumpDeadlocks;
}
public void beforeRun() throws Exception {
}
public void run() throws Exception {
result = dumpDeadlocks ? ThreadDumpGenerator.dumpDeadlocks() : ThreadDumpGenerator.dumpAllThreads();
}
public void afterRun() throws Exception {
}
public boolean returnsResponse() {
return true;
}
public Object getResponse() {
return result;
}
protected void writeInternal(ObjectDataOutput out) throws IOException {
out.writeBoolean(dumpDeadlocks);
}
protected void readInternal(ObjectDataInput in) throws IOException {
dumpDeadlocks = in.readBoolean();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_management_operation_ThreadDumpOperation.java |
1,351 | public class ProjectSourceFile extends SourceFile implements IResourceAware {
public ProjectSourceFile(ProjectPhasedUnit phasedUnit) {
super(phasedUnit);
}
@Override
public ProjectPhasedUnit getPhasedUnit() {
return (ProjectPhasedUnit) super.getPhasedUnit();
}
@Override
public IProject getProjectResource() {
return getPhasedUnit().getProjectResource();
}
@Override
public IFile getFileResource() {
return getPhasedUnit().getSourceFileResource();
}
@Override
public IFolder getRootFolderResource() {
return getPhasedUnit().getSourceFolderResource();
}
public CompilationUnitDelta buildDeltaAgainstModel() {
try {
final ProjectPhasedUnit modelPhaseUnit = getPhasedUnit();
if (modelPhaseUnit != null) {
final ResourceVirtualFile virtualSrcFile = ResourceVirtualFile.createResourceVirtualFile(modelPhaseUnit.getSourceFileResource());
final ResourceVirtualFile virtualSrcDir = ResourceVirtualFile.createResourceVirtualFile(modelPhaseUnit.getSourceFolderResource());
final TypeChecker currentTypechecker = modelPhaseUnit.getTypeChecker();
final ModuleManager currentModuleManager = currentTypechecker.getPhasedUnits().getModuleManager();
Package singleSourceUnitPackage = new SingleSourceUnitPackage(getPackage(), virtualSrcFile.getPath());
PhasedUnit lastPhasedUnit = new CeylonSourceParser<PhasedUnit>() {
@Override
protected String getCharset() {
try {
return modelPhaseUnit.getProjectResource().getDefaultCharset();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
@Override
protected PhasedUnit createPhasedUnit(CompilationUnit cu, Package pkg, CommonTokenStream tokenStream) {
return new PhasedUnit(virtualSrcFile,
virtualSrcDir, cu, pkg,
currentModuleManager,
currentTypechecker.getContext(),
tokenStream.getTokens()) {
@Override
protected boolean reuseExistingDescriptorModels() {
return true;
}
};
}
}.parseFileToPhasedUnit(
currentModuleManager,
currentTypechecker,
virtualSrcFile,
virtualSrcDir,
singleSourceUnitPackage);
if (lastPhasedUnit != null) {
lastPhasedUnit.validateTree();
lastPhasedUnit.visitSrcModulePhase();
lastPhasedUnit.visitRemainingModulePhase();
lastPhasedUnit.scanDeclarations();
lastPhasedUnit.scanTypeDeclarations();
lastPhasedUnit.validateRefinement();
lastPhasedUnit.analyseFlow();
UnknownTypeCollector utc = new UnknownTypeCollector();
lastPhasedUnit.getCompilationUnit().visit(utc);
if (lastPhasedUnit.getCompilationUnit().getErrors().isEmpty()) {
return buildDeltas_.buildDeltas(modelPhaseUnit, lastPhasedUnit);
}
}
}
} catch(Exception e) {
} catch(ceylon.language.AssertionError e) {
e.printStackTrace();
}
return null;
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_ProjectSourceFile.java |
750 | public class TxnListSizeRequest extends TxnCollectionRequest {
public TxnListSizeRequest() {
}
public TxnListSizeRequest(String name) {
super(name);
}
@Override
public Object innerCall() throws Exception {
return getEndpoint().getTransactionContext(txnId).getList(name).size();
}
@Override
public String getServiceName() {
return ListService.SERVICE_NAME;
}
@Override
public int getClassId() {
return CollectionPortableHook.TXN_LIST_SIZE;
}
@Override
public Permission getRequiredPermission() {
return new ListPermission(name, ActionConstants.ACTION_READ);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_client_TxnListSizeRequest.java |
1,976 | public static final Scoping UNSCOPED = new Scoping() {
public <V> V acceptVisitor(BindingScopingVisitor<V> visitor) {
return visitor.visitNoScoping();
}
@Override
public Scope getScopeInstance() {
return Scopes.NO_SCOPE;
}
@Override
public String toString() {
return Scopes.NO_SCOPE.toString();
}
public void applyTo(ScopedBindingBuilder scopedBindingBuilder) {
// do nothing
}
}; | 0true
| src_main_java_org_elasticsearch_common_inject_internal_Scoping.java |
1,286 | public static final class RemoteDBRunner {
public static void main(String[] args) throws Exception {
OGlobalConfiguration.CACHE_LEVEL1_ENABLED.setValue(false);
OGlobalConfiguration.CACHE_LEVEL1_SIZE.setValue(0);
OGlobalConfiguration.CACHE_LEVEL2_ENABLED.setValue(false);
OGlobalConfiguration.CACHE_LEVEL2_SIZE.setValue(0);
OServer server = OServerMain.create();
server.startup(RemoteDBRunner.class
.getResourceAsStream("/com/orientechnologies/orient/core/storage/impl/local/paginated/db-create-config.xml"));
server.activate();
while (true)
;
}
} | 0true
| server_src_test_java_com_orientechnologies_orient_core_storage_impl_local_paginated_LocalPaginatedStorageCreateCrashRestore.java |
767 | public class OIntentMassiveInsert implements OIntent {
private boolean previousLevel1CacheEnabled;
private boolean previousLevel2CacheEnabled;
private boolean previousRetainRecords;
private boolean previousRetainObjects;
public void begin(final ODatabaseRaw iDatabase, final Object... iArgs) {
previousLevel1CacheEnabled = iDatabase.getDatabaseOwner().getLevel1Cache().isEnabled();
iDatabase.getDatabaseOwner().getLevel1Cache().setEnable(false);
previousLevel2CacheEnabled = iDatabase.getDatabaseOwner().getLevel2Cache().isEnabled();
iDatabase.getDatabaseOwner().getLevel2Cache().setEnable(false);
ODatabaseComplex<?> ownerDb = iDatabase.getDatabaseOwner();
if (ownerDb instanceof ODatabaseRecord) {
previousRetainRecords = ((ODatabaseRecord) ownerDb).isRetainRecords();
((ODatabaseRecord) ownerDb).setRetainRecords(false);
}
while (ownerDb.getDatabaseOwner() != ownerDb)
ownerDb = ownerDb.getDatabaseOwner();
if (ownerDb instanceof ODatabaseObject) {
previousRetainObjects = ((ODatabaseObject) ownerDb).isRetainObjects();
((ODatabaseObject) ownerDb).setRetainObjects(false);
}
}
public void end(final ODatabaseRaw iDatabase) {
iDatabase.getDatabaseOwner().getLevel1Cache().setEnable(previousLevel1CacheEnabled);
iDatabase.getDatabaseOwner().getLevel2Cache().setEnable(previousLevel2CacheEnabled);
ODatabaseComplex<?> ownerDb = iDatabase.getDatabaseOwner();
if (ownerDb instanceof ODatabaseRecord)
((ODatabaseRecord) ownerDb).setRetainRecords(previousRetainRecords);
while (ownerDb.getDatabaseOwner() != ownerDb)
ownerDb = ownerDb.getDatabaseOwner();
if (ownerDb instanceof ODatabaseObject)
((ODatabaseObject) ownerDb).setRetainObjects(previousRetainObjects);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_intent_OIntentMassiveInsert.java |
488 | @SuppressWarnings("serial")
public class ODatabaseExportException extends RuntimeException {
public ODatabaseExportException() {
super();
}
public ODatabaseExportException(String message, Throwable cause) {
super(message, cause);
}
public ODatabaseExportException(String message) {
super(message);
}
public ODatabaseExportException(Throwable cause) {
super(cause);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseExportException.java |
57 | public class HttpPostCommand extends HttpCommand {
boolean nextLine;
boolean readyToReadData;
private ByteBuffer data;
private ByteBuffer line = ByteBuffer.allocate(500);
private String contentType;
private final SocketTextReader socketTextRequestReader;
private boolean chunked;
public HttpPostCommand(SocketTextReader socketTextRequestReader, String uri) {
super(TextCommandType.HTTP_POST, uri);
this.socketTextRequestReader = socketTextRequestReader;
}
/**
* POST /path HTTP/1.0
* User-Agent: HTTPTool/1.0
* Content-TextCommandType: application/x-www-form-urlencoded
* Content-Length: 45
* <next_line>
* <next_line>
* byte[45]
* <next_line>
*
* @param cb
* @return
*/
public boolean readFrom(ByteBuffer cb) {
boolean complete = doActualRead(cb);
while (!complete && readyToReadData && chunked && cb.hasRemaining()) {
complete = doActualRead(cb);
}
if (complete) {
if (data != null) {
data.flip();
}
}
return complete;
}
public byte[] getData() {
if (data == null) {
return null;
} else {
return data.array();
}
}
public byte[] getContentType() {
if (contentType == null) {
return null;
} else {
return stringToBytes(contentType);
}
}
public boolean doActualRead(ByteBuffer cb) {
if (readyToReadData) {
if (chunked && (data == null || !data.hasRemaining())) {
boolean hasLine = readLine(cb);
String lineStr = null;
if (hasLine) {
lineStr = toStringAndClear(line).trim();
}
if (hasLine) {
// hex string
int dataSize = lineStr.length() == 0 ? 0 : Integer.parseInt(lineStr, 16);
if (dataSize == 0) {
return true;
}
if (data != null) {
ByteBuffer newData = ByteBuffer.allocate(data.capacity() + dataSize);
newData.put(data.array());
data = newData;
} else {
data = ByteBuffer.allocate(dataSize);
}
}
}
IOUtil.copyToHeapBuffer(cb, data);
}
while (!readyToReadData && cb.hasRemaining()) {
byte b = cb.get();
char c = (char) b;
if (c == '\n') {
processLine(toStringAndClear(line).toLowerCase());
if (nextLine) {
readyToReadData = true;
}
nextLine = true;
} else if (c != '\r') {
nextLine = false;
line.put(b);
}
}
return !chunked && ((data != null) && !data.hasRemaining());
}
String toStringAndClear(ByteBuffer bb) {
if (bb == null) {
return "";
}
String result;
if (bb.position() == 0) {
result = "";
} else {
result = StringUtil.bytesToString(bb.array(), 0, bb.position());
}
bb.clear();
return result;
}
boolean readLine(ByteBuffer cb) {
while (cb.hasRemaining()) {
byte b = cb.get();
char c = (char) b;
if (c == '\n') {
return true;
} else if (c != '\r') {
line.put(b);
}
}
return false;
}
private void processLine(String currentLine) {
if (contentType == null && currentLine.startsWith(HEADER_CONTENT_TYPE)) {
contentType = currentLine.substring(currentLine.indexOf(' ') + 1);
} else if (data == null && currentLine.startsWith(HEADER_CONTENT_LENGTH)) {
data = ByteBuffer.allocate(Integer.parseInt(currentLine.substring(currentLine.indexOf(' ') + 1)));
} else if (!chunked && currentLine.startsWith(HEADER_CHUNKED)) {
chunked = true;
} else if (currentLine.startsWith(HEADER_EXPECT_100)) {
socketTextRequestReader.sendResponse(new NoOpCommand(RES_100));
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpPostCommand.java |
17 | public class CompletionProposal implements ICompletionProposal,
ICompletionProposalExtension2, ICompletionProposalExtension4,
ICompletionProposalExtension6 {
protected final String text;
private final Image image;
protected final String prefix;
private final String description;
protected int offset;
private int length;
private boolean toggleOverwrite;
public CompletionProposal(int offset, String prefix, Image image,
String desc, String text) {
this.text = text;
this.image = image;
this.offset = offset;
this.prefix = prefix;
this.length = prefix.length();
this.description = desc;
Assert.isNotNull(description);
}
@Override
public Image getImage() {
return image;
}
@Override
public Point getSelection(IDocument document) {
return new Point(offset + text.length() - prefix.length(), 0);
}
public void apply(IDocument document) {
try {
document.replace(start(), length(document),
withoutDupeSemi(document));
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
protected ReplaceEdit createEdit(IDocument document) {
return new ReplaceEdit(start(), length(document),
withoutDupeSemi(document));
}
public int length(IDocument document) {
String overwrite = EditorsUI.getPreferenceStore().getString(COMPLETION);
if ("overwrite".equals(overwrite)!=toggleOverwrite) {
int length = prefix.length();
try {
for (int i=offset;
i<document.getLength() &&
Character.isJavaIdentifierPart(document.getChar(i));
i++) {
length++;
}
}
catch (BadLocationException e) {
e.printStackTrace();
}
return length;
}
else {
return this.length;
}
}
public int start() {
return offset-prefix.length();
}
public String withoutDupeSemi(IDocument document) {
try {
if (text.endsWith(";") &&
document.getChar(offset)==';') {
return text.substring(0,text.length()-1);
}
}
catch (BadLocationException e) {
e.printStackTrace();
}
return text;
}
public String getDisplayString() {
return description;
}
public String getAdditionalProposalInfo() {
return null;
}
@Override
public boolean isAutoInsertable() {
return true;
}
protected boolean qualifiedNameIsPath() {
return false;
}
@Override
public StyledString getStyledDisplayString() {
StyledString result = new StyledString();
Highlights.styleProposal(result, getDisplayString(),
qualifiedNameIsPath());
return result;
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask,
int offset) {
toggleOverwrite = (stateMask&SWT.CTRL)!=0;
length = prefix.length() + offset - this.offset;
apply(viewer.getDocument());
}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int offset, DocumentEvent event) {
if (offset<this.offset) {
return false;
}
try {
//TODO: really this strategy is only applicable
// for completion of declaration names, so
// move this implementation to subclasses
int start = this.offset-prefix.length();
String typedText = document.get(start, offset-start);
return isNameMatching(typedText, text);
// String typedText = document.get(this.offset, offset-this.offset);
// return text.substring(prefix.length())
// .startsWith(typedText);
}
catch (BadLocationException e) {
return false;
}
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CompletionProposal.java |
174 | public class DirectMappedLogBuffer implements LogBuffer
{
// 500k
static final int BUFFER_SIZE = 1024 * 512;
private final StoreChannel fileChannel;
private final ByteBuffer byteBuffer;
private long bufferStartPosition;
private final ByteCounterMonitor monitor;
public DirectMappedLogBuffer( StoreChannel fileChannel, ByteCounterMonitor monitor ) throws IOException
{
this.fileChannel = fileChannel;
this.monitor = monitor;
bufferStartPosition = fileChannel.position();
byteBuffer = ByteBuffer.allocateDirect( BUFFER_SIZE );
}
private void ensureCapacity( int plusSize ) throws IOException
{
if (( BUFFER_SIZE - byteBuffer.position() ) < plusSize )
{
writeOut();
}
assert BUFFER_SIZE - byteBuffer.position() >= plusSize : "after writing out buffer, position is "
+ byteBuffer.position()
+ " and requested size is "
+ plusSize;
}
public LogBuffer put( byte b ) throws IOException
{
ensureCapacity( 1 );
byteBuffer.put( b );
return this;
}
public LogBuffer putShort( short s ) throws IOException
{
ensureCapacity( 2 );
byteBuffer.putShort( s );
return this;
}
public LogBuffer putInt( int i ) throws IOException
{
ensureCapacity( 4 );
byteBuffer.putInt( i );
return this;
}
public LogBuffer putLong( long l ) throws IOException
{
ensureCapacity( 8 );
byteBuffer.putLong( l );
return this;
}
public LogBuffer putFloat( float f ) throws IOException
{
ensureCapacity( 4 );
byteBuffer.putFloat( f );
return this;
}
public LogBuffer putDouble( double d ) throws IOException
{
ensureCapacity( 8 );
byteBuffer.putDouble( d );
return this;
}
public LogBuffer put( byte[] bytes ) throws IOException
{
put( bytes, 0 );
return this;
}
private void put( byte[] bytes, int offset ) throws IOException
{
int bytesToWrite = bytes.length - offset;
if ( bytesToWrite > BUFFER_SIZE )
{
bytesToWrite = BUFFER_SIZE;
}
ensureCapacity( bytesToWrite );
byteBuffer.put( bytes, offset, bytesToWrite );
offset += bytesToWrite;
if ( offset < bytes.length )
{
put( bytes, offset );
}
}
public LogBuffer put( char[] chars ) throws IOException
{
put( chars, 0 );
return this;
}
private void put( char[] chars, int offset ) throws IOException
{
int charsToWrite = chars.length - offset;
if ( charsToWrite * 2 > BUFFER_SIZE )
{
charsToWrite = BUFFER_SIZE / 2;
}
ensureCapacity( charsToWrite * 2 );
int oldPos = byteBuffer.position();
byteBuffer.asCharBuffer().put( chars, offset, charsToWrite );
byteBuffer.position( oldPos + ( charsToWrite * 2 ) );
offset += charsToWrite;
if ( offset < chars.length )
{
put( chars, offset );
}
}
@Override
public void writeOut() throws IOException
{
byteBuffer.flip();
// We use .clear() to reset this buffer, so position will always be 0
long expectedEndPosition = bufferStartPosition + byteBuffer.limit();
long bytesWritten;
while((bufferStartPosition += (bytesWritten = fileChannel.write( byteBuffer, bufferStartPosition ))) < expectedEndPosition)
{
if( bytesWritten <= 0 )
{
throw new IOException( "Unable to write to disk, reported bytes written was " + bytesWritten );
}
}
monitor.bytesWritten( bytesWritten );
byteBuffer.clear();
}
public void force() throws IOException
{
writeOut();
fileChannel.force( false );
}
public long getFileChannelPosition()
{
if ( byteBuffer != null )
{
return bufferStartPosition + byteBuffer.position();
}
return bufferStartPosition;
}
public StoreChannel getFileChannel()
{
return fileChannel;
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_DirectMappedLogBuffer.java |
575 | private static class InitialMembershipListenerImpl implements InitialMembershipListener {
private List<EventObject> events = Collections.synchronizedList(new LinkedList<EventObject>());
public void init(InitialMembershipEvent e) {
events.add(e);
}
public void memberAdded(MembershipEvent e) {
events.add(e);
}
public void memberRemoved(MembershipEvent e) {
events.add(e);
}
public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) {
}
public void assertEventCount(int expected) {
assertEquals(expected, events.size());
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_cluster_ClusterMembershipTest.java |
6,273 | public class LessThanAssertion extends Assertion {
private static final ESLogger logger = Loggers.getLogger(LessThanAssertion.class);
public LessThanAssertion(String field, Object expectedValue) {
super(field, expectedValue);
}
@Override
@SuppressWarnings("unchecked")
protected void doAssert(Object actualValue, Object expectedValue) {
logger.trace("assert that [{}] is less than [{}]", actualValue, expectedValue);
assertThat(actualValue, instanceOf(Comparable.class));
assertThat(expectedValue, instanceOf(Comparable.class));
assertThat(errorMessage(), (Comparable)actualValue, lessThan((Comparable)expectedValue));
}
private String errorMessage() {
return "field [" + getField() + "] is not less than [" + getExpectedValue() + "]";
}
} | 1no label
| src_test_java_org_elasticsearch_test_rest_section_LessThanAssertion.java |
1,259 | addOperation(operations, new Runnable() {
public void run() {
IMap map = hazelcast.getMap("myMap");
Iterator it = map.localKeySet().iterator();
while (it.hasNext()) {
it.next();
}
}
}, 10); | 0true
| hazelcast_src_main_java_com_hazelcast_examples_AllTest.java |
1,158 | public class OSQLMethodSize extends OAbstractSQLMethod {
public static final String NAME = "size";
public OSQLMethodSize() {
super(NAME);
}
@Override
public Object execute(final OIdentifiable iCurrentRecord, final OCommandContext iContext, final Object ioResult,
final Object[] iMethodParams) {
final Number size;
if (ioResult != null) {
if (ioResult instanceof ORecord<?>)
size = 1;
else
size = OMultiValue.getSize(ioResult);
} else
size = 0;
return size;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodSize.java |
35 | static final class ThenRun extends Completion {
final CompletableFuture<?> src;
final Runnable fn;
final CompletableFuture<Void> dst;
final Executor executor;
ThenRun(CompletableFuture<?> src,
Runnable fn,
CompletableFuture<Void> dst,
Executor executor) {
this.src = src; this.fn = fn; this.dst = dst;
this.executor = executor;
}
public final void run() {
final CompletableFuture<?> a;
final Runnable fn;
final CompletableFuture<Void> dst;
Object r; Throwable ex;
if ((dst = this.dst) != null &&
(fn = this.fn) != null &&
(a = this.src) != null &&
(r = a.result) != null &&
compareAndSet(0, 1)) {
if (r instanceof AltResult)
ex = ((AltResult)r).ex;
else
ex = null;
Executor e = executor;
if (ex == null) {
try {
if (e != null)
e.execute(new AsyncRun(fn, dst));
else
fn.run();
} catch (Throwable rex) {
ex = rex;
}
}
if (e == null || ex != null)
dst.internalComplete(null, ex);
}
}
private static final long serialVersionUID = 5232453952276885070L;
} | 0true
| src_main_java_jsr166e_CompletableFuture.java |
3,462 | public class ShardGetModule extends AbstractModule {
@Override
protected void configure() {
bind(ShardGetService.class).asEagerSingleton();
}
} | 0true
| src_main_java_org_elasticsearch_index_get_ShardGetModule.java |
758 | public class CompleteOrderActivity extends BaseActivity<CheckoutContext> {
public CompleteOrderActivity() {
//no specific state to set here for the rollback handler; it's always safe for it to run
setAutomaticallyRegisterRollbackHandler(true);
}
@Override
public CheckoutContext execute(CheckoutContext context) throws Exception {
CheckoutSeed seed = context.getSeedData();
seed.getOrder().setStatus(OrderStatus.SUBMITTED);
seed.getOrder().setOrderNumber(new SimpleDateFormat("yyyyMMddHHmmssS").format(SystemTime.asDate()) + seed.getOrder().getId());
seed.getOrder().setSubmitDate(Calendar.getInstance().getTime());
return context;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_checkout_service_workflow_CompleteOrderActivity.java |
1,863 | boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
try {
final TransactionalMap<String, String> txMap = context.getMap("default");
assertEquals("value0", txMap.put("var", "value1"));
assertEquals("value1", txMap.getForUpdate("var"));
} catch (Exception e) {
}
return true;
}
}); | 0true
| hazelcast_src_test_java_com_hazelcast_map_MapTransactionTest.java |
24 | private SortedSet<Edge> outEdges = new ConcurrentSkipListSet<Edge>(new Comparator<Edge>() {
@Override
public int compare(Edge e1, Edge e2) {
return e1.getEnd().compareTo(e2.getEnd());
}
}); | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
2,651 | threadPool.schedule(TimeValue.timeValueMillis(timeout.millis() / 2), ThreadPool.Names.GENERIC, new Runnable() {
@Override
public void run() {
try {
sendPings(timeout, TimeValue.timeValueMillis(timeout.millis() / 2), sendPingsHandler);
ConcurrentMap<DiscoveryNode, PingResponse> responses = receivedResponses.remove(sendPingsHandler.id());
sendPingsHandler.close();
for (DiscoveryNode node : sendPingsHandler.nodeToDisconnect) {
logger.trace("[{}] disconnecting from {}", sendPingsHandler.id(), node);
transportService.disconnectFromNode(node);
}
listener.onPing(responses.values().toArray(new PingResponse[responses.size()]));
} catch (EsRejectedExecutionException ex) {
logger.debug("Ping execution rejected", ex);
}
}
}); | 0true
| src_main_java_org_elasticsearch_discovery_zen_ping_unicast_UnicastZenPing.java |
3,604 | public static class Defaults extends AbstractFieldMapper.Defaults {
public static final int PRECISION_STEP = NumericUtils.PRECISION_STEP_DEFAULT;
public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE);
static {
FIELD_TYPE.setTokenized(false);
FIELD_TYPE.setOmitNorms(true);
FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_ONLY);
FIELD_TYPE.setStoreTermVectors(false);
FIELD_TYPE.freeze();
}
public static final Explicit<Boolean> IGNORE_MALFORMED = new Explicit<Boolean>(false, false);
public static final Explicit<Boolean> COERCE = new Explicit<Boolean>(true, false);
} | 0true
| src_main_java_org_elasticsearch_index_mapper_core_NumberFieldMapper.java |
1,282 | public class ClusterInfo {
private final ImmutableMap<String, DiskUsage> usages;
private final ImmutableMap<String, Long> shardSizes;
public ClusterInfo(ImmutableMap<String, DiskUsage> usages, ImmutableMap<String, Long> shardSizes) {
this.usages = usages;
this.shardSizes = shardSizes;
}
public Map<String, DiskUsage> getNodeDiskUsages() {
return this.usages;
}
public Map<String, Long> getShardSizes() {
return this.shardSizes;
}
} | 0true
| src_main_java_org_elasticsearch_cluster_ClusterInfo.java |
1,436 | public class CategoryLookupTag extends AbstractCatalogTag {
private static final Log LOG = LogFactory.getLog(CategoryTag.class);
private static final long serialVersionUID = 1L;
private String var;
private String categoryName;
@Override
public void doTag() throws JspException {
catalogService = super.getCatalogService();
Category category = catalogService.findCategoryByName(categoryName);
if(category == null && LOG.isDebugEnabled()){
LOG.debug("The category returned was null for categoryName: " + categoryName);
}
getJspContext().setAttribute(var, category);
}
public String getVar() {
return var;
}
public void setVar(String var) {
this.var = var;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_catalog_taglib_CategoryLookupTag.java |
3,689 | public class TTLFieldMapper extends LongFieldMapper implements InternalMapper, RootMapper {
public static final String NAME = "_ttl";
public static final String CONTENT_TYPE = "_ttl";
public static class Defaults extends LongFieldMapper.Defaults {
public static final String NAME = TTLFieldMapper.CONTENT_TYPE;
public static final FieldType TTL_FIELD_TYPE = new FieldType(LongFieldMapper.Defaults.FIELD_TYPE);
static {
TTL_FIELD_TYPE.setStored(true);
TTL_FIELD_TYPE.setIndexed(true);
TTL_FIELD_TYPE.setTokenized(false);
TTL_FIELD_TYPE.freeze();
}
public static final EnabledAttributeMapper ENABLED_STATE = EnabledAttributeMapper.DISABLED;
public static final long DEFAULT = -1;
}
public static class Builder extends NumberFieldMapper.Builder<Builder, TTLFieldMapper> {
private EnabledAttributeMapper enabledState = EnabledAttributeMapper.UNSET_DISABLED;
private long defaultTTL = Defaults.DEFAULT;
public Builder() {
super(Defaults.NAME, new FieldType(Defaults.TTL_FIELD_TYPE));
}
public Builder enabled(EnabledAttributeMapper enabled) {
this.enabledState = enabled;
return builder;
}
public Builder defaultTTL(long defaultTTL) {
this.defaultTTL = defaultTTL;
return builder;
}
@Override
public TTLFieldMapper build(BuilderContext context) {
return new TTLFieldMapper(fieldType, enabledState, defaultTTL, ignoreMalformed(context),coerce(context), postingsProvider, docValuesProvider, fieldDataSettings, context.indexSettings());
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
TTLFieldMapper.Builder builder = ttl();
parseField(builder, builder.name, node, parserContext);
for (Map.Entry<String, Object> entry : node.entrySet()) {
String fieldName = Strings.toUnderscoreCase(entry.getKey());
Object fieldNode = entry.getValue();
if (fieldName.equals("enabled")) {
EnabledAttributeMapper enabledState = nodeBooleanValue(fieldNode) ? EnabledAttributeMapper.ENABLED : EnabledAttributeMapper.DISABLED;
builder.enabled(enabledState);
} else if (fieldName.equals("default")) {
TimeValue ttlTimeValue = nodeTimeValue(fieldNode, null);
if (ttlTimeValue != null) {
builder.defaultTTL(ttlTimeValue.millis());
}
}
}
return builder;
}
}
private EnabledAttributeMapper enabledState;
private long defaultTTL;
public TTLFieldMapper() {
this(new FieldType(Defaults.TTL_FIELD_TYPE), Defaults.ENABLED_STATE, Defaults.DEFAULT, Defaults.IGNORE_MALFORMED, Defaults.COERCE, null, null, null, ImmutableSettings.EMPTY);
}
protected TTLFieldMapper(FieldType fieldType, EnabledAttributeMapper enabled, long defaultTTL, Explicit<Boolean> ignoreMalformed,
Explicit<Boolean> coerce, PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider,
@Nullable Settings fieldDataSettings, Settings indexSettings) {
super(new Names(Defaults.NAME, Defaults.NAME, Defaults.NAME, Defaults.NAME), Defaults.PRECISION_STEP,
Defaults.BOOST, fieldType, null, Defaults.NULL_VALUE, ignoreMalformed, coerce,
postingsProvider, docValuesProvider, null, null, fieldDataSettings, indexSettings, MultiFields.empty(), null);
this.enabledState = enabled;
this.defaultTTL = defaultTTL;
}
public boolean enabled() {
return this.enabledState.enabled;
}
public long defaultTTL() {
return this.defaultTTL;
}
@Override
public boolean hasDocValues() {
return false;
}
// Overrides valueForSearch to display live value of remaining ttl
@Override
public Object valueForSearch(Object value) {
long now;
SearchContext searchContext = SearchContext.current();
if (searchContext != null) {
now = searchContext.nowInMillis();
} else {
now = System.currentTimeMillis();
}
long val = value(value);
return val - now;
}
// Other implementation for realtime get display
public Object valueForSearch(long expirationTime) {
return expirationTime - System.currentTimeMillis();
}
@Override
public void validate(ParseContext context) throws MapperParsingException {
}
@Override
public void preParse(ParseContext context) throws IOException {
}
@Override
public void postParse(ParseContext context) throws IOException {
super.parse(context);
}
@Override
public void parse(ParseContext context) throws IOException, MapperParsingException {
if (context.sourceToParse().ttl() < 0) { // no ttl has been provided externally
long ttl;
if (context.parser().currentToken() == XContentParser.Token.VALUE_STRING) {
ttl = TimeValue.parseTimeValue(context.parser().text(), null).millis();
} else {
ttl = context.parser().longValue(coerce.value());
}
if (ttl <= 0) {
throw new MapperParsingException("TTL value must be > 0. Illegal value provided [" + ttl + "]");
}
context.sourceToParse().ttl(ttl);
}
}
@Override
public boolean includeInObject() {
return true;
}
@Override
protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException, AlreadyExpiredException {
if (enabledState.enabled && !context.sourceToParse().flyweight()) {
long ttl = context.sourceToParse().ttl();
if (ttl <= 0 && defaultTTL > 0) { // no ttl provided so we use the default value
ttl = defaultTTL;
context.sourceToParse().ttl(ttl);
}
if (ttl > 0) { // a ttl has been provided either externally or in the _source
long timestamp = context.sourceToParse().timestamp();
long expire = new Date(timestamp + ttl).getTime();
long now = System.currentTimeMillis();
// there is not point indexing already expired doc
if (context.sourceToParse().origin() == SourceToParse.Origin.PRIMARY && now >= expire) {
throw new AlreadyExpiredException(context.index(), context.type(), context.id(), timestamp, ttl, now);
}
// the expiration timestamp (timestamp + ttl) is set as field
fields.add(new CustomLongNumericField(this, expire, fieldType));
}
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
boolean includeDefaults = params.paramAsBoolean("include_defaults", false);
// if all are defaults, no sense to write it at all
if (!includeDefaults && enabledState == Defaults.ENABLED_STATE && defaultTTL == Defaults.DEFAULT) {
return builder;
}
builder.startObject(CONTENT_TYPE);
if (includeDefaults || enabledState != Defaults.ENABLED_STATE) {
builder.field("enabled", enabledState.enabled);
}
if (includeDefaults || defaultTTL != Defaults.DEFAULT && enabledState.enabled) {
builder.field("default", defaultTTL);
}
builder.endObject();
return builder;
}
@Override
public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
TTLFieldMapper ttlMergeWith = (TTLFieldMapper) mergeWith;
if (!mergeContext.mergeFlags().simulate()) {
if (ttlMergeWith.defaultTTL != -1) {
this.defaultTTL = ttlMergeWith.defaultTTL;
}
if (ttlMergeWith.enabledState != enabledState && !ttlMergeWith.enabledState.unset()) {
this.enabledState = ttlMergeWith.enabledState;
}
}
}
} | 1no label
| src_main_java_org_elasticsearch_index_mapper_internal_TTLFieldMapper.java |
3,420 | public class IndexShardGatewayException extends IndexShardException {
public IndexShardGatewayException(ShardId shardId, String msg) {
super(shardId, msg);
}
public IndexShardGatewayException(ShardId shardId, String msg, Throwable cause) {
super(shardId, msg, cause);
}
} | 0true
| src_main_java_org_elasticsearch_index_gateway_IndexShardGatewayException.java |
2,915 | public class PersianAnalyzerProvider extends AbstractIndexAnalyzerProvider<PersianAnalyzer> {
private final PersianAnalyzer analyzer;
@Inject
public PersianAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) {
super(index, indexSettings, name, settings);
analyzer = new PersianAnalyzer(version,
Analysis.parseStopWords(env, settings, PersianAnalyzer.getDefaultStopSet(), version));
}
@Override
public PersianAnalyzer get() {
return this.analyzer;
}
} | 0true
| src_main_java_org_elasticsearch_index_analysis_PersianAnalyzerProvider.java |
3,323 | final static class Empty extends FSTBytesAtomicFieldData {
Empty(int numDocs) {
super(null, new EmptyOrdinals(numDocs));
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public int getNumDocs() {
return ordinals.getNumDocs();
}
@Override
public boolean isValuesOrdered() {
return true;
}
@Override
public BytesValues.WithOrdinals getBytesValues(boolean needsHashes) {
return new EmptyByteValuesWithOrdinals(ordinals.ordinals());
}
@Override
public ScriptDocValues.Strings getScriptValues() {
return ScriptDocValues.EMPTY_STRINGS;
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_FSTBytesAtomicFieldData.java |
875 | public class KryoSerializer {
public static final int DEFAULT_MAX_OUTPUT_SIZE = 10 * 1024 * 1024; // 10 MB in bytes
public static final int KRYO_ID_OFFSET = 50;
private final boolean registerRequired;
private final ThreadLocal<Kryo> kryos;
private final Map<Integer,TypeRegistration> registrations;
private final int maxOutputSize;
private static final StaticBuffer.Factory<Input> INPUT_FACTORY = new StaticBuffer.Factory<Input>() {
@Override
public Input get(byte[] array, int offset, int limit) {
//Needs to copy array - otherwise we see BufferUnderflow exceptions from concurrent access
//See https://github.com/EsotericSoftware/kryo#threading
return new Input(Arrays.copyOfRange(array,offset,limit));
}
};
public KryoSerializer(final List<Class> defaultRegistrations) {
this(defaultRegistrations, false);
}
public KryoSerializer(final List<Class> defaultRegistrations, boolean registrationRequired) {
this(defaultRegistrations, registrationRequired, DEFAULT_MAX_OUTPUT_SIZE);
}
public KryoSerializer(final List<Class> defaultRegistrations, boolean registrationRequired, int maxOutputSize) {
this.maxOutputSize = maxOutputSize;
this.registerRequired = registrationRequired;
this.registrations = new HashMap<Integer,TypeRegistration>();
for (Class clazz : defaultRegistrations) {
// Preconditions.checkArgument(isValidClass(clazz),"Class does not have a default constructor: %s",clazz.getName());
objectVerificationCache.put(clazz,Boolean.TRUE);
}
kryos = new ThreadLocal<Kryo>() {
public Kryo initialValue() {
Kryo k = new Kryo();
k.setRegistrationRequired(registerRequired);
k.register(Class.class,new DefaultSerializers.ClassSerializer());
for (int i=0;i<defaultRegistrations.size();i++) {
Class clazz = defaultRegistrations.get(i);
k.register(clazz, KRYO_ID_OFFSET + i);
}
return k;
}
};
}
Kryo getKryo() {
return kryos.get();
}
public Object readClassAndObject(ReadBuffer buffer) {
Input i = buffer.asRelative(INPUT_FACTORY);
int startPos = i.position();
Object value = getKryo().readClassAndObject(i);
buffer.movePositionTo(buffer.getPosition()+i.position()-startPos);
return value;
}
// public <T> T readObject(ReadBuffer buffer, Class<T> type) {
// Input i = buffer.asRelative(INPUT_FACTORY);
// int startPos = i.position();
// T value = getKryo().readObjectOrNull(i, type);
// buffer.movePositionTo(buffer.getPosition()+i.position()-startPos);
// return value;
// }
public <T> T readObjectNotNull(ReadBuffer buffer, Class<T> type) {
Input i = buffer.asRelative(INPUT_FACTORY);
int startPos = i.position();
T value = getKryo().readObject(i, type);
buffer.movePositionTo(buffer.getPosition()+i.position()-startPos);
return value;
}
private Output getOutput(Object object) {
return new Output(128,maxOutputSize);
}
private void writeOutput(WriteBuffer out, Output output) {
byte[] array = output.getBuffer();
int limit = output.position();
for (int i=0;i<limit;i++) out.putByte(array[i]);
}
// public void writeObject(WriteBuffer out, Object object, Class<?> type) {
// Preconditions.checkArgument(isValidObject(object), "Cannot de-/serialize object: %s", object);
// Output output = getOutput(object);
// getKryo().writeObjectOrNull(output, object, type);
// writeOutput(out,output);
// }
public void writeObjectNotNull(WriteBuffer out, Object object) {
Preconditions.checkNotNull(object);
Preconditions.checkArgument(isValidObject(object), "Cannot de-/serialize object: %s", object);
Output output = getOutput(object);
getKryo().writeObject(output, object);
writeOutput(out,output);
}
public void writeClassAndObject(WriteBuffer out, Object object) {
Preconditions.checkArgument(isValidObject(object), "Cannot de-/serialize object: %s", object);
Output output = getOutput(object);
getKryo().writeClassAndObject(output, object);
writeOutput(out,output);
}
private final Cache<Class<?>,Boolean> objectVerificationCache = CacheBuilder.newBuilder()
.maximumSize(10000).concurrencyLevel(4).initialCapacity(32).build();
final boolean isValidObject(final Object o) {
if (o==null) return true;
Boolean status = objectVerificationCache.getIfPresent(o.getClass());
if (status==null) {
Kryo kryo = getKryo();
if (!(kryo.getSerializer(o.getClass()) instanceof FieldSerializer)) status=Boolean.TRUE;
else if (!isValidClass(o.getClass())) status=Boolean.FALSE;
else {
try {
Output out = new Output(128, maxOutputSize);
kryo.writeClassAndObject(out,o);
Input in = new Input(out.getBuffer(),0,out.position());
Object ocopy = kryo.readClassAndObject(in);
status=(o.equals(ocopy)?Boolean.TRUE:Boolean.FALSE);
} catch (Throwable e) {
status=Boolean.FALSE;
}
}
objectVerificationCache.put(o.getClass(),status);
}
return status;
}
public static final boolean isValidClass(Class<?> type) {
if (type.isPrimitive()) return true;
else if (Enum.class.isAssignableFrom(type)) return true;
else if (type.isArray()) {
return isValidClass(type.getComponentType());
} else {
for (Constructor c : type.getDeclaredConstructors()) {
if (c.getParameterTypes().length==0) return true;
}
return false;
}
}
private static class TypeRegistration {
final Class type;
final com.esotericsoftware.kryo.Serializer serializer;
TypeRegistration(Class type, com.esotericsoftware.kryo.Serializer serializer) {
this.type=type;
this.serializer=serializer;
}
}
} | 1no label
| titan-core_src_main_java_com_thinkaurelius_titan_graphdb_database_serialize_kryo_KryoSerializer.java |
535 | class ShardGatewaySnapshotRequest extends BroadcastShardOperationRequest {
ShardGatewaySnapshotRequest() {
}
public ShardGatewaySnapshotRequest(String index, int shardId, GatewaySnapshotRequest request) {
super(index, shardId, request);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_gateway_snapshot_ShardGatewaySnapshotRequest.java |
796 | static final class Fields {
static final XContentBuilderString TOOK = new XContentBuilderString("took");
static final XContentBuilderString TOTAL = new XContentBuilderString("total");
static final XContentBuilderString MATCHES = new XContentBuilderString("matches");
static final XContentBuilderString _INDEX = new XContentBuilderString("_index");
static final XContentBuilderString _ID = new XContentBuilderString("_id");
static final XContentBuilderString _SCORE = new XContentBuilderString("_score");
static final XContentBuilderString HIGHLIGHT = new XContentBuilderString("highlight");
} | 0true
| src_main_java_org_elasticsearch_action_percolate_PercolateResponse.java |
464 | public interface QuantityBasedRule extends Serializable {
/**
* The quantity for which a match must be found using the rule. This generally
* equates to order item quantity (e.g. 2 shirts matching the rule are required in order to receive a discount)
*
* @return the quantity of matches required
*/
public Integer getQuantity();
/**
* The quantity for which a match must be found using the rule. This generally
* equates to order item quantity (e.g. 2 shirts matching the rule are required in order to receive a discount)
*
* @param quantity the quantity of matches required
*/
public void setQuantity(Integer quantity);
/**
* The rule in the form of an MVEL expression
*
* @return the rule as an MVEL string
*/
public String getMatchRule();
/**
* Sets the match rule used to test this item.
*
* @param matchRule the rule as an MVEL string
*/
public void setMatchRule(String matchRule);
/**
* The primary key value for this rule object
*
* @return the primary key value
*/
public Long getId();
/**
* The primary key value for this rule object
*
* @param id the primary key value
*/
public void setId(Long id);
} | 0true
| common_src_main_java_org_broadleafcommerce_common_rule_QuantityBasedRule.java |
1,246 | public class OMMapManagerOld extends OMMapManagerAbstract implements OMMapManager {
private static final long MIN_MEMORY = 50000000;
private static OMMapManagerOld.OVERLAP_STRATEGY overlapStrategy;
private static OMMapManager.ALLOC_STRATEGY lastStrategy;
private static int blockSize;
private static long maxMemory;
private static long totalMemory;
private static final ReadWriteLock lock = new ReentrantReadWriteLock();
private static long metricUsedChannel = 0;
private static long metricReusedPagesBetweenLast = 0;
private static long metricReusedPages = 0;
private static long metricOverlappedPageUsingChannel = 0;
private static List<OMMapBufferEntry> bufferPoolLRU = new ArrayList<OMMapBufferEntry>();
private static Map<OFileMMap, List<OMMapBufferEntry>> bufferPoolPerFile = new HashMap<OFileMMap, List<OMMapBufferEntry>>();
/**
* Strategy that determine what should manager do if mmapped files overlaps.
*/
public enum OVERLAP_STRATEGY {
NO_OVERLAP_USE_CHANNEL, NO_OVERLAP_FLUSH_AND_USE_CHANNEL, OVERLAP
}
OMMapManagerOld() {
}
public void init() {
blockSize = OGlobalConfiguration.FILE_MMAP_BLOCK_SIZE.getValueAsInteger();
maxMemory = OGlobalConfiguration.FILE_MMAP_MAX_MEMORY.getValueAsLong();
setOverlapStrategy(OGlobalConfiguration.FILE_MMAP_OVERLAP_STRATEGY.getValueAsInteger());
Orient
.instance()
.getProfiler()
.registerHookValue("system.file.mmap.totalMemory", "Total memory used by memory mapping", METRIC_TYPE.SIZE,
new OProfilerHookValue() {
public Object getValue() {
return totalMemory;
}
});
Orient
.instance()
.getProfiler()
.registerHookValue("system.file.mmap.maxMemory", "Maximum memory usable by memory mapping", METRIC_TYPE.SIZE,
new OProfilerHookValue() {
public Object getValue() {
return maxMemory;
}
});
Orient
.instance()
.getProfiler()
.registerHookValue("system.file.mmap.blockSize", "Total block size used for memory mapping", METRIC_TYPE.SIZE,
new OProfilerHookValue() {
public Object getValue() {
return blockSize;
}
});
Orient
.instance()
.getProfiler()
.registerHookValue("system.file.mmap.blocks", "Total memory used by memory mapping", METRIC_TYPE.COUNTER,
new OProfilerHookValue() {
public Object getValue() {
lock.readLock().lock();
try {
return bufferPoolLRU.size();
} finally {
lock.readLock().unlock();
}
}
});
Orient
.instance()
.getProfiler()
.registerHookValue("system.file.mmap.alloc.strategy", "Memory mapping allocation strategy", METRIC_TYPE.TEXT,
new OProfilerHookValue() {
public Object getValue() {
return lastStrategy;
}
});
Orient
.instance()
.getProfiler()
.registerHookValue("system.file.mmap.overlap.strategy", "Memory mapping overlapping strategy", METRIC_TYPE.TEXT,
new OProfilerHookValue() {
public Object getValue() {
return overlapStrategy;
}
});
Orient
.instance()
.getProfiler()
.registerHookValue("system.file.mmap.usedChannel",
"Number of times the memory mapping has been bypassed to use direct file channel", METRIC_TYPE.COUNTER,
new OProfilerHookValue() {
public Object getValue() {
return metricUsedChannel;
}
});
Orient
.instance()
.getProfiler()
.registerHookValue("system.file.mmap.reusedPagesBetweenLast",
"Number of times a memory mapped page has been reused in short time", METRIC_TYPE.COUNTER, new OProfilerHookValue() {
public Object getValue() {
return metricReusedPagesBetweenLast;
}
});
Orient
.instance()
.getProfiler()
.registerHookValue("system.file.mmap.reusedPages", "Number of times a memory mapped page has been reused",
METRIC_TYPE.COUNTER, new OProfilerHookValue() {
public Object getValue() {
return metricReusedPages;
}
});
Orient
.instance()
.getProfiler()
.registerHookValue("system.file.mmap.overlappedPageUsingChannel",
"Number of times a direct file channel access has been used because overlapping", METRIC_TYPE.COUNTER,
new OProfilerHookValue() {
public Object getValue() {
return metricOverlappedPageUsingChannel;
}
});
}
public OMMapBufferEntry[] acquire(final OFileMMap iFile, final long iBeginOffset, final int iSize,
final OMMapManager.OPERATION_TYPE iOperationType, final OMMapManager.ALLOC_STRATEGY iStrategy) {
return acquire(iFile, iBeginOffset, iSize, false, iOperationType, iStrategy);
}
/**
* Requests a mmap buffer to use.
*
* @param iFile
* MMap file
* @param iBeginOffset
* Begin offset
* @param iSize
* Portion size requested
* @param iForce
* Tells if the size is mandatory or can be rounded to the next segment
* @param iOperationType
* READ or WRITE
* @param iStrategy
* used to determine how to use mmap. List of sttrategies is available in {@code OGlobalConfiguration} class.
* @return The mmap buffer entry if found, or null if the operation is READ and the buffer pool is full.
*/
private OMMapBufferEntry[] acquire(final OFileMMap iFile, final long iBeginOffset, final int iSize, final boolean iForce,
final OMMapManager.OPERATION_TYPE iOperationType, final OMMapManager.ALLOC_STRATEGY iStrategy) {
if (iStrategy == OMMapManager.ALLOC_STRATEGY.MMAP_NEVER)
return null;
lock.writeLock().lock();
try {
lastStrategy = iStrategy;
OMMapBufferEntry entry = searchBetweenLastBlocks(iFile, iBeginOffset, iSize);
try {
if (entry != null && entry.buffer != null)
return new OMMapBufferEntry[] { entry };
// SEARCH THE REQUESTED RANGE IN THE CACHED BUFFERS
List<OMMapBufferEntry> fileEntries = bufferPoolPerFile.get(iFile);
if (fileEntries == null) {
fileEntries = new ArrayList<OMMapBufferEntry>();
bufferPoolPerFile.put(iFile, fileEntries);
}
int position = searchEntry(fileEntries, iBeginOffset, iSize);
if (position > -1) {
// FOUND !!!
entry = fileEntries.get(position);
if (entry != null && entry.buffer != null)
return new OMMapBufferEntry[] { entry };
}
int p = (position + 2) * -1;
// CHECK IF THERE IS A BUFFER THAT OVERLAPS
if (!allocIfOverlaps(iBeginOffset, iSize, fileEntries, p)) {
metricUsedChannel++;
return null;
}
int bufferSize = computeBestEntrySize(iFile, iBeginOffset, iSize, iForce, fileEntries, p);
if (totalMemory + bufferSize > maxMemory
&& (iStrategy == OMMapManager.ALLOC_STRATEGY.MMAP_ONLY_AVAIL_POOL || iOperationType == OMMapManager.OPERATION_TYPE.READ
&& iStrategy == OMMapManager.ALLOC_STRATEGY.MMAP_WRITE_ALWAYS_READ_IF_AVAIL_POOL)) {
metricUsedChannel++;
return null;
}
entry = null;
// FREE LESS-USED BUFFERS UNTIL THE FREE-MEMORY IS DOWN THE CONFIGURED MAX LIMIT
do {
if (totalMemory + bufferSize > maxMemory)
freeResources();
// RECOMPUTE THE POSITION AFTER REMOVING
fileEntries = bufferPoolPerFile.get(iFile);
position = searchEntry(fileEntries, iBeginOffset, iSize);
if (position > -1) {
// FOUND: THIS IS PRETTY STRANGE SINCE IT WASN'T FOUND!
entry = fileEntries.get(position);
if (entry != null && entry.buffer != null)
return new OMMapBufferEntry[] { entry };
}
// LOAD THE PAGE
try {
entry = mapBuffer(iFile, iBeginOffset, bufferSize);
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
// REDUCE MAX MEMORY TO FORCE EMPTY BUFFERS
maxMemory = maxMemory * 90 / 100;
OLogManager.instance().warn(OMMapManagerOld.class, "Memory mapping error, try to reduce max memory to %d and retry...",
e, maxMemory);
}
} while (entry == null && maxMemory > MIN_MEMORY);
if (entry == null || !entry.isValid())
throw new OIOException("You cannot access to the file portion " + iBeginOffset + "-" + iBeginOffset + iSize + " bytes");
totalMemory += bufferSize;
bufferPoolLRU.add(entry);
p = (position + 2) * -1;
if (p < 0)
p = 0;
if (fileEntries == null) {
// IN CASE THE CLEAN HAS REMOVED THE LIST
fileEntries = new ArrayList<OMMapBufferEntry>();
bufferPoolPerFile.put(iFile, fileEntries);
}
fileEntries.add(p, entry);
if (entry != null && entry.buffer != null)
return new OMMapBufferEntry[] { entry };
} finally {
if (entry != null) {
entry.acquireLock();
if (iOperationType == OMMapManager.OPERATION_TYPE.WRITE)
entry.setDirty();
}
}
return null;
} finally {
lock.writeLock().unlock();
}
}
private static void freeResources() {
final long memoryThreshold = (long) (maxMemory * 0.75);
final long startingMemory = totalMemory;
if (OLogManager.instance().isDebugEnabled())
OLogManager.instance().debug(null, "Freeing off-heap memory as mmmap blocks, target is %s...",
OFileUtils.getSizeAsString(startingMemory - memoryThreshold));
// SORT AS LRU, FIRST = MOST USED
Collections.sort(bufferPoolLRU, new Comparator<OMMapBufferEntry>() {
public int compare(final OMMapBufferEntry o1, final OMMapBufferEntry o2) {
return (int) (o1.getLastUsed() - o2.getLastUsed());
}
});
// REMOVE THE LESS USED ENTRY AND UPDATE THE TOTAL MEMORY
for (Iterator<OMMapBufferEntry> it = bufferPoolLRU.iterator(); it.hasNext();) {
final OMMapBufferEntry entry = it.next();
// REMOVE FROM COLLECTIONS
if (removeEntry(entry))
it.remove();
if (totalMemory < memoryThreshold)
break;
}
if (OLogManager.instance().isDebugEnabled())
OLogManager.instance().debug(null, "Freed off-heap memory as mmmap blocks for %s...",
OFileUtils.getSizeAsString(startingMemory - totalMemory));
}
private static OMMapBufferEntry searchBetweenLastBlocks(final OFileMMap iFile, final long iBeginOffset, final int iSize) {
if (!bufferPoolLRU.isEmpty()) {
// SEARCH IF IT'S BETWEEN THE LAST 5 BLOCK USED: THIS IS THE COMMON CASE ON MASSIVE INSERTION
final int min = Math.max(bufferPoolLRU.size() - 5, -1);
for (int i = bufferPoolLRU.size() - 1; i > min; --i) {
final OMMapBufferEntry e = bufferPoolLRU.get(i);
if (e.isValid() && e.file == iFile && iBeginOffset >= e.beginOffset && iBeginOffset + iSize <= e.beginOffset + e.size) {
// FOUND: USE IT
metricReusedPagesBetweenLast++;
e.updateLastUsedTime();
return e;
}
}
}
return null;
}
/**
* Flushes away all the buffers of closed files. This frees the memory.
*/
public void flush() {
lock.writeLock().lock();
try {
OMMapBufferEntry entry;
for (Iterator<OMMapBufferEntry> it = bufferPoolLRU.iterator(); it.hasNext();) {
entry = it.next();
if (entry.file != null && entry.file.isClosed()) {
if (removeEntry(entry))
it.remove();
}
}
} finally {
lock.writeLock().unlock();
}
}
protected static boolean removeEntry(final OMMapBufferEntry entry) {
if (!entry.flush())
return false;
entry.acquireLock();
try {
// COMMITTED: REMOVE IT
final List<OMMapBufferEntry> file = bufferPoolPerFile.get(entry.file);
if (file != null) {
file.remove(entry);
if (file.isEmpty())
bufferPoolPerFile.remove(entry.file);
}
entry.close();
totalMemory -= entry.size;
return true;
} finally {
entry.releaseLock();
}
}
/**
* Removes the file.
*/
public void removeFile(final OFileMMap iFile) {
lock.writeLock().lock();
try {
final List<OMMapBufferEntry> entries = bufferPoolPerFile.remove(iFile);
if (entries != null) {
for (OMMapBufferEntry entry : entries) {
bufferPoolLRU.remove(entry);
removeEntry(entry);
}
}
} finally {
lock.writeLock().unlock();
}
}
/**
* Flushes all the buffers of the passed file.
*
* @param iFile
* file to flush on disk.
*/
public boolean flushFile(final OFileMMap iFile) {
lock.readLock().lock();
try {
final List<OMMapBufferEntry> entries = bufferPoolPerFile.get(iFile);
boolean allFlushed = true;
if (entries != null)
for (OMMapBufferEntry entry : entries)
if (!entry.flush())
allFlushed = false;
return allFlushed;
} finally {
lock.readLock().unlock();
}
}
public void shutdown() {
lock.writeLock().lock();
try {
for (OMMapBufferEntry entry : new ArrayList<OMMapBufferEntry>(bufferPoolLRU))
removeEntry(entry);
bufferPoolLRU.clear();
bufferPoolPerFile.clear();
totalMemory = 0;
} finally {
lock.writeLock().unlock();
}
}
public long getMaxMemory() {
return maxMemory;
}
public static void setMaxMemory(final long iMaxMemory) {
maxMemory = iMaxMemory;
}
public long getTotalMemory() {
return totalMemory;
}
public int getBlockSize() {
return blockSize;
}
public static void setBlockSize(final int blockSize) {
OMMapManagerOld.blockSize = blockSize;
}
public OVERLAP_STRATEGY getOverlapStrategy() {
return overlapStrategy;
}
public static void setOverlapStrategy(int overlapStrategy) {
OMMapManagerOld.overlapStrategy = OVERLAP_STRATEGY.values()[overlapStrategy];
}
public void setOverlapStrategy(OVERLAP_STRATEGY overlapStrategy) {
OMMapManagerOld.overlapStrategy = overlapStrategy;
}
public int getOverlappedBlocks() {
lock.readLock().lock();
try {
int count = 0;
for (OFileMMap f : bufferPoolPerFile.keySet()) {
count += getOverlappedBlocks(f);
}
return count;
} finally {
lock.readLock().unlock();
}
}
private int getOverlappedBlocks(final OFileMMap iFile) {
lock.readLock().lock();
try {
int count = 0;
final List<OMMapBufferEntry> blocks = bufferPoolPerFile.get(iFile);
long lastPos = -1;
for (OMMapBufferEntry block : blocks) {
if (lastPos > -1 && lastPos > block.beginOffset) {
OLogManager.instance().warn(null, "Found overlapped block for file %s at position %d. Previous offset+size was %d",
iFile, block.beginOffset, lastPos);
count++;
}
lastPos = block.beginOffset + block.size;
}
return count;
} finally {
lock.readLock().unlock();
}
}
private static OMMapBufferEntry mapBuffer(final OFileMMap iFile, final long iBeginOffset, final int iSize) throws IOException {
long timer = Orient.instance().getProfiler().startChrono();
try {
return new OMMapBufferEntry(iFile, iFile.map(iBeginOffset, iSize), iBeginOffset, iSize);
} finally {
Orient.instance().getProfiler().stopChrono("OMMapManager.loadPage", "Load a memory mapped page in memory", timer);
}
}
/**
* Search for a buffer in the ordered list.
*
* @param fileEntries
* to search necessary record.
* @param iBeginOffset
* file offset to start search from it.
* @param iSize
* that will be contained in founded entries.
* @return negative number means not found. The position to insert is the (return value +1)*-1. Zero or positive number is the
* found position.
*/
private static int searchEntry(final List<OMMapBufferEntry> fileEntries, final long iBeginOffset, final int iSize) {
if (fileEntries == null || fileEntries.size() == 0)
return -1;
int high = fileEntries.size() - 1;
if (high < 0)
// NOT FOUND
return -1;
int low = 0;
int mid = -1;
// BINARY SEARCH
OMMapBufferEntry e;
while (low <= high) {
mid = (low + high) >>> 1;
e = fileEntries.get(mid);
if (iBeginOffset >= e.beginOffset && iBeginOffset + iSize <= e.beginOffset + e.size) {
// FOUND: USE IT
metricReusedPages++;
e.updateLastUsedTime();
return mid;
}
if (low == high) {
if (iBeginOffset > e.beginOffset)
// NEXT POSITION
low++;
// NOT FOUND
return (low + 2) * -1;
}
if (iBeginOffset >= e.beginOffset)
low = mid + 1;
else
high = mid;
}
// NOT FOUND
return mid;
}
private static boolean allocIfOverlaps(final long iBeginOffset, final int iSize, final List<OMMapBufferEntry> fileEntries,
final int p) {
if (overlapStrategy == OVERLAP_STRATEGY.OVERLAP)
return true;
boolean overlaps = false;
OMMapBufferEntry entry = null;
if (p > 0) {
// CHECK LOWER OFFSET
entry = fileEntries.get(p - 1);
overlaps = entry.beginOffset <= iBeginOffset && entry.beginOffset + entry.size >= iBeginOffset;
}
if (!overlaps && p < fileEntries.size() - 1) {
// CHECK HIGHER OFFSET
entry = fileEntries.get(p);
overlaps = iBeginOffset + iSize >= entry.beginOffset;
}
if (overlaps) {
// READ NOT IN BUFFER POOL: RETURN NULL TO LET TO THE CALLER TO EXECUTE A DIRECT READ WITHOUT MMAP
metricOverlappedPageUsingChannel++;
if (overlapStrategy == OVERLAP_STRATEGY.NO_OVERLAP_FLUSH_AND_USE_CHANNEL)
entry.flush();
return false;
}
return true;
}
private static int computeBestEntrySize(final OFileMMap iFile, final long iBeginOffset, final int iSize, final boolean iForce,
List<OMMapBufferEntry> fileEntries, int p) {
int bufferSize;
if (p > -1 && p < fileEntries.size()) {
// GET NEXT ENTRY AS SIZE LIMIT
bufferSize = (int) (fileEntries.get(p).beginOffset - iBeginOffset);
if (bufferSize < iSize)
// ROUND TO THE BUFFER SIZE
bufferSize = iSize;
if (bufferSize < blockSize)
bufferSize = blockSize;
} else {
// ROUND TO THE BUFFER SIZE
bufferSize = iForce ? iSize : iSize < blockSize ? blockSize : iSize;
if (iBeginOffset + bufferSize > iFile.getFileSize())
// REQUESTED BUFFER IS TOO LARGE: GET AS MAXIMUM AS POSSIBLE
bufferSize = (int) (iFile.getFileSize() - iBeginOffset);
}
if (bufferSize <= 0)
throw new IllegalArgumentException("Invalid range requested for file " + iFile + ". Requested " + iSize
+ " bytes from the address " + iBeginOffset + " while the total file size is " + iFile.getFileSize());
return bufferSize;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_fs_OMMapManagerOld.java |
101 | class ConvertToPositionalArgumentsProposal extends CorrectionProposal {
public ConvertToPositionalArgumentsProposal(int offset, Change change) {
super("Convert to positional arguments", change, new Region(offset, 0));
}
public static void addConvertToPositionalArgumentsProposal(Collection<ICompletionProposal> proposals,
IFile file, Tree.CompilationUnit cu, CeylonEditor editor, int currentOffset) {
Tree.NamedArgumentList nal =
findNamedArgumentList(currentOffset, cu);
if (nal==null) {
return;
}
final TextChange tc =
new TextFileChange("Convert to Positional Arguments", file);
Integer start = nal.getStartIndex();
try {
if (EditorUtil.getDocument(tc).getChar(start-1)==' ') {
start--;
}
}
catch (BadLocationException e1) {
e1.printStackTrace();
}
int length = nal.getStopIndex()-start+1;
StringBuilder result = new StringBuilder().append("(");
List<CommonToken> tokens = editor.getParseController().getTokens();
List<Tree.NamedArgument> args = nal.getNamedArguments();
Tree.SequencedArgument sa = nal.getSequencedArgument();
for (Parameter p: nal.getNamedArgumentList().getParameterList()
.getParameters()) {
boolean found = false;
if (sa!=null) {
Parameter param = sa.getParameter();
if (param==null) {
return;
}
if (param.getModel().equals(p.getModel())) {
found = true;
result.append("{ ")
.append(Nodes.toString(sa, tokens))
.append(" }");
}
}
for (Tree.NamedArgument na: args) {
Parameter param = na.getParameter();
if (param==null) {
return;
}
if (param.getModel().equals(p.getModel())) {
found = true;
if (na instanceof Tree.SpecifiedArgument) {
Tree.SpecifiedArgument sna = (Tree.SpecifiedArgument) na;
Tree.SpecifierExpression se = sna.getSpecifierExpression();
if (se!=null && se.getExpression()!=null) {
result.append(Nodes.toString(se.getExpression(), tokens));
}
break;
}
else if (na instanceof Tree.MethodArgument) {
Tree.MethodArgument ma = (Tree.MethodArgument) na;
if (ma.getDeclarationModel().isDeclaredVoid()) {
result.append("void ");
}
for (Tree.ParameterList pl: ma.getParameterLists()) {
result.append(Nodes.toString(pl, tokens));
}
if (ma.getBlock()!=null) {
result.append(" ")
.append(Nodes.toString(ma.getBlock(), tokens));
}
if (ma.getSpecifierExpression()!=null) {
result.append(" ")
.append(Nodes.toString(ma.getSpecifierExpression(), tokens));
}
}
else {
return;
}
}
}
if (found) {
result.append(", ");
}
}
if (result.length()>1) {
result.setLength(result.length()-2);
}
result.append(")");
tc.setEdit(new ReplaceEdit(start, length, result.toString()));
int offset = start+result.toString().length();
proposals.add(new ConvertToPositionalArgumentsProposal(offset, tc));
}
private static Tree.NamedArgumentList findNamedArgumentList(
int currentOffset, Tree.CompilationUnit cu) {
FindNamedArgumentsVisitor fpav =
new FindNamedArgumentsVisitor(currentOffset);
fpav.visit(cu);
return fpav.getArgumentList();
}
private static class FindNamedArgumentsVisitor
extends Visitor
implements NaturalVisitor {
Tree.NamedArgumentList argumentList;
int offset;
private Tree.NamedArgumentList getArgumentList() {
return argumentList;
}
private FindNamedArgumentsVisitor(int offset) {
this.offset = offset;
}
@Override
public void visit(Tree.NamedArgumentList that) {
if (offset>=that.getStartIndex() &&
offset<=that.getStopIndex()+1) {
argumentList = that;
}
super.visit(that);
}
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToPositionalArgumentsProposal.java |
776 | public class MoreLikeThisRequest extends ActionRequest<MoreLikeThisRequest> {
private static final XContentType contentType = Requests.CONTENT_TYPE;
private String index;
private String type;
private String id;
private String routing;
private String[] fields;
private float percentTermsToMatch = -1;
private int minTermFreq = -1;
private int maxQueryTerms = -1;
private String[] stopWords = null;
private int minDocFreq = -1;
private int maxDocFreq = -1;
private int minWordLength = -1;
private int maxWordLength = -1;
private float boostTerms = -1;
private SearchType searchType = SearchType.DEFAULT;
private int searchSize = 0;
private int searchFrom = 0;
private String searchQueryHint;
private String[] searchIndices;
private String[] searchTypes;
private Scroll searchScroll;
private BytesReference searchSource;
private boolean searchSourceUnsafe;
MoreLikeThisRequest() {
}
/**
* Constructs a new more like this request for a document that will be fetch from the provided index.
* Use {@link #type(String)} and {@link #id(String)} to specify the document to load.
*/
public MoreLikeThisRequest(String index) {
this.index = index;
}
/**
* The index to load the document from which the "like" query will run with.
*/
public String index() {
return index;
}
/**
* The type of document to load from which the "like" query will run with.
*/
public String type() {
return type;
}
void index(String index) {
this.index = index;
}
/**
* The type of document to load from which the "like" query will execute with.
*/
public MoreLikeThisRequest type(String type) {
this.type = type;
return this;
}
/**
* The id of document to load from which the "like" query will execute with.
*/
public String id() {
return id;
}
/**
* The id of document to load from which the "like" query will execute with.
*/
public MoreLikeThisRequest id(String id) {
this.id = id;
return this;
}
/**
* @return The routing for this request. This used for the `get` part of the mlt request.
*/
public String routing() {
return routing;
}
public void routing(String routing) {
this.routing = routing;
}
/**
* The fields of the document to use in order to find documents "like" this one. Defaults to run
* against all the document fields.
*/
public String[] fields() {
return this.fields;
}
/**
* The fields of the document to use in order to find documents "like" this one. Defaults to run
* against all the document fields.
*/
public MoreLikeThisRequest fields(String... fields) {
this.fields = fields;
return this;
}
/**
* The percent of the terms to match for each field. Defaults to <tt>0.3f</tt>.
*/
public MoreLikeThisRequest percentTermsToMatch(float percentTermsToMatch) {
this.percentTermsToMatch = percentTermsToMatch;
return this;
}
/**
* The percent of the terms to match for each field. Defaults to <tt>0.3f</tt>.
*/
public float percentTermsToMatch() {
return this.percentTermsToMatch;
}
/**
* The frequency below which terms will be ignored in the source doc. Defaults to <tt>2</tt>.
*/
public MoreLikeThisRequest minTermFreq(int minTermFreq) {
this.minTermFreq = minTermFreq;
return this;
}
/**
* The frequency below which terms will be ignored in the source doc. Defaults to <tt>2</tt>.
*/
public int minTermFreq() {
return this.minTermFreq;
}
/**
* The maximum number of query terms that will be included in any generated query. Defaults to <tt>25</tt>.
*/
public MoreLikeThisRequest maxQueryTerms(int maxQueryTerms) {
this.maxQueryTerms = maxQueryTerms;
return this;
}
/**
* The maximum number of query terms that will be included in any generated query. Defaults to <tt>25</tt>.
*/
public int maxQueryTerms() {
return this.maxQueryTerms;
}
/**
* Any word in this set is considered "uninteresting" and ignored.
* <p/>
* <p>Even if your Analyzer allows stopwords, you might want to tell the MoreLikeThis code to ignore them, as
* for the purposes of document similarity it seems reasonable to assume that "a stop word is never interesting".
* <p/>
* <p>Defaults to no stop words.
*/
public MoreLikeThisRequest stopWords(String... stopWords) {
this.stopWords = stopWords;
return this;
}
/**
* Any word in this set is considered "uninteresting" and ignored.
* <p/>
* <p>Even if your Analyzer allows stopwords, you might want to tell the MoreLikeThis code to ignore them, as
* for the purposes of document similarity it seems reasonable to assume that "a stop word is never interesting".
* <p/>
* <p>Defaults to no stop words.
*/
public String[] stopWords() {
return this.stopWords;
}
/**
* The frequency at which words will be ignored which do not occur in at least this
* many docs. Defaults to <tt>5</tt>.
*/
public MoreLikeThisRequest minDocFreq(int minDocFreq) {
this.minDocFreq = minDocFreq;
return this;
}
/**
* The frequency at which words will be ignored which do not occur in at least this
* many docs. Defaults to <tt>5</tt>.
*/
public int minDocFreq() {
return this.minDocFreq;
}
/**
* The maximum frequency in which words may still appear. Words that appear
* in more than this many docs will be ignored. Defaults to unbounded.
*/
public MoreLikeThisRequest maxDocFreq(int maxDocFreq) {
this.maxDocFreq = maxDocFreq;
return this;
}
/**
* The maximum frequency in which words may still appear. Words that appear
* in more than this many docs will be ignored. Defaults to unbounded.
*/
public int maxDocFreq() {
return this.maxDocFreq;
}
/**
* The minimum word length below which words will be ignored. Defaults to <tt>0</tt>.
*/
public MoreLikeThisRequest minWordLength(int minWordLength) {
this.minWordLength = minWordLength;
return this;
}
/**
* The minimum word length below which words will be ignored. Defaults to <tt>0</tt>.
*/
public int minWordLength() {
return this.minWordLength;
}
/**
* The maximum word length above which words will be ignored. Defaults to unbounded.
*/
public MoreLikeThisRequest maxWordLength(int maxWordLength) {
this.maxWordLength = maxWordLength;
return this;
}
/**
* The maximum word length above which words will be ignored. Defaults to unbounded.
*/
public int maxWordLength() {
return this.maxWordLength;
}
/**
* The boost factor to use when boosting terms. Defaults to <tt>1</tt>.
*/
public MoreLikeThisRequest boostTerms(float boostTerms) {
this.boostTerms = boostTerms;
return this;
}
/**
* The boost factor to use when boosting terms. Defaults to <tt>1</tt>.
*/
public float boostTerms() {
return this.boostTerms;
}
void beforeLocalFork() {
if (searchSourceUnsafe) {
searchSource = searchSource.copyBytesArray();
searchSourceUnsafe = false;
}
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequest searchSource(SearchSourceBuilder sourceBuilder) {
this.searchSource = sourceBuilder.buildAsBytes(Requests.CONTENT_TYPE);
this.searchSourceUnsafe = false;
return this;
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequest searchSource(String searchSource) {
this.searchSource = new BytesArray(searchSource);
this.searchSourceUnsafe = false;
return this;
}
public MoreLikeThisRequest searchSource(Map searchSource) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(contentType);
builder.map(searchSource);
return searchSource(builder);
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + searchSource + "]", e);
}
}
public MoreLikeThisRequest searchSource(XContentBuilder builder) {
this.searchSource = builder.bytes();
this.searchSourceUnsafe = false;
return this;
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequest searchSource(byte[] searchSource) {
return searchSource(searchSource, 0, searchSource.length, false);
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequest searchSource(byte[] searchSource, int offset, int length, boolean unsafe) {
return searchSource(new BytesArray(searchSource, offset, length), unsafe);
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequest searchSource(BytesReference searchSource, boolean unsafe) {
this.searchSource = searchSource;
this.searchSourceUnsafe = unsafe;
return this;
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public BytesReference searchSource() {
return this.searchSource;
}
public boolean searchSourceUnsafe() {
return searchSourceUnsafe;
}
/**
* The search type of the mlt search query.
*/
public MoreLikeThisRequest searchType(SearchType searchType) {
this.searchType = searchType;
return this;
}
/**
* The search type of the mlt search query.
*/
public MoreLikeThisRequest searchType(String searchType) throws ElasticsearchIllegalArgumentException {
return searchType(SearchType.fromString(searchType));
}
/**
* The search type of the mlt search query.
*/
public SearchType searchType() {
return this.searchType;
}
/**
* The indices the resulting mlt query will run against. If not set, will run
* against the index the document was fetched from.
*/
public MoreLikeThisRequest searchIndices(String... searchIndices) {
this.searchIndices = searchIndices;
return this;
}
/**
* The indices the resulting mlt query will run against. If not set, will run
* against the index the document was fetched from.
*/
public String[] searchIndices() {
return this.searchIndices;
}
/**
* The types the resulting mlt query will run against. If not set, will run
* against the type of the document fetched.
*/
public MoreLikeThisRequest searchTypes(String... searchTypes) {
this.searchTypes = searchTypes;
return this;
}
/**
* The types the resulting mlt query will run against. If not set, will run
* against the type of the document fetched.
*/
public String[] searchTypes() {
return this.searchTypes;
}
/**
* Optional search query hint.
*/
public MoreLikeThisRequest searchQueryHint(String searchQueryHint) {
this.searchQueryHint = searchQueryHint;
return this;
}
/**
* Optional search query hint.
*/
public String searchQueryHint() {
return this.searchQueryHint;
}
/**
* An optional search scroll request to be able to continue and scroll the search
* operation.
*/
public MoreLikeThisRequest searchScroll(Scroll searchScroll) {
this.searchScroll = searchScroll;
return this;
}
/**
* An optional search scroll request to be able to continue and scroll the search
* operation.
*/
public Scroll searchScroll() {
return this.searchScroll;
}
/**
* The number of documents to return, defaults to 10.
*/
public MoreLikeThisRequest searchSize(int size) {
this.searchSize = size;
return this;
}
public int searchSize() {
return this.searchSize;
}
/**
* From which search result set to return.
*/
public MoreLikeThisRequest searchFrom(int from) {
this.searchFrom = from;
return this;
}
public int searchFrom() {
return this.searchFrom;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (index == null) {
validationException = ValidateActions.addValidationError("index is missing", validationException);
}
if (type == null) {
validationException = ValidateActions.addValidationError("type is missing", validationException);
}
if (id == null) {
validationException = ValidateActions.addValidationError("id is missing", validationException);
}
return validationException;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
index = in.readString();
type = in.readString();
id = in.readString();
// no need to pass threading over the network, they are always false when coming throw a thread pool
int size = in.readVInt();
if (size == 0) {
fields = Strings.EMPTY_ARRAY;
} else {
fields = new String[size];
for (int i = 0; i < size; i++) {
fields[i] = in.readString();
}
}
percentTermsToMatch = in.readFloat();
minTermFreq = in.readVInt();
maxQueryTerms = in.readVInt();
size = in.readVInt();
if (size > 0) {
stopWords = new String[size];
for (int i = 0; i < size; i++) {
stopWords[i] = in.readString();
}
}
minDocFreq = in.readVInt();
maxDocFreq = in.readVInt();
minWordLength = in.readVInt();
maxWordLength = in.readVInt();
boostTerms = in.readFloat();
searchType = SearchType.fromId(in.readByte());
if (in.readBoolean()) {
searchQueryHint = in.readString();
}
size = in.readVInt();
if (size == 0) {
searchIndices = null;
} else if (size == 1) {
searchIndices = Strings.EMPTY_ARRAY;
} else {
searchIndices = new String[size - 1];
for (int i = 0; i < searchIndices.length; i++) {
searchIndices[i] = in.readString();
}
}
size = in.readVInt();
if (size == 0) {
searchTypes = null;
} else if (size == 1) {
searchTypes = Strings.EMPTY_ARRAY;
} else {
searchTypes = new String[size - 1];
for (int i = 0; i < searchTypes.length; i++) {
searchTypes[i] = in.readString();
}
}
if (in.readBoolean()) {
searchScroll = readScroll(in);
}
searchSourceUnsafe = false;
searchSource = in.readBytesReference();
searchSize = in.readVInt();
searchFrom = in.readVInt();
routing = in.readOptionalString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(index);
out.writeString(type);
out.writeString(id);
if (fields == null) {
out.writeVInt(0);
} else {
out.writeVInt(fields.length);
for (String field : fields) {
out.writeString(field);
}
}
out.writeFloat(percentTermsToMatch);
out.writeVInt(minTermFreq);
out.writeVInt(maxQueryTerms);
if (stopWords == null) {
out.writeVInt(0);
} else {
out.writeVInt(stopWords.length);
for (String stopWord : stopWords) {
out.writeString(stopWord);
}
}
out.writeVInt(minDocFreq);
out.writeVInt(maxDocFreq);
out.writeVInt(minWordLength);
out.writeVInt(maxWordLength);
out.writeFloat(boostTerms);
out.writeByte(searchType.id());
if (searchQueryHint == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
out.writeString(searchQueryHint);
}
if (searchIndices == null) {
out.writeVInt(0);
} else {
out.writeVInt(searchIndices.length + 1);
for (String index : searchIndices) {
out.writeString(index);
}
}
if (searchTypes == null) {
out.writeVInt(0);
} else {
out.writeVInt(searchTypes.length + 1);
for (String type : searchTypes) {
out.writeString(type);
}
}
if (searchScroll == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
searchScroll.writeTo(out);
}
out.writeBytesReference(searchSource);
out.writeVInt(searchSize);
out.writeVInt(searchFrom);
out.writeOptionalString(routing);
}
} | 0true
| src_main_java_org_elasticsearch_action_mlt_MoreLikeThisRequest.java |
773 | createIndexAction.execute(new CreateIndexRequest(request.index()).cause("auto(index api)").masterNodeTimeout(request.timeout()), new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse result) {
innerExecute(request, listener);
}
@Override
public void onFailure(Throwable e) {
if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) {
// we have the index, do it
try {
innerExecute(request, listener);
} catch (Throwable e1) {
listener.onFailure(e1);
}
} else {
listener.onFailure(e);
}
}
}); | 0true
| src_main_java_org_elasticsearch_action_index_TransportIndexAction.java |
934 | public class OfferDiscountType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, OfferDiscountType> TYPES = new LinkedHashMap<String, OfferDiscountType>();
public static final OfferDiscountType PERCENT_OFF = new OfferDiscountType("PERCENT_OFF", "Percent Off");
public static final OfferDiscountType AMOUNT_OFF = new OfferDiscountType("AMOUNT_OFF", "Amount Off");
public static final OfferDiscountType FIX_PRICE = new OfferDiscountType("FIX_PRICE", "Fixed Price");
public static OfferDiscountType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public OfferDiscountType() {
//do nothing
}
public OfferDiscountType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
}
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OfferDiscountType other = (OfferDiscountType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_type_OfferDiscountType.java |
589 | public class ServiceMonitor {
private static final Log LOG = LogFactory.getLog(ServiceMonitor.class);
protected Map<ServiceStatusDetectable, StatusHandler> serviceHandlers = new HashMap<ServiceStatusDetectable, StatusHandler>();
protected StatusHandler defaultHandler = new LogStatusHandler();
protected Map<ServiceStatusDetectable, ServiceStatusType> statusMap = new HashMap<ServiceStatusDetectable, ServiceStatusType>();
public synchronized void init() {
for (ServiceStatusDetectable statusDetectable : serviceHandlers.keySet()) {
checkService(statusDetectable);
}
}
public Object checkServiceAOP(ProceedingJoinPoint call) throws Throwable {
try {
checkService((ServiceStatusDetectable) call.getThis());
} catch (Throwable e) {
LOG.error("Could not check service status", e);
}
return call.proceed();
}
public void checkService(ServiceStatusDetectable statusDetectable) {
ServiceStatusType type = statusDetectable.getServiceStatus();
if (!statusMap.containsKey(statusDetectable)) {
statusMap.put(statusDetectable, type);
if (type.equals(ServiceStatusType.DOWN)) {
handleStatusChange(statusDetectable, type);
}
}
if (!statusMap.get(statusDetectable).equals(type)) {
handleStatusChange(statusDetectable, type);
statusMap.put(statusDetectable, type);
}
}
protected void handleStatusChange(ServiceStatusDetectable serviceStatus, ServiceStatusType serviceStatusType) {
if (serviceHandlers.containsKey(serviceStatus)) {
serviceHandlers.get(serviceStatus).handleStatus(serviceStatus.getServiceName(), serviceStatusType);
} else {
defaultHandler.handleStatus(serviceStatus.getServiceName(), serviceStatusType);
}
}
public Map<ServiceStatusDetectable, StatusHandler> getServiceHandlers() {
return serviceHandlers;
}
public void setServiceHandlers(Map<ServiceStatusDetectable, StatusHandler> serviceHandlers) {
this.serviceHandlers = serviceHandlers;
}
public StatusHandler getDefaultHandler() {
return defaultHandler;
}
public void setDefaultHandler(StatusHandler defaultHandler) {
this.defaultHandler = defaultHandler;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_vendor_service_monitor_ServiceMonitor.java |
1,795 | private static class DummyValue {
} | 0true
| hazelcast_src_test_java_com_hazelcast_map_IssuesTest.java |
3,217 | public class ReplicatedMapInitChunkOperation
extends AbstractReplicatedMapOperation
implements IdentifiedDataSerializable {
private String name;
private Member origin;
private ReplicatedRecord[] replicatedRecords;
private int recordCount;
private boolean finalChunk;
private boolean notYetReadyChooseSomeoneElse;
ReplicatedMapInitChunkOperation() {
}
public ReplicatedMapInitChunkOperation(String name, Member origin) {
this(name, origin, new ReplicatedRecord[0], 0, true);
this.notYetReadyChooseSomeoneElse = true;
}
// Findbugs warning suppressed since the array is serialized anyways and is never about to be changed
@SuppressWarnings("EI_EXPOSE_REP")
public ReplicatedMapInitChunkOperation(String name, Member origin, ReplicatedRecord[] replicatedRecords, int recordCount,
boolean finalChunk) {
this.name = name;
this.origin = origin;
this.replicatedRecords = replicatedRecords;
this.recordCount = recordCount;
this.finalChunk = finalChunk;
}
public String getName() {
return name;
}
@Override
public void run()
throws Exception {
ReplicatedMapService replicatedMapService = getService();
AbstractReplicatedRecordStore recordStorage;
recordStorage = (AbstractReplicatedRecordStore) replicatedMapService.getReplicatedRecordStore(name, true);
ReplicationPublisher replicationPublisher = recordStorage.getReplicationPublisher();
if (notYetReadyChooseSomeoneElse) {
replicationPublisher.retryWithDifferentReplicationNode(origin);
} else {
for (int i = 0; i < recordCount; i++) {
ReplicatedRecord record = replicatedRecords[i];
Object key = record.getKey();
Object value = record.getValue();
VectorClock vectorClock = record.getVectorClock();
int updateHash = record.getLatestUpdateHash();
long ttlMillis = record.getTtlMillis();
ReplicationMessage update = new ReplicationMessage(name, key, value, vectorClock, origin, updateHash, ttlMillis);
replicationPublisher.queueUpdateMessage(update);
}
if (finalChunk) {
recordStorage.finalChunkReceived();
}
}
}
@Override
public int getFactoryId() {
return ReplicatedMapDataSerializerHook.F_ID;
}
@Override
public int getId() {
return ReplicatedMapDataSerializerHook.OP_INIT_CHUNK;
}
@Override
protected void writeInternal(ObjectDataOutput out)
throws IOException {
out.writeUTF(name);
origin.writeData(out);
out.writeInt(recordCount);
for (int i = 0; i < recordCount; i++) {
replicatedRecords[i].writeData(out);
}
out.writeBoolean(finalChunk);
}
@Override
protected void readInternal(ObjectDataInput in)
throws IOException {
name = in.readUTF();
origin = new MemberImpl();
origin.readData(in);
recordCount = in.readInt();
replicatedRecords = new ReplicatedRecord[recordCount];
for (int i = 0; i < recordCount; i++) {
ReplicatedRecord replicatedRecord = new ReplicatedRecord();
replicatedRecord.readData(in);
replicatedRecords[i] = replicatedRecord;
}
finalChunk = in.readBoolean();
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_replicatedmap_operation_ReplicatedMapInitChunkOperation.java |
1,201 | public class InsufficientFundsException extends PaymentException {
private static final long serialVersionUID = 1L;
public InsufficientFundsException() {
super();
}
public InsufficientFundsException(String message, Throwable cause) {
super(message, cause);
}
public InsufficientFundsException(String message) {
super(message);
}
public InsufficientFundsException(Throwable cause) {
super(cause);
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_exception_InsufficientFundsException.java |
1,852 | class InjectorShell {
private final List<Element> elements;
private final InjectorImpl injector;
private final PrivateElements privateElements;
private InjectorShell(Builder builder, List<Element> elements, InjectorImpl injector) {
this.privateElements = builder.privateElements;
this.elements = elements;
this.injector = injector;
}
PrivateElements getPrivateElements() {
return privateElements;
}
InjectorImpl getInjector() {
return injector;
}
List<Element> getElements() {
return elements;
}
static class Builder {
private final List<Element> elements = Lists.newArrayList();
private final List<Module> modules = Lists.newArrayList();
/**
* lazily constructed
*/
private State state;
private InjectorImpl parent;
private Stage stage;
/**
* null unless this exists in a {@link Binder#newPrivateBinder private environment}
*/
private PrivateElementsImpl privateElements;
Builder parent(InjectorImpl parent) {
this.parent = parent;
this.state = new InheritingState(parent.state);
return this;
}
Builder stage(Stage stage) {
this.stage = stage;
return this;
}
Builder privateElements(PrivateElements privateElements) {
this.privateElements = (PrivateElementsImpl) privateElements;
this.elements.addAll(privateElements.getElements());
return this;
}
void addModules(Iterable<? extends Module> modules) {
for (Module module : modules) {
this.modules.add(module);
}
}
/**
* Synchronize on this before calling {@link #build}.
*/
Object lock() {
return getState().lock();
}
/**
* Creates and returns the injector shells for the current modules. Multiple shells will be
* returned if any modules contain {@link Binder#newPrivateBinder private environments}. The
* primary injector will be first in the returned list.
*/
List<InjectorShell> build(Initializer initializer, BindingProcessor bindingProcessor,
Stopwatch stopwatch, Errors errors) {
checkState(stage != null, "Stage not initialized");
checkState(privateElements == null || parent != null, "PrivateElements with no parent");
checkState(state != null, "no state. Did you remember to lock() ?");
InjectorImpl injector = new InjectorImpl(parent, state, initializer);
if (privateElements != null) {
privateElements.initInjector(injector);
}
// bind Stage and Singleton if this is a top-level injector
if (parent == null) {
modules.add(0, new RootModule(stage));
new TypeConverterBindingProcessor(errors).prepareBuiltInConverters(injector);
}
elements.addAll(Elements.getElements(stage, modules));
stopwatch.resetAndLog("Module execution");
new MessageProcessor(errors).process(injector, elements);
new TypeListenerBindingProcessor(errors).process(injector, elements);
List<TypeListenerBinding> listenerBindings = injector.state.getTypeListenerBindings();
injector.membersInjectorStore = new MembersInjectorStore(injector, listenerBindings);
stopwatch.resetAndLog("TypeListeners creation");
new ScopeBindingProcessor(errors).process(injector, elements);
stopwatch.resetAndLog("Scopes creation");
new TypeConverterBindingProcessor(errors).process(injector, elements);
stopwatch.resetAndLog("Converters creation");
bindInjector(injector);
bindLogger(injector);
bindingProcessor.process(injector, elements);
stopwatch.resetAndLog("Binding creation");
List<InjectorShell> injectorShells = Lists.newArrayList();
injectorShells.add(new InjectorShell(this, elements, injector));
// recursively build child shells
PrivateElementProcessor processor = new PrivateElementProcessor(errors, stage);
processor.process(injector, elements);
for (Builder builder : processor.getInjectorShellBuilders()) {
injectorShells.addAll(builder.build(initializer, bindingProcessor, stopwatch, errors));
}
stopwatch.resetAndLog("Private environment creation");
return injectorShells;
}
private State getState() {
if (state == null) {
state = new InheritingState(State.NONE);
}
return state;
}
}
/**
* The Injector is a special case because we allow both parent and child injectors to both have
* a binding for that key.
*/
private static void bindInjector(InjectorImpl injector) {
Key<Injector> key = Key.get(Injector.class);
InjectorFactory injectorFactory = new InjectorFactory(injector);
injector.state.putBinding(key,
new ProviderInstanceBindingImpl<Injector>(injector, key, SourceProvider.UNKNOWN_SOURCE,
injectorFactory, Scoping.UNSCOPED, injectorFactory,
ImmutableSet.<InjectionPoint>of()));
}
private static class InjectorFactory implements InternalFactory<Injector>, Provider<Injector> {
private final Injector injector;
private InjectorFactory(Injector injector) {
this.injector = injector;
}
public Injector get(Errors errors, InternalContext context, Dependency<?> dependency)
throws ErrorsException {
return injector;
}
public Injector get() {
return injector;
}
public String toString() {
return "Provider<Injector>";
}
}
/**
* The Logger is a special case because it knows the injection point of the injected member. It's
* the only binding that does this.
*/
private static void bindLogger(InjectorImpl injector) {
Key<Logger> key = Key.get(Logger.class);
LoggerFactory loggerFactory = new LoggerFactory();
injector.state.putBinding(key,
new ProviderInstanceBindingImpl<Logger>(injector, key,
SourceProvider.UNKNOWN_SOURCE, loggerFactory, Scoping.UNSCOPED,
loggerFactory, ImmutableSet.<InjectionPoint>of()));
}
private static class LoggerFactory implements InternalFactory<Logger>, Provider<Logger> {
public Logger get(Errors errors, InternalContext context, Dependency<?> dependency) {
InjectionPoint injectionPoint = dependency.getInjectionPoint();
return injectionPoint == null
? Logger.getAnonymousLogger()
: Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}
public Logger get() {
return Logger.getAnonymousLogger();
}
public String toString() {
return "Provider<Logger>";
}
}
private static class RootModule implements Module {
final Stage stage;
private RootModule(Stage stage) {
this.stage = checkNotNull(stage, "stage");
}
public void configure(Binder binder) {
binder = binder.withSource(SourceProvider.UNKNOWN_SOURCE);
binder.bind(Stage.class).toInstance(stage);
binder.bindScope(Singleton.class, SINGLETON);
}
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_InjectorShell.java |
1,305 | public class ProductSearchResult {
protected List<Product> products;
protected List<SearchFacetDTO> facets;
protected Integer totalResults;
protected Integer page;
protected Integer pageSize;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public List<SearchFacetDTO> getFacets() {
return facets;
}
public void setFacets(List<SearchFacetDTO> facets) {
this.facets = facets;
}
public Integer getTotalResults() {
return totalResults;
}
public void setTotalResults(Integer totalResults) {
this.totalResults = totalResults;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getStartResult() {
return (products == null || products.size() == 0) ? 0 : ((page - 1) * pageSize) + 1;
}
public Integer getEndResult() {
return Math.min(page * pageSize, totalResults);
}
public Integer getTotalPages() {
return (products == null || products.size() == 0) ? 1 : (int) Math.ceil(totalResults * 1.0 / pageSize);
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_domain_ProductSearchResult.java |
920 | public interface ItemOfferProcessor extends OrderOfferProcessor {
/**
* Review an item level offer against the list of discountable items from the order. If the
* offer applies, add it to the qualifiedItemOffers list.
*
* @param order the BLC order
* @param qualifiedItemOffers the container list for any qualified offers
* @param discreteOrderItems the order items to evaluate
* @param offer the offer in question
*/
public void filterItemLevelOffer(PromotableOrder order, List<PromotableCandidateItemOffer> qualifiedItemOffers, Offer offer);
/**
* Private method that takes a list of sorted CandidateItemOffers and determines if each offer can be
* applied based on the restrictions (stackable and/or combinable) on that offer. OrderItemAdjustments
* are create on the OrderItem for each applied CandidateItemOffer. An offer with stackable equals false
* cannot be applied to an OrderItem that already contains an OrderItemAdjustment. An offer with combinable
* equals false cannot be applied to an OrderItem if that OrderItem already contains an
* OrderItemAdjustment, unless the offer is the same offer as the OrderItemAdjustment offer.
*
* @param itemOffers a sorted list of CandidateItemOffer
*/
public void applyAllItemOffers(List<PromotableCandidateItemOffer> itemOffers, PromotableOrder order);
public void applyAndCompareOrderAndItemOffers(PromotableOrder order, List<PromotableCandidateOrderOffer> qualifiedOrderOffers, List<PromotableCandidateItemOffer> qualifiedItemOffers);
public void filterOffers(PromotableOrder order, List<Offer> filteredOffers, List<PromotableCandidateOrderOffer> qualifiedOrderOffers, List<PromotableCandidateItemOffer> qualifiedItemOffers);
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_processor_ItemOfferProcessor.java |
884 | return new PortableFactory() {
@Override
public Portable create(int classId) {
switch (classId) {
case COUNT_DOWN:
return new CountDownRequest();
case AWAIT:
return new AwaitRequest();
case SET_COUNT:
return new SetCountRequest();
case GET_COUNT:
return new GetCountRequest();
default:
return null;
}
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_countdownlatch_client_CountDownLatchPortableHook.java |
1,842 | InternalFactory<T> internalFactory = new InternalFactory<T>() {
public T get(Errors errors, InternalContext context, Dependency dependency)
throws ErrorsException {
errors = errors.withSource(providerKey);
Provider<?> provider = providerBinding.getInternalFactory().get(
errors, context, dependency);
try {
Object o = provider.get();
if (o != null && !rawType.isInstance(o)) {
throw errors.subtypeNotProvided(providerType, rawType).toException();
}
@SuppressWarnings("unchecked") // protected by isInstance() check above
T t = (T) o;
return t;
} catch (RuntimeException e) {
throw errors.errorInProvider(e).toException();
}
}
}; | 0true
| src_main_java_org_elasticsearch_common_inject_InjectorImpl.java |
1,550 | new OProfilerHookValue() {
@Override
public Object getValue() {
final StringBuilder dbs = new StringBuilder();
for (String dbName : getAvailableStorageNames().keySet()) {
if (dbs.length() > 0)
dbs.append(',');
dbs.append(dbName);
}
return dbs.toString();
}
}); | 0true
| server_src_main_java_com_orientechnologies_orient_server_OServer.java |
1,472 | public class HazelcastQueryResultsRegion extends AbstractGeneralRegion<LocalRegionCache> implements QueryResultsRegion {
public HazelcastQueryResultsRegion(final HazelcastInstance instance, final String name, final Properties props) {
// Note: We can pass HazelcastInstance as null, because instead of invalidation
// timestamps cache can take care of outdated queries.
super(instance, name, props, new LocalRegionCache(name, null, null));
}
} | 0true
| hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_region_HazelcastQueryResultsRegion.java |
4,916 | public class RestGetAction extends BaseRestHandler {
@Inject
public RestGetAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/{index}/{type}/{id}", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
final GetRequest getRequest = new GetRequest(request.param("index"), request.param("type"), request.param("id"));
getRequest.listenerThreaded(false);
getRequest.operationThreaded(true);
getRequest.refresh(request.paramAsBoolean("refresh", getRequest.refresh()));
getRequest.routing(request.param("routing")); // order is important, set it after routing, so it will set the routing
getRequest.parent(request.param("parent"));
getRequest.preference(request.param("preference"));
getRequest.realtime(request.paramAsBoolean("realtime", null));
String sField = request.param("fields");
if (sField != null) {
String[] sFields = Strings.splitStringByCommaToArray(sField);
if (sFields != null) {
getRequest.fields(sFields);
}
}
getRequest.version(RestActions.parseVersion(request));
getRequest.versionType(VersionType.fromString(request.param("version_type"), getRequest.versionType()));
getRequest.fetchSourceContext(FetchSourceContext.parseFromRestRequest(request));
client.get(getRequest, new ActionListener<GetResponse>() {
@Override
public void onResponse(GetResponse response) {
try {
XContentBuilder builder = restContentBuilder(request);
response.toXContent(builder, request);
if (!response.isExists()) {
channel.sendResponse(new XContentRestResponse(request, NOT_FOUND, builder));
} else {
channel.sendResponse(new XContentRestResponse(request, OK, builder));
}
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new XContentThrowableRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}
} | 1no label
| src_main_java_org_elasticsearch_rest_action_get_RestGetAction.java |
737 | public class CollectionRemoveRequest extends CollectionRequest {
private Data value;
public CollectionRemoveRequest() {
}
public CollectionRemoveRequest(String name, Data value) {
super(name);
this.value = value;
}
@Override
protected Operation prepareOperation() {
return new CollectionRemoveOperation(name, value);
}
@Override
public int getClassId() {
return CollectionPortableHook.COLLECTION_REMOVE;
}
public void write(PortableWriter writer) throws IOException {
super.write(writer);
value.writeData(writer.getRawDataOutput());
}
public void read(PortableReader reader) throws IOException {
super.read(reader);
value = new Data();
value.readData(reader.getRawDataInput());
}
@Override
public String getRequiredAction() {
return ActionConstants.ACTION_REMOVE;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_client_CollectionRemoveRequest.java |
2,306 | public class RegexTests extends ElasticsearchTestCase {
@Test
public void testFlags() {
String[] supportedFlags = new String[]{"CASE_INSENSITIVE", "MULTILINE", "DOTALL", "UNICODE_CASE", "CANON_EQ", "UNIX_LINES",
"LITERAL", "COMMENTS", "UNICODE_CHAR_CLASS"};
int[] flags = new int[]{Pattern.CASE_INSENSITIVE, Pattern.MULTILINE, Pattern.DOTALL, Pattern.UNICODE_CASE, Pattern.CANON_EQ,
Pattern.UNIX_LINES, Pattern.LITERAL, Pattern.COMMENTS, Regex.UNICODE_CHARACTER_CLASS};
Random random = getRandom();
int num = 10 + random.nextInt(100);
for (int i = 0; i < num; i++) {
int numFlags = random.nextInt(flags.length + 1);
int current = 0;
StringBuilder builder = new StringBuilder();
for (int j = 0; j < numFlags; j++) {
int index = random.nextInt(flags.length);
current |= flags[index];
builder.append(supportedFlags[index]);
if (j < numFlags - 1) {
builder.append("|");
}
}
String flagsToString = Regex.flagsToString(current);
assertThat(Regex.flagsFromString(builder.toString()), equalTo(current));
assertThat(Regex.flagsFromString(builder.toString()), equalTo(Regex.flagsFromString(flagsToString)));
Pattern.compile("\\w\\d{1,2}", current); // accepts the flags?
}
}
@Test(timeout = 1000)
public void testDoubleWildcardMatch() {
assertTrue(Regex.simpleMatch("ddd", "ddd"));
assertTrue(Regex.simpleMatch("d*d*d", "dadd"));
assertTrue(Regex.simpleMatch("**ddd", "dddd"));
assertFalse(Regex.simpleMatch("**ddd", "fff"));
assertTrue(Regex.simpleMatch("fff*ddd", "fffabcddd"));
assertTrue(Regex.simpleMatch("fff**ddd", "fffabcddd"));
assertFalse(Regex.simpleMatch("fff**ddd", "fffabcdd"));
assertTrue(Regex.simpleMatch("fff*******ddd", "fffabcddd"));
assertFalse(Regex.simpleMatch("fff******ddd", "fffabcdd"));
}
} | 0true
| src_test_java_org_elasticsearch_common_regex_RegexTests.java |
258 | @Entity
@Table(name = "BLC_EMAIL_TRACKING_CLICKS")
public class EmailTrackingClicksImpl implements EmailTrackingClicks {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "ClickId")
@GenericGenerator(
name="ClickId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="EmailTrackingClicksImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.common.email.domain.EmailTrackingClicksImpl")
}
)
@Column(name = "CLICK_ID")
protected Long id;
@ManyToOne(optional=false, targetEntity = EmailTrackingImpl.class)
@JoinColumn(name = "EMAIL_TRACKING_ID")
@Index(name="TRACKINGCLICKS_TRACKING_INDEX", columnNames={"EMAIL_TRACKING_ID"})
protected EmailTracking emailTracking;
@Column(nullable=false, name = "DATE_CLICKED")
protected Date dateClicked;
@Column(name = "CUSTOMER_ID")
@Index(name="TRACKINGCLICKS_CUSTOMER_INDEX", columnNames={"CUSTOMER_ID"})
protected String customerId;
@Column(name = "DESTINATION_URI")
protected String destinationUri;
@Column(name = "QUERY_STRING")
protected String queryString;
/* (non-Javadoc)
* @see org.broadleafcommerce.common.email.domain.EmailTrackingClicks#getId()
*/
@Override
public Long getId() {
return id;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.common.email.domain.EmailTrackingClicks#setId(java.lang.Long)
*/
@Override
public void setId(Long id) {
this.id = id;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.common.email.domain.EmailTrackingClicks#getDateClicked()
*/
@Override
public Date getDateClicked() {
return dateClicked;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.common.email.domain.EmailTrackingClicks#setDateClicked(java.util.Date)
*/
@Override
public void setDateClicked(Date dateClicked) {
this.dateClicked = dateClicked;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.common.email.domain.EmailTrackingClicks#getDestinationUri()
*/
@Override
public String getDestinationUri() {
return destinationUri;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.common.email.domain.EmailTrackingClicks#setDestinationUri(java.lang.String)
*/
@Override
public void setDestinationUri(String destinationUri) {
this.destinationUri = destinationUri;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.common.email.domain.EmailTrackingClicks#getQueryString()
*/
@Override
public String getQueryString() {
return queryString;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.common.email.domain.EmailTrackingClicks#setQueryString(java.lang.String)
*/
@Override
public void setQueryString(String queryString) {
this.queryString = queryString;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.common.email.domain.EmailTrackingClicks#getEmailTracking()
*/
@Override
public EmailTracking getEmailTracking() {
return emailTracking;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.common.email.domain.EmailTrackingClicks#setEmailTracking(org.broadleafcommerce.common.email.domain.EmailTrackingImpl)
*/
@Override
public void setEmailTracking(EmailTracking emailTracking) {
this.emailTracking = emailTracking;
}
/**
* @return the customer
*/
@Override
public String getCustomerId() {
return customerId;
}
/**
* @param customerId the customer to set
*/
@Override
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((dateClicked == null) ? 0 : dateClicked.hashCode());
result = prime * result + ((destinationUri == null) ? 0 : destinationUri.hashCode());
result = prime * result + ((emailTracking == null) ? 0 : emailTracking.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;
EmailTrackingClicksImpl other = (EmailTrackingClicksImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (dateClicked == null) {
if (other.dateClicked != null)
return false;
} else if (!dateClicked.equals(other.dateClicked))
return false;
if (destinationUri == null) {
if (other.destinationUri != null)
return false;
} else if (!destinationUri.equals(other.destinationUri))
return false;
if (emailTracking == null) {
if (other.emailTracking != null)
return false;
} else if (!emailTracking.equals(other.emailTracking))
return false;
return true;
}
} | 1no label
| common_src_main_java_org_broadleafcommerce_common_email_domain_EmailTrackingClicksImpl.java |
6,416 | public class LocalTransport extends AbstractLifecycleComponent<Transport> implements Transport {
private final ThreadPool threadPool;
private final Version version;
private volatile TransportServiceAdapter transportServiceAdapter;
private volatile BoundTransportAddress boundAddress;
private volatile LocalTransportAddress localAddress;
private final static ConcurrentMap<TransportAddress, LocalTransport> transports = newConcurrentMap();
private static final AtomicLong transportAddressIdGenerator = new AtomicLong();
private final ConcurrentMap<DiscoveryNode, LocalTransport> connectedNodes = newConcurrentMap();
@Inject
public LocalTransport(Settings settings, ThreadPool threadPool, Version version) {
super(settings);
this.threadPool = threadPool;
this.version = version;
}
@Override
public TransportAddress[] addressesFromString(String address) {
return new TransportAddress[]{new LocalTransportAddress(address)};
}
@Override
public boolean addressSupported(Class<? extends TransportAddress> address) {
return LocalTransportAddress.class.equals(address);
}
@Override
protected void doStart() throws ElasticsearchException {
localAddress = new LocalTransportAddress(Long.toString(transportAddressIdGenerator.incrementAndGet()));
transports.put(localAddress, this);
boundAddress = new BoundTransportAddress(localAddress, localAddress);
}
@Override
protected void doStop() throws ElasticsearchException {
transports.remove(localAddress);
// now, go over all the transports connected to me, and raise disconnected event
for (final LocalTransport targetTransport : transports.values()) {
for (final Map.Entry<DiscoveryNode, LocalTransport> entry : targetTransport.connectedNodes.entrySet()) {
if (entry.getValue() == this) {
targetTransport.disconnectFromNode(entry.getKey());
}
}
}
}
@Override
protected void doClose() throws ElasticsearchException {
}
@Override
public void transportServiceAdapter(TransportServiceAdapter transportServiceAdapter) {
this.transportServiceAdapter = transportServiceAdapter;
}
@Override
public BoundTransportAddress boundAddress() {
return boundAddress;
}
@Override
public boolean nodeConnected(DiscoveryNode node) {
return connectedNodes.containsKey(node);
}
@Override
public void connectToNodeLight(DiscoveryNode node) throws ConnectTransportException {
connectToNode(node);
}
@Override
public void connectToNode(DiscoveryNode node) throws ConnectTransportException {
synchronized (this) {
if (connectedNodes.containsKey(node)) {
return;
}
final LocalTransport targetTransport = transports.get(node.address());
if (targetTransport == null) {
throw new ConnectTransportException(node, "Failed to connect");
}
connectedNodes.put(node, targetTransport);
transportServiceAdapter.raiseNodeConnected(node);
}
}
@Override
public void disconnectFromNode(DiscoveryNode node) {
synchronized (this) {
LocalTransport removed = connectedNodes.remove(node);
if (removed != null) {
transportServiceAdapter.raiseNodeDisconnected(node);
}
}
}
@Override
public long serverOpen() {
return 0;
}
@Override
public void sendRequest(final DiscoveryNode node, final long requestId, final String action, final TransportRequest request, TransportRequestOptions options) throws IOException, TransportException {
final Version version = Version.smallest(node.version(), this.version);
BytesStreamOutput bStream = new BytesStreamOutput();
StreamOutput stream = new HandlesStreamOutput(bStream);
stream.setVersion(version);
stream.writeLong(requestId);
byte status = 0;
status = TransportStatus.setRequest(status);
stream.writeByte(status); // 0 for request, 1 for response.
stream.writeString(action);
request.writeTo(stream);
stream.close();
final LocalTransport targetTransport = connectedNodes.get(node);
if (targetTransport == null) {
throw new NodeNotConnectedException(node, "Node not connected");
}
final byte[] data = bStream.bytes().toBytes();
transportServiceAdapter.sent(data.length);
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
targetTransport.messageReceived(data, action, LocalTransport.this, version, requestId);
}
});
}
ThreadPool threadPool() {
return this.threadPool;
}
protected void messageReceived(byte[] data, String action, LocalTransport sourceTransport, Version version, @Nullable final Long sendRequestId) {
try {
transportServiceAdapter.received(data.length);
StreamInput stream = new BytesStreamInput(data, false);
stream = CachedStreamInput.cachedHandles(stream);
stream.setVersion(version);
long requestId = stream.readLong();
byte status = stream.readByte();
boolean isRequest = TransportStatus.isRequest(status);
if (isRequest) {
handleRequest(stream, requestId, sourceTransport, version);
} else {
final TransportResponseHandler handler = transportServiceAdapter.remove(requestId);
// ignore if its null, the adapter logs it
if (handler != null) {
if (TransportStatus.isError(status)) {
handlerResponseError(stream, handler);
} else {
handleResponse(stream, handler);
}
}
}
} catch (Throwable e) {
if (sendRequestId != null) {
TransportResponseHandler handler = transportServiceAdapter.remove(sendRequestId);
if (handler != null) {
handleException(handler, new RemoteTransportException(nodeName(), localAddress, action, e));
}
} else {
logger.warn("Failed to receive message for action [" + action + "]", e);
}
}
}
private void handleRequest(StreamInput stream, long requestId, LocalTransport sourceTransport, Version version) throws Exception {
final String action = stream.readString();
final LocalTransportChannel transportChannel = new LocalTransportChannel(this, sourceTransport, action, requestId, version);
try {
final TransportRequestHandler handler = transportServiceAdapter.handler(action);
if (handler == null) {
throw new ActionNotFoundTransportException("Action [" + action + "] not found");
}
final TransportRequest request = handler.newInstance();
request.readFrom(stream);
if (handler.executor() == ThreadPool.Names.SAME) {
//noinspection unchecked
handler.messageReceived(request, transportChannel);
} else {
threadPool.executor(handler.executor()).execute(new AbstractRunnable() {
@Override
public void run() {
try {
//noinspection unchecked
handler.messageReceived(request, transportChannel);
} catch (Throwable e) {
if (lifecycleState() == Lifecycle.State.STARTED) {
// we can only send a response transport is started....
try {
transportChannel.sendResponse(e);
} catch (Throwable e1) {
logger.warn("Failed to send error message back to client for action [" + action + "]", e1);
logger.warn("Actual Exception", e);
}
}
}
}
@Override
public boolean isForceExecution() {
return handler.isForceExecution();
}
});
}
} catch (Throwable e) {
try {
transportChannel.sendResponse(e);
} catch (Throwable e1) {
logger.warn("Failed to send error message back to client for action [" + action + "]", e);
logger.warn("Actual Exception", e1);
}
}
}
protected void handleResponse(StreamInput buffer, final TransportResponseHandler handler) {
final TransportResponse response = handler.newInstance();
try {
response.readFrom(buffer);
} catch (Throwable e) {
handleException(handler, new TransportSerializationException("Failed to deserialize response of type [" + response.getClass().getName() + "]", e));
return;
}
handleParsedRespone(response, handler);
}
protected void handleParsedRespone(final TransportResponse response, final TransportResponseHandler handler) {
threadPool.executor(handler.executor()).execute(new Runnable() {
@SuppressWarnings({"unchecked"})
@Override
public void run() {
try {
handler.handleResponse(response);
} catch (Throwable e) {
handleException(handler, new ResponseHandlerFailureTransportException(e));
}
}
});
}
private void handlerResponseError(StreamInput buffer, final TransportResponseHandler handler) {
Throwable error;
try {
ThrowableObjectInputStream ois = new ThrowableObjectInputStream(buffer, settings.getClassLoader());
error = (Throwable) ois.readObject();
} catch (Throwable e) {
error = new TransportSerializationException("Failed to deserialize exception response from stream", e);
}
handleException(handler, error);
}
private void handleException(final TransportResponseHandler handler, Throwable error) {
if (!(error instanceof RemoteTransportException)) {
error = new RemoteTransportException("None remote transport exception", error);
}
final RemoteTransportException rtx = (RemoteTransportException) error;
try {
handler.handleException(rtx);
} catch (Throwable t) {
logger.error("failed to handle exception response [{}]", t, handler);
}
}
} | 1no label
| src_main_java_org_elasticsearch_transport_local_LocalTransport.java |
950 | public class OBase64Utils {
/* ******** P U B L I C F I E L D S ******** */
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
/** Specify encoding in first bit. Value is one. */
public final static int ENCODE = 1;
/** Specify decoding in first bit. Value is zero. */
public final static int DECODE = 0;
/** Specify that data should be gzip-compressed in second bit. Value is two. */
public final static int GZIP = 2;
/** Specify that gzipped data should <em>not</em> be automatically gunzipped. */
public final static int DONT_GUNZIP = 4;
/** Do break lines when encoding. Value is 8. */
public final static int DO_BREAK_LINES = 8;
/**
* Encode using Base64-like encoding that is URL- and Filename-safe as described in Section 4 of RFC3548: <a
* href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. It is important to note that data
* encoded this way is <em>not</em> officially valid Base64, or at the very least should not be called Base64 without also
* specifying that is was encoded using the URL- and Filename-safe dialect.
*/
public final static int URL_SAFE = 16;
/**
* Encode using the special "ordered" dialect of Base64 described here: <a
* href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
public final static int ORDERED = 32;
/* ******** P R I V A T E F I E L D S ******** */
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte) '=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte) '\n';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "US-ASCII";
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in
// encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in
// encoding
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
/** The 64 valid Base64 values. */
/* Host platform me be something funny like EBCDIC, so we hardcode these values. */
private final static byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
(byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P',
(byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
(byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
(byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't',
(byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
(byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' };
/**
* Translates a Base64 value to either its 6-bit reconstruction value or a negative number indicating some other meaning.
**/
private final static byte[] _STANDARD_DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5, -5, // Whitespace: Tab and Linefeed
-9, -9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
-9, -9, -9, -9, -9, // Decimal 27 - 31
-5, // Whitespace: Space
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9, -9, -9, // Decimal 44 - 46
63, // Slash at decimal 47
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
-9, -9, -9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9, -9, -9, // Decimal 62 - 64
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
-9, -9, -9, -9, -9, -9, // Decimal 91 - 96
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
-9, -9, -9, -9, -9 // Decimal 123 - 127
, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255
};
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/**
* Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: <a
* href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. Notice that the last two bytes become
* "hyphen" and "underscore" instead of "plus" and "slash."
*/
private final static byte[] _URL_SAFE_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
(byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P',
(byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
(byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
(byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't',
(byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
(byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_' };
/**
* Used in decoding URL- and Filename-safe dialects of Base64.
*/
private final static byte[] _URL_SAFE_DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5, -5, // Whitespace: Tab and Linefeed
-9, -9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
-9, -9, -9, -9, -9, // Decimal 27 - 31
-5, // Whitespace: Space
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
62, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
-9, -9, -9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9, -9, -9, // Decimal 62 - 64
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
-9, -9, -9, -9, // Decimal 91 - 94
63, // Underscore at decimal 95
-9, // Decimal 96
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
-9, -9, -9, -9, -9 // Decimal 123 - 127
, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255
};
/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
/**
* I don't get the point of this technique, but someone requested it, and it is described here: <a
* href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
private final static byte[] _ORDERED_ALPHABET = { (byte) '-', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
(byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E',
(byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O',
(byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y',
(byte) 'Z', (byte) '_', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h',
(byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r',
(byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z' };
/**
* Used in decoding the "ordered" dialect of Base64.
*/
private final static byte[] _ORDERED_DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5, -5, // Whitespace: Tab and Linefeed
-9, -9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
-9, -9, -9, -9, -9, // Decimal 27 - 31
-5, // Whitespace: Space
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
0, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine
-9, -9, -9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9, -9, -9, // Decimal 62 - 64
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M'
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z'
-9, -9, -9, -9, // Decimal 91 - 94
37, // Underscore at decimal 95
-9, // Decimal 96
38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm'
51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z'
-9, -9, -9, -9, -9 // Decimal 123 - 127
, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255
};
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
/**
* Returns one of the _SOMETHING_ALPHABET byte arrays depending on the options specified. It's possible, though silly, to specify
* ORDERED <b>and</b> URLSAFE in which case one of them will be picked, though there is no guarantee as to which one will be
* picked.
*/
private final static byte[] getAlphabet(int options) {
if ((options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_ALPHABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_ALPHABET;
} else {
return _STANDARD_ALPHABET;
}
} // end getAlphabet
/**
* Returns one of the _SOMETHING_DECODABET byte arrays depending on the options specified. It's possible, though silly, to specify
* ORDERED and URL_SAFE in which case one of them will be picked, though there is no guarantee as to which one will be picked.
*/
private final static byte[] getDecodabet(int options) {
if ((options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_DECODABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_DECODABET;
} else {
return _STANDARD_DECODABET;
}
} // end getAlphabet
/** Defeats instantiation. */
private OBase64Utils() {
}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Encodes up to the first three bytes of array <var>threeBytes</var> and returns a four-byte array in Base64 notation. The actual
* number of significant bytes in your array is given by <var>numSigBytes</var>. The array <var>threeBytes</var> needs only be as
* big as <var>numSigBytes</var>. Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
*
* @param b4
* A reusable byte array to reduce array instantiation
* @param threeBytes
* the array to convert
* @param numSigBytes
* the number of significant bytes in your array
* @return four byte array in Base64 notation.
* @since 1.5.1
*/
private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes, int options) {
encode3to4(threeBytes, 0, numSigBytes, b4, 0, options);
return b4;
} // end encode3to4
/**
* <p>
* Encodes up to three bytes of the array <var>source</var> and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated anywhere along their length by specifying <var>srcOffset</var> and
* <var>destOffset</var>. This method does not check to make sure your arrays are large enough to accomodate <var>srcOffset</var>
* + 3 for the <var>source</var> array or <var>destOffset</var> + 4 for the <var>destination</var> array. The actual number of
* significant bytes in your array is given by <var>numSigBytes</var>.
* </p>
* <p>
* This is the lowest level of the encoding methods with all possible parameters.
* </p>
*
* @param source
* the array to convert
* @param srcOffset
* the index where conversion begins
* @param numSigBytes
* the number of significant bytes in your array
* @param destination
* the array to hold the conversion
* @param destOffset
* the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options) {
byte[] ALPHABET = getAlphabet(options);
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
| (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
| (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
return destination;
case 2:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer, writing it to the <code>encoded</code> ByteBuffer. This is an
* experimental feature. Currently it does not pass along any options (such as {@link #DO_BREAK_LINES} or {@link #GZIP}.
*
* @param raw
* input buffer
* @param encoded
* output buffer
* @since 2.3
*/
public static void encode(java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded) {
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while (raw.hasRemaining()) {
int rem = Math.min(3, raw.remaining());
raw.get(raw3, 0, rem);
OBase64Utils.encode3to4(enc4, raw3, rem, OBase64Utils.NO_OPTIONS);
encoded.put(enc4);
} // end input remaining
}
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer, writing it to the <code>encoded</code> CharBuffer. This is an
* experimental feature. Currently it does not pass along any options (such as {@link #DO_BREAK_LINES} or {@link #GZIP}.
*
* @param raw
* input buffer
* @param encoded
* output buffer
* @since 2.3
*/
public static void encode(java.nio.ByteBuffer raw, java.nio.CharBuffer encoded) {
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while (raw.hasRemaining()) {
int rem = Math.min(3, raw.remaining());
raw.get(raw3, 0, rem);
OBase64Utils.encode3to4(enc4, raw3, rem, OBase64Utils.NO_OPTIONS);
for (int i = 0; i < 4; i++) {
encoded.put((char) (enc4[i] & 0xFF));
}
} // end input remaining
}
/**
* Serializes an object and returns the Base64-encoded version of that serialized object.
*
* <p>
* As of v 2.3, if the object cannot be serialized or there is another error, the method will throw an java.io.IOException.
* <b>This is new to v2.3!</b> In earlier versions, it just returned a null value, but in retrospect that's a pretty poor way to
* handle it.
* </p>
*
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject
* The object to encode
* @return The Base64-encoded object
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if serializedObject is null
* @since 1.4
*/
public static String encodeObject(java.io.Serializable serializableObject) throws java.io.IOException {
return encodeObject(serializableObject, NO_OPTIONS);
} // end encodeObject
/**
* Serializes an object and returns the Base64-encoded version of that serialized object.
*
* <p>
* As of v 2.3, if the object cannot be serialized or there is another error, the method will throw an java.io.IOException.
* <b>This is new to v2.3!</b> In earlier versions, it just returned a null value, but in retrospect that's a pretty poor way to
* handle it.
* </p>
*
* The object is not GZip-compressed before being encoded.
* <p>
* Example options:
*
* <pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* </pre>
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
* @param serializableObject
* The object to encode
* @param options
* Specified options
* @return The Base64-encoded object
* @see OBase64Utils#GZIP
* @see OBase64Utils#DO_BREAK_LINES
* @throws java.io.IOException
* if there is an error
* @since 2.0
*/
public static String encodeObject(java.io.Serializable serializableObject, int options) throws java.io.IOException {
if (serializableObject == null) {
throw new NullPointerException("Cannot serialize a null object.");
} // end if: null
// Streams
java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.util.zip.GZIPOutputStream gzos = null;
java.io.ObjectOutputStream oos = null;
try {
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
b64os = new OBase64Utils.OutputStream(baos, ENCODE | options);
if ((options & GZIP) != 0) {
// Gzip
gzos = new java.util.zip.GZIPOutputStream(b64os, 16384); // 16KB
oos = new java.io.ObjectOutputStream(gzos);
} else {
// Not gzipped
oos = new java.io.ObjectOutputStream(b64os);
}
oos.writeObject(serializableObject);
} // end try
catch (java.io.IOException e) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try {
oos.close();
} catch (Exception e) {
}
try {
gzos.close();
} catch (Exception e) {
}
try {
b64os.close();
} catch (Exception e) {
}
try {
baos.close();
} catch (Exception e) {
}
} // end finally
// Return value according to relevant encoding.
try {
return new String(baos.toByteArray(), PREFERRED_ENCODING);
} // end try
catch (java.io.UnsupportedEncodingException uue) {
// Fall back to some Java default
return new String(baos.toByteArray());
} // end catch
} // end encode
/**
* Encodes a byte array into Base64 notation. Does not GZip-compress data.
*
* @param source
* The data to convert
* @return The data in Base64-encoded form
* @throws NullPointerException
* if source array is null
* @since 1.4
*/
public static StringBuilder encodeBytes(final StringBuilder iOutput, final byte[] source) {
if (source != null) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
try {
iOutput.append(encodeBytes(source, 0, source.length, NO_OPTIONS));
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
}
}
return iOutput;
}
/**
* Encodes a byte array into Base64 notation. Does not GZip-compress data.
*
* @param source
* The data to convert
* @return The data in Base64-encoded form
* @throws NullPointerException
* if source array is null
* @since 1.4
*/
public static String encodeBytes(final byte[] source) {
if (source == null)
return null;
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:
*
* <pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>
* As of v 2.3, if there is an error with the GZIP stream, the method will throw an java.io.IOException. <b>This is new to
* v2.3!</b> In earlier versions, it just returned a null value, but in retrospect that's a pretty poor way to handle it.
* </p>
*
*
* @param source
* The data to convert
* @param options
* Specified options
* @return The Base64-encoded data as a String
* @see OBase64Utils#GZIP
* @see OBase64Utils#DO_BREAK_LINES
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if source array is null
* @since 2.0
*/
public static String encodeBytes(byte[] source, int options) throws java.io.IOException {
return encodeBytes(source, 0, source.length, options);
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation. Does not GZip-compress data.
*
* <p>
* As of v 2.3, if there is an error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier
* versions, it just returned a null value, but in retrospect that's a pretty poor way to handle it.
* </p>
*
*
* @param source
* The data to convert
* @param off
* Offset in array where conversion should begin
* @param len
* Length of data to convert
* @return The Base64-encoded data as a String
* @throws NullPointerException
* if source array is null
* @throws IllegalArgumentException
* if source array, offset, or length are invalid
* @since 1.4
*/
public static String encodeBytes(byte[] source, int off, int len) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes(source, off, len, NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:
*
* <pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>
* As of v 2.3, if there is an error with the GZIP stream, the method will throw an java.io.IOException. <b>This is new to
* v2.3!</b> In earlier versions, it just returned a null value, but in retrospect that's a pretty poor way to handle it.
* </p>
*
*
* @param source
* The data to convert
* @param off
* Offset in array where conversion should begin
* @param len
* Length of data to convert
* @param options
* Specified options
* @return The Base64-encoded data as a String
* @see OBase64Utils#GZIP
* @see OBase64Utils#DO_BREAK_LINES
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if source array is null
* @throws IllegalArgumentException
* if source array, offset, or length are invalid
* @since 2.0
*/
public static String encodeBytes(final byte[] source, final int off, final int len, final int options) throws java.io.IOException {
final byte[] encoded = encodeBytesToBytes(source, off, len, options);
// Return value according to relevant encoding.
try {
return new String(encoded, PREFERRED_ENCODING);
} // end try
catch (java.io.UnsupportedEncodingException uue) {
return new String(encoded);
} // end catch
} // end encodeBytes
/**
* Similar to {@link #encodeBytes(byte[])} but returns a byte array instead of instantiating a String. This is more efficient if
* you're working with I/O streams and have large data sets to encode.
*
*
* @param source
* The data to convert
* @return The Base64-encoded data as a byte[] (of ASCII characters)
* @throws NullPointerException
* if source array is null
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes(byte[] source) {
byte[] encoded = null;
try {
encoded = encodeBytesToBytes(source, 0, source.length, OBase64Utils.NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
}
return encoded;
}
/**
* Similar to {@link #encodeBytes(byte[], int, int, int)} but returns a byte array instead of instantiating a String. This is more
* efficient if you're working with I/O streams and have large data sets to encode.
*
*
* @param source
* The data to convert
* @param off
* Offset in array where conversion should begin
* @param len
* Length of data to convert
* @param options
* Specified options
* @return The Base64-encoded data as a String
* @see OBase64Utils#GZIP
* @see OBase64Utils#DO_BREAK_LINES
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if source array is null
* @throws IllegalArgumentException
* if source array, offset, or length are invalid
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int options) throws java.io.IOException {
if (source == null) {
throw new NullPointerException("Cannot serialize a null array.");
} // end if: null
if (off < 0) {
throw new IllegalArgumentException("Cannot have negative offset: " + off);
} // end if: off < 0
if (len < 0) {
throw new IllegalArgumentException("Cannot have length offset: " + len);
} // end if: len < 0
if (off + len > source.length) {
throw new IllegalArgumentException(String.format("Cannot have offset of %d and length of %d with array of length %d", off,
len, source.length));
} // end if: off < 0
// Compress?
if ((options & GZIP) != 0) {
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
OBase64Utils.OutputStream b64os = null;
try {
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new OBase64Utils.OutputStream(baos, ENCODE | options);
gzos = new java.util.zip.GZIPOutputStream(b64os, 16384); // 16KB
gzos.write(source, off, len);
gzos.close();
} // end try
catch (java.io.IOException e) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try {
gzos.close();
} catch (Exception e) {
}
try {
b64os.close();
} catch (Exception e) {
}
try {
baos.close();
} catch (Exception e) {
}
} // end finally
return baos.toByteArray();
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else {
boolean breakLines = (options & DO_BREAK_LINES) != 0;
// int len43 = len * 4 / 3;
// byte[] outBuff = new byte[ ( len43 ) // Main 4:3
// + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
// + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
// Try to determine more precisely how big the array needs to be.
// If we get it right, we don't have to do an array copy, and
// we save a bunch of memory.
int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed for actual encoding
if (breakLines) {
encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters
}
byte[] outBuff = new byte[encLen];
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for (; d < len2; d += 3, e += 4) {
encode3to4(source, d + off, 3, outBuff, e, options);
lineLength += 4;
if (breakLines && lineLength >= MAX_LINE_LENGTH) {
outBuff[e + 4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e, options);
e += 4;
} // end if: some padding needed
// Only resize array if we didn't guess it right.
if (e <= outBuff.length - 1) {
// If breaking lines and the last byte falls right at
// the line length (76 bytes per line), there will be
// one extra byte, and the array will need to be resized.
// Not too bad of an estimate on array size, I'd say.
byte[] finalOut = new byte[e];
System.arraycopy(outBuff, 0, finalOut, 0, e);
// System.err.println("Having to resize array from " + outBuff.length + " to " + e );
return finalOut;
} else {
// System.err.println("No need to resize array.");
return outBuff;
}
} // end else: don't compress
} // end encodeBytesToBytes
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var> and writes the resulting bytes (up to three of them) to <var>destination</var>.
* The source and destination arrays can be manipulated anywhere along their length by specifying <var>srcOffset</var> and
* <var>destOffset</var>. This method does not check to make sure your arrays are large enough to accomodate <var>srcOffset</var>
* + 4 for the <var>source</var> array or <var>destOffset</var> + 3 for the <var>destination</var> array. This method returns the
* actual number of bytes that were converted from the Base64 encoding.
* <p>
* This is the lowest level of the decoding methods with all possible parameters.
* </p>
*
*
* @param source
* the array to convert
* @param srcOffset
* the index where conversion begins
* @param destination
* the array to hold the conversion
* @param destOffset
* the index where output will be put
* @param options
* alphabet type is pulled from this (standard, url-safe, ordered)
* @return the number of decoded bytes converted
* @throws NullPointerException
* if source or destination arrays are null
* @throws IllegalArgumentException
* if srcOffset or destOffset are invalid or there is not enough room in the array.
* @since 1.3
*/
private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset, int options) {
// Lots of error checking and exception throwing
if (source == null) {
throw new NullPointerException("Source array was null.");
} // end if
if (destination == null) {
throw new NullPointerException("Destination array was null.");
} // end if
if (srcOffset < 0 || srcOffset + 3 >= source.length) {
throw new IllegalArgumentException(String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset));
} // end if
if (destOffset < 0 || destOffset + 2 >= destination.length) {
throw new IllegalArgumentException(String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset));
} // end if
byte[] DECODABET = getDecodabet(options);
// Example: Dk==
if (source[srcOffset + 2] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12);
destination[destOffset] = (byte) (outBuff >>> 16);
return 1;
}
// Example: DkL=
else if (source[srcOffset + 3] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
| ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6);
destination[destOffset] = (byte) (outBuff >>> 16);
destination[destOffset + 1] = (byte) (outBuff >>> 8);
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
| ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) | ((DECODABET[source[srcOffset + 3]] & 0xFF));
destination[destOffset] = (byte) (outBuff >> 16);
destination[destOffset + 1] = (byte) (outBuff >> 8);
destination[destOffset + 2] = (byte) (outBuff);
return 3;
}
} // end decodeToBytes
/**
* Low-level access to decoding ASCII characters in the form of a byte array. <strong>Ignores GUNZIP option, if it's set.</strong>
* This is not generally a recommended method, although it is used internally as part of the decoding process. Special case: if
* len = 0, an empty array is returned. Still, if you need more speed and reduced memory footprint (and aren't gzipping), consider
* this method.
*
* @param source
* The Base64 encoded data
* @return decoded data
* @since 2.3.1
*/
public static byte[] decode(byte[] source) throws java.io.IOException {
byte[] decoded = null;
// try {
decoded = decode(source, 0, source.length, OBase64Utils.NO_OPTIONS);
// } catch( java.io.IOException ex ) {
// assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
// }
return decoded;
}
/**
* Low-level access to decoding ASCII characters in the form of a byte array. <strong>Ignores GUNZIP option, if it's set.</strong>
* This is not generally a recommended method, although it is used internally as part of the decoding process. Special case: if
* len = 0, an empty array is returned. Still, if you need more speed and reduced memory footprint (and aren't gzipping), consider
* this method.
*
* @param source
* The Base64 encoded data
* @param off
* The offset of where to begin decoding
* @param len
* The length of characters to decode
* @param options
* Can specify options such as alphabet type to use
* @return decoded data
* @throws java.io.IOException
* If bogus characters exist in source data
* @since 1.3
*/
public static byte[] decode(byte[] source, int off, int len, int options) {
// Lots of error checking and exception throwing
if (source == null) {
throw new NullPointerException("Cannot decode null source array.");
} // end if
if (off < 0 || off + len > source.length) {
throw new IllegalArgumentException(String.format(
"Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len));
} // end if
if (len == 0) {
return new byte[0];
} else if (len < 4) {
throw new IllegalArgumentException("Base64-encoded string must have at least four characters, but length specified was "
+ len);
} // end if
byte[] DECODABET = getDecodabet(options);
int len34 = len * 3 / 4; // Estimate on array size
byte[] outBuff = new byte[len34]; // Upper limit on size of output
int outBuffPosn = 0; // Keep track of where we're writing
byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
int b4Posn = 0; // Keep track of four byte input buffer
int i = 0; // Source array counter
byte sbiDecode = 0; // Special value from DECODABET
for (i = off; i < off + len; i++) { // Loop through source
sbiDecode = DECODABET[source[i] & 0xFF];
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if (sbiDecode >= WHITE_SPACE_ENC) {
if (sbiDecode >= EQUALS_SIGN_ENC) {
b4[b4Posn++] = source[i]; // Save non-whitespace
if (b4Posn > 3) { // Time to decode?
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, options);
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if (source[i] == EQUALS_SIGN) {
break;
} // end if: equals sign
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
// There's a bad input character in the Base64 stream.
throw new OIOException(String.format("Bad Base64 input character decimal %d in array position %d", (source[i]) & 0xFF, i));
} // end else:
} // each input character
byte[] out = new byte[outBuffPosn];
System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically detecting gzip-compressed data and decompressing it.
*
* @param s
* the string to decode
* @return the decoded data
* @throws java.io.IOException
* If there is a problem
* @since 1.4
*/
public static byte[] decode(String s) {
return decode(s, DONT_GUNZIP);
}
/**
* Decodes data from Base64 notation, automatically detecting gzip-compressed data and decompressing it.
*
* @param s
* the string to decode
* @param options
* encode options such as URL_SAFE
* @return the decoded data
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if <tt>s</tt> is null
* @since 1.4
*/
public static byte[] decode(String s, int options) {
if (s == null) {
throw new NullPointerException("Input string was null.");
} // end if
byte[] bytes;
try {
bytes = s.getBytes(PREFERRED_ENCODING);
} // end try
catch (java.io.UnsupportedEncodingException uee) {
bytes = s.getBytes();
} // end catch
// </change>
// Decode
bytes = decode(bytes, 0, bytes.length, options);
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
boolean dontGunzip = (options & DONT_GUNZIP) != 0;
if ((bytes != null) && (bytes.length >= 4) && (!dontGunzip)) {
int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) {
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length = 0;
try {
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream(bytes);
gzis = new java.util.zip.GZIPInputStream(bais, 16384); // 16KB
while ((length = gzis.read(buffer)) >= 0) {
baos.write(buffer, 0, length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch (java.io.IOException e) {
e.printStackTrace();
// Just return originally-decoded bytes
} // end catch
finally {
try {
baos.close();
} catch (Exception e) {
}
try {
gzis.close();
} catch (Exception e) {
}
try {
bais.close();
} catch (Exception e) {
}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
} // end decode
/**
* Attempts to decode Base64 data and deserialize a Java Object within. Returns <tt>null</tt> if there was an error.
*
* @param encodedObject
* The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException
* if encodedObject is null
* @throws java.io.IOException
* if there is a general error
* @throws ClassNotFoundException
* if the decoded object is of a class that cannot be found by the JVM
* @since 1.5
*/
public static Object decodeToObject(String encodedObject) throws java.io.IOException, java.lang.ClassNotFoundException {
return decodeToObject(encodedObject, NO_OPTIONS, null);
}
/**
* Attempts to decode Base64 data and deserialize a Java Object within. Returns <tt>null</tt> if there was an error. If
* <tt>loader</tt> is not null, it will be the class loader used when deserializing.
*
* @param encodedObject
* The Base64 data to decode
* @param options
* Various parameters related to decoding
* @param loader
* Optional class loader to use in deserializing classes.
* @return The decoded and deserialized object
* @throws NullPointerException
* if encodedObject is null
* @throws java.io.IOException
* if there is a general error
* @throws ClassNotFoundException
* if the decoded object is of a class that cannot be found by the JVM
* @since 2.3.4
*/
public static Object decodeToObject(String encodedObject, int options, final ClassLoader loader) throws java.io.IOException,
java.lang.ClassNotFoundException {
// Decode and gunzip if necessary
byte[] objBytes = decode(encodedObject, options);
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream(objBytes);
// If no custom class loader is provided, use Java's builtin OIS.
if (loader == null) {
ois = new java.io.ObjectInputStream(bais);
} // end if: no loader provided
// Else make a customized object input stream that uses
// the provided class loader.
else {
ois = new java.io.ObjectInputStream(bais) {
@Override
public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException {
Class<?> c = Class.forName(streamClass.getName(), false, loader);
if (c == null) {
return super.resolveClass(streamClass);
} else {
return c; // Class loader knows of this class.
} // end else: not null
} // end resolveClass
}; // end ois
} // end else: no custom class loader
obj = ois.readObject();
} // end try
catch (java.io.IOException e) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
catch (java.lang.ClassNotFoundException e) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
finally {
try {
bais.close();
} catch (Exception e) {
}
try {
ois.close();
} catch (Exception e) {
}
} // end finally
return obj;
} // end decodeObject
/**
* Convenience method for encoding data to a file.
*
* <p>
* As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier
* versions, it just returned false, but in retrospect that's a pretty poor way to handle it.
* </p>
*
* @param dataToEncode
* byte array of data to encode in base64 form
* @param filename
* Filename for saving encoded data
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if dataToEncode is null
* @since 2.1
*/
public static void encodeToFile(byte[] dataToEncode, String filename) throws java.io.IOException {
if (dataToEncode == null) {
throw new NullPointerException("Data to encode was null.");
} // end iff
OBase64Utils.OutputStream bos = null;
try {
bos = new OBase64Utils.OutputStream(new java.io.FileOutputStream(filename), OBase64Utils.ENCODE);
bos.write(dataToEncode);
} // end try
catch (java.io.IOException e) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try {
bos.close();
} catch (Exception e) {
}
} // end finally
} // end encodeToFile
/**
* Convenience method for decoding data to a file.
*
* <p>
* As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier
* versions, it just returned false, but in retrospect that's a pretty poor way to handle it.
* </p>
*
* @param dataToDecode
* Base64-encoded data as a string
* @param filename
* Filename for saving decoded data
* @throws java.io.IOException
* if there is an error
* @since 2.1
*/
public static void decodeToFile(String dataToDecode, String filename) throws java.io.IOException {
OBase64Utils.OutputStream bos = null;
try {
bos = new OBase64Utils.OutputStream(new java.io.FileOutputStream(filename), OBase64Utils.DECODE);
bos.write(dataToDecode.getBytes(PREFERRED_ENCODING));
} // end try
catch (java.io.IOException e) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try {
bos.close();
} catch (Exception e) {
}
} // end finally
} // end decodeToFile
/**
* Convenience method for reading a base64-encoded file and decoding it.
*
* <p>
* As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier
* versions, it just returned false, but in retrospect that's a pretty poor way to handle it.
* </p>
*
* @param filename
* Filename for reading encoded data
* @return decoded byte array
* @throws java.io.IOException
* if there is an error
* @since 2.1
*/
public static byte[] decodeFromFile(String filename) throws java.io.IOException {
byte[] decodedData = null;
OBase64Utils.InputStream bis = null;
try {
// Set up some useful variables
java.io.File file = new java.io.File(filename);
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if (file.length() > Integer.MAX_VALUE) {
throw new java.io.IOException("File is too big for this convenience method (" + file.length() + " bytes).");
} // end if: file too big for int index
buffer = new byte[(int) file.length()];
// Open a stream
bis = new OBase64Utils.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), OBase64Utils.DECODE);
// Read until done
while ((numBytes = bis.read(buffer, length, 4096)) >= 0) {
length += numBytes;
} // end while
// Save in a variable to return
decodedData = new byte[length];
System.arraycopy(buffer, 0, decodedData, 0, length);
} // end try
catch (java.io.IOException e) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try {
bis.close();
} catch (Exception e) {
}
} // end finally
return decodedData;
} // end decodeFromFile
/**
* Convenience method for reading a binary file and base64-encoding it.
*
* <p>
* As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier
* versions, it just returned false, but in retrospect that's a pretty poor way to handle it.
* </p>
*
* @param filename
* Filename for reading binary data
* @return base64-encoded string
* @throws java.io.IOException
* if there is an error
* @since 2.1
*/
public static String encodeFromFile(String filename) throws java.io.IOException {
String encodedData = null;
OBase64Utils.InputStream bis = null;
try {
// Set up some useful variables
java.io.File file = new java.io.File(filename);
byte[] buffer = new byte[Math.max((int) (file.length() * 1.4 + 1), 40)]; // Need max() for math on small files (v2.2.1); Need
// +1 for a few corner cases (v2.3.5)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new OBase64Utils.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), OBase64Utils.ENCODE);
// Read until done
while ((numBytes = bis.read(buffer, length, 4096)) >= 0) {
length += numBytes;
} // end while
// Save in a variable to return
encodedData = new String(buffer, 0, length, OBase64Utils.PREFERRED_ENCODING);
} // end try
catch (java.io.IOException e) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try {
bis.close();
} catch (Exception e) {
}
} // end finally
return encodedData;
} // end encodeFromFile
/**
* Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
*
* @param infile
* Input file
* @param outfile
* Output file
* @throws java.io.IOException
* if there is an error
* @since 2.2
*/
public static void encodeFileToFile(String infile, String outfile) throws java.io.IOException {
String encoded = OBase64Utils.encodeFromFile(infile);
java.io.OutputStream out = null;
try {
out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
out.write(encoded.getBytes("US-ASCII")); // Strict, 7-bit output.
} // end try
catch (java.io.IOException e) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try {
out.close();
} catch (Exception ex) {
}
} // end finally
} // end encodeFileToFile
/**
* Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
*
* @param infile
* Input file
* @param outfile
* Output file
* @throws java.io.IOException
* if there is an error
* @since 2.2
*/
public static void decodeFileToFile(String infile, String outfile) throws java.io.IOException {
byte[] decoded = OBase64Utils.decodeFromFile(infile);
java.io.OutputStream out = null;
try {
out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
out.write(decoded);
} // end try
catch (java.io.IOException e) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try {
out.close();
} catch (Exception ex) {
}
} // end finally
} // end decodeFileToFile
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
/**
* A {@link OBase64Utils.InputStream} will read data from another <tt>java.io.InputStream</tt>, given in the constructor, and
* encode/decode to/from Base64 notation on the fly.
*
* @see OBase64Utils
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream {
private boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private byte[] buffer; // Small buffer holding converted data
private int bufferLength; // Length of buffer (3 or 4)
private int numSigBytes; // Number of meaningful bytes in the buffer
private int lineLength;
private boolean breakLines; // Break lines at less than 80 characters
private int options; // Record options used to create the stream.
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link OBase64Utils.InputStream} in DECODE mode.
*
* @param in
* the <tt>java.io.InputStream</tt> from which to read data.
* @since 1.3
*/
public InputStream(java.io.InputStream in) {
this(in, DECODE);
} // end constructor
/**
* Constructs a {@link OBase64Utils.InputStream} in either ENCODE or DECODE mode.
* <p>
* Valid options:
*
* <pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
*
*
* @param in
* the <tt>java.io.InputStream</tt> from which to read data.
* @param options
* Specified options
* @see OBase64Utils#ENCODE
* @see OBase64Utils#DECODE
* @see OBase64Utils#DO_BREAK_LINES
* @since 2.0
*/
public InputStream(java.io.InputStream in, int options) {
super(in);
this.options = options; // Record for later
this.breakLines = (options & DO_BREAK_LINES) > 0;
this.encode = (options & ENCODE) > 0;
this.bufferLength = encode ? 4 : 3;
this.buffer = new byte[bufferLength];
this.position = -1;
this.lineLength = 0;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Reads enough of the input stream to convert to/from Base64 and returns the next byte.
*
* @return next byte
* @since 1.3
*/
@Override
public int read() throws java.io.IOException {
// Do we need to get data?
if (position < 0) {
if (encode) {
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for (int i = 0; i < 3; i++) {
int b = in.read();
// If end of stream, b is -1.
if (b >= 0) {
b3[i] = (byte) b;
numBinaryBytes++;
} else {
break; // out of for loop
} // end else: end of stream
} // end for: each needed input byte
if (numBinaryBytes > 0) {
encode3to4(b3, 0, numBinaryBytes, buffer, 0, options);
position = 0;
numSigBytes = 4;
} // end if: got data
else {
return -1; // Must be end of stream
} // end else
} // end if: encoding
// Else decoding
else {
byte[] b4 = new byte[4];
int i = 0;
for (i = 0; i < 4; i++) {
// Read four "meaningful" bytes:
int b = 0;
do {
b = in.read();
} while (b >= 0 && decodabet[b & 0x7f] <= WHITE_SPACE_ENC);
if (b < 0) {
break; // Reads a -1 if end of stream
} // end if: end of stream
b4[i] = (byte) b;
} // end for: each needed input byte
if (i == 4) {
numSigBytes = decode4to3(b4, 0, buffer, 0, options);
position = 0;
} // end if: got four characters
else if (i == 0) {
return -1;
} // end else if: also padded correctly
else {
// Must have broken out from above.
throw new java.io.IOException("Improperly padded Base64 input.");
} // end
} // end else: decode
} // end else: get data
// Got data?
if (position >= 0) {
// End of relevant data?
if ( /* !encode && */position >= numSigBytes) {
return -1;
} // end if: got data
if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) {
lineLength = 0;
return '\n';
} // end if
else {
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[position++];
if (position >= bufferLength) {
position = -1;
} // end if: end
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else {
throw new java.io.IOException("Error in Base64 code reading stream.");
} // end else
} // end read
/**
* Calls {@link #read()} repeatedly until the end of stream is reached or <var>len</var> bytes are read. Returns number of bytes
* read into array or -1 if end of stream is encountered.
*
* @param dest
* array to hold values
* @param off
* offset for array
* @param len
* max number of bytes to read into array
* @return bytes read into array or -1 if end of stream is encountered.
* @since 1.3
*/
@Override
public int read(byte[] dest, int off, int len) throws java.io.IOException {
int i;
int b;
for (i = 0; i < len; i++) {
b = read();
if (b >= 0) {
dest[off + i] = (byte) b;
} else if (i == 0) {
return -1;
} else {
break; // Out of 'for' loop
} // Out of 'for' loop
} // end for: each byte read
return i;
} // end read
} // end inner class InputStream
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
/**
* A {@link OBase64Utils.OutputStream} will write data to another <tt>java.io.OutputStream</tt>, given in the constructor, and
* encode/decode to/from Base64 notation on the fly.
*
* @see OBase64Utils
* @since 1.3
*/
public static class OutputStream extends java.io.FilterOutputStream {
private boolean encode;
private int position;
private byte[] buffer;
private int bufferLength;
private int lineLength;
private boolean breakLines;
private byte[] b4; // Scratch used in a few places
private boolean suspendEncoding;
private int options; // Record for later
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link OBase64Utils.OutputStream} in ENCODE mode.
*
* @param out
* the <tt>java.io.OutputStream</tt> to which data will be written.
* @since 1.3
*/
public OutputStream(java.io.OutputStream out) {
this(out, ENCODE);
} // end constructor
/**
* Constructs a {@link OBase64Utils.OutputStream} in either ENCODE or DECODE mode.
* <p>
* Valid options:
*
* <pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
*
* @param out
* the <tt>java.io.OutputStream</tt> to which data will be written.
* @param options
* Specified options.
* @see OBase64Utils#ENCODE
* @see OBase64Utils#DECODE
* @see OBase64Utils#DO_BREAK_LINES
* @since 1.3
*/
public OutputStream(java.io.OutputStream out, int options) {
super(out);
this.breakLines = (options & DO_BREAK_LINES) != 0;
this.encode = (options & ENCODE) != 0;
this.bufferLength = encode ? 3 : 4;
this.buffer = new byte[bufferLength];
this.position = 0;
this.lineLength = 0;
this.suspendEncoding = false;
this.b4 = new byte[4];
this.options = options;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Writes the byte to the output stream after converting to/from Base64 notation. When encoding, bytes are buffered three at a
* time before the output stream actually gets a write() call. When decoding, bytes are buffered four at a time.
*
* @param theByte
* the byte to write
* @since 1.3
*/
@Override
public void write(int theByte) throws java.io.IOException {
// Encoding suspended?
if (suspendEncoding) {
this.out.write(theByte);
return;
} // end if: supsended
// Encode?
if (encode) {
buffer[position++] = (byte) theByte;
if (position >= bufferLength) { // Enough to encode.
this.out.write(encode3to4(b4, buffer, bufferLength, options));
lineLength += 4;
if (breakLines && lineLength >= MAX_LINE_LENGTH) {
this.out.write(NEW_LINE);
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else {
// Meaningful Base64 character?
if (decodabet[theByte & 0x7f] > WHITE_SPACE_ENC) {
buffer[position++] = (byte) theByte;
if (position >= bufferLength) { // Enough to output.
int len = OBase64Utils.decode4to3(buffer, 0, b4, 0, options);
out.write(b4, 0, len);
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if (decodabet[theByte & 0x7f] != WHITE_SPACE_ENC) {
throw new java.io.IOException("Invalid character in Base64 data.");
} // end else: not white space either
} // end else: decoding
} // end write
/**
* Calls {@link #write(int)} repeatedly until <var>len</var> bytes are written.
*
* @param theBytes
* array from which to read bytes
* @param off
* offset for array
* @param len
* max number of bytes to read into array
* @since 1.3
*/
@Override
public void write(byte[] theBytes, int off, int len) throws java.io.IOException {
// Encoding suspended?
if (suspendEncoding) {
this.out.write(theBytes, off, len);
return;
} // end if: supsended
for (int i = 0; i < len; i++) {
write(theBytes[off + i]);
} // end for: each byte written
} // end write
/**
* Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer without closing the stream.
*
* @throws java.io.IOException
* if there's an error.
*/
public void flushBase64() throws java.io.IOException {
if (position > 0) {
if (encode) {
out.write(encode3to4(b4, buffer, position, options));
position = 0;
} // end if: encoding
else {
throw new java.io.IOException("Base64 input not properly padded.");
} // end else: decoding
} // end if: buffer partially full
} // end flush
/**
* Flushes and closes (I think, in the superclass) the stream.
*
* @since 1.3
*/
@Override
public void close() throws java.io.IOException {
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
} // end close
/**
* Suspends encoding of the stream. May be helpful if you need to embed a piece of base64-encoded data in a stream.
*
* @throws java.io.IOException
* if there's an error flushing
* @since 1.5.1
*/
public void suspendEncoding() throws java.io.IOException {
flushBase64();
this.suspendEncoding = true;
} // end suspendEncoding
/**
* Resumes encoding of the stream. May be helpful if you need to embed a piece of base64-encoded data in a stream.
*
* @since 1.5.1
*/
public void resumeEncoding() {
this.suspendEncoding = false;
} // end resumeEncoding
} // end inner class OutputStream
} // end class Base64 | 0true
| core_src_main_java_com_orientechnologies_orient_core_serialization_OBase64Utils.java |
1,773 | public class OMailPlugin extends OServerPluginAbstract implements OScriptInjection {
private static final String CONFIG_PROFILE_PREFIX = "profile.";
private static final String CONFIG_MAIL_PREFIX = "mail.";
private Map<String, OMailProfile> profiles = new HashMap<String, OMailProfile>();
public OMailPlugin() {
Orient.instance().getScriptManager().registerInjection(this);
}
@Override
public void config(final OServer oServer, final OServerParameterConfiguration[] iParams) {
for (OServerParameterConfiguration param : iParams) {
if (param.name.equalsIgnoreCase("enabled")) {
if (!Boolean.parseBoolean(param.value))
// DISABLE IT
return;
} else if (param.name.startsWith(CONFIG_PROFILE_PREFIX)) {
final String parts = param.name.substring(CONFIG_PROFILE_PREFIX.length());
int pos = parts.indexOf('.');
if (pos == -1)
continue;
final String profileName = parts.substring(0, pos);
final String profileParam = parts.substring(pos + 1);
OMailProfile profile = profiles.get(profileName);
if (profile == null) {
profile = new OMailProfile();
profiles.put(profileName, profile);
}
if (profileParam.startsWith(CONFIG_MAIL_PREFIX)) {
profile.put("mail." + profileParam.substring(CONFIG_MAIL_PREFIX.length()), param.value);
}
}
}
OLogManager.instance().info(this, "Mail plugin installed and active. Loaded %d profile(s): %s", profiles.size(),
profiles.keySet());
}
/**
* Sends an email. Supports the following configuration: subject, message, to, cc, bcc, date, attachments
*
* @param iMessage
* Configuration as Map<String,Object>
* @throws AddressException
* @throws MessagingException
* @throws ParseException
*/
public void send(final Map<String, Object> iMessage) throws AddressException, MessagingException, ParseException {
final String profileName = (String) iMessage.get("profile");
final OMailProfile profile = profiles.get(profileName);
if (profile == null)
throw new IllegalArgumentException("Mail profile '" + profileName + "' is not configured on server");
// creates a new session with an authenticator
Authenticator auth = new OSMTPAuthenticator((String) profile.getProperty("mail.smtp.user"),
(String) profile.getProperty("mail.smtp.password"));
Session session = Session.getInstance(profile, auth);
// creates a new e-mail message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress((String) iMessage.get("from")));
InternetAddress[] toAddresses = { new InternetAddress(
(String) iMessage.get("to")) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
String cc = (String) iMessage.get("cc");
if (cc != null && !cc.isEmpty()) {
InternetAddress[] ccAddresses = { new InternetAddress(cc) };
msg.setRecipients(Message.RecipientType.CC, ccAddresses);
}
String bcc = (String) iMessage.get("bcc");
if (bcc != null && !bcc.isEmpty()) {
InternetAddress[] bccAddresses = { new InternetAddress(bcc) };
msg.setRecipients(Message.RecipientType.BCC, bccAddresses);
}
msg.setSubject((String) iMessage.get("subject"));
// DATE
Object date = iMessage.get("date");
final Date sendDate;
if (date == null)
// NOT SPECIFIED = NOW
sendDate = new Date();
else if (date instanceof Date)
// PASSED
sendDate = (Date) date;
else {
// FORMAT IT
String dateFormat = (String) profile.getProperty("mail.date.format");
if (dateFormat == null)
dateFormat = "yyyy-MM-dd HH:mm:ss";
sendDate = new SimpleDateFormat(dateFormat).parse(date.toString());
}
msg.setSentDate(sendDate);
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(iMessage.get("message"), "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
final String[] attachments = (String[]) iMessage.get("attachments");
// adds attachments
if (attachments != null && attachments.length > 0) {
for (String filePath : attachments) {
addAttachment(multipart, filePath);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
/**
* Adds a file as an attachment to the email's content
*
* @param multipart
* @param filePath
* @throws MessagingException
*/
private void addAttachment(final Multipart multipart, final String filePath) throws MessagingException {
MimeBodyPart attachPart = new MimeBodyPart();
DataSource source = new FileDataSource(filePath);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(new File(filePath).getName());
multipart.addBodyPart(attachPart);
}
@Override
public void bind(Bindings binding) {
binding.put("mail", this);
}
@Override
public void unbind(Bindings binding) {
binding.remove("mail");
}
@Override
public String getName() {
return "mail";
}
public Set<String> getProfileNames() {
return profiles.keySet();
}
public OMailProfile getProfile(final String iName) {
return profiles.get(iName);
}
public OMailPlugin registerProfile(final String iName, final OMailProfile iProfile) {
profiles.put(iName, iProfile);
return this;
}
} | 1no label
| server_src_main_java_com_orientechnologies_orient_server_plugin_mail_OMailPlugin.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.