code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
@Override
public boolean containsKey(Object key)
{
if (key == null) {
return false;
}
K []keys = _keys;
for (int i = _size - 1 ; i >= 0; i--) {
K testKey = keys[i];
if (key.equals(testKey)) {
return true;
}
}
return false;
} | java |
public void start()
{
_state = _state.toStart();
_bufferCapacity = DEFAULT_SIZE;
_tBuf = TempBuffer.create();
_buffer = _tBuf.buffer();
_startOffset = bufferStart();
_offset = _startOffset;
_contentLength = 0;
} | java |
@Override
public void write(int ch)
throws IOException
{
if (isClosed() || isHead()) {
return;
}
int offset = _offset;
if (SIZE <= offset) {
flushByteBuffer();
offset = _offset;
}
_buffer[offset++] = (byte) ch;
_offset = offset;
} | java |
@Override
public void write(byte []buffer, int offset, int length)
{
if (isClosed() || isHead()) {
return;
}
int byteLength = _offset;
while (true) {
int sublen = Math.min(length, SIZE - byteLength);
System.arraycopy(buffer, offset, _buffer, byteLength, sublen);
offset += sublen;
length -= sublen;
byteLength += sublen;
if (length <= 0) {
break;
}
_offset = byteLength;
flushByteBuffer();
byteLength = _offset;
}
_offset = byteLength;
} | java |
@Override
public byte []nextBuffer(int offset)
throws IOException
{
if (offset < 0 || SIZE < offset) {
throw new IllegalStateException(L.l("Invalid offset: " + offset));
}
if (_bufferCapacity <= SIZE
|| _bufferCapacity <= offset + _bufferSize) {
_offset = offset;
flushByteBuffer();
return buffer();
}
else {
_tBuf.length(offset);
_bufferSize += offset;
TempBuffer tempBuf = TempBuffer.create();
_tBuf.next(tempBuf);
_tBuf = tempBuf;
_buffer = _tBuf.buffer();
_offset = _startOffset;
return _buffer;
}
} | java |
@Override
public final void close()
throws IOException
{
State state = _state;
if (state.isClosing()) {
return;
}
_state = state.toClosing();
try {
flush(true);
} finally {
try {
_state = _state.toClose();
} catch (RuntimeException e) {
throw new RuntimeException(state + ": " + e, e);
}
}
} | java |
private void flush(boolean isEnd)
{
if (_startOffset == _offset && _bufferSize == 0) {
if (! isCommitted() || isEnd) {
flush(null, isEnd);
_startOffset = bufferStart();
_offset = _startOffset;
}
return;
}
int sublen = _offset - _startOffset;
_tBuf.length(_offset);
_contentLength += _offset - _startOffset;
_bufferSize = 0;
if (_startOffset > 0) {
fillChunkHeader(_tBuf, sublen);
}
flush(_tBuf, isEnd);
if (! isEnd) {
_tBuf = TempBuffer.create();
_startOffset = bufferStart();
_offset = _startOffset;
_tBuf.length(_offset);
_buffer = _tBuf.buffer();
}
else {
_tBuf = null;
}
} | java |
private boolean readSend(InH3 hIn,
OutboxAmp outbox,
HeadersAmp headers)
throws IOException
{
MethodRefHamp methodHamp = null;
try {
methodHamp = readMethod(hIn);
} catch (Throwable e) {
log.log(Level.FINER, e.toString(), e);
skipArgs(hIn);
return true;
}
MethodRefAmp method = methodHamp.getMethod();
//ClassLoader loader = method.getService().getManager().getClassLoader();
ClassLoader loader = methodHamp.getClassLoader();
Thread thread = Thread.currentThread();
thread.setContextClassLoader(loader);
// XXX: _serializer.setClassLoader(loader);
Object []args = readArgs(methodHamp, hIn);
if (log.isLoggable(_logLevel)) {
log.log(_logLevel, this + " send-r " + method.getName() + debugArgs(args)
+ " {to:" + method + ", " + headers + "}");
}
// XXX: s/b systemMailbox
SendMessage_N sendMessage
= new SendMessage_N(outbox,
headers,
method.serviceRef(), method.method(),
args);
long timeout = 1000L; // mailbox delay timeout
try {
//sendMessage.offer(timeout);
//sendMessage.offerQueue(timeout);
// // sendMessage.getWorker().wake();
sendMessage.offer(timeout);
} catch (Throwable e) {
log.fine(e.toString());
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, e.toString(), e);
}
}
return true;
} | java |
private void readQuery(InH3 hIn,
OutboxAmp outbox,
HeadersAmp headers)
throws IOException
{
GatewayReply from = readFromAddress(hIn);
long qid = hIn.readLong();
long timeout = 120 * 1000L;
/*
AmpQueryRef queryRef
= new QueryItem(NullMethodRef.NULL, _context, headers, timeout);
*/
MethodRefHamp methodHamp = null;
MethodRefAmp methodRef = null;
try {
try {
methodHamp = readMethod(hIn);
} catch (Throwable e) {
skipArgs(hIn);
throw e;
}
methodRef = methodHamp.getMethod();
ClassLoader loader = methodHamp.getClassLoader();
Thread thread = Thread.currentThread();
thread.setContextClassLoader(loader);
// XXX: _serializer.setClassLoader(loader);
Object []args = readArgs(methodHamp, hIn);
QueryGatewayReadMessage_N msg
= new QueryGatewayReadMessage_N(outbox,
getInboxCaller(),
headers,
from, qid,
methodRef.serviceRef(),
methodRef.method(),
timeout, args);
//msg.offer(_queueTimeout);
//msg.offerQueue(_queueTimeout);
// msg.getWorker().wake();
msg.offer(_queueTimeout);
//outbox.flush();
if (log.isLoggable(_logLevel)) {
log.log(_logLevel, "hamp-query " + methodRef.getName() + " " + debugArgs(args)
+ " (in " + this + ")"
+ "\n {qid:" + qid + ", to:" + methodRef.serviceRef() + ", from:" + from + "," + headers + "}");
}
} catch (Throwable e) {
if (log.isLoggable(Level.FINE)) {
log.fine("hamp-query error " + e
+ " (in " + this + ")"
+ "\n {id:" + qid + ", from:" + from + "," + headers + "," + methodRef + "}");
}
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, e.toString(), e);
}
ServiceRefAmp serviceRef = getInboxCaller().serviceRef();
MethodRefError methodErr;
if (methodRef == null) {
methodErr = new MethodRefError(serviceRef, "unknown-method");
}
else {
methodErr = new MethodRefError(serviceRef, methodRef.getName());
}
QueryGatewayReadMessage_N queryRef
= new QueryGatewayReadMessage_N(outbox,
getInboxCaller(),
headers,
from, qid,
serviceRef, methodErr.method(),
timeout, null);
queryRef.toSent();
// queryRef.failed(headers, e);
//System.out.println("FAIL: " + e);
if (e instanceof ServiceException) {
queryRef.fail(e);
outbox.flush();
}
else {
HampException exn = new HampException(L.l("{0}\n while reading {1}", e.toString(), methodRef), e);
queryRef.fail(exn);
}
}
} | java |
private void readQueryResult(InH3 hIn, HeadersAmp headers)
throws IOException
{
ServiceRefAmp serviceRef = readToAddress(hIn);
long id = hIn.readLong();
QueryRefAmp queryRef = serviceRef.removeQueryRef(id);
if (queryRef != null) {
ClassLoader loader = queryRef.getClassLoader();
Thread thread = Thread.currentThread();
thread.setContextClassLoader(loader);
// XXX: _serializer.setClassLoader(loader);
}
else {
// XX: _serializer.setClassLoader(null);
}
Object value = hIn.readObject();
if (log.isLoggable(_logLevel)) {
log.log(_logLevel, "query-result-r " + value + " (in " + this + ")"
+ "\n {id:" + id + ", to:" + serviceRef + "," + headers + "}");
}
if (queryRef != null) {
queryRef.complete(headers, value);
}
else if (log.isLoggable(Level.WARNING)) {
log.warning("query-result qid=" + id + " for service " + serviceRef +
" does not match any known queries.\n" + headers);
}
} | java |
public void addInclude(PathPatternType pattern)
{
if (_includeList == null)
_includeList = new ArrayList<PathPatternType>();
_includeList.add(pattern);
} | java |
public void setUserPathPrefix(String prefix)
{
if (prefix != null && ! prefix.equals("") && ! prefix.endsWith("/"))
_userPathPrefix = prefix + "/";
else
_userPathPrefix = prefix;
} | java |
@Override
public ExprKraken getKeyExpr(String name)
{
if (name.equals(_column.getColumn().name())) {
return getRight();
}
else {
return null;
}
} | java |
@Override
public void write(byte []buf, int offset, int length, boolean isEnd)
throws IOException
{
OutputStream stream = getStream();
if (stream == null) {
return;
}
synchronized (stream) {
stream.write(buf, offset, length);
if (isEnd) {
stream.flush();
}
}
} | java |
@Override
public void flush()
throws IOException
{
OutputStream stream = getStream();
if (stream == null) {
return;
}
synchronized (stream) {
stream.flush();
}
} | java |
public synchronized static void setStdout(OutputStream os)
{
if (_stdoutStream == null) {
initStdout();
}
if (os == _systemErr || os == _systemOut) {
return;
}
if (os instanceof WriteStream) {
WriteStream out = (WriteStream) os;
/*
if (out.getSource() == StdoutStream.create()
|| out.getSource() == StderrStream.create()) {
return;
}
*/
}
_stdoutStream.setStream(os);
} | java |
public static synchronized void setStderr(OutputStream os)
{
if (_stderrStream == null) {
initStderr();
}
if (os == _systemErr || os == _systemOut) {
return;
}
if (os instanceof WriteStream) {
WriteStream out = (WriteStream) os;
/*
if (out.getSource() == StdoutStream.create()
|| out.getSource() == StderrStream.create()) {
return;
}
*/
}
_stderrStream.setStream(os);
} | java |
protected static <E extends SubSystemBase> SystemManager
preCreate(Class<E> serviceClass)
{
SystemManager system = SystemManager.getCurrent();
if (system == null)
throw new IllegalStateException(L.l("{0} must be created before {1}",
SystemManager.class.getSimpleName(),
serviceClass.getSimpleName()));
if (system.getSystem(serviceClass) != null)
throw new IllegalStateException(L.l("{0} was previously created",
serviceClass.getSimpleName()));
return system;
} | java |
public String addConnectionRequirement(NodeTemplate target, String type, String varName) {
Map<String, Object> requirement = new LinkedHashMap();
String requirementName = "endpoint";
Map requirementMap = new LinkedHashMap<String, Object>();
requirement.put(requirementName, requirementMap);
requirementMap.put("node", target.getName());
requirementMap.put("type", type);
if (!varName.isEmpty()) {
Map<String, String> properties = new LinkedHashMap();
properties.put("prop.name", varName);
requirementMap.put("properties", properties);
}
requirements().add(requirement);
return requirementName;
} | java |
@Override
public boolean stop()
{
if (! _lifecycle.toStopping())
return false;
log.finest(this + " stopping");
closeConnections();
destroy();
return true;
} | java |
int writePageIndex(byte []buffer,
int head,
int type,
int pid,
int nextPid,
int entryOffset,
int entryLength)
{
int sublen = 1 + 4 * 4;
if (BLOCK_SIZE - 8 < head + sublen) {
return -1;
}
buffer[head] = (byte) type;
head++;
BitsUtil.writeInt(buffer, head, pid);
head += 4;
BitsUtil.writeInt(buffer, head, nextPid);
head += 4;
BitsUtil.writeInt(buffer, head, entryOffset);
head += 4;
BitsUtil.writeInt(buffer, head, entryLength);
head += 4;
return head;
} | java |
public void readEntries(TableKelp table,
InSegment reader,
SegmentEntryCallback cb)
{
TempBuffer tBuf = TempBuffer.createLarge();
byte []buffer = tBuf.buffer();
InStore sIn = reader.getStoreRead();
byte []tableKey = new byte[TableKelp.TABLE_KEY_SIZE];
for (int ptr = length() - BLOCK_SIZE; ptr > 0; ptr -= BLOCK_SIZE) {
sIn.read(getAddress() + ptr, buffer, 0, buffer.length);
int index = 0;
long seq = BitsUtil.readLong(buffer, index);
index += 8;
if (seq != getSequence()) {
log.warning(L.l("Invalid sequence {0} expected {1} at 0x{2}",
seq,
getSequence(),
Long.toHexString(getAddress() + ptr)));
break;
}
System.arraycopy(buffer, index, tableKey, 0, tableKey.length);
index += tableKey.length;
if (! Arrays.equals(tableKey, _tableKey)) {
log.warning(L.l("Invalid table {0} table {1} at 0x{2}",
Hex.toShortHex(tableKey),
Hex.toShortHex(_tableKey),
Long.toHexString(getAddress() + ptr)));
break;
}
/*
int tail = BitsUtil.readInt16(buffer, index);
index += 2;
if (tail <= 0) {
throw new IllegalStateException();
}
*/
int head = index;
while (head < BLOCK_SIZE && buffer[head] != 0) {
head = readEntry(table, buffer, head, cb, getAddress());
}
boolean isCont = buffer[head + 1] != 0;
if (! isCont) {
break;
}
}
tBuf.free();
} | java |
public int getSize()
{
int size = length();
if (_blobs == null) {
return size;
}
for (BlobOutputStream blob : _blobs) {
if (blob != null) {
size += blob.getSize();
}
}
return size;
} | java |
public final OutputStream openOutputStream(int index)
{
Column column = _row.columns()[index];
return column.openOutputStream(this);
} | java |
public static Path currentDataDirectory()
{
RootDirectorySystem rootService = getCurrent();
if (rootService == null)
throw new IllegalStateException(L.l("{0} must be active for getCurrentDataDirectory().",
RootDirectorySystem.class.getSimpleName()));
return rootService.dataDirectory();
} | java |
public static JournalStore create(Path path, boolean isMmap)
throws IOException
{
// RampManager rampManager = Ramp.newManager();
long segmentSize = 4 * 1024 * 1024;
JournalStore.Builder builder = JournalStore.Builder.create(path);
builder.segmentSize(segmentSize);
// builder.rampManager(rampManager);
builder.mmap(isMmap);
JournalStore store = builder.build();
return store;
} | java |
public static void clearJarCache()
{
LruCache<PathImpl,Jar> jarCache = _jarCache;
if (jarCache == null)
return;
ArrayList<Jar> jars = new ArrayList<Jar>();
synchronized (jarCache) {
Iterator<Jar> iter = jarCache.values();
while (iter.hasNext())
jars.add(iter.next());
}
for (int i = 0; i < jars.size(); i++) {
Jar jar = jars.get(i);
if (jar != null)
jar.clearCache();
}
} | java |
private Path keyStoreFile()
{
String fileName = _config.get(_prefix + ".ssl.key-store");
if (fileName == null) {
return null;
}
return Vfs.path(fileName);
} | java |
private String keyStorePassword()
{
String password = _config.get(_prefix + ".ssl.key-store-password");
if (password != null) {
return password;
}
else {
return _config.get(_prefix + ".ssl.password");
}
} | java |
private SSLSocketFactory createFactory()
throws Exception
{
SSLSocketFactory ssFactory = null;
String host = "localhost";
int port = 8086;
if (_keyStore == null) {
return createAnonymousFactory(null, port);
}
SSLContext sslContext = SSLContext.getInstance(_sslContext);
KeyManagerFactory kmf
= KeyManagerFactory.getInstance(keyManagerFactory());
kmf.init(_keyStore, keyStorePassword().toCharArray());
sslContext.init(kmf.getKeyManagers(), null, null);
/*
if (_cipherSuites != null)
sslContext.createSSLEngine().setEnabledCipherSuites(_cipherSuites);
*/
SSLEngine engine = sslContext.createSSLEngine();
_enabledProtocols = enabledProtocols(engine.getEnabledProtocols());
engine.setEnabledProtocols(_enabledProtocols);
ssFactory = sslContext.getSocketFactory();
return ssFactory;
} | java |
public static InjectorImpl current(ClassLoader loader)
{
if (loader instanceof DynamicClassLoader) {
return _localManager.getLevel(loader);
}
else {
SoftReference<InjectorImpl> injectRef = _loaderManagerMap.get(loader);
if (injectRef != null) {
return injectRef.get();
}
else {
return null;
}
}
} | java |
@Override
public <T> T instance(Class<T> type)
{
Key<T> key = Key.of(type);
return instance(key);
} | java |
@Override
public <T> T instance(Key<T> key)
{
Objects.requireNonNull(key);
Class<T> type = (Class) key.rawClass();
if (type.equals(Provider.class)) {
TypeRef typeRef = TypeRef.of(key.type());
TypeRef param = typeRef.param(0);
return (T) provider(Key.of(param.type()));
}
Provider<T> provider = provider(key);
if (provider != null) {
return provider.get();
}
else {
return null;
}
} | java |
@Override
public <T> T instance(InjectionPoint<T> ip)
{
Objects.requireNonNull(ip);
Provider<T> provider = provider(ip);
if (provider != null) {
return provider.get();
}
else {
return null;
}
} | java |
@Override
public <T> Provider<T> provider(InjectionPoint<T> ip)
{
Objects.requireNonNull(ip);
Provider<T> provider = lookupProvider(ip);
if (provider != null) {
return provider;
}
provider = autoProvider(ip);
if (provider != null) {
return provider;
}
return new ProviderNull(ip.key(), -10000, new InjectScopeSingleton());
} | java |
@Override
public <T> Provider<T> provider(Key<T> key)
{
Objects.requireNonNull(key);
Provider<T> provider = (Provider) _providerMap.get(key);
if (provider == null) {
provider = lookupProvider(key);
if (provider == null) {
provider = autoProvider(key);
}
_providerMap.putIfAbsent(key, provider);
provider = (Provider) _providerMap.get(key);
}
return provider;
} | java |
private <T> Provider<T> lookupProvider(Key<T> key)
{
BindingInject<T> bean = findBean(key);
if (bean != null) {
return bean.provider();
}
BindingAmp<T> binding = findBinding(key);
if (binding != null) {
return binding.provider();
}
binding = findObjectBinding(key);
if (binding != null) {
return binding.provider(InjectionPoint.of(key));
}
return null;
} | java |
private <T> Provider<T> lookupProvider(InjectionPoint<T> ip)
{
Key<T> key = ip.key();
BindingInject<T> bean = findBean(key);
if (bean != null) {
return bean.provider(ip);
}
BindingAmp<T> provider = findBinding(key);
if (provider != null) {
return provider.provider(ip);
}
provider = findObjectBinding(key);
if (provider != null) {
return provider.provider(ip);
}
return null;
} | java |
private <T> InjectScope<T> findScope(AnnotatedElement annElement)
{
for (Annotation ann : annElement.getAnnotations()) {
Class<? extends Annotation> annType = ann.annotationType();
if (annType.isAnnotationPresent(Scope.class)) {
Supplier<InjectScope<T>> scopeGen = (Supplier) _scopeMap.get(annType);
if (scopeGen != null) {
return scopeGen.get();
}
else {
log.fine(L.l("@{0} is an unknown scope", annType.getSimpleName()));
}
}
}
return new InjectScopeFactory<>();
} | java |
@Override
public <T> Iterable<Binding<T>> bindings(Class<T> type)
{
BindingSet<T> set = (BindingSet) _bindingSetMap.get(type);
if (set != null) {
return (Iterable) set;
}
else {
return Collections.EMPTY_LIST;
}
} | java |
@Override
public <T> List<Binding<T>> bindings(Key<T> key)
{
BindingSet<T> set = (BindingSet) _bindingSetMap.get(key.rawClass());
if (set != null) {
return set.bindings(key);
}
else {
return Collections.EMPTY_LIST;
}
} | java |
<T> InjectScope<T> scope(Class<? extends Annotation> scopeType)
{
Supplier<InjectScope<T>> scopeGen = (Supplier) _scopeMap.get(scopeType);
if (scopeGen == null) {
throw error("{0} is an unknown scope",
scopeType.getSimpleName());
}
return scopeGen.get();
} | java |
@Override
public <T> Consumer<T> injector(Class<T> type)
{
ArrayList<InjectProgram> injectList = new ArrayList<>();
introspectInject(injectList, type);
introspectInit(injectList, type);
return new InjectProgramImpl<T>(injectList);
} | java |
@Override
public Provider<?> []program(Parameter []params)
{
Provider<?> []program = new Provider<?>[params.length];
for (int i = 0; i < program.length; i++) {
//Key<?> key = Key.of(params[i]);
program[i] = provider(InjectionPoint.of(params[i]));
}
return program;
} | java |
private <T> BindingInject<T> findBean(Key<T> key)
{
for (InjectProvider provider : _providerList) {
BindingInject<T> bean = (BindingInject) provider.lookup(key.rawClass());
if (bean != null) {
return bean;
}
}
return null;
} | java |
private <T> BindingAmp<T> findObjectBinding(Key<T> key)
{
Objects.requireNonNull(key);
if (key.qualifiers().length != 1) {
throw new IllegalArgumentException();
}
return (BindingAmp) findBinding(Key.of(Object.class,
key.qualifiers()[0]));
} | java |
private <T> BindingAmp<T> findBinding(Key<T> key)
{
BindingSet<T> set = (BindingSet) _bindingSetMap.get(key.rawClass());
if (set != null) {
BindingAmp<T> binding = set.find(key);
if (binding != null) {
return binding;
}
}
return null;
} | java |
public void setLevel(Level level)
{
_level = level;
if (level.intValue() < _lowLevel.intValue())
_lowLevel = level;
} | java |
public boolean waitForActive(long timeout)
{
LifecycleState state = getState();
if (state.isActive()) {
return true;
}
else if (state.isAfterActive()) {
return false;
}
// server/1d2j
long waitEnd = CurrentTime.getCurrentTimeActual() + timeout;
synchronized (this) {
while ((state = _state).isBeforeActive()
&& CurrentTime.getCurrentTimeActual() < waitEnd) {
if (state.isActive()) {
return true;
}
else if (state.isAfterActive()) {
return false;
}
try {
long delta = waitEnd - CurrentTime.getCurrentTimeActual();
if (delta > 0) {
wait(delta);
}
} catch (InterruptedException e) {
}
}
}
return _state.isActive();
} | java |
public boolean toPostInit()
{
synchronized (this) {
if (_state == STOPPED) {
_state = INIT;
_lastChangeTime = CurrentTime.currentTime();
notifyListeners(STOPPED, INIT);
return true;
}
else {
return _state.isInit();
}
}
} | java |
public boolean toStarting()
{
LifecycleState state;
synchronized (this) {
state = _state;
if (state.isAfterStarting() && ! state.isStopped()) {
return false;
}
_state = STARTING;
_lastChangeTime = CurrentTime.currentTime();
if (_log != null && _log.isLoggable(_level) && _log.isLoggable(Level.FINER)) {
_log.finer("starting " + _name);
}
}
notifyListeners(state, STARTING);
return true;
} | java |
public boolean toActive()
{
LifecycleState state;
synchronized (this) {
state = _state;
if (state.isAfterActive() && ! state.isStopped()) {
return false;
}
_state = ACTIVE;
_lastChangeTime = CurrentTime.currentTime();
}
if (_log != null && _log.isLoggable(_level))
_log.log(_level, "active " + _name);
notifyListeners(state, ACTIVE);
return true;
} | java |
public boolean toFail()
{
LifecycleState state;
synchronized (this) {
state = _state;
if (state.isAfterDestroying()) {
return false;
}
_state = FAILED;
_lastChangeTime = CurrentTime.currentTime();
}
if (_log != null && _log.isLoggable(_level))
_log.log(_level, "fail " + _name);
notifyListeners(state, FAILED);
_failCount++;
return true;
} | java |
public boolean toStopping()
{
LifecycleState state;
synchronized (this) {
state = _state;
if (state.isAfterStopping() || state.isStarting()) {
return false;
}
_state = STOPPING;
_lastChangeTime = CurrentTime.currentTime();
}
if (_log != null && _log.isLoggable(_level)) {
_log.log(_level, "stopping " + _name);
}
notifyListeners(state, STOPPING);
return true;
} | java |
public void addListener(LifecycleListener listener)
{
synchronized (this) {
if (isDestroyed()) {
IllegalStateException e = new IllegalStateException("attempted to add listener to a destroyed lifecyle " + this);
if (_log != null)
_log.log(Level.WARNING, e.toString(), e);
else
Logger.getLogger(Lifecycle.class.getName()).log(Level.WARNING, e.toString(), e);
return;
}
if (_listeners == null)
_listeners = new ArrayList<WeakReference<LifecycleListener>>();
for (int i = _listeners.size() - 1; i >= 0; i--) {
LifecycleListener oldListener = _listeners.get(i).get();
if (listener == oldListener)
return;
else if (oldListener == null)
_listeners.remove(i);
}
_listeners.add(new WeakReference<LifecycleListener>(listener));
}
} | java |
@Override
public String serialize(Object obj) throws JsonMarshallingException {
try {
return serializeChecked(obj);
} catch (Exception e) {
throw new JsonMarshallingException(e);
}
} | java |
public void setExecutorTaskMax(int max)
{
if (getThreadMax() < max)
throw new ConfigException(L.l("<thread-executor-max> ({0}) must be less than <thread-max> ({1})",
max, getThreadMax()));
if (max == 0)
throw new ConfigException(L.l("<thread-executor-max> must not be zero."));
_executorTaskMax = max;
} | java |
public boolean scheduleExecutorTask(Runnable task)
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
synchronized (_executorLock) {
_executorTaskCount++;
if (_executorTaskCount <= _executorTaskMax || _executorTaskMax < 0) {
boolean isPriority = false;
boolean isQueue = true;
boolean isWake = true;
return scheduleImpl(task, loader, MAX_EXPIRE, isPriority, isQueue, isWake);
}
else {
ExecutorQueueItem item = new ExecutorQueueItem(task, loader);
if (_executorQueueTail != null)
_executorQueueTail._next = item;
else
_executorQueueHead = item;
_executorQueueTail = item;
return false;
}
}
} | java |
public void completeExecutorTask()
{
ExecutorQueueItem item = null;
synchronized (_executorLock) {
_executorTaskCount--;
assert(_executorTaskCount >= 0);
if (_executorQueueHead != null) {
item = _executorQueueHead;
_executorQueueHead = item._next;
if (_executorQueueHead == null)
_executorQueueTail = null;
}
}
if (item != null) {
Runnable task = item.getRunnable();
ClassLoader loader = item.getLoader();
boolean isPriority = false;
boolean isQueue = true;
boolean isWake = true;
scheduleImpl(task, loader, MAX_EXPIRE, isPriority, isQueue, isWake);
}
} | java |
public Offering getOffering(String offeringName) {
BasicDBObject query = new BasicDBObject("offering_name", offeringName);
FindIterable<Document> cursor = this.offeringsCollection.find(query);
return Offering.fromDB(cursor.first());
} | java |
public String addOffering(Offering offering) {
this.offeringsCollection.insertOne(offering.toDBObject());
this.offeringNames.add(offering.getName());
return offering.getName();
} | java |
public boolean removeOffering(String offeringName) {
if(offeringName == null)
throw new NullPointerException("The parameter \"cloudOfferingId\" cannot be null.");
BasicDBObject query = new BasicDBObject("offering_name", offeringName);
Document removedOffering = this.offeringsCollection.findOneAndDelete(query);
return removedOffering != null;
} | java |
public void initializeOfferings() {
FindIterable<Document> offerings = this.offeringsCollection.find();
for (Document d : offerings) {
offeringNames.add((String) d.get("offering_name"));
}
} | java |
public void generateSingleOffering(String offeringNodeTemplates) {
this.removeOffering("0");
Offering singleOffering = new Offering("all");
singleOffering.toscaString = offeringNodeTemplates;
this.addOffering(singleOffering);
} | java |
public JClass getSuperClass()
{
lazyLoad();
if (_superClass == null)
return null;
else
return getClassLoader().forName(_superClass.replace('/', '.'));
} | java |
public void addInterface(String className)
{
_interfaces.add(className);
if (_isWrite)
getConstantPool().addClass(className);
} | java |
public JClass []getInterfaces()
{
lazyLoad();
JClass []interfaces = new JClass[_interfaces.size()];
for (int i = 0; i < _interfaces.size(); i++) {
String name = _interfaces.get(i);
name = name.replace('/', '.');
interfaces[i] = getClassLoader().forName(name);
}
return interfaces;
} | java |
public JavaField getField(String name)
{
ArrayList<JavaField> fieldList = getFieldList();
for (int i = 0; i < fieldList.size(); i++) {
JavaField field = fieldList.get(i);
if (field.getName().equals(name))
return field;
}
return null;
} | java |
public JavaMethod getMethod(String name)
{
ArrayList<JavaMethod> methodList = getMethodList();
for (int i = 0; i < methodList.size(); i++) {
JavaMethod method = methodList.get(i);
if (method.getName().equals(name))
return method;
}
return null;
} | java |
public JavaMethod findMethod(String name, String descriptor)
{
ArrayList<JavaMethod> methodList = getMethodList();
for (int i = 0; i < methodList.size(); i++) {
JavaMethod method = methodList.get(i);
if (method.getName().equals(name) &&
method.getDescriptor().equals(descriptor))
return method;
}
return null;
} | java |
public JField []getDeclaredFields()
{
ArrayList<JavaField> fieldList = getFieldList();
JField[] fields = new JField[fieldList.size()];
fieldList.toArray(fields);
return fields;
} | java |
public JField []getFields()
{
ArrayList<JField> fieldList = new ArrayList<JField>();
getFields(fieldList);
JField []fields = new JField[fieldList.size()];
fieldList.toArray(fields);
return fields;
} | java |
private void getFields(ArrayList<JField> fieldList)
{
for (JField field : getDeclaredFields()) {
if (! fieldList.contains(field))
fieldList.add(field);
}
if (getSuperClass() != null) {
for (JField field : getSuperClass().getFields()) {
if (! fieldList.contains(field))
fieldList.add(field);
}
}
} | java |
private void lazyLoad()
{
if (_major > 0)
return;
try {
if (_url == null)
throw new IllegalStateException();
try (InputStream is = _url.openStream()) {
//ReadStream rs = VfsOld.openRead(is);
_major = 1;
ByteCodeParser parser = new ByteCodeParser();
parser.setClassLoader(_loader);
parser.setJavaClass(this);
parser.parse(is);
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java |
public void write(OutputStream os)
throws IOException
{
ByteCodeWriter out = new ByteCodeWriter(os, this);
out.writeInt(MAGIC);
out.writeShort(_minor);
out.writeShort(_major);
_constantPool.write(out);
out.writeShort(_accessFlags);
out.writeClass(_thisClass);
out.writeClass(_superClass);
out.writeShort(_interfaces.size());
for (int i = 0; i < _interfaces.size(); i++) {
String className = _interfaces.get(i);
out.writeClass(className);
}
out.writeShort(_fields.size());
for (int i = 0; i < _fields.size(); i++) {
JavaField field = _fields.get(i);
field.write(out);
}
out.writeShort(_methods.size());
for (int i = 0; i < _methods.size(); i++) {
JavaMethod method = _methods.get(i);
method.write(out);
}
out.writeShort(_attributes.size());
for (int i = 0; i < _attributes.size(); i++) {
Attribute attr = _attributes.get(i);
attr.write(out);
}
} | java |
public final I getInvocation(Object protocolKey)
{
I invocation = null;
// XXX: see if can remove this
LruCache<Object,I> invocationCache = _invocationCache;
if (invocationCache != null) {
invocation = invocationCache.get(protocolKey);
}
if (invocation == null) {
return null;
}
else if (invocation.isModified()) {
return null;
}
else {
return invocation;
}
} | java |
public I buildInvocation(Object protocolKey, I invocation)
throws ConfigException
{
Objects.requireNonNull(invocation);
invocation = buildInvocation(invocation);
// XXX: see if can remove this, and rely on the invocation cache existing
LruCache<Object,I> invocationCache = _invocationCache;
if (invocationCache != null) {
I oldInvocation;
oldInvocation = invocationCache.get(protocolKey);
// server/10r2
if (oldInvocation != null && ! oldInvocation.isModified()) {
return oldInvocation;
}
if (invocation.getURLLength() < _maxURLLength) {
invocationCache.put(protocolKey, invocation);
}
}
return invocation;
} | java |
public void clearCache()
{
// XXX: see if can remove this, and rely on the invocation cache existing
LruCache<Object,I> invocationCache = _invocationCache;
if (invocationCache != null) {
invocationCache.clear();
}
} | java |
public ArrayList<I> getInvocations()
{
LruCache<Object,I> invocationCache = _invocationCache;
ArrayList<I> invocationList = new ArrayList<>();
synchronized (invocationCache) {
Iterator<I> iter;
iter = invocationCache.values();
while (iter.hasNext()) {
invocationList.add(iter.next());
}
}
return invocationList;
} | java |
private void loadManifest()
{
if (_isManifestRead)
return;
synchronized (this) {
if (_isManifestRead)
return;
try {
_manifest = _jarPath.getManifest();
if (_manifest == null)
return;
Attributes attr = _manifest.getMainAttributes();
if (attr != null)
addManifestPackage("", attr);
Map<String,Attributes> entries = _manifest.getEntries();
for (Map.Entry<String,Attributes> entry : entries.entrySet()) {
String pkg = entry.getKey();
attr = entry.getValue();
if (attr == null)
continue;
addManifestPackage(pkg, attr);
}
} catch (IOException e) {
log.log(Level.WARNING, e.toString(), e);
} finally {
_isManifestRead = true;
}
}
} | java |
private void addManifestPackage(String name, Attributes attr)
{
// only add packages
if (! name.endsWith("/") && ! name.equals(""))
return;
String specTitle = attr.getValue("Specification-Title");
String specVersion = attr.getValue("Specification-Version");
String specVendor = attr.getValue("Specification-Vendor");
String implTitle = attr.getValue("Implementation-Title");
String implVersion = attr.getValue("Implementation-Version");
String implVendor = attr.getValue("Implementation-Vendor");
// If all none, then it isn't a package entry
if (specTitle == null && specVersion == null && specVendor != null &&
implTitle == null && implVersion == null && implVendor != null)
return;
ClassPackage pkg = new ClassPackage(name);
pkg.setSpecificationTitle(specTitle);
pkg.setSpecificationVersion(specVersion);
pkg.setSpecificationVendor(specVendor);
pkg.setImplementationTitle(implTitle);
pkg.setImplementationVersion(implVersion);
pkg.setImplementationVendor(implVendor);
_packages.add(pkg);
} | java |
public void validate()
throws ConfigException
{
loadManifest();
if (_manifest != null)
validateManifest(_jarPath.getContainer().getURL(), _manifest);
} | java |
public static void validateManifest(String manifestName, Manifest manifest)
throws ConfigException
{
Attributes attr = manifest.getMainAttributes();
if (attr == null)
return;
String extList = attr.getValue("Extension-List");
if (extList == null)
return;
Pattern pattern = Pattern.compile("[, \t]+");
String []split = pattern.split(extList);
for (int i = 0; i < split.length; i++) {
String ext = split[i];
String name = attr.getValue(ext + "-Extension-Name");
if (name == null)
continue;
Package pkg = Package.getPackage(name);
if (pkg == null) {
log.warning(L.l("package {0} is missing. {1} requires package {0}.",
name, manifestName));
continue;
}
String version = attr.getValue(ext + "-Specification-Version");
if (version == null)
continue;
if (pkg.getSpecificationVersion() == null ||
pkg.getSpecificationVersion().equals("")) {
log.warning(L.l("installed {0} is not compatible with version `{1}'. {2} requires version {1}.",
name, version, manifestName));
}
else if (! pkg.isCompatibleWith(version)) {
log.warning(L.l("installed {0} is not compatible with version `{1}'. {2} requires version {1}.",
name, version, manifestName));
}
}
} | java |
public CodeSource getCodeSource(String path)
{
try {
PathImpl jarPath = _jarPath.lookup(path);
Certificate []certificates = jarPath.getCertificates();
URL url = new URL(_jarPath.getContainer().getURL());
return new CodeSource(url, certificates);
} catch (Exception e) {
log.log(Level.WARNING, e.toString(), e);
return null;
}
} | java |
public GuaranteeTermEvaluationResult evaluate(
IAgreement agreement, IGuaranteeTerm term, List<IMonitoringMetric> metrics, Date now) {
/*
* throws NullPointerException if not property initialized
*/
checkInitialized();
logger.debug("evaluate(agreement={}, term={}, now={})",
agreement.getAgreementId(), term.getKpiName(), now);
final List<IViolation> violations = serviceLevelEval.evaluate(agreement, term, metrics, now);
logger.debug("Found " + violations.size() + " violations");
final List<? extends ICompensation> compensations = businessEval.evaluate(agreement, term, violations, now);
logger.debug("Found " + compensations.size() + " compensations");
GuaranteeTermEvaluationResult result = new GuaranteeTermEvaluationResult(violations, compensations);
return result;
} | java |
@Override
public int read(byte []buf, int offset, int len) throws IOException
{
int available = _available;
// The chunk still has more data left
if (available > 0) {
len = Math.min(len, available);
len = _next.read(buf, offset, len);
if (len > 0) {
_available -= len;
}
}
// The chunk is done, so read the next chunk
else if (available == 0) {
_available = readChunkLength();
// the new chunk has data
if (_available > 0) {
len = Math.min(len, _available);
len = _next.read(buf, offset, len);
if (len > 0)
_available -= len;
}
// the new chunk is the last
else {
_available = -1;
len = -1;
}
}
else {
len = -1;
}
return len;
} | java |
private int readChunkLength()
throws IOException
{
int length = 0;
int ch;
ReadStream is = _next;
// skip whitespace
for (ch = is.read();
ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
ch = is.read()) {
}
// XXX: This doesn't properly handle the case when when the browser
// sends headers at the end of the data. See the HTTP/1.1 spec.
for (; ch > 0 && ch != '\r' && ch != '\n'; ch = is.read()) {
if ('0' <= ch && ch <= '9')
length = 16 * length + ch - '0';
else if ('a' <= ch && ch <= 'f')
length = 16 * length + ch - 'a' + 10;
else if ('A' <= ch && ch <= 'F')
length = 16 * length + ch - 'A' + 10;
else if (ch == ' ' || ch == '\t') {
//if (dbg.canWrite())
// dbg.println("unexpected chunk whitespace.");
}
else {
StringBuilder sb = new StringBuilder();
sb.append((char) ch);
for (int ch1 = is.read();
ch1 >= 0 && ch1 != '\r' && ch1 != '\n';
ch1 = is.read()) {
sb.append((char) ch1);
}
throw new IOException("HTTP/1.1 protocol error: bad chunk at"
+ " '" + sb + "'"
+ " 0x" + Integer.toHexString(ch)
+ " length=" + length);
}
}
if (ch == '\r')
ch = is.read();
return length;
} | java |
private String getSlaUrl(String envSlaUrl, UriInfo uriInfo) {
String baseUrl = uriInfo.getBaseUri().toString();
if (envSlaUrl == null) {
envSlaUrl = "";
}
String result = ("".equals(envSlaUrl))? baseUrl : envSlaUrl;
logger.debug("getSlaUrl(env={}, supplied={}) = {}", envSlaUrl, baseUrl, result);
return result;
} | java |
private String getMetricsBaseUrl(String suppliedBaseUrl, String envBaseUrl) {
String result = ("".equals(suppliedBaseUrl))? envBaseUrl : suppliedBaseUrl;
logger.debug("getMetricsBaseUrl(env={}, supplied={}) = {}", envBaseUrl, suppliedBaseUrl, result);
return result;
} | java |
public int read(byte []buffer, int offset, int length)
throws IOException
{
return _stream.read(buffer, offset, length);
} | java |
@Override
public PathImpl getParent()
{
if (_pathname.length() <= 1)
return lookup("/");
int length = _pathname.length();
int lastSlash = _pathname.lastIndexOf('/');
if (lastSlash < 1)
return lookup("/");
if (lastSlash == length - 1) {
lastSlash = _pathname.lastIndexOf('/', length - 2);
if (lastSlash < 1)
return lookup("/");
}
return lookup(_pathname.substring(0, lastSlash));
} | java |
static protected String normalizePath(String oldPath,
String newPath,
int offset,
char separatorChar)
{
CharBuffer cb = new CharBuffer();
normalizePath(cb, oldPath, newPath, offset, separatorChar);
return cb.toString();
} | java |
static protected void normalizePath(CharBuffer cb, String oldPath,
String newPath, int offset,
char separatorChar)
{
cb.clear();
cb.append(oldPath);
if (cb.length() == 0 || cb.lastChar() != '/')
cb.append('/');
int length = newPath.length();
int i = offset;
while (i < length) {
char ch = newPath.charAt(i);
char ch2;
switch (ch) {
default:
if (ch != separatorChar) {
cb.append(ch);
i++;
break;
}
// the separator character falls through to be treated as '/'
case '/':
// "//" -> "/"
if (cb.lastChar() != '/')
cb.append('/');
i++;
break;
case '.':
if (cb.lastChar() != '/') {
cb.append('.');
i++;
break;
}
// "/." -> ""
if (i + 1 >= length) {
i += 2;
break;
}
switch (newPath.charAt(i + 1)) {
default:
if (newPath.charAt(i + 1) != separatorChar) {
cb.append('.');
i++;
break;
}
// the separator falls through to be treated as '/'
// "/./" -> "/"
case '/':
i += 2;
break;
// "foo/.." -> ""
case '.':
if ((i + 2 >= length ||
(ch2 = newPath.charAt(i + 2)) == '/' || ch2 == separatorChar) &&
cb.lastChar() == '/') {
int segment = cb.lastIndexOf('/', cb.length() - 2);
if (segment == -1) {
cb.clear();
cb.append('/');
} else
cb.length(segment + 1);
i += 3;
} else {
cb.append('.');
i++;
}
break;
}
}
}
// strip trailing "/"
/*
if (cb.length() > 1 && cb.getLastChar() == '/')
cb.setLength(cb.length() - 1);
*/
} | java |
public String getFullPath()
{
if (_root == this || _root == null)
return getPath();
String rootPath = _root.getFullPath();
String path = getPath();
if (rootPath.length() <= 1)
return path;
else if (path.length() <= 1)
return rootPath;
else
return rootPath + path;
} | java |
public Class<?> getClass(int index)
{
Object value = _values[index - 1];
if (value == null) {
return null;
}
else {
return value.getClass();
}
} | java |
public String getString(int index)
{
Object value = _values[index - 1];
if (value != null) {
return value.toString();
}
else {
return null;
}
} | java |
public long getLong(int index)
{
Object value = _values[index - 1];
if (value instanceof Long) {
return (Long) value;
}
else if (value instanceof Integer) {
return (Integer) value;
}
else {
return Long.valueOf(value.toString());
}
} | java |
public double getDouble(int index)
{
Object value = _values[index - 1];
if (value instanceof Double) {
return (Double) value;
}
else if (value instanceof Float) {
return (Float) value;
}
else if (value instanceof Number) {
return (Double) ((Number) value);
}
else {
return Double.valueOf(value.toString());
}
} | java |
public boolean getBoolean(int index)
{
Object value = _values[index - 1];
if (value instanceof Boolean) {
return (Boolean) value;
}
else {
return Boolean.valueOf(value.toString());
}
} | java |
@InService(SegmentServiceImpl.class)
public
Page writeCheckpoint(TableKelp table,
OutSegment sOut,
long oldSequence,
int saveLength,
int tail,
int saveSequence)
throws IOException
{
return null;
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.