code
stringlengths
73
34.1k
label
stringclasses
1 value
public DoubleConstant getDoubleByValue(double value) { for (int i = 0; i < _entries.size(); i++) { ConstantPoolEntry entry = _entries.get(i); if (! (entry instanceof DoubleConstant)) continue; DoubleConstant doubleEntry = (DoubleConstant) entry; if (doubleEntry.getValue() == value) return doubleEntry; } return null; }
java
public DoubleConstant addDouble(double value) { DoubleConstant entry = getDoubleByValue(value); if (entry != null) return entry; entry = new DoubleConstant(this, _entries.size(), value); addConstant(entry); addConstant(null); return entry; }
java
public ClassConstant getClass(String name) { for (int i = 0; i < _entries.size(); i++) { ConstantPoolEntry entry = _entries.get(i); if (! (entry instanceof ClassConstant)) continue; ClassConstant classEntry = (ClassConstant) entry; if (classEntry.getName().equals(name)) return classEntry; } return null; }
java
public ClassConstant addClass(String name) { ClassConstant entry = getClass(name); if (entry != null) return entry; Utf8Constant utf8 = addUTF8(name); entry = new ClassConstant(this, _entries.size(), utf8.getIndex()); addConstant(entry); return entry; }
java
public NameAndTypeConstant getNameAndType(String name, String type) { for (int i = 0; i < _entries.size(); i++) { ConstantPoolEntry entry = _entries.get(i); if (! (entry instanceof NameAndTypeConstant)) continue; NameAndTypeConstant methodEntry = (NameAndTypeConstant) entry; if (methodEntry.getName().equals(name) && methodEntry.getType().equals(type)) return methodEntry; } return null; }
java
public NameAndTypeConstant addNameAndType(String name, String type) { NameAndTypeConstant entry = getNameAndType(name, type); if (entry != null) return entry; Utf8Constant nameEntry = addUTF8(name); Utf8Constant typeEntry = addUTF8(type); entry = new NameAndTypeConstant(this, _entries.size(), nameEntry.getIndex(), typeEntry.getIndex()); addConstant(entry); return entry; }
java
public FieldRefConstant addFieldRef(String className, String name, String type) { FieldRefConstant entry = getFieldRef(className, name, type); if (entry != null) return entry; ClassConstant classEntry = addClass(className); NameAndTypeConstant typeEntry = addNameAndType(name, type); entry = new FieldRefConstant(this, _entries.size(), classEntry.getIndex(), typeEntry.getIndex()); addConstant(entry); return entry; }
java
public MethodHandleConstant getMethodHandle(MethodHandleType mhType, ConstantPoolEntry cpEntry) { for (int i = 0; i < _entries.size(); i++) { ConstantPoolEntry entry = _entries.get(i); if (! (entry instanceof MethodHandleConstant)) { continue; } MethodHandleConstant methodHandle = (MethodHandleConstant) entry; if (methodHandle.getType().equals(mhType) && methodHandle.getConstantEntry().equals(cpEntry)) { return methodHandle; } } return null; }
java
public InterfaceMethodRefConstant getInterfaceRef(String className, String name, String type) { for (int i = 0; i < _entries.size(); i++) { ConstantPoolEntry entry = _entries.get(i); if (! (entry instanceof InterfaceMethodRefConstant)) continue; InterfaceMethodRefConstant methodEntry; methodEntry = (InterfaceMethodRefConstant) entry; if (methodEntry.getClassName().equals(className) && methodEntry.getName().equals(name) && methodEntry.getType().equals(type)) return methodEntry; } return null; }
java
public InterfaceMethodRefConstant addInterfaceRef(String className, String name, String type) { InterfaceMethodRefConstant entry = getInterfaceRef(className, name, type); if (entry != null) return entry; ClassConstant classEntry = addClass(className); NameAndTypeConstant typeEntry = addNameAndType(name, type); entry = new InterfaceMethodRefConstant(this, _entries.size(), classEntry.getIndex(), typeEntry.getIndex()); addConstant(entry); return entry; }
java
public InvokeDynamicConstant addInvokeDynamicRef(BootstrapMethodAttribute attr, String methodName, String methodType, String bootClass, String bootMethod, String bootType, ConstantPoolEntry []cpEntries) { NameAndTypeConstant methodEntry = addNameAndType(methodName, methodType); MethodRefConstant bootMethodRef = addMethodRef(bootClass, bootMethod, bootType); MethodHandleConstant bootMethodHandle = addMethodHandle(MethodHandleType.INVOKE_STATIC, bootMethodRef); int bootIndex = attr.addMethod(bootMethodHandle.getIndex(), cpEntries); InvokeDynamicConstant invokedynamicRef = new InvokeDynamicConstant(this, _entries.size(), attr, bootIndex, methodEntry.getIndex()); addConstant(invokedynamicRef); return invokedynamicRef; }
java
public void write(ByteCodeWriter out) throws IOException { out.writeShort(_entries.size()); for (int i = 1; i < _entries.size(); i++) { ConstantPoolEntry entry = _entries.get(i); if (entry != null) entry.write(out); } }
java
public void write(int b) throws IOException { log.info("random-write(0x" + Long.toHexString(getFilePointer()) + ",1)"); _file.write(b); }
java
private Topology createAdHocTopologyFromSuitableOptions(SuitableOptions appInfoSuitableOptions) { Topology topology = new Topology(); TopologyElement current = null; TopologyElement previous = null; for (String moduleName : appInfoSuitableOptions.getStringIterator()) { if (current == null) { // first element treated. None of them needs to point at it current = new TopologyElement(moduleName); topology.addModule(current); } else {// There were explored already other modules previous = current; current = new TopologyElement(moduleName); previous.addElementCalled(current); topology.addModule(current); } } return topology; }
java
public int read(byte []buffer, int offset, int length) throws IOException { int len = _next.read(buffer, offset, length); _crc = Crc64.generate(_crc, buffer, offset, len); return len; }
java
public void removeDirectory(String path, String tail, Result<Object> result) { // _dirRemove.exec(result, path, tail); result.ok(null); }
java
void updateRack(HeartbeatImpl heartbeat, UpdateRackHeartbeat updateRack) { for (UpdateServerHeartbeat serverUpdate : updateRack.getServers()) { if (serverUpdate == null) { continue; } update(serverUpdate); // updateTargetServers(); ServerHeartbeat peerServer = findServer(serverUpdate.getAddress(), serverUpdate.getPort()); if (peerServer.isSelf()) { continue; } heartbeat.updateServer(peerServer, serverUpdate); /* String externalId = serverUpdate.getExternalId(); heartbeat.updateExternal(peerServer, externalId); if (peerServer.onHeartbeatUpdate(serverUpdate)) { if (peerServer.isUp()) { onServerStart(peerServer); } else { onServerStop(peerServer); } } */ } update(); }
java
@Override public String get(String key, String defaultValue) { String value = _map.get(key); if (value != null) { return value; } else { return defaultValue; } }
java
@SuppressWarnings("unchecked") public <T> T get(String key, Class<T> type, T defaultValue) { Objects.requireNonNull(key); Objects.requireNonNull(type); String value = _map.get(key); if (value == null) { return defaultValue; } if (type.equals(String.class)) { return (T) value; } T valueType = _converter.convert(type, value); if (valueType != null) { return valueType; } else { log.warning(L.l("Unexpected type for key={0} type={1} value={2}", key, type, value)); /* throw new ConfigException(L.l("Unexpected type for key={0} type={1} value={2}", key, type, value)); */ return defaultValue; } }
java
@Override public <T> void inject(T bean, String prefix) { Objects.requireNonNull(bean); ConfigStub stub = new ConfigStub(bean.getClass(), prefix); stub.inject(bean, this); }
java
private static void readChar(ByteToChar converter, CharReader is, int ch, boolean isTop) throws IOException { if (ch == '+') { if (isTop) converter.addByte(' '); else converter.addChar(' '); } else if (ch == '%') { int ch1 = is.next(); if (ch1 == 'u') { ch1 = is.next(); int ch2 = is.next(); int ch3 = is.next(); int ch4 = is.next(); converter.addChar((char) ((toHex(ch1) << 12) + (toHex(ch2) << 8) + (toHex(ch3) << 4) + (toHex(ch4)))); } else { int ch2 = is.next(); converter.addByte(((toHex(ch1) << 4) + toHex(ch2))); } } else if (isTop) { converter.addByte((byte) ch); } else { converter.addChar((char) ch); } }
java
@Override public void run() { try { runImpl(); } catch (final Throwable e) { // env/0203 vs env/0206 if (e instanceof DisplayableException) log.warning(e.getMessage()); else log.warning(e.toString()); _exception = e; } finally { notifyComplete(); } }
java
@Override public void write(int v) throws IOException { _buf[0] = (byte) v; _stream.write(_buf, 0, 1, false); }
java
public static String getLocation(String providerName) { for (String key : map.keySet()) { if (providerName.startsWith(key)) { return map.get(key); } } return null; }
java
public void read(ByteCodeParser in) throws IOException { int length = in.readInt(); if (length != 2) throw new IOException("expected length of 2 at " + length); int code = in.readShort(); _signature = in.getUTF8(code); }
java
public void write(String s, int offset, int length) throws IOException { while (length > 0) { if (_tail == null) addBuffer(TempCharBuffer.allocate()); else if (_tail._buf.length <= _tail._length) { addBuffer(TempCharBuffer.allocate()); // XXX: see TempStream for backing files } int sublen = _tail._buf.length - _tail._length; if (length < sublen) sublen = length; s.getChars(offset, offset + sublen, _tail._buf, _tail._length); offset += sublen; length -= sublen; _tail._length += sublen; } }
java
private static ClassLoader getInitParent(ClassLoader parent, boolean isRoot) { if (parent == null) parent = Thread.currentThread().getContextClassLoader(); if (isRoot || parent instanceof DynamicClassLoader) return parent; else { //return RootDynamicClassLoader.create(parent); return parent; } }
java
@Override public void write(int ch) throws IOException { char []buffer = _tempCharBuffer; buffer[0] = (char) ch; write(buffer, 0, 1); }
java
@Override public void write(String s, int off, int len) throws IOException { char []buffer = _tempCharBuffer; int bufferLength = buffer.length; while (len > 0) { int sublen = Math.min(len, bufferLength); s.getChars(off, off + sublen, buffer, 0); write(buffer, 0, sublen); off += sublen; len -= sublen; } }
java
@Override final public void write(String s) throws IOException { if (s == null) { write(_nullChars, 0, _nullChars.length); return; } write(s, 0, s.length()); }
java
public HeaderParams put(String name, String value) { values.put(cleanAndValidate(name), cleanAndValidate(value)); return this; }
java
public void setBackgroundPeriod(long period) { if (period < 1) { throw new ConfigException(L.l("profile period '{0}ms' is too small. The period must be greater than 10ms.", period)); } _profilerService.setBackgroundInterval(period, TimeUnit.MILLISECONDS); }
java
public void setLocation(String filename, int line) throws IOException { if (_lineMap != null && filename != null && line >= 0) { _lineMap.add(filename, line, _destLine, _isPreferLast); } }
java
public void print(String s) throws IOException { if (_startLine) printIndent(); if (s == null) { _lastCr = false; _os.print("null"); return; } int len = s.length(); for (int i = 0; i < len; i++) { int ch = s.charAt(i); if (ch == '\n' && !_lastCr) _destLine++; else if (ch == '\r') _destLine++; _lastCr = ch == '\r'; _os.print((char) ch); } }
java
public void print(char ch) throws IOException { if (_startLine) printIndent(); if (ch == '\r') { _destLine++; } else if (ch == '\n' && !_lastCr) _destLine++; _lastCr = ch == '\r'; _os.print(ch); }
java
public void print(boolean b) throws IOException { if (_startLine) printIndent(); _os.print(b); _lastCr = false; }
java
public void print(long l) throws IOException { if (_startLine) printIndent(); _os.print(l); _lastCr = false; }
java
public void print(Object o) throws IOException { if (_startLine) printIndent(); _os.print(o); _lastCr = false; }
java
public void println() throws IOException { _os.println(); if (!_lastCr) _destLine++; _lastCr = false; _startLine = true; }
java
public void printClass(Class<?> cl) throws IOException { if (! cl.isArray()) print(cl.getName().replace('$', '.')); else { printClass(cl.getComponentType()); print("[]"); } }
java
@SuppressWarnings("unchecked") public void printType(Type type) throws IOException { if (type instanceof Class<?>) { printTypeClass((Class<?>) type); } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; printParameterizedType(parameterizedType); } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; printWildcardType(wildcardType); } else if (type instanceof TypeVariable<?>) { TypeVariable<? extends GenericDeclaration> typeVariable = (TypeVariable<? extends GenericDeclaration>) type; printTypeVariable(typeVariable); } else if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; printType(genericArrayType.getGenericComponentType()); print("[]"); } else { throw new UnsupportedOperationException(type.getClass().getName() + " " + String.valueOf(type)); } }
java
public void printIndent() throws IOException { _startLine = false; for (int i = 0; i < _indentDepth; i++) _os.print(' '); _lastCr = false; }
java
public static Parameter getActionParameter(Action action, String paramName) { for (Parameter param : action.getParameters()) { if (paramName.equals(param.getName())) { return param; } } return NOT_FOUND_PARAMETER; }
java
public static List<Action> getActions(MonitoringRule rule, String nameFilter) { List<Action> result = new ArrayList<Action>(); if (nameFilter == null) { throw new NullPointerException("nameFilter cannot be null"); } for (Action action : getActions(rule)) { if (nameFilter.equalsIgnoreCase(action.getName())) { result.add(action); } } return result; }
java
public static List<Action> getActions(MonitoringRule rule) { List<Action> result; if (rule.getActions() != null && rule.getActions().getActions() != null) { result = rule.getActions().getActions(); } else { result = Collections.<Action> emptyList(); } return result; }
java
public static ObjectName getObjectName(String domain, Map<String,String> properties) throws MalformedObjectNameException { StringBuilder cb = new StringBuilder(); cb.append(domain); cb.append(':'); boolean isFirst = true; Pattern escapePattern = Pattern.compile("[,=:\"*?]"); // sort type first String type = properties.get("type"); if (type != null) { cb.append("type="); if (escapePattern.matcher(type).find()) type = ObjectName.quote(type); cb.append(type); isFirst = false; } for (String key : properties.keySet()) { if (key.equals("type")) { continue; } if (! isFirst) cb.append(','); isFirst = false; cb.append(key); cb.append('='); String value = properties.get(key); if (value == null) { throw new NullPointerException(String.valueOf(key)); } if (value.length() == 0 || (escapePattern.matcher(value).find() && ! (value.startsWith("\"") && value.endsWith("\"")))) { value = ObjectName.quote(value); } cb.append(value); } return new ObjectName(cb.toString()); }
java
private boolean isMethodApi(Method method) { if (_type == _api) { return true; } for (Method methodApi : _api.getMethods()) { if (methodApi.getName().equals(method.getName())) { return true; } } return false; }
java
@Override public StateConnection service() { try { StateConnection nextState = _state.service(this); //return StateConnection.CLOSE; return nextState; /* if (_invocation == null && getRequestHttp().parseInvocation()) { if (_invocation == null) { return NextState.CLOSE; } return _invocation.service(this, getResponse()); } else if (_upgrade != null) { return _upgrade.service(); } else if (_invocation != null) { return _invocation.service(this); } else { return StateConnection.CLOSE; } */ } catch (Throwable e) { log.warning(e.toString()); log.log(Level.FINER, e.toString(), e); //e.printStackTrace(); toClose(); return StateConnection.CLOSE_READ_A; } }
java
@Override public void exec(String sql, Result<Object> result, Object ...args) { _kraken.query(sql).exec(result, args); }
java
@Override public void prepare(String sql, Result<CursorPrepareSync> result) { result.ok(_kraken.query(sql).prepare()); }
java
@Override public void findOne(String sql, Result<Cursor> result, Object ...args) { _kraken.query(sql).findOne(result, args); }
java
public void find(ResultStream<Cursor> result, String sql, Object ...args) { _kraken.findStream(sql, args, result); }
java
@Override public void map(MethodRef method, String sql, Object ...args) { _kraken.map(method, sql, args); }
java
public void writeAttribute(String name, Object value) { if (!_isElementOpen) throw new IllegalStateException("no open element"); if (value == null) return; _isElementOpen = false; try { _strategy.writeAttribute(this, name, value); } finally { _isElementOpen = true; } }
java
public void writeAttribute(String name, Object ... values) { if (!_isElementOpen) throw new IllegalStateException("no open element"); _isElementOpen = false; try { _strategy.writeAttribute(this, name, values); } finally { _isElementOpen = true; } }
java
public void requestPubkey(final BitmessageAddress contact) { BitmessageAddress stored = addressRepository.getAddress(contact.getAddress()); tryToFindMatchingPubkey(contact); if (contact.getPubkey() != null) { if (stored != null) { stored.setPubkey(contact.getPubkey()); addressRepository.save(stored); } else { addressRepository.save(contact); } return; } if (stored == null) { addressRepository.save(contact); } long expires = UnixTime.now(TTL.getpubkey()); LOG.info("Expires at " + expires); final ObjectMessage request = new ObjectMessage.Builder() .stream(contact.getStream()) .expiresTime(expires) .payload(new GetPubkey(contact)) .build(); proofOfWorkService.doProofOfWork(request); }
java
public void addForeignWatch(TableKraken table, byte []key, String serverId) { WatchForeign watch = new WatchForeign(key, table, serverId); WatchTable watchTable = getWatchTable(table); watchTable.addWatchForeign(watch, key); }
java
@Override public void notifyWatch(TableKraken table, byte []key) { WatchTable watchTable = _tableMap.get(table); if (watchTable != null) { watchTable.onPut(key, TableListener.TypePut.REMOTE); } }
java
public void notifyLocalWatch(TableKraken table, byte []key) { WatchTable watchTable = _tableMap.get(table); if (watchTable != null) { watchTable.onPut(key, TableListener.TypePut.LOCAL); } }
java
public void addTable(TableKelp tableKelp, String sql, BackupKelp backupCb) { // TableKelp tableKelp = tableKraken.getTableKelp(); RowCursor cursor = _metaTable.cursor(); cursor.setBytes(1, tableKelp.tableKey(), 0); cursor.setString(2, tableKelp.getName()); cursor.setString(3, sql); //BackupCallback backupCb = _metaTable.getBackupCallback(); //_metaTable.getTableKelp().put(cursor, backupCb, // new CreateTableCompletion(tableKraken, result)); // _metaTable.getTableKelp().put(cursor, backupCb, // result.from(v->tableKraken)); _metaTable.put(cursor, backupCb, Result.ignore()); // tableKraken.start(); }
java
public void write(byte []buffer, int offset, int length) throws IOException { _file.write(buffer, offset, length); }
java
public void write(long fileOffset, byte []buffer, int offset, int length) throws IOException { _file.seek(fileOffset); _file.write(buffer, offset, length); }
java
public OutputStream getOutputStream() throws IOException { if (_os == null) _os = new FileOutputStream(_file.getFD()); return _os; }
java
public InputStream getInputStream() throws IOException { if (_is == null) _is = new FileInputStream(_file.getFD()); return _is; }
java
public static String encodeString(String uri) { CharBuffer cb = CharBuffer.allocate(); for (int i = 0; i < uri.length(); i++) { char ch = uri.charAt(i); switch (ch) { case '<': cb.append("&lt;"); break; case '>': cb.append("&gt;"); break; case '&': cb.append("&amp;"); break; default: cb.append(ch); } } return cb.close(); }
java
public double getLatencyFactor() { long now = CurrentTime.currentTime(); long decayPeriod = 60000; long delta = decayPeriod - (now - _lastSuccessTime); // decay the latency factor over 60s if (delta <= 0) return 0; else return (_latencyFactor * delta) / decayPeriod; }
java
public double getCpuLoadAvg() { double avg = _cpuLoadAvg; long time = _cpuSetTime; long now = CurrentTime.currentTime(); if (now - time < 10000L) return avg; else return avg * 10000L / (now - time); }
java
@Override public void success() { _currentFailCount = 0; long now = CurrentTime.currentTime(); if (_firstSuccessTime <= 0) { _firstSuccessTime = now; } // reset the connection fail recover time _dynamicFailRecoverTime = 1000L; }
java
@Override public ClientSocket openWarm() { State state = _state; if (! state.isEnabled()) { return null; } /* long now = CurrentTime.getCurrentTime(); if (isFailed(now)) { return null; } */ ClientSocket stream = openRecycle(); if (stream != null) { return stream; } if (canOpenWarm()) { return connect(); } else { return null; } }
java
@Override public ClientSocket openIfLive() { if (_state.isClosed()) { return null; } ClientSocket stream = openRecycle(); if (stream != null) return stream; long now = CurrentTime.currentTime(); if (isFailed(now)) return null; else if (_state == State.FAIL && _startingCount.get() > 0) { // if in fail state, only one thread should try to connect return null; } return connect(); }
java
public ClientSocket openIfHeartbeatActive() { if (_state.isClosed()) { return null; } if (! _isHeartbeatActive && _isHeartbeatServer) { return null; } ClientSocket stream = openRecycle(); if (stream != null) return stream; return connect(); }
java
public ClientSocket openSticky() { State state = _state; if (! state.isSessionEnabled()) { return null; } ClientSocket stream = openRecycle(); if (stream != null) return stream; long now = CurrentTime.currentTime(); if (isFailed(now)) { return null; } if (isBusy(now)) { return null; } return connect(); }
java
@Override public ClientSocket open() { State state = _state; if (! state.isInit()) return null; ClientSocket stream = openRecycle(); if (stream != null) return stream; return connect(); }
java
private ClientSocket openRecycle() { long now = CurrentTime.currentTime(); ClientSocket stream = null; synchronized (this) { if (_idleHead != _idleTail) { stream = _idle[_idleHead]; long freeTime = stream.getIdleStartTime(); _idle[_idleHead] = null; _idleHead = (_idleHead + _idle.length - 1) % _idle.length; // System.out.println("RECYCLE: " + stream + " " + (freeTime - now) + " " + _loadBalanceIdleTime); if (now < freeTime + _loadBalanceIdleTime) { _activeCount.incrementAndGet(); _keepaliveCountTotal++; stream.clearIdleStartTime(); stream.toActive(); return stream; } } } if (stream != null) { if (log.isLoggable(Level.FINER)) log.finer(this + " close idle " + stream + " expire=" + QDate.formatISO8601(stream.getIdleStartTime() + _loadBalanceIdleTime)); stream.closeImpl(); } return null; }
java
private ClientSocket connect() { if (_maxConnections <= _activeCount.get() + _startingCount.get()) { if (log.isLoggable(Level.WARNING)) { log.warning(this + " connect exceeded max-connections" + "\n max-connections=" + _maxConnections + "\n activeCount=" + _activeCount.get() + "\n startingCount=" + _startingCount.get()); } return null; } _startingCount.incrementAndGet(); State state = _state; if (! state.isInit()) { _startingCount.decrementAndGet(); IllegalStateException e = new IllegalStateException(L.l("'{0}' connection cannot be opened because the server pool has not been started.", this)); log.log(Level.WARNING, e.toString(), e); throw e; } if (getPort() <= 0) { return null; } long connectionStartTime = CurrentTime.currentTime(); try { ReadWritePair pair = openTCPPair(); ReadStreamOld rs = pair.getReadStream(); rs.setEnableReadTime(true); //rs.setAttribute("timeout", new Integer((int) _loadBalanceSocketTimeout)); _activeCount.incrementAndGet(); _connectCountTotal.incrementAndGet(); ClientSocket stream = new ClientSocket(this, _streamCount++, rs, pair.getWriteStream()); if (log.isLoggable(Level.FINER)) log.finer("connect " + stream); if (_firstSuccessTime <= 0) { if (_state.isStarting()) { if (_loadBalanceWarmupTime > 0) _state = State.WARMUP; else _state = State.ACTIVE; _firstSuccessTime = CurrentTime.currentTime(); } if (_warmupState < 0) _warmupState = 0; } return stream; } catch (IOException e) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, this + " " + e.toString(), e); else log.finer(this + " " + e.toString()); failConnect(connectionStartTime); return null; } finally { _startingCount.decrementAndGet(); } }
java
public boolean canConnect() { try { wake(); ClientSocket stream = open(); if (stream != null) { stream.free(stream.getIdleStartTime()); return true; } return false; } catch (Exception e) { log.log(Level.FINER, e.toString(), e); return false; } }
java
@Override public void write(byte []buffer, int offset, int length) { write(buffer, offset, length, true); }
java
@Override public void writePart(byte []buffer, int offset, int length) { write(buffer, offset, length, false); }
java
private void write(byte []buffer, int offset, int length, boolean isFinal) { Objects.requireNonNull(buffer); _frameOut.write(buffer, offset, length, isFinal); }
java
@Override public void close(WebSocketClose reason, String text) { Objects.requireNonNull(reason); if (_state.isClosed()) { return; } _state = _state.closeSelf(); _frameOut.close(reason, text); if (_state.isClosed()) { disconnect(); } }
java
private void readClose(FrameIn fIs) throws IOException { if (_state.isClosed()) { return; } _state = _state.closePeer(); int code = fIs.readClose(); StringBuilder sb = new StringBuilder(); fIs.readText(sb); if (_service != null) { WebSocketClose codeWs = WebSocketCloses.of(code); try { _service.close(codeWs, sb.toString(), this); } catch (Exception e) { throw new IOException(e); } } else { close(); } if (_state.isClosed()) { disconnect(); } //System.out.println("READ_C: " + code + " " + sb);; }
java
@Override public void fail(Throwable exn) { log.log(Level.WARNING, exn.toString(), exn); }
java
public static PathImpl lookup(String url) { PathImpl pwd = getPwd(); if (! url.startsWith("/")) { return pwd.lookup(url, null); } else { return PWD.lookup(url, null); } }
java
public static PathImpl getPwd() { PathImpl pwd = ENV_PWD.get(); if (pwd == null) { if (PWD == null) { /* JNI set later PWD = JniFilePath.create(); if (PWD == null) PWD = new FilePath(null); */ PWD = new FilePath(null); } pwd = PWD; ENV_PWD.setGlobal(pwd); } return pwd; }
java
public static PathImpl lookupNative(String url, Map<String,Object> attr) { return getPwd().lookupNative(url, attr); }
java
public static ReadStreamOld openRead(InputStream is) { if (is instanceof ReadStreamOld) return (ReadStreamOld) is; VfsStreamOld s = new VfsStreamOld(is, null); return new ReadStreamOld(s); }
java
public static ReadStreamOld openRead(Reader reader) { if (reader instanceof ReadStreamOld.StreamReader) return ((ReadStreamOld.StreamReader) reader).getStream(); ReaderWriterStream s = new ReaderWriterStream(reader, null); ReadStreamOld is = new ReadStreamOld(s); try { is.setEncoding("utf-8"); } catch (Exception e) { } return is; }
java
public static WriteStreamOld openWrite(CharBuffer cb) { com.caucho.v5.vfs.VfsStringWriter s = new com.caucho.v5.vfs.VfsStringWriter(cb); WriteStreamOld os = new WriteStreamOld(s); try { os.setEncoding("utf-8"); } catch (Exception e) { } return os; }
java
public static void initJNI() { if (_isInitJNI.getAndSet(true)) { return; } // order matters because of static init and license checking FilesystemPath jniFilePath = JniFilePath.create(); if (jniFilePath != null) { DEFAULT_SCHEME_MAP.put("file", jniFilePath); SchemeMap localMap = _localSchemeMap.get(); if (localMap != null) localMap.put("file", jniFilePath); localMap = _localSchemeMap.get(ClassLoader.getSystemClassLoader()); if (localMap != null) localMap.put("file", jniFilePath); VfsOld.PWD = jniFilePath; VfsOld.setPwd(jniFilePath); } }
java
private void writeMetaTable(TableEntry entry) { TempBuffer tBuf = TempBuffer.create(); byte []buffer = tBuf.buffer(); int offset = 0; buffer[offset++] = CODE_TABLE; offset += BitsUtil.write(buffer, offset, entry.tableKey()); offset += BitsUtil.writeInt16(buffer, offset, entry.rowLength()); offset += BitsUtil.writeInt16(buffer, offset, entry.keyOffset()); offset += BitsUtil.writeInt16(buffer, offset, entry.keyLength()); byte []data = entry.data(); offset += BitsUtil.writeInt16(buffer, offset, data.length); System.arraycopy(data, 0, buffer, offset, data.length); offset += data.length; int crc = _nonce; crc = Crc32Caucho.generate(crc, buffer, 0, offset); offset += BitsUtil.writeInt(buffer, offset, crc); // XXX: overflow try (OutStore sOut = openWrite(_metaOffset, offset)) { sOut.write(_metaOffset, buffer, 0, offset); _metaOffset += offset; } tBuf.free(); if (_metaTail - _metaOffset < 16) { writeMetaContinuation(); } }
java
private void writeMetaContinuation() { TempBuffer tBuf = TempBuffer.create(); byte []buffer = tBuf.buffer(); int metaLength = _segmentMeta[0].size(); SegmentExtent extent = new SegmentExtent(0, _addressTail, metaLength); _metaExtents.add(extent); _addressTail += metaLength; int offset = 0; buffer[offset++] = CODE_META_SEGMENT; long address = extent.address(); int length = extent.length(); long value = (address & ~0xffff) | (length >> 16); offset += BitsUtil.writeLong(buffer, offset, value); int crc = _nonce; crc = Crc32Caucho.generate(crc, buffer, 0, offset); offset += BitsUtil.writeInt(buffer, offset, crc); try (OutStore sOut = openWrite(_metaOffset, offset)) { sOut.write(_metaOffset, buffer, 0, offset); } tBuf.free(); _metaAddress = address; _metaOffset = address; _metaTail = address + length; }
java
private boolean readMetaData() throws IOException { SegmentExtent metaExtentInit = new SegmentExtent(0, 0, META_SEGMENT_SIZE); try (InSegment reader = openRead(metaExtentInit)) { ReadStream is = reader.in(); if (! readMetaDataHeader(is)) { return false; } _segmentId = 1; } int metaLength = _segmentMeta[0].size(); SegmentExtent metaExtent = new SegmentExtent(0, 0, metaLength); _metaExtents.clear(); _metaExtents.add(metaExtent); _metaAddress = 0; _metaOffset = META_OFFSET; _metaTail = _metaOffset + metaLength; while (true) { try (InSegment reader = openRead(metaExtent)) { ReadStream is = reader.in(); if (metaExtent.address() == 0) { is.position(META_OFFSET); } long metaAddress = _metaAddress; while (readMetaDataEntry(is)) { } if (_metaAddress == metaAddress) { return true; } metaExtent = new SegmentExtent(0, _metaAddress, metaLength); } } }
java
private boolean readMetaDataHeader(ReadStream is) throws IOException { long magic = BitsUtil.readLong(is); if (magic != KELP_MAGIC) { log.info(L.l("Mismatched kelp version {0} {1}\n", Long.toHexString(magic), _path)); return false; } int crc = CRC_INIT; crc = Crc32Caucho.generate(crc, magic); _nonce = BitsUtil.readInt(is); crc = Crc32Caucho.generateInt32(crc, _nonce); int headers = BitsUtil.readInt(is); crc = Crc32Caucho.generateInt32(crc, headers); for (int i = 0; i < headers; i++) { int key = BitsUtil.readInt(is); crc = Crc32Caucho.generateInt32(crc, key); int value = BitsUtil.readInt(is); crc = Crc32Caucho.generateInt32(crc, value); } int count = BitsUtil.readInt(is); crc = Crc32Caucho.generateInt32(crc, count); ArrayList<Integer> segmentSizes = new ArrayList<>(); for (int i = 0; i < count; i++) { int size = BitsUtil.readInt(is); crc = Crc32Caucho.generateInt32(crc, size); segmentSizes.add(size); } int crcFile = BitsUtil.readInt(is); if (crc != crcFile) { log.info(L.l("Mismatched crc files in kelp meta header")); return false; } SegmentMeta []segmentMetaList = new SegmentMeta[segmentSizes.size()]; for (int i = 0; i < segmentMetaList.length; i++) { segmentMetaList[i] = new SegmentMeta(segmentSizes.get(i)); } _segmentMeta = segmentMetaList; _metaOffset = is.position(); _addressTail = META_SEGMENT_SIZE; return true; }
java
private boolean readMetaDataEntry(ReadStream is) throws IOException { int crc = _nonce; int code = is.read(); crc = Crc32Caucho.generate(crc, code); switch (code) { case CODE_TABLE: readMetaTable(is, crc); break; case CODE_SEGMENT: readMetaSegment(is, crc); break; case CODE_META_SEGMENT: readMetaContinuation(is, crc); break; default: return false; } _metaOffset = is.position(); return true; }
java
private boolean readMetaTable(ReadStream is, int crc) throws IOException { byte []key = new byte[TABLE_KEY_SIZE]; is.read(key, 0, key.length); crc = Crc32Caucho.generate(crc, key); int rowLength = BitsUtil.readInt16(is); crc = Crc32Caucho.generateInt16(crc, rowLength); int keyOffset = BitsUtil.readInt16(is); crc = Crc32Caucho.generateInt16(crc, keyOffset); int keyLength = BitsUtil.readInt16(is); crc = Crc32Caucho.generateInt16(crc, keyLength); int dataLength = BitsUtil.readInt16(is); crc = Crc32Caucho.generateInt16(crc, dataLength); byte []data = new byte[dataLength]; is.readAll(data, 0, data.length); crc = Crc32Caucho.generate(crc, data); int crcFile = BitsUtil.readInt(is); if (crcFile != crc) { log.fine("meta-table crc mismatch"); return false; } TableEntry entry = new TableEntry(key, rowLength, keyOffset, keyLength, data); _tableList.add(entry); return true; }
java
private boolean readMetaSegment(ReadStream is, int crc) throws IOException { long value = BitsUtil.readLong(is); crc = Crc32Caucho.generate(crc, value); int crcFile = BitsUtil.readInt(is); if (crcFile != crc) { log.fine("meta-segment crc mismatch"); return false; } long address = value & ~0xffff; int length = (int) ((value & 0xffff) << 16); SegmentExtent segment = new SegmentExtent(_segmentId++, address, length); SegmentMeta segmentMeta = findSegmentMeta(length); segmentMeta.addSegment(segment); return true; }
java
private boolean readMetaContinuation(ReadStream is, int crc) throws IOException { long value = BitsUtil.readLong(is); crc = Crc32Caucho.generate(crc, value); int crcFile = BitsUtil.readInt(is); if (crcFile != crc) { log.fine("meta-segment crc mismatch"); return false; } long address = value & ~0xffff; int length = (int) ((value & 0xffff) << 16); if (length != _segmentMeta[0].size()) { throw new IllegalStateException(); } SegmentExtent extent = new SegmentExtent(0, address, length); _metaExtents.add(extent); _metaAddress = address; _metaOffset = address; _metaTail = address + length; // false continues to the next segment return false; }
java
private SegmentMeta findSegmentMeta(int size) { for (SegmentMeta segmentMeta : this._segmentMeta) { if (segmentMeta.size() == size) { return segmentMeta; } } throw new IllegalStateException(L.l("{0} is an invalid segment size", size)); }
java
public SegmentKelp createSegment(int length, byte []tableKey, long sequence) { SegmentMeta segmentMeta = findSegmentMeta(length); SegmentKelp segment; SegmentExtent extent = segmentMeta.allocate(); if (extent == null) { extent = allocateSegment(segmentMeta); } segment = new SegmentKelp(extent, sequence, tableKey, this); segment.writing(); segmentMeta.addLoaded(segment); return segment; }
java
private void findAfterLocal(Result<Cursor> result, RowCursor cursor, Object []args, Cursor cursorLocal) { long version = 0; if (cursorLocal != null) { version = cursorLocal.getVersion(); long time = cursorLocal.getUpdateTime(); long timeout = cursorLocal.getTimeout(); long now = CurrentTime.currentTime(); if (now <= time + timeout) { result.ok(cursorLocal); return; } } TablePod tablePod = _table.getTablePod(); tablePod.getIfUpdate(cursor.getKey(), version, result.then((table,r)->_selectQueryLocal.findOne(r, args))); }
java