code
stringlengths
73
34.1k
label
stringclasses
1 value
protected void startOutgoingConnection (final Connection conn, InetSocketAddress addr) { final SocketChannel sockchan = conn.getChannel(); try { // register our channel with the selector (if this fails, we abandon ship immediately) conn.selkey = sockchan.register(_selector, S...
java
protected void processAuthedConnections (long iterStamp) { AuthingConnection conn; while ((conn = _authq.getNonBlocking()) != null) { try { // construct a new running connection to handle this connections network traffic // from here on out ...
java
protected boolean writeDatagram (PresentsConnection conn, byte[] data) { InetSocketAddress target = conn.getDatagramAddress(); if (target == null) { log.warning("No address to send datagram", "conn", conn); return false; } _databuf.clear(); _databuf.p...
java
public OccupantInfo getOccupantInfo (Name username) { try { for (OccupantInfo info : occupantInfo) { if (info.username.equals(username)) { return info; } } } catch (Throwable t) { log.warning("PlaceObject.getOccu...
java
public static double getJulianDayNumber(Calendar time) { if (time == null) { time = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT")); } double jd = BASE_JD + time.getTimeInMillis() / MILLISEC_PER_DAY; return jd; }
java
protected final int decodeLength () { // if we don't have enough bytes to determine our frame size, stop // here and let the caller know that we're not ready if (_have < HEADER_SIZE) { return -1; } // decode the frame length _buffer.rewind(); int ...
java
public static void addExistingImports (String asFile, ImportSet imports) { // Discover the location of the 'public class' declaration. // We won't search past there. Matcher m = AS_PUBLIC_CLASS_DECL.matcher(asFile); int searchTo = asFile.length(); if (m.find()) { ...
java
public static void convertBaseClasses (ImportSet imports) { // replace primitive types with OOO types (required for unboxing) imports.replace("byte", "com.threerings.util.Byte"); imports.replace("boolean", "com.threerings.util.langBoolean"); imports.replace("[B", "flash.utils.ByteArr...
java
public void noteClassMappingsReceived (Collection<Class<?>> sclasses) { // sanity check if (_classmap == null) { throw new RuntimeException("Missing class map"); } // make each class's code positive to signify that we no longer need to send metadata for (Class<?>...
java
public void noteInternMappingsReceived (Collection<String> sinterns) { // sanity check if (_internmap == null) { throw new RuntimeException("Missing intern map"); } // make each intern's code positive to signify that we no longer need to send metadata for (String...
java
@Override public void write(int b) throws IOException { int newcount = count + 1; if (newcount > buf.length) { buf = Arrays.copyOf(buf, oversize(newcount)); } buf[count] = (byte) b; count = newcount; }
java
@Override public void write(byte[] b, int offset, int length) throws IOException { if (length == 0) { return; } int newcount = count + length; if (newcount > buf.length) { buf = Arrays.copyOf(buf, oversize(newcount)); } System.arraycopy(b, offs...
java
public void skip(int length) { int newcount = count + length; if (newcount > buf.length) { buf = Arrays.copyOf(buf, oversize(newcount)); } count = newcount; }
java
public void parseEvents(MarcXchangeEventConsumer consumer) throws XMLStreamException { Objects.requireNonNull(consumer); if (builder.getMarcListeners() != null) { for (Map.Entry<String, MarcListener> entry : builder.getMarcListeners().entrySet()) { consumer.setMarcListener(en...
java
public int wrapFields(String type, ChunkStream<byte[], BytesReference> stream, boolean withCollection) throws IOException { int count = 0; MarcListener marcListener = builder.getMarcListener(type); if (marcListener == null) { return count; } ...
java
public long wrapRecords(ChunkStream<byte[], BytesReference> stream, boolean withCollection) throws IOException { final AtomicInteger l = new AtomicInteger(); try { // keep reference to our record listener here, because builder will // enforce an intern...
java
protected void gotAuthResponse (AuthResponse rsp) throws LogonException { AuthResponseData data = rsp.getData(); if (!data.code.equals(AuthResponseData.SUCCESS)) { throw new LogonException(data.code); } logonSucceeded(data); }
java
public void setAccessor (Accessor<E> accessor) { removeAll(); _accessor = accessor; _table = new ObjectEditorTable(_entryClass, _editableFields, _accessor.getInterp(_interp), _displayFields); add(new JScrollPane(_table), BorderLayout.CENTER); }
java
protected void addEntry (E entry) { if (_entryFilter == null || _entryFilter.apply(entry)) { int index = _keys.insertSorted(getKey(entry)); _table.insertDatum(entry, index); } }
java
protected void removeKey (Comparable<?> key) { int index = _keys.indexOf(key); if (index != -1) { _keys.remove(index); _table.removeDatum(index); } }
java
public void actionPerformed (ActionEvent event) { CommandEvent ce = (CommandEvent)event; _accessor.updateEntry(_setName, (DSet.Entry)ce.getArgument()); }
java
public void clear(String layerName) { synchronized (this) { log.info("clearing cache for layer " + layerName); for (String key : cache.keySet()) { if (key.contains(layerName)) remove(key); } } }
java
public synchronized void put(WmsRequest request, byte[] image) { synchronized (this) { String key = getKey(request); // make sure it's the last on the list of keys so won't be dropped // from cache keys.remove(key); keys.add(key); if (keys....
java
public static String cloneArgument (Class<?> dsclazz, Field field, String name) { Class<?> clazz = field.getType(); if (clazz.isArray() || dsclazz.equals(clazz)) { return "(" + name + " == null) ? null : " + name + ".clone()"; } else if (dsclazz.isAssignableFrom(clazz)) { ...
java
public static String readClassName (File source) throws IOException { // load up the file and determine it's package and classname String pkgname = null, name = null; BufferedReader bin = new BufferedReader(new FileReader(source)); String line; while ((line = bin.read...
java
@AnyThread public void bodyRemovedFromChannel (ChatChannel channel, final int bodyId) { _peerMan.invokeNodeAction(new ChannelAction(channel) { @Override protected void execute () { ChannelInfo info = _channelMan._channels.get(_channel); if (info != null) { ...
java
@AnyThread public void collectChatHistory (final Name user, final ResultListener<ChatHistoryResult> lner) { _peerMan.invokeNodeRequest(new NodeRequest() { public boolean isApplicable (NodeObject nodeobj) { return true; // poll all nodes } @Override pro...
java
public void speak (ClientObject caller, final ChatChannel channel, String message, byte mode) { BodyObject body = _locator.forClient(caller); final UserMessage umsg = new UserMessage(body.getVisibleName(), null, message, mode); // if we're hosting this channel, dispatch it directly ...
java
protected void resolveAndDispatch (final ChatChannel channel) { NodeObject.Lock lock = new NodeObject.Lock("ChatChannel", channel.getLockName()); _peerMan.performWithLock(lock, new PeerManager.LockedOperation() { public void run () { ((CrowdNodeObject)_peerMan.getNodeObje...
java
protected void resolutionComplete (ChatChannel channel, Set<Integer> parts) { // map the participants of our now resolved channel ChannelInfo info = new ChannelInfo(); info.channel = channel; info.participants = parts; _channels.put(channel, info); // dispatch any pe...
java
protected void resolutionFailed (ChatChannel channel, Exception cause) { log.warning("Failed to resolve chat channel", "channel", channel, cause); // alas, we just drop all pending messages because we're hosed _resolving.remove(channel); }
java
protected void dispatchSpeak (ChatChannel channel, final UserMessage message) { final ChannelInfo info = _channels.get(channel); if (info == null) { // TODO: maybe we should just reresolve the channel... log.warning("Requested to dispatch speak on unhosted channel", "channel"...
java
protected void deliverSpeak (ChatChannel channel, UserMessage message, int[] bodyIds) { channel = intern(channel); for (int bodyId : bodyIds) { BodyObject bobj = getBodyObject(bodyId); if (bobj != null && shouldDeliverSpeak(channel, message, bobj)) { _chatHist...
java
protected void closeIdleChannels () { long now = System.currentTimeMillis(); Iterator<Map.Entry<ChatChannel, ChannelInfo>> iter = _channels.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<ChatChannel, ChannelInfo> entry = iter.next(); if (now - entry.getValu...
java
protected ChatChannel intern (ChatChannel channel) { ChannelInfo chinfo = _channels.get(channel); if (chinfo != null) { return chinfo.channel; } return channel; }
java
public static <E extends Enum<E>> StreamableEnumSet<E> noneOf (Class<E> elementType) { return new StreamableEnumSet<E>(elementType); }
java
public static <E extends Enum<E>> StreamableEnumSet<E> allOf (Class<E> elementType) { StreamableEnumSet<E> set = new StreamableEnumSet<E>(elementType); for (E constant : elementType.getEnumConstants()) { set.add(constant); } return set; }
java
public static <E extends Enum<E>> StreamableEnumSet<E> copyOf (StreamableEnumSet<E> s) { return s.clone(); }
java
public static <E extends Enum<E>> StreamableEnumSet<E> of (E first, E... rest) { StreamableEnumSet<E> set = new StreamableEnumSet<E>(first.getDeclaringClass()); set.add(first); for (E e : rest) { set.add(e); } return set; }
java
public boolean add (int oid) { // check for existence for (int ii = 0; ii < _size; ii++) { if (_oids[ii] == oid) { return false; } } // make room if necessary if (_size+1 >= _oids.length) { expand(); } // a...
java
public boolean remove (int oid) { // scan for the oid in question for (int ii = 0; ii < _size; ii++) { if (_oids[ii] == oid) { // shift the rest of the list back one System.arraycopy(_oids, ii+1, _oids, ii, --_size-ii); return true; ...
java
public boolean contains (int oid) { for (int ii = 0; ii < _size; ii++) { if (_oids[ii] == oid) { return true; } } return false; }
java
public JPanel getEditor (PresentsContext ctx, Field field) { if (field.getType().equals(Boolean.TYPE)) { return new BooleanFieldEditor(ctx, field, this); } else { return new AsStringFieldEditor(ctx, field, this); } }
java
public void getConfigInfo (AdminService.ConfigInfoListener arg1) { AdminMarshaller.ConfigInfoMarshaller listener1 = new AdminMarshaller.ConfigInfoMarshaller(); listener1.listener = arg1; sendRequest(GET_CONFIG_INFO, new Object[] { listener1 }); }
java
public void dispatchRequest (ClientObject source, int methodId, Object[] args) throws InvocationException { log.warning("Requested to dispatch unknown method", "provider", provider, "sourceOid", source.getOid(), "methodId", methodId, "args", args); }
java
public void speak (String arg1, byte arg2) { sendRequest(SPEAK, new Object[] { arg1, Byte.valueOf(arg2) }); }
java
public static boolean isBlank (Name name) { return (name == null || name.toString().equals(BLANK.toString())); }
java
public String getNormal () { if (_normal == null) { _normal = normalize(_name); // if _normal is an equals() String, ensure both point to the // same string for efficiency if (_normal.equals(_name)) { _normal = _name; } } ...
java
public boolean scheduleRegularReboot () { // maybe schedule an automatic reboot based on our configuration int freq = getDayFrequency(); int hour = getRebootHour(); if (freq <= 0) { return false; } Calendars.Builder cal = Calendars.now(); int curH...
java
public void cancelReboot () { if (_interval != null) { _interval.cancel(); _interval = null; } _nextReboot = 0L; _rebootSoon = false; _initiator = null; }
java
public int preventReboot (String whereFrom) { if (whereFrom == null) { throw new IllegalArgumentException("whereFrom must be descriptive."); } int lockId = _nextRebootLockId++; _rebootLocks.put(lockId, whereFrom); return lockId; }
java
protected void scheduleReboot (long rebootTime, boolean exact, String initiator) { // if there's already a reboot scheduled, cancel it cancelReboot(); long now = System.currentTimeMillis(); rebootTime = Math.max(rebootTime, now); // don't let reboots happen in the past long ...
java
protected String getRebootMessage (String key, int minutes) { String msg = getCustomRebootMessage(); if (StringUtil.isBlank(msg)) { msg = "m.reboot_msg_standard"; } return MessageBundle.compose(key, MessageBundle.taint("" + minutes), msg); }
java
protected void doWarning (int level, int minutes) { _rebootSoon = (level > -1); int[] warnings = getWarnings(); if (level == warnings.length) { if (checkLocks()) { return; } // that's it! do the reboot log.info("Performing aut...
java
protected boolean checkLocks () { if (_rebootLocks.isEmpty()) { return false; } log.info("Reboot delayed due to outstanding locks", "locks", _rebootLocks.elements()); broadcast("m.reboot_delayed"); (_interval = _omgr.newInterval(new Runnable() { publi...
java
protected void notifyObservers (int level) { final int warningsLeft = getWarnings().length - level - 1; final long msLeft = _nextReboot - System.currentTimeMillis(); _observers.apply(new ObserverList.ObserverOp<PendingShutdownObserver>() { public boolean apply (PendingShutdownObs...
java
public void registerFlushDelay (Class<?> objclass, long delay) { _delays.put(objclass, Long.valueOf(delay)); }
java
public void processMessage (Message msg) { if (_client.getRunQueue().isRunning()) { // append it to our queue _actions.append(msg); // and queue ourselves up to be run _client.getRunQueue().postRunnable(this); } else { log.info("Dropping me...
java
public void cleanup () { // tell any pending object subscribers that they're not getting their bits for (PendingRequest<?> req : _penders.values()) { for (Subscriber<?> sub : req.targets) { sub.requestFailed(req.oid, new ObjectAccessException("Client connection closed"));...
java
protected void dispatchEvent (DEvent event) { // Log.info("Dispatching event: " + evt); // look up the object on which we're dispatching this event int remoteOid = event.getTargetOid(); DObject target = _ocache.get(remoteOid); if (target == null) { if (!_dead.con...
java
protected void dispatchEvent (int remoteOid, DObject target, DEvent event) { try { // apply the event to the object boolean notify = event.applyToObject(target); // if this is an object destroyed event, we need to remove the object from our table if (event in...
java
protected <T extends DObject> void registerObjectAndNotify (ObjectResponse<T> orsp) { // let the object know that we'll be managing it T obj = orsp.getObject(); obj.setManager(this); // stick the object into the proxy object table _ocache.put(obj.getOid(), obj); // ...
java
protected void flushObject (DObject obj) { // move this object into the dead pool so that we don't claim to have it around anymore; // once our unsubscribe message is processed, it'll be 86ed int ooid = obj.getOid(); _ocache.remove(ooid); _dead.put(ooid, obj); // shi...
java
protected void flushObjects () { long now = System.currentTimeMillis(); for (Iterator<IntMap.IntEntry<FlushRecord>> iter = _flushes.intEntrySet().iterator(); iter.hasNext(); ) { IntMap.IntEntry<FlushRecord> entry = iter.next(); // int oid = entry.getIntKey(); ...
java
public static Cipher getAESCipher (int mode, byte[] key) { try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec aesKey = new SecretKeySpec(key, "AES"); cipher.init(mode, aesKey, IVPS); return cipher; } catch (GeneralSecurityE...
java
public static Cipher getRSACipher (int mode, Key key) { try { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(mode, key); return cipher; } catch (GeneralSecurityException gse) { log.warning("Failed to create cipher", gse); } retu...
java
public static KeyPair genRSAKeyPair (int bits) { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(bits); return kpg.genKeyPair(); } catch (GeneralSecurityException gse) { log.warning("Failed to create key pair", gse); ...
java
public static PublicKey stringToRSAPublicKey (String str) { try { BigInteger mod = new BigInteger(str.substring(0, str.indexOf(SPLIT)), 16); BigInteger exp = new BigInteger(str.substring(str.indexOf(SPLIT) + 1), 16); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(mod, ex...
java
public static PrivateKey stringToRSAPrivateKey (String str) { try { BigInteger mod = new BigInteger(str.substring(0, str.indexOf(SPLIT)), 16); BigInteger exp = new BigInteger(str.substring(str.indexOf(SPLIT) + 1), 16); RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(mod...
java
public static byte[] encryptBytes (PublicKey key, byte[] secret, byte[] salt) { byte[] encrypt = new byte[secret.length + salt.length]; for (int ii = 0; ii < secret.length; ii++) { encrypt[ii] = secret[ii]; } for (int ii = 0; ii < salt.length; ii++) { encrypt[...
java
public static byte[] decryptBytes (PrivateKey key, byte[] encrypted, byte[] salt) { try { byte[] decrypted = getRSACipher(key).doFinal(encrypted); for (int ii = 0; ii < salt.length; ii++) { if (decrypted[decrypted.length - salt.length + ii] != salt[ii]) { ...
java
public static byte[] xorBytes (byte[] data, byte[] key) { byte[] xored = new byte[data.length]; for (int ii = 0; ii < data.length; ii++) { xored[ii] = (byte)(data[ii] ^ key[ii % key.length]); } return xored; }
java
public void commit () { // first clear our target clearTarget(); // then post this event onto the queue (but only if we actually // accumulated some events) int size = _events.size(); switch (size) { case 0: // nothing doing break; case 1:...
java
public PlaceConfig moveTo (BodyObject source, int placeOid) throws InvocationException { // make sure the place in question actually exists PlaceManager pmgr = _plreg.getPlaceManager(placeOid); if (pmgr == null) { log.info("Requested to move to non-existent place", "who",...
java
public void leaveOccupiedPlace (BodyObject source) { Place oldloc = source.location; if (oldloc == null) { return; // nothing to do if they weren't previously in some location } PlaceManager pmgr = _plreg.getPlaceManager(oldloc.placeOid); if (pmgr == null) { ...
java
public void init (int invOid, int invCode, InvocationDirector invDir) { _invOid = invOid; _invCode = invCode; _invdir = invDir; }
java
protected void sendRequest (int methodId, Object[] args, Transport transport) { _invdir.sendRequest(_invOid, _invCode, methodId, args, transport); }
java
public static FieldMarshaller getFieldMarshaller (Field field) { if (_marshallers == null) { // multiple threads may attempt to create the stock marshallers, but they'll just do // extra work and _marshallers will only ever contain a fully populated table _marshallers = c...
java
protected void sendOutgoingMessages (long iterStamp) { // first attempt to send any messages waiting on the overflow queues if (_oflowqs.size() > 0) { // do this on a snapshot as a network failure writing oflow queue messages will result // in the queue being removed from _of...
java
protected boolean writeMessage (Connection conn, byte[] data, PartialWriteHandler pwh) { // if the connection to which this message is destined is closed, drop the message and move // along quietly; this is perfectly legal, a user can logoff whenever they like, even if we // still have thing...
java
protected void connectionFailed (Connection conn, IOException ioe) { // remove this connection from our mappings (it is automatically removed from the Selector // when the socket is closed) _handlers.remove(conn.selkey); _connections.remove(conn.getConnectionId()); _oflowqs.r...
java
protected void connectionClosed (Connection conn) { // remove this connection from our mappings (it is automatically removed from the Selector // when the socket is closed) _handlers.remove(conn.selkey); _connections.remove(conn.getConnectionId()); _oflowqs.remove(conn); ...
java
public static <K, V> StreamableHashMap<K, V> newMap (Map<? extends K, ? extends V> map) { return new StreamableHashMap<K, V>(map); }
java
public void shutdown () { if (_chatdir != null) { _chatdir.removeChatFilter(this); _chatdir = null; } _ctx.getClient().removeClientObserver(this); }
java
public void setMuted (Name username, boolean mute) { boolean changed = mute ? _mutelist.add(username) : _mutelist.remove(username); String feedback; if (mute) { feedback = "m.muted"; } else { feedback = changed ? "m.unmuted" : "m.notmuted"; } ...
java
public String filter (String msg, Name otherUser, boolean outgoing) { // we are only concerned with filtering things going to or coming // from muted users if ((otherUser != null) && isMuted(otherUser)) { // if it was outgoing, explain the dropped message, otherwise /...
java
protected void notifyObservers (final Name username, final boolean muted) { _observers.apply(new ObserverList.ObserverOp<MuteObserver>() { public boolean apply (MuteObserver observer) { observer.muteChanged(username, muted); return true; } }); ...
java
public void clearDispatcher (InvocationMarshaller<?> marsh) { _omgr.requireEventThread(); // sanity check if (marsh == null) { log.warning("Refusing to unregister null marshaller.", new Exception()); return; } if (_dispatchers.remove(marsh.getInvocationCode(...
java
public List<InvocationMarshaller<?>> getBootstrapServices (String[] bootGroups) { List<InvocationMarshaller<?>> services = Lists.newArrayList(); for (String group : bootGroups) { services.addAll(_bootlists.get(group)); } return services; }
java
public Class<?> getDispatcherClass (int invCode) { Object dispatcher = _dispatchers.get(invCode); return (dispatcher == null) ? null : dispatcher.getClass(); }
java
protected void dispatchRequest ( int clientOid, int invCode, int methodId, Object[] args, Transport transport) { // make sure the client is still around ClientObject source = (ClientObject)_omgr.getObject(clientOid); if (source == null) { log.info("Client no longer around...
java
public void setClientInfo (String msg, String ltype) { message = msg; localtype = ltype; bundle = null; timestamp = System.currentTimeMillis(); }
java
protected int innerCompare(Comparable<Object> co1, Comparable<Object> co2) { return co1.compareTo(co2); }
java
protected void processClass (File source) { CtClass clazz; InputStream in = null; try { clazz = _pool.makeClass(in = new BufferedInputStream(new FileInputStream(source))); } catch (IOException ioe) { System.err.println("Failed to load " + source + ": " + ioe);...
java
protected synchronized void createAgent (int agentId) { Subscriber<AgentObject> delegator = new Subscriber<AgentObject>() { public void objectAvailable (AgentObject agentObject) { BureauDirector.this.objectAvailable(agentObject); } public void requestFaile...
java
protected synchronized void destroyAgent (int agentId) { Agent agent = null; agent = _agents.remove(agentId); if (agent == null) { log.warning("Lost an agent, id " + agentId); } else { try { agent.stop(); } catch (Throwable t) { ...
java
protected synchronized void objectAvailable (AgentObject agentObject) { int oid = agentObject.getOid(); log.info("Object " + oid + " now available"); Agent agent; try { agent = createAgent(agentObject); agent.init(agentObject); agent.start(); ...
java
public void handleSuccess () { if (_listener instanceof InvocationService.ConfirmListener) { reportRequestProcessed(); } else if (_listener instanceof InvocationService.ResultListener && _resultSet) { reportRequestProcessed(_result); } }
java
public void handleFailure (Exception error) { if (error instanceof InvocationException) { _listener.requestFailed(error.getMessage()); } else { if (_args != null) { log.warning(getFailureMessage(), ArrayUtil.append(_args, error)); } else { ...
java
public void addConstraint (Shutdowner lhs, Constraint constraint, Shutdowner rhs) { switch (constraint) { case RUNS_BEFORE: _cycle.addShutdownConstraint(lhs, Lifecycle.Constraint.RUNS_BEFORE, rhs); break; case RUNS_AFTER: _cycle.addShutdownConstraint(lhs, ...
java