repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
threerings/narya
core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java
PresentsConnectionManager.startOutgoingConnection
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, SelectionKey.OP_CONNECT); // start our connection process (now if we fail we need to clean things up) NetEventHandler handler; if (sockchan.connect(addr)) { _outConnValidator.validateOutgoing(sockchan); // may throw // it is possible even for a non-blocking socket to connect immediately, in which // case we stick the connection in as its event handler immediately handler = conn; } else { // otherwise we wire up a special event handler that will wait for our socket to // finish the connection process and then wire things up fully handler = new OutgoingConnectionHandler(conn); } _handlers.put(conn.selkey, handler); } catch (IOException ioe) { log.warning("Failed to initiate connection for " + sockchan + ".", ioe); conn.connectFailure(ioe); // nothing else to clean up } }
java
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, SelectionKey.OP_CONNECT); // start our connection process (now if we fail we need to clean things up) NetEventHandler handler; if (sockchan.connect(addr)) { _outConnValidator.validateOutgoing(sockchan); // may throw // it is possible even for a non-blocking socket to connect immediately, in which // case we stick the connection in as its event handler immediately handler = conn; } else { // otherwise we wire up a special event handler that will wait for our socket to // finish the connection process and then wire things up fully handler = new OutgoingConnectionHandler(conn); } _handlers.put(conn.selkey, handler); } catch (IOException ioe) { log.warning("Failed to initiate connection for " + sockchan + ".", ioe); conn.connectFailure(ioe); // nothing else to clean up } }
[ "protected", "void", "startOutgoingConnection", "(", "final", "Connection", "conn", ",", "InetSocketAddress", "addr", ")", "{", "final", "SocketChannel", "sockchan", "=", "conn", ".", "getChannel", "(", ")", ";", "try", "{", "// register our channel with the selector ...
Starts the connection process for an outgoing connection. This is called as part of the conmgr tick for any pending outgoing connections.
[ "Starts", "the", "connection", "process", "for", "an", "outgoing", "connection", ".", "This", "is", "called", "as", "part", "of", "the", "conmgr", "tick", "for", "any", "pending", "outgoing", "connections", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java#L384-L410
train
threerings/narya
core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java
PresentsConnectionManager.processAuthedConnections
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 PresentsConnection rconn = new PresentsConnection(); rconn.init(this, conn.getChannel(), iterStamp); rconn.selkey = conn.selkey; // we need to keep using the same object input and output streams from the // beginning of the session because they have context that needs to be preserved rconn.inheritStreams(conn); // replace the mapping in the handlers table from the old conn with the new one _handlers.put(rconn.selkey, rconn); // add a mapping for the connection id and set the datagram secret _connections.put(rconn.getConnectionId(), rconn); rconn.setDatagramSecret(conn.getAuthRequest().getCredentials().getDatagramSecret()); // transfer any overflow queue for that connection OverflowQueue oflowHandler = _oflowqs.remove(conn); if (oflowHandler != null) { _oflowqs.put(rconn, oflowHandler); } // and let the client manager know about our new connection _clmgr.connectionEstablished(rconn, conn.getAuthName(), conn.getAuthRequest(), conn.getAuthResponse()); } catch (IOException ioe) { log.warning("Failure upgrading authing connection to running.", ioe); } } }
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 PresentsConnection rconn = new PresentsConnection(); rconn.init(this, conn.getChannel(), iterStamp); rconn.selkey = conn.selkey; // we need to keep using the same object input and output streams from the // beginning of the session because they have context that needs to be preserved rconn.inheritStreams(conn); // replace the mapping in the handlers table from the old conn with the new one _handlers.put(rconn.selkey, rconn); // add a mapping for the connection id and set the datagram secret _connections.put(rconn.getConnectionId(), rconn); rconn.setDatagramSecret(conn.getAuthRequest().getCredentials().getDatagramSecret()); // transfer any overflow queue for that connection OverflowQueue oflowHandler = _oflowqs.remove(conn); if (oflowHandler != null) { _oflowqs.put(rconn, oflowHandler); } // and let the client manager know about our new connection _clmgr.connectionEstablished(rconn, conn.getAuthName(), conn.getAuthRequest(), conn.getAuthResponse()); } catch (IOException ioe) { log.warning("Failure upgrading authing connection to running.", ioe); } } }
[ "protected", "void", "processAuthedConnections", "(", "long", "iterStamp", ")", "{", "AuthingConnection", "conn", ";", "while", "(", "(", "conn", "=", "_authq", ".", "getNonBlocking", "(", ")", ")", "!=", "null", ")", "{", "try", "{", "// construct a new runni...
Converts connections that have completed the authentication process into full running connections and notifies the client manager that new connections have been established.
[ "Converts", "connections", "that", "have", "completed", "the", "authentication", "process", "into", "full", "running", "connections", "and", "notifies", "the", "client", "manager", "that", "new", "connections", "have", "been", "established", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java#L501-L537
train
threerings/narya
core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java
PresentsConnectionManager.writeDatagram
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.put(data).flip(); try { return conn.getDatagramChannel().send(_databuf, target) > 0; } catch (IOException ioe) { log.warning("Failed to send datagram.", ioe); return false; } }
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.put(data).flip(); try { return conn.getDatagramChannel().send(_databuf, target) > 0; } catch (IOException ioe) { log.warning("Failed to send datagram.", ioe); return false; } }
[ "protected", "boolean", "writeDatagram", "(", "PresentsConnection", "conn", ",", "byte", "[", "]", "data", ")", "{", "InetSocketAddress", "target", "=", "conn", ".", "getDatagramAddress", "(", ")", ";", "if", "(", "target", "==", "null", ")", "{", "log", "...
Sends a datagram to the specified connection. @return true if the datagram was sent, false if we failed to send for any reason.
[ "Sends", "a", "datagram", "to", "the", "specified", "connection", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java#L556-L572
train
threerings/narya
core/src/main/java/com/threerings/crowd/data/PlaceObject.java
PlaceObject.getOccupantInfo
public OccupantInfo getOccupantInfo (Name username) { try { for (OccupantInfo info : occupantInfo) { if (info.username.equals(username)) { return info; } } } catch (Throwable t) { log.warning("PlaceObject.getOccupantInfo choked.", t); } return null; }
java
public OccupantInfo getOccupantInfo (Name username) { try { for (OccupantInfo info : occupantInfo) { if (info.username.equals(username)) { return info; } } } catch (Throwable t) { log.warning("PlaceObject.getOccupantInfo choked.", t); } return null; }
[ "public", "OccupantInfo", "getOccupantInfo", "(", "Name", "username", ")", "{", "try", "{", "for", "(", "OccupantInfo", "info", ":", "occupantInfo", ")", "{", "if", "(", "info", ".", "username", ".", "equals", "(", "username", ")", ")", "{", "return", "i...
Looks up a user's occupant info by name. @return the occupant info record for the named user or null if no user in the room has that username.
[ "Looks", "up", "a", "user", "s", "occupant", "info", "by", "name", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/data/PlaceObject.java#L136-L148
train
davidmoten/grumpy
grumpy-ogc-layers/src/main/java/com/github/davidmoten/grumpy/wms/layer/darkness/TimeUtil.java
TimeUtil.getJulianDayNumber
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
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; }
[ "public", "static", "double", "getJulianDayNumber", "(", "Calendar", "time", ")", "{", "if", "(", "time", "==", "null", ")", "{", "time", "=", "GregorianCalendar", ".", "getInstance", "(", "TimeZone", ".", "getTimeZone", "(", "\"GMT\"", ")", ")", ";", "}",...
Calculate the Julian day number corresponding to the time provided @param time , the time for which the Julian Day number is required. If null, the current time will be used. @return - the Julian day number corresponding to the supplied time
[ "Calculate", "the", "Julian", "day", "number", "corresponding", "to", "the", "time", "provided" ]
f2d03e6b9771f15425fb3f76314837efc08c1233
https://github.com/davidmoten/grumpy/blob/f2d03e6b9771f15425fb3f76314837efc08c1233/grumpy-ogc-layers/src/main/java/com/github/davidmoten/grumpy/wms/layer/darkness/TimeUtil.java#L34-L43
train
threerings/narya
core/src/main/java/com/threerings/io/FramedInputStream.java
FramedInputStream.decodeLength
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 length = (_buffer.get() & 0xFF) << 24; length += (_buffer.get() & 0xFF) << 16; length += (_buffer.get() & 0xFF) << 8; length += (_buffer.get() & 0xFF); _buffer.position(_have); return length; }
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 length = (_buffer.get() & 0xFF) << 24; length += (_buffer.get() & 0xFF) << 16; length += (_buffer.get() & 0xFF) << 8; length += (_buffer.get() & 0xFF); _buffer.position(_have); return length; }
[ "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", ";", "}", "// deco...
Decodes and returns the length of the current frame from the buffer if possible. Returns -1 otherwise.
[ "Decodes", "and", "returns", "the", "length", "of", "the", "current", "frame", "from", "the", "buffer", "if", "possible", ".", "Returns", "-", "1", "otherwise", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/io/FramedInputStream.java#L151-L168
train
threerings/narya
tools/src/main/java/com/threerings/presents/tools/ActionScriptUtils.java
ActionScriptUtils.addExistingImports
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()) { searchTo = m.start(); } m = AS_IMPORT.matcher(asFile.substring(0, searchTo)); while (m.find()) { imports.add(m.group(3)); } }
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()) { searchTo = m.start(); } m = AS_IMPORT.matcher(asFile.substring(0, searchTo)); while (m.find()) { imports.add(m.group(3)); } }
[ "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", "(",...
Adds an existing ActionScript file's imports to the given ImportSet. @param asFile a String containing the contents of an ActionScript file
[ "Adds", "an", "existing", "ActionScript", "file", "s", "imports", "to", "the", "given", "ImportSet", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/tools/src/main/java/com/threerings/presents/tools/ActionScriptUtils.java#L46-L60
train
threerings/narya
tools/src/main/java/com/threerings/presents/tools/ActionScriptUtils.java
ActionScriptUtils.convertBaseClasses
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.ByteArray"); imports.replace("float", "com.threerings.util.Float"); imports.replace("long", "com.threerings.util.Long"); if (imports.removeAll("[*") > 0) { imports.add("com.threerings.io.TypedArray"); } // convert java primitive boxes to their ooo counterparts imports.replace(Integer.class, "com.threerings.util.Integer"); // convert some java.util types to their ooo counterparts imports.replace(Map.class, "com.threerings.util.Map"); // get rid of java.lang stuff and any remaining primitives imports.removeGlobals(); // get rid of remaining arrays imports.removeArrays(); }
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.ByteArray"); imports.replace("float", "com.threerings.util.Float"); imports.replace("long", "com.threerings.util.Long"); if (imports.removeAll("[*") > 0) { imports.add("com.threerings.io.TypedArray"); } // convert java primitive boxes to their ooo counterparts imports.replace(Integer.class, "com.threerings.util.Integer"); // convert some java.util types to their ooo counterparts imports.replace(Map.class, "com.threerings.util.Map"); // get rid of java.lang stuff and any remaining primitives imports.removeGlobals(); // get rid of remaining arrays imports.removeArrays(); }
[ "public", "static", "void", "convertBaseClasses", "(", "ImportSet", "imports", ")", "{", "// replace primitive types with OOO types (required for unboxing)", "imports", ".", "replace", "(", "\"byte\"", ",", "\"com.threerings.util.Byte\"", ")", ";", "imports", ".", "replace"...
Converts java types to their actionscript equivalents for ooo-style streaming.
[ "Converts", "java", "types", "to", "their", "actionscript", "equivalents", "for", "ooo", "-", "style", "streaming", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/tools/src/main/java/com/threerings/presents/tools/ActionScriptUtils.java#L229-L253
train
threerings/narya
core/src/main/java/com/threerings/io/UnreliableObjectOutputStream.java
UnreliableObjectOutputStream.noteClassMappingsReceived
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<?> sclass : sclasses) { ClassMapping cmap = _classmap.get(sclass); if (cmap == null) { throw new RuntimeException("No class mapping for " + sclass.getName()); } cmap.code = (short)Math.abs(cmap.code); } }
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<?> sclass : sclasses) { ClassMapping cmap = _classmap.get(sclass); if (cmap == null) { throw new RuntimeException("No class mapping for " + sclass.getName()); } cmap.code = (short)Math.abs(cmap.code); } }
[ "public", "void", "noteClassMappingsReceived", "(", "Collection", "<", "Class", "<", "?", ">", ">", "sclasses", ")", "{", "// sanity check", "if", "(", "_classmap", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"Missing class map\"", ")", ...
Notes that the receiver has received the mappings for a group of classes and thus that from now on, only the codes need be sent.
[ "Notes", "that", "the", "receiver", "has", "received", "the", "mappings", "for", "a", "group", "of", "classes", "and", "thus", "that", "from", "now", "on", "only", "the", "codes", "need", "be", "sent", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/io/UnreliableObjectOutputStream.java#L85-L100
train
threerings/narya
core/src/main/java/com/threerings/io/UnreliableObjectOutputStream.java
UnreliableObjectOutputStream.noteInternMappingsReceived
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 sintern : sinterns) { Short code = _internmap.get(sintern); if (code == null) { throw new RuntimeException("No intern mapping for " + sintern); } short scode = code; if (scode < 0) { _internmap.put(sintern, (short)-code); } } }
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 sintern : sinterns) { Short code = _internmap.get(sintern); if (code == null) { throw new RuntimeException("No intern mapping for " + sintern); } short scode = code; if (scode < 0) { _internmap.put(sintern, (short)-code); } } }
[ "public", "void", "noteInternMappingsReceived", "(", "Collection", "<", "String", ">", "sinterns", ")", "{", "// sanity check", "if", "(", "_internmap", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"Missing intern map\"", ")", ";", "}", "//...
Notes that the receiver has received the mappings for a group of interns and thus that from now on, only the codes need be sent.
[ "Notes", "that", "the", "receiver", "has", "received", "the", "mappings", "for", "a", "group", "of", "interns", "and", "thus", "that", "from", "now", "on", "only", "the", "codes", "need", "be", "sent", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/io/UnreliableObjectOutputStream.java#L106-L124
train
xbib/marc
src/main/java/org/xbib/marc/io/BytesStreamOutput.java
BytesStreamOutput.write
@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(int b) throws IOException { int newcount = count + 1; if (newcount > buf.length) { buf = Arrays.copyOf(buf, oversize(newcount)); } buf[count] = (byte) b; count = newcount; }
[ "@", "Override", "public", "void", "write", "(", "int", "b", ")", "throws", "IOException", "{", "int", "newcount", "=", "count", "+", "1", ";", "if", "(", "newcount", ">", "buf", ".", "length", ")", "{", "buf", "=", "Arrays", ".", "copyOf", "(", "b...
Write an integer. @param b int @throws IOException if write fails
[ "Write", "an", "integer", "." ]
d8426fcfc686507cab59b3d8181b08f83718418c
https://github.com/xbib/marc/blob/d8426fcfc686507cab59b3d8181b08f83718418c/src/main/java/org/xbib/marc/io/BytesStreamOutput.java#L89-L97
train
xbib/marc
src/main/java/org/xbib/marc/io/BytesStreamOutput.java
BytesStreamOutput.write
@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, offset, buf, count, length); 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, offset, buf, count, length); count = newcount; }
[ "@", "Override", "public", "void", "write", "(", "byte", "[", "]", "b", ",", "int", "offset", ",", "int", "length", ")", "throws", "IOException", "{", "if", "(", "length", "==", "0", ")", "{", "return", ";", "}", "int", "newcount", "=", "count", "+...
Write byte array. @param b byte array @param offset offset @param length length @throws IOException if write fails
[ "Write", "byte", "array", "." ]
d8426fcfc686507cab59b3d8181b08f83718418c
https://github.com/xbib/marc/blob/d8426fcfc686507cab59b3d8181b08f83718418c/src/main/java/org/xbib/marc/io/BytesStreamOutput.java#L107-L118
train
xbib/marc
src/main/java/org/xbib/marc/io/BytesStreamOutput.java
BytesStreamOutput.skip
public void skip(int length) { int newcount = count + length; if (newcount > buf.length) { buf = Arrays.copyOf(buf, oversize(newcount)); } count = newcount; }
java
public void skip(int length) { int newcount = count + length; if (newcount > buf.length) { buf = Arrays.copyOf(buf, oversize(newcount)); } count = newcount; }
[ "public", "void", "skip", "(", "int", "length", ")", "{", "int", "newcount", "=", "count", "+", "length", ";", "if", "(", "newcount", ">", "buf", ".", "length", ")", "{", "buf", "=", "Arrays", ".", "copyOf", "(", "buf", ",", "oversize", "(", "newco...
Skip a number of bytes. @param length the number of bytes to skip.
[ "Skip", "a", "number", "of", "bytes", "." ]
d8426fcfc686507cab59b3d8181b08f83718418c
https://github.com/xbib/marc/blob/d8426fcfc686507cab59b3d8181b08f83718418c/src/main/java/org/xbib/marc/io/BytesStreamOutput.java#L124-L130
train
xbib/marc
src/main/java/org/xbib/marc/Marc.java
Marc.parseEvents
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(entry.getKey(), entry.getValue()); } } XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(builder.getInputStream()); while (xmlEventReader.hasNext()) { consumer.add(xmlEventReader.nextEvent()); } xmlEventReader.close(); }
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(entry.getKey(), entry.getValue()); } } XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(builder.getInputStream()); while (xmlEventReader.hasNext()) { consumer.add(xmlEventReader.nextEvent()); } xmlEventReader.close(); }
[ "public", "void", "parseEvents", "(", "MarcXchangeEventConsumer", "consumer", ")", "throws", "XMLStreamException", "{", "Objects", ".", "requireNonNull", "(", "consumer", ")", ";", "if", "(", "builder", ".", "getMarcListeners", "(", ")", "!=", "null", ")", "{", ...
Run XML stream parser over an XML input stream, with an XML event consumer. @param consumer the XML event consumer @throws XMLStreamException if parsing fails
[ "Run", "XML", "stream", "parser", "over", "an", "XML", "input", "stream", "with", "an", "XML", "event", "consumer", "." ]
d8426fcfc686507cab59b3d8181b08f83718418c
https://github.com/xbib/marc/blob/d8426fcfc686507cab59b3d8181b08f83718418c/src/main/java/org/xbib/marc/Marc.java#L127-L140
train
xbib/marc
src/main/java/org/xbib/marc/Marc.java
Marc.wrapFields
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; } try { if (withCollection) { // write XML declaration if required if (marcListener instanceof ContentHandler) { ((ContentHandler) marcListener).startDocument(); } marcListener.beginCollection(); } if (builder.marcGenerator == null) { builder.marcGenerator = builder.createGenerator(); } Chunk<byte[], BytesReference> chunk; while ((chunk = stream.readChunk()) != null) { builder.marcGenerator.chunk(chunk); count++; } stream.close(); builder.marcGenerator.flush(); if (withCollection) { marcListener.endCollection(); if (marcListener instanceof ContentHandler) { ((ContentHandler) marcListener).endDocument(); } } } catch (SAXException e) { throw new IOException(e); } finally { if (builder.getInputStream() != null) { // essential builder.getInputStream().close(); } } return count; }
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; } try { if (withCollection) { // write XML declaration if required if (marcListener instanceof ContentHandler) { ((ContentHandler) marcListener).startDocument(); } marcListener.beginCollection(); } if (builder.marcGenerator == null) { builder.marcGenerator = builder.createGenerator(); } Chunk<byte[], BytesReference> chunk; while ((chunk = stream.readChunk()) != null) { builder.marcGenerator.chunk(chunk); count++; } stream.close(); builder.marcGenerator.flush(); if (withCollection) { marcListener.endCollection(); if (marcListener instanceof ContentHandler) { ((ContentHandler) marcListener).endDocument(); } } } catch (SAXException e) { throw new IOException(e); } finally { if (builder.getInputStream() != null) { // essential builder.getInputStream().close(); } } return count; }
[ "public", "int", "wrapFields", "(", "String", "type", ",", "ChunkStream", "<", "byte", "[", "]", ",", "BytesReference", ">", "stream", ",", "boolean", "withCollection", ")", "throws", "IOException", "{", "int", "count", "=", "0", ";", "MarcListener", "marcLi...
Pass a given chunk stream to a MARC generator, chunk by chunk. Can process any MARC streams, not only separator streams. @param type the MARC record type @param stream a chunk stream @param withCollection true if stream should be wrapped into a collection element @return the number of chunks in the stream @throws IOException if chunk reading fails
[ "Pass", "a", "given", "chunk", "stream", "to", "a", "MARC", "generator", "chunk", "by", "chunk", ".", "Can", "process", "any", "MARC", "streams", "not", "only", "separator", "streams", "." ]
d8426fcfc686507cab59b3d8181b08f83718418c
https://github.com/xbib/marc/blob/d8426fcfc686507cab59b3d8181b08f83718418c/src/main/java/org/xbib/marc/Marc.java#L294-L334
train
xbib/marc
src/main/java/org/xbib/marc/Marc.java
Marc.wrapRecords
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 internal record listener MarcRecordListener marcRecordListener = builder.getMarcRecordListener(); if (withCollection) { // write XML declaration if required if (marcRecordListener instanceof ContentHandler) { ((ContentHandler) marcRecordListener).startDocument(); } marcRecordListener.beginCollection(); } if (builder.marcGenerator == null) { builder.marcGenerator = builder.createGenerator(); } // short-circuit: set MARC listener of the MARC generator to builder to capture records builder.marcGenerator.setMarcListener(builder); builder.marcGenerator.setCharset(builder.getCharset()); builder.stream = stream; // voila: now we can stream records builder.recordStream().forEach(record -> { marcRecordListener.record(record); l.incrementAndGet(); }); stream.close(); builder.marcGenerator.flush(); if (withCollection) { marcRecordListener.endCollection(); if (marcRecordListener instanceof ContentHandler) { ((ContentHandler) marcRecordListener).endDocument(); } } } catch (SAXException e) { throw new IOException(e); } finally { // we close input stream always if (builder.getInputStream() != null) { builder.getInputStream().close(); } } return l.get(); }
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 internal record listener MarcRecordListener marcRecordListener = builder.getMarcRecordListener(); if (withCollection) { // write XML declaration if required if (marcRecordListener instanceof ContentHandler) { ((ContentHandler) marcRecordListener).startDocument(); } marcRecordListener.beginCollection(); } if (builder.marcGenerator == null) { builder.marcGenerator = builder.createGenerator(); } // short-circuit: set MARC listener of the MARC generator to builder to capture records builder.marcGenerator.setMarcListener(builder); builder.marcGenerator.setCharset(builder.getCharset()); builder.stream = stream; // voila: now we can stream records builder.recordStream().forEach(record -> { marcRecordListener.record(record); l.incrementAndGet(); }); stream.close(); builder.marcGenerator.flush(); if (withCollection) { marcRecordListener.endCollection(); if (marcRecordListener instanceof ContentHandler) { ((ContentHandler) marcRecordListener).endDocument(); } } } catch (SAXException e) { throw new IOException(e); } finally { // we close input stream always if (builder.getInputStream() != null) { builder.getInputStream().close(); } } return l.get(); }
[ "public", "long", "wrapRecords", "(", "ChunkStream", "<", "byte", "[", "]", ",", "BytesReference", ">", "stream", ",", "boolean", "withCollection", ")", "throws", "IOException", "{", "final", "AtomicInteger", "l", "=", "new", "AtomicInteger", "(", ")", ";", ...
Wrap records into a collection. Can process any MARC streams, not only separator streams. @param stream a chunk stream @param withCollection true if {@code collection} elements should be used, false if not @return the number of chunks in the stream @throws IOException if chunk reading fails
[ "Wrap", "records", "into", "a", "collection", ".", "Can", "process", "any", "MARC", "streams", "not", "only", "separator", "streams", "." ]
d8426fcfc686507cab59b3d8181b08f83718418c
https://github.com/xbib/marc/blob/d8426fcfc686507cab59b3d8181b08f83718418c/src/main/java/org/xbib/marc/Marc.java#L361-L404
train
threerings/narya
core/src/main/java/com/threerings/presents/client/Communicator.java
Communicator.gotAuthResponse
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
protected void gotAuthResponse (AuthResponse rsp) throws LogonException { AuthResponseData data = rsp.getData(); if (!data.code.equals(AuthResponseData.SUCCESS)) { throw new LogonException(data.code); } logonSucceeded(data); }
[ "protected", "void", "gotAuthResponse", "(", "AuthResponse", "rsp", ")", "throws", "LogonException", "{", "AuthResponseData", "data", "=", "rsp", ".", "getData", "(", ")", ";", "if", "(", "!", "data", ".", "code", ".", "equals", "(", "AuthResponseData", ".",...
Subclasses must call this method when they receive the authentication response.
[ "Subclasses", "must", "call", "this", "method", "when", "they", "receive", "the", "authentication", "response", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/Communicator.java#L100-L108
train
threerings/narya
core/src/main/java/com/threerings/admin/client/DSetEditor.java
DSetEditor.setAccessor
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
public void setAccessor (Accessor<E> accessor) { removeAll(); _accessor = accessor; _table = new ObjectEditorTable(_entryClass, _editableFields, _accessor.getInterp(_interp), _displayFields); add(new JScrollPane(_table), BorderLayout.CENTER); }
[ "public", "void", "setAccessor", "(", "Accessor", "<", "E", ">", "accessor", ")", "{", "removeAll", "(", ")", ";", "_accessor", "=", "accessor", ";", "_table", "=", "new", "ObjectEditorTable", "(", "_entryClass", ",", "_editableFields", ",", "_accessor", "."...
Sets the logic for how this editor interacts with its underlying data.
[ "Sets", "the", "logic", "for", "how", "this", "editor", "interacts", "with", "its", "underlying", "data", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/admin/client/DSetEditor.java#L147-L154
train
threerings/narya
core/src/main/java/com/threerings/admin/client/DSetEditor.java
DSetEditor.addEntry
protected void addEntry (E entry) { if (_entryFilter == null || _entryFilter.apply(entry)) { int index = _keys.insertSorted(getKey(entry)); _table.insertDatum(entry, index); } }
java
protected void addEntry (E entry) { if (_entryFilter == null || _entryFilter.apply(entry)) { int index = _keys.insertSorted(getKey(entry)); _table.insertDatum(entry, index); } }
[ "protected", "void", "addEntry", "(", "E", "entry", ")", "{", "if", "(", "_entryFilter", "==", "null", "||", "_entryFilter", ".", "apply", "(", "entry", ")", ")", "{", "int", "index", "=", "_keys", ".", "insertSorted", "(", "getKey", "(", "entry", ")",...
Handles the addition of an entry, assuming our filter allows it.
[ "Handles", "the", "addition", "of", "an", "entry", "assuming", "our", "filter", "allows", "it", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/admin/client/DSetEditor.java#L199-L205
train
threerings/narya
core/src/main/java/com/threerings/admin/client/DSetEditor.java
DSetEditor.removeKey
protected void removeKey (Comparable<?> key) { int index = _keys.indexOf(key); if (index != -1) { _keys.remove(index); _table.removeDatum(index); } }
java
protected void removeKey (Comparable<?> key) { int index = _keys.indexOf(key); if (index != -1) { _keys.remove(index); _table.removeDatum(index); } }
[ "protected", "void", "removeKey", "(", "Comparable", "<", "?", ">", "key", ")", "{", "int", "index", "=", "_keys", ".", "indexOf", "(", "key", ")", ";", "if", "(", "index", "!=", "-", "1", ")", "{", "_keys", ".", "remove", "(", "index", ")", ";",...
Takes care of removing a key from
[ "Takes", "care", "of", "removing", "a", "key", "from" ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/admin/client/DSetEditor.java#L210-L217
train
threerings/narya
core/src/main/java/com/threerings/admin/client/DSetEditor.java
DSetEditor.actionPerformed
public void actionPerformed (ActionEvent event) { CommandEvent ce = (CommandEvent)event; _accessor.updateEntry(_setName, (DSet.Entry)ce.getArgument()); }
java
public void actionPerformed (ActionEvent event) { CommandEvent ce = (CommandEvent)event; _accessor.updateEntry(_setName, (DSet.Entry)ce.getArgument()); }
[ "public", "void", "actionPerformed", "(", "ActionEvent", "event", ")", "{", "CommandEvent", "ce", "=", "(", "CommandEvent", ")", "event", ";", "_accessor", ".", "updateEntry", "(", "_setName", ",", "(", "DSet", ".", "Entry", ")", "ce", ".", "getArgument", ...
documentation inherited from interface ActionListener
[ "documentation", "inherited", "from", "interface", "ActionListener" ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/admin/client/DSetEditor.java#L220-L224
train
davidmoten/grumpy
grumpy-ogc/src/main/java/com/github/davidmoten/grumpy/wms/ImageCache.java
ImageCache.clear
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 void clear(String layerName) { synchronized (this) { log.info("clearing cache for layer " + layerName); for (String key : cache.keySet()) { if (key.contains(layerName)) remove(key); } } }
[ "public", "void", "clear", "(", "String", "layerName", ")", "{", "synchronized", "(", "this", ")", "{", "log", ".", "info", "(", "\"clearing cache for layer \"", "+", "layerName", ")", ";", "for", "(", "String", "key", ":", "cache", ".", "keySet", "(", "...
TOOD improve this
[ "TOOD", "improve", "this" ]
f2d03e6b9771f15425fb3f76314837efc08c1233
https://github.com/davidmoten/grumpy/blob/f2d03e6b9771f15425fb3f76314837efc08c1233/grumpy-ogc/src/main/java/com/github/davidmoten/grumpy/wms/ImageCache.java#L70-L78
train
davidmoten/grumpy
grumpy-ogc/src/main/java/com/github/davidmoten/grumpy/wms/ImageCache.java
ImageCache.put
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.size() > maxSize) remove(keys.get(0)); if (maxSize > 0 && layers.containsAll(request.getLayers())) { cache.put(key, image); log.info("cached image with key=" + 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.size() > maxSize) remove(keys.get(0)); if (maxSize > 0 && layers.containsAll(request.getLayers())) { cache.put(key, image); log.info("cached image with key=" + key); } } }
[ "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 w...
Sets the cached image for the request. @param request the WMS http request @param image bytes of the image
[ "Sets", "the", "cached", "image", "for", "the", "request", "." ]
f2d03e6b9771f15425fb3f76314837efc08c1233
https://github.com/davidmoten/grumpy/blob/f2d03e6b9771f15425fb3f76314837efc08c1233/grumpy-ogc/src/main/java/com/github/davidmoten/grumpy/wms/ImageCache.java#L151-L165
train
threerings/narya
tools/src/main/java/com/threerings/presents/tools/GenUtil.java
GenUtil.cloneArgument
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)) { return "(" + name + " == null) ? null : " + "(" + simpleName(field) + ")" + name + ".clone()"; } else { return name; } }
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)) { return "(" + name + " == null) ? null : " + "(" + simpleName(field) + ")" + name + ".clone()"; } else { return name; } }
[ "public", "static", "String", "cloneArgument", "(", "Class", "<", "?", ">", "dsclazz", ",", "Field", "field", ",", "String", "name", ")", "{", "Class", "<", "?", ">", "clazz", "=", "field", ".", "getType", "(", ")", ";", "if", "(", "clazz", ".", "i...
Potentially clones the supplied argument if it is the type that needs such treatment.
[ "Potentially", "clones", "the", "supplied", "argument", "if", "it", "is", "the", "type", "that", "needs", "such", "treatment", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/tools/src/main/java/com/threerings/presents/tools/GenUtil.java#L189-L200
train
threerings/narya
tools/src/main/java/com/threerings/presents/tools/GenUtil.java
GenUtil.readClassName
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.readLine()) != null) { Matcher pm = PACKAGE_PATTERN.matcher(line); if (pm.find()) { pkgname = pm.group(1); } Matcher nm = NAME_PATTERN.matcher(line); if (nm.find()) { name = nm.group(2); break; } } bin.close(); // make sure we found something if (name == null) { throw new IOException("Unable to locate class or interface name in " + source + "."); } // prepend the package name to get a name we can Class.forName() if (pkgname != null) { name = pkgname + "." + name; } return name; }
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.readLine()) != null) { Matcher pm = PACKAGE_PATTERN.matcher(line); if (pm.find()) { pkgname = pm.group(1); } Matcher nm = NAME_PATTERN.matcher(line); if (nm.find()) { name = nm.group(2); break; } } bin.close(); // make sure we found something if (name == null) { throw new IOException("Unable to locate class or interface name in " + source + "."); } // prepend the package name to get a name we can Class.forName() if (pkgname != null) { name = pkgname + "." + name; } return name; }
[ "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...
Reads in the supplied source file and locates the package and class or interface name and returns a fully qualified class name.
[ "Reads", "in", "the", "supplied", "source", "file", "and", "locates", "the", "package", "and", "class", "or", "interface", "name", "and", "returns", "a", "fully", "qualified", "class", "name", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/tools/src/main/java/com/threerings/presents/tools/GenUtil.java#L206-L237
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java
ChatChannelManager.bodyRemovedFromChannel
@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) { info.participants.remove(bodyId); } else if (_channelMan._resolving.containsKey(_channel)) { log.warning("Oh for fuck's sake, distributed systems are complicated", "channel", _channel); } } }); }
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) { info.participants.remove(bodyId); } else if (_channelMan._resolving.containsKey(_channel)) { log.warning("Oh for fuck's sake, distributed systems are complicated", "channel", _channel); } } }); }
[ "@", "AnyThread", "public", "void", "bodyRemovedFromChannel", "(", "ChatChannel", "channel", ",", "final", "int", "bodyId", ")", "{", "_peerMan", ".", "invokeNodeAction", "(", "new", "ChannelAction", "(", "channel", ")", "{", "@", "Override", "protected", "void"...
When a body loses channel membership, this method should be called so that any server that happens to be hosting that channel can be told that the body in question is now a participant.
[ "When", "a", "body", "loses", "channel", "membership", "this", "method", "should", "be", "called", "so", "that", "any", "server", "that", "happens", "to", "be", "hosting", "that", "channel", "can", "be", "told", "that", "the", "body", "in", "question", "is...
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java#L114-L128
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java
ChatChannelManager.collectChatHistory
@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 protected void execute (InvocationService.ResultListener listener) { // find all the UserMessages for the given user and send them back listener.requestProcessed(Lists.newArrayList(Iterables.filter( _chatHistory.get(user), IS_USER_MESSAGE))); } @Inject protected transient ChatHistory _chatHistory; }, new NodeRequestsListener<List<ChatHistory.Entry>>() { public void requestsProcessed (NodeRequestsResult<List<ChatHistory.Entry>> rRes) { ChatHistoryResult chRes = new ChatHistoryResult(); chRes.failedNodes = rRes.getNodeErrors().keySet(); chRes.history = Lists.newArrayList( Iterables.concat(rRes.getNodeResults().values())); Collections.sort(chRes.history, SORT_BY_TIMESTAMP); lner.requestCompleted(chRes); } public void requestFailed (String cause) { lner.requestFailed(new InvocationException(cause)); } }); }
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 protected void execute (InvocationService.ResultListener listener) { // find all the UserMessages for the given user and send them back listener.requestProcessed(Lists.newArrayList(Iterables.filter( _chatHistory.get(user), IS_USER_MESSAGE))); } @Inject protected transient ChatHistory _chatHistory; }, new NodeRequestsListener<List<ChatHistory.Entry>>() { public void requestsProcessed (NodeRequestsResult<List<ChatHistory.Entry>> rRes) { ChatHistoryResult chRes = new ChatHistoryResult(); chRes.failedNodes = rRes.getNodeErrors().keySet(); chRes.history = Lists.newArrayList( Iterables.concat(rRes.getNodeResults().values())); Collections.sort(chRes.history, SORT_BY_TIMESTAMP); lner.requestCompleted(chRes); } public void requestFailed (String cause) { lner.requestFailed(new InvocationException(cause)); } }); }
[ "@", "AnyThread", "public", "void", "collectChatHistory", "(", "final", "Name", "user", ",", "final", "ResultListener", "<", "ChatHistoryResult", ">", "lner", ")", "{", "_peerMan", ".", "invokeNodeRequest", "(", "new", "NodeRequest", "(", ")", "{", "public", "...
Collects all chat messages heard by the given user on all peers.
[ "Collects", "all", "chat", "messages", "heard", "by", "the", "given", "user", "on", "all", "peers", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java#L133-L159
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java
ChatChannelManager.speak
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 if (_channels.containsKey(channel)) { dispatchSpeak(channel, umsg); return; } // if we're resolving this channel, queue up our message for momentary deliver List<UserMessage> msgs = _resolving.get(channel); if (msgs != null) { msgs.add(umsg); return; } // forward the speak request to the server that hosts the channel in question _peerMan.invokeNodeAction(new ChannelAction(channel) { @Override protected void execute () { _channelMan.dispatchSpeak(_channel, umsg); } }, new Runnable() { public void run () { _resolving.put(channel, Lists.newArrayList(umsg)); resolveAndDispatch(channel); } }); }
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 if (_channels.containsKey(channel)) { dispatchSpeak(channel, umsg); return; } // if we're resolving this channel, queue up our message for momentary deliver List<UserMessage> msgs = _resolving.get(channel); if (msgs != null) { msgs.add(umsg); return; } // forward the speak request to the server that hosts the channel in question _peerMan.invokeNodeAction(new ChannelAction(channel) { @Override protected void execute () { _channelMan.dispatchSpeak(_channel, umsg); } }, new Runnable() { public void run () { _resolving.put(channel, Lists.newArrayList(umsg)); resolveAndDispatch(channel); } }); }
[ "public", "void", "speak", "(", "ClientObject", "caller", ",", "final", "ChatChannel", "channel", ",", "String", "message", ",", "byte", "mode", ")", "{", "BodyObject", "body", "=", "_locator", ".", "forClient", "(", "caller", ")", ";", "final", "UserMessage...
from interface ChannelSpeakProvider
[ "from", "interface", "ChannelSpeakProvider" ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java#L162-L191
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java
ChatChannelManager.resolveAndDispatch
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.getNodeObject()).addToHostedChannels(channel); finishResolveAndDispatch(channel); } public void fail (String peerName) { final List<UserMessage> msgs = _resolving.remove(channel); if (peerName == null) { log.warning("Failed to resolve chat channel due to lock failure", "channel", channel); } else { // some other peer resolved this channel first, so forward any queued messages // directly to that node _peerMan.invokeNodeAction(peerName, new ChannelAction(channel) { @Override protected void execute () { for (final UserMessage msg : msgs) { _channelMan.dispatchSpeak(_channel, msg); } } }); } } }); }
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.getNodeObject()).addToHostedChannels(channel); finishResolveAndDispatch(channel); } public void fail (String peerName) { final List<UserMessage> msgs = _resolving.remove(channel); if (peerName == null) { log.warning("Failed to resolve chat channel due to lock failure", "channel", channel); } else { // some other peer resolved this channel first, so forward any queued messages // directly to that node _peerMan.invokeNodeAction(peerName, new ChannelAction(channel) { @Override protected void execute () { for (final UserMessage msg : msgs) { _channelMan.dispatchSpeak(_channel, msg); } } }); } } }); }
[ "protected", "void", "resolveAndDispatch", "(", "final", "ChatChannel", "channel", ")", "{", "NodeObject", ".", "Lock", "lock", "=", "new", "NodeObject", ".", "Lock", "(", "\"ChatChannel\"", ",", "channel", ".", "getLockName", "(", ")", ")", ";", "_peerMan", ...
Resolves the channel specified in the supplied action and then dispatches it.
[ "Resolves", "the", "channel", "specified", "in", "the", "supplied", "action", "and", "then", "dispatches", "it", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java#L211-L237
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java
ChatChannelManager.resolutionComplete
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 pending messages now that we know where they go for (UserMessage msg : _resolving.remove(channel)) { dispatchSpeak(channel, msg); } }
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 pending messages now that we know where they go for (UserMessage msg : _resolving.remove(channel)) { dispatchSpeak(channel, msg); } }
[ "protected", "void", "resolutionComplete", "(", "ChatChannel", "channel", ",", "Set", "<", "Integer", ">", "parts", ")", "{", "// map the participants of our now resolved channel", "ChannelInfo", "info", "=", "new", "ChannelInfo", "(", ")", ";", "info", ".", "channe...
This should be called when a channel's participant set has been resolved.
[ "This", "should", "be", "called", "when", "a", "channel", "s", "participant", "set", "has", "been", "resolved", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java#L253-L265
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java
ChatChannelManager.resolutionFailed
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 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); }
[ "protected", "void", "resolutionFailed", "(", "ChatChannel", "channel", ",", "Exception", "cause", ")", "{", "log", ".", "warning", "(", "\"Failed to resolve chat channel\"", ",", "\"channel\"", ",", "channel", ",", "cause", ")", ";", "// alas, we just drop all pendin...
This should be called if channel resolution fails.
[ "This", "should", "be", "called", "if", "channel", "resolution", "fails", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java#L270-L276
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java
ChatChannelManager.dispatchSpeak
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", channel, "msg", message); return; } // validate the speaker if (!info.participants.contains(getBodyId(message.speaker))) { log.warning("Dropping channel chat message from non-speaker", "channel", channel, "message", message); return; } // note that we're dispatching a message on this channel info.lastMessage = System.currentTimeMillis(); // generate a mapping from node name to an array of body ids for the participants that are // currently on the node in question final Map<String,int[]> partMap = Maps.newHashMap(); for (NodeObject nodeobj : _peerMan.getNodeObjects()) { ArrayIntSet nodeBodyIds = new ArrayIntSet(); for (ClientInfo clinfo : nodeobj.clients) { int bodyId = getBodyId(((CrowdClientInfo)clinfo).visibleName); if (info.participants.contains(bodyId)) { nodeBodyIds.add(bodyId); } } partMap.put(nodeobj.nodeName, nodeBodyIds.toIntArray()); } for (Map.Entry<String,int[]> entry : partMap.entrySet()) { final int[] bodyIds = entry.getValue(); _peerMan.invokeNodeAction(entry.getKey(), new ChannelAction(channel) { @Override protected void execute () { _channelMan.deliverSpeak(_channel, message, bodyIds); } }); } }
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", channel, "msg", message); return; } // validate the speaker if (!info.participants.contains(getBodyId(message.speaker))) { log.warning("Dropping channel chat message from non-speaker", "channel", channel, "message", message); return; } // note that we're dispatching a message on this channel info.lastMessage = System.currentTimeMillis(); // generate a mapping from node name to an array of body ids for the participants that are // currently on the node in question final Map<String,int[]> partMap = Maps.newHashMap(); for (NodeObject nodeobj : _peerMan.getNodeObjects()) { ArrayIntSet nodeBodyIds = new ArrayIntSet(); for (ClientInfo clinfo : nodeobj.clients) { int bodyId = getBodyId(((CrowdClientInfo)clinfo).visibleName); if (info.participants.contains(bodyId)) { nodeBodyIds.add(bodyId); } } partMap.put(nodeobj.nodeName, nodeBodyIds.toIntArray()); } for (Map.Entry<String,int[]> entry : partMap.entrySet()) { final int[] bodyIds = entry.getValue(); _peerMan.invokeNodeAction(entry.getKey(), new ChannelAction(channel) { @Override protected void execute () { _channelMan.deliverSpeak(_channel, message, bodyIds); } }); } }
[ "protected", "void", "dispatchSpeak", "(", "ChatChannel", "channel", ",", "final", "UserMessage", "message", ")", "{", "final", "ChannelInfo", "info", "=", "_channels", ".", "get", "(", "channel", ")", ";", "if", "(", "info", "==", "null", ")", "{", "// TO...
Requests that we dispatch the supplied message to all participants of the specified chat channel. The speaker will be validated prior to dispatching the message as the originating server does not have the information it needs to validate the speaker and must leave that to us, the channel hosting server.
[ "Requests", "that", "we", "dispatch", "the", "supplied", "message", "to", "all", "participants", "of", "the", "specified", "chat", "channel", ".", "The", "speaker", "will", "be", "validated", "prior", "to", "dispatching", "the", "message", "as", "the", "origin...
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java#L284-L326
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java
ChatChannelManager.deliverSpeak
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)) { _chatHistory.record(channel, bobj.getChatIdentifier(message), message, bobj.getVisibleName()); bobj.postMessage(ChatCodes.CHAT_CHANNEL_NOTIFICATION, channel, message); } } }
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)) { _chatHistory.record(channel, bobj.getChatIdentifier(message), message, bobj.getVisibleName()); bobj.postMessage(ChatCodes.CHAT_CHANNEL_NOTIFICATION, channel, message); } } }
[ "protected", "void", "deliverSpeak", "(", "ChatChannel", "channel", ",", "UserMessage", "message", ",", "int", "[", "]", "bodyIds", ")", "{", "channel", "=", "intern", "(", "channel", ")", ";", "for", "(", "int", "bodyId", ":", "bodyIds", ")", "{", "Body...
Delivers the supplied chat channel message to the specified bodies.
[ "Delivers", "the", "supplied", "chat", "channel", "message", "to", "the", "specified", "bodies", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java#L331-L341
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java
ChatChannelManager.closeIdleChannels
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.getValue().lastMessage > IDLE_CHANNEL_CLOSE_TIME) { ((CrowdNodeObject)_peerMan.getNodeObject()).removeFromHostedChannels( entry.getKey()); iter.remove(); } } }
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.getValue().lastMessage > IDLE_CHANNEL_CLOSE_TIME) { ((CrowdNodeObject)_peerMan.getNodeObject()).removeFromHostedChannels( entry.getKey()); iter.remove(); } } }
[ "protected", "void", "closeIdleChannels", "(", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "Iterator", "<", "Map", ".", "Entry", "<", "ChatChannel", ",", "ChannelInfo", ">", ">", "iter", "=", "_channels", ".", "entrySet...
Called periodically to check for and close any channels that have been idle too long.
[ "Called", "periodically", "to", "check", "for", "and", "close", "any", "channels", "that", "have", "been", "idle", "too", "long", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java#L346-L358
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java
ChatChannelManager.intern
protected ChatChannel intern (ChatChannel channel) { ChannelInfo chinfo = _channels.get(channel); if (chinfo != null) { return chinfo.channel; } return channel; }
java
protected ChatChannel intern (ChatChannel channel) { ChannelInfo chinfo = _channels.get(channel); if (chinfo != null) { return chinfo.channel; } return channel; }
[ "protected", "ChatChannel", "intern", "(", "ChatChannel", "channel", ")", "{", "ChannelInfo", "chinfo", "=", "_channels", ".", "get", "(", "channel", ")", ";", "if", "(", "chinfo", "!=", "null", ")", "{", "return", "chinfo", ".", "channel", ";", "}", "re...
Returns a widely referenced instance equivalent to the given channel, if one is available. This reduces memory usage since clients send new channel instances with each message.
[ "Returns", "a", "widely", "referenced", "instance", "equivalent", "to", "the", "given", "channel", "if", "one", "is", "available", ".", "This", "reduces", "memory", "usage", "since", "clients", "send", "new", "channel", "instances", "with", "each", "message", ...
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java#L374-L381
train
threerings/narya
core/src/main/java/com/threerings/util/StreamableEnumSet.java
StreamableEnumSet.noneOf
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> noneOf (Class<E> elementType) { return new StreamableEnumSet<E>(elementType); }
[ "public", "static", "<", "E", "extends", "Enum", "<", "E", ">", ">", "StreamableEnumSet", "<", "E", ">", "noneOf", "(", "Class", "<", "E", ">", "elementType", ")", "{", "return", "new", "StreamableEnumSet", "<", "E", ">", "(", "elementType", ")", ";", ...
Creates an empty set of the specified type.
[ "Creates", "an", "empty", "set", "of", "the", "specified", "type", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/util/StreamableEnumSet.java#L50-L53
train
threerings/narya
core/src/main/java/com/threerings/util/StreamableEnumSet.java
StreamableEnumSet.allOf
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> allOf (Class<E> elementType) { StreamableEnumSet<E> set = new StreamableEnumSet<E>(elementType); for (E constant : elementType.getEnumConstants()) { set.add(constant); } return set; }
[ "public", "static", "<", "E", "extends", "Enum", "<", "E", ">", ">", "StreamableEnumSet", "<", "E", ">", "allOf", "(", "Class", "<", "E", ">", "elementType", ")", "{", "StreamableEnumSet", "<", "E", ">", "set", "=", "new", "StreamableEnumSet", "<", "E"...
Creates a set containing all elements of the specified type.
[ "Creates", "a", "set", "containing", "all", "elements", "of", "the", "specified", "type", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/util/StreamableEnumSet.java#L58-L65
train
threerings/narya
core/src/main/java/com/threerings/util/StreamableEnumSet.java
StreamableEnumSet.copyOf
public static <E extends Enum<E>> StreamableEnumSet<E> copyOf (StreamableEnumSet<E> s) { return s.clone(); }
java
public static <E extends Enum<E>> StreamableEnumSet<E> copyOf (StreamableEnumSet<E> s) { return s.clone(); }
[ "public", "static", "<", "E", "extends", "Enum", "<", "E", ">", ">", "StreamableEnumSet", "<", "E", ">", "copyOf", "(", "StreamableEnumSet", "<", "E", ">", "s", ")", "{", "return", "s", ".", "clone", "(", ")", ";", "}" ]
Creates a set containing all elements in the set provided.
[ "Creates", "a", "set", "containing", "all", "elements", "in", "the", "set", "provided", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/util/StreamableEnumSet.java#L89-L92
train
threerings/narya
core/src/main/java/com/threerings/util/StreamableEnumSet.java
StreamableEnumSet.of
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 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; }
[ "public", "static", "<", "E", "extends", "Enum", "<", "E", ">", ">", "StreamableEnumSet", "<", "E", ">", "of", "(", "E", "first", ",", "E", "...", "rest", ")", "{", "StreamableEnumSet", "<", "E", ">", "set", "=", "new", "StreamableEnumSet", "<", "E",...
Creates a set consisting of the specified elements.
[ "Creates", "a", "set", "consisting", "of", "the", "specified", "elements", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/util/StreamableEnumSet.java#L112-L120
train
threerings/narya
core/src/main/java/com/threerings/presents/dobj/OidList.java
OidList.add
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(); } // add the oid _oids[_size++] = oid; return true; }
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(); } // add the oid _oids[_size++] = oid; return true; }
[ "public", "boolean", "add", "(", "int", "oid", ")", "{", "// check for existence", "for", "(", "int", "ii", "=", "0", ";", "ii", "<", "_size", ";", "ii", "++", ")", "{", "if", "(", "_oids", "[", "ii", "]", "==", "oid", ")", "{", "return", "false"...
Adds the specified object id to the list if it is not already there. @return true if the object was added, false if it was already in the list.
[ "Adds", "the", "specified", "object", "id", "to", "the", "list", "if", "it", "is", "not", "already", "there", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/dobj/OidList.java#L78-L95
train
threerings/narya
core/src/main/java/com/threerings/presents/dobj/OidList.java
OidList.remove
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; } } return false; }
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; } } return false; }
[ "public", "boolean", "remove", "(", "int", "oid", ")", "{", "// scan for the oid in question", "for", "(", "int", "ii", "=", "0", ";", "ii", "<", "_size", ";", "ii", "++", ")", "{", "if", "(", "_oids", "[", "ii", "]", "==", "oid", ")", "{", "// shi...
Removes the specified oid from the list. @return true if the oid was in the list and was removed, false otherwise.
[ "Removes", "the", "specified", "oid", "from", "the", "list", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/dobj/OidList.java#L103-L115
train
threerings/narya
core/src/main/java/com/threerings/presents/dobj/OidList.java
OidList.contains
public boolean contains (int oid) { for (int ii = 0; ii < _size; ii++) { if (_oids[ii] == oid) { return true; } } return false; }
java
public boolean contains (int oid) { for (int ii = 0; ii < _size; ii++) { if (_oids[ii] == oid) { return true; } } return false; }
[ "public", "boolean", "contains", "(", "int", "oid", ")", "{", "for", "(", "int", "ii", "=", "0", ";", "ii", "<", "_size", ";", "ii", "++", ")", "{", "if", "(", "_oids", "[", "ii", "]", "==", "oid", ")", "{", "return", "true", ";", "}", "}", ...
Returns true if the specified oid is in the list, false if not.
[ "Returns", "true", "if", "the", "specified", "oid", "is", "in", "the", "list", "false", "if", "not", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/dobj/OidList.java#L120-L129
train
threerings/narya
core/src/main/java/com/threerings/admin/data/ConfigObject.java
ConfigObject.getEditor
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 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); } }
[ "public", "JPanel", "getEditor", "(", "PresentsContext", "ctx", ",", "Field", "field", ")", "{", "if", "(", "field", ".", "getType", "(", ")", ".", "equals", "(", "Boolean", ".", "TYPE", ")", ")", "{", "return", "new", "BooleanFieldEditor", "(", "ctx", ...
Returns the editor panel for the specified field.
[ "Returns", "the", "editor", "panel", "for", "the", "specified", "field", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/admin/data/ConfigObject.java#L42-L49
train
threerings/narya
core/src/main/java/com/threerings/admin/data/AdminMarshaller.java
AdminMarshaller.getConfigInfo
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 getConfigInfo (AdminService.ConfigInfoListener arg1) { AdminMarshaller.ConfigInfoMarshaller listener1 = new AdminMarshaller.ConfigInfoMarshaller(); listener1.listener = arg1; sendRequest(GET_CONFIG_INFO, new Object[] { listener1 }); }
[ "public", "void", "getConfigInfo", "(", "AdminService", ".", "ConfigInfoListener", "arg1", ")", "{", "AdminMarshaller", ".", "ConfigInfoMarshaller", "listener1", "=", "new", "AdminMarshaller", ".", "ConfigInfoMarshaller", "(", ")", ";", "listener1", ".", "listener", ...
from interface AdminService
[ "from", "interface", "AdminService" ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/admin/data/AdminMarshaller.java#L79-L86
train
threerings/narya
core/src/main/java/com/threerings/presents/server/InvocationDispatcher.java
InvocationDispatcher.dispatchRequest
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 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); }
[ "public", "void", "dispatchRequest", "(", "ClientObject", "source", ",", "int", "methodId", ",", "Object", "[", "]", "args", ")", "throws", "InvocationException", "{", "log", ".", "warning", "(", "\"Requested to dispatch unknown method\"", ",", "\"provider\"", ",", ...
Dispatches the specified method to our provider.
[ "Dispatches", "the", "specified", "method", "to", "our", "provider", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/InvocationDispatcher.java#L52-L57
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/data/SpeakMarshaller.java
SpeakMarshaller.speak
public void speak (String arg1, byte arg2) { sendRequest(SPEAK, new Object[] { arg1, Byte.valueOf(arg2) }); }
java
public void speak (String arg1, byte arg2) { sendRequest(SPEAK, new Object[] { arg1, Byte.valueOf(arg2) }); }
[ "public", "void", "speak", "(", "String", "arg1", ",", "byte", "arg2", ")", "{", "sendRequest", "(", "SPEAK", ",", "new", "Object", "[", "]", "{", "arg1", ",", "Byte", ".", "valueOf", "(", "arg2", ")", "}", ")", ";", "}" ]
from interface SpeakService
[ "from", "interface", "SpeakService" ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/data/SpeakMarshaller.java#L47-L52
train
threerings/narya
core/src/main/java/com/threerings/util/Name.java
Name.isBlank
public static boolean isBlank (Name name) { return (name == null || name.toString().equals(BLANK.toString())); }
java
public static boolean isBlank (Name name) { return (name == null || name.toString().equals(BLANK.toString())); }
[ "public", "static", "boolean", "isBlank", "(", "Name", "name", ")", "{", "return", "(", "name", "==", "null", "||", "name", ".", "toString", "(", ")", ".", "equals", "(", "BLANK", ".", "toString", "(", ")", ")", ")", ";", "}" ]
Returns true if this name is null or blank, false if it contains useful data. This works on derived classes as well.
[ "Returns", "true", "if", "this", "name", "is", "null", "or", "blank", "false", "if", "it", "contains", "useful", "data", ".", "This", "works", "on", "derived", "classes", "as", "well", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/util/Name.java#L45-L48
train
threerings/narya
core/src/main/java/com/threerings/util/Name.java
Name.getNormal
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; } } return _normal; }
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; } } return _normal; }
[ "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", ...
Returns the normalized version of this name.
[ "Returns", "the", "normalized", "version", "of", "this", "name", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/util/Name.java#L61-L72
train
threerings/narya
core/src/main/java/com/threerings/presents/server/RebootManager.java
RebootManager.scheduleRegularReboot
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 curHour = cal.get(Calendar.HOUR_OF_DAY); cal = cal.zeroTime().addHours(hour).addDays((curHour < hour) ? (freq - 1) : freq); // maybe avoid weekends if (getSkipWeekends()) { switch (cal.get(Calendar.DAY_OF_WEEK)) { case Calendar.SATURDAY: cal.addDays(2); break; case Calendar.SUNDAY: cal.addDays(1); break; } } scheduleReboot(cal.toTime(), true, AUTOMATIC_INITIATOR); // schedule exactly return true; }
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 curHour = cal.get(Calendar.HOUR_OF_DAY); cal = cal.zeroTime().addHours(hour).addDays((curHour < hour) ? (freq - 1) : freq); // maybe avoid weekends if (getSkipWeekends()) { switch (cal.get(Calendar.DAY_OF_WEEK)) { case Calendar.SATURDAY: cal.addDays(2); break; case Calendar.SUNDAY: cal.addDays(1); break; } } scheduleReboot(cal.toTime(), true, AUTOMATIC_INITIATOR); // schedule exactly return true; }
[ "public", "boolean", "scheduleRegularReboot", "(", ")", "{", "// maybe schedule an automatic reboot based on our configuration", "int", "freq", "=", "getDayFrequency", "(", ")", ";", "int", "hour", "=", "getRebootHour", "(", ")", ";", "if", "(", "freq", "<=", "0", ...
Schedules our next regularly scheduled reboot. @return true if a reboot was scheduled, false if regularly scheduled reboots are disabled.
[ "Schedules", "our", "next", "regularly", "scheduled", "reboot", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/RebootManager.java#L78-L106
train
threerings/narya
core/src/main/java/com/threerings/presents/server/RebootManager.java
RebootManager.cancelReboot
public void cancelReboot () { if (_interval != null) { _interval.cancel(); _interval = null; } _nextReboot = 0L; _rebootSoon = false; _initiator = null; }
java
public void cancelReboot () { if (_interval != null) { _interval.cancel(); _interval = null; } _nextReboot = 0L; _rebootSoon = false; _initiator = null; }
[ "public", "void", "cancelReboot", "(", ")", "{", "if", "(", "_interval", "!=", "null", ")", "{", "_interval", ".", "cancel", "(", ")", ";", "_interval", "=", "null", ";", "}", "_nextReboot", "=", "0L", ";", "_rebootSoon", "=", "false", ";", "_initiator...
Cancel the currently scheduled reboot, if any.
[ "Cancel", "the", "currently", "scheduled", "reboot", "if", "any", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/RebootManager.java#L127-L136
train
threerings/narya
core/src/main/java/com/threerings/presents/server/RebootManager.java
RebootManager.preventReboot
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
public int preventReboot (String whereFrom) { if (whereFrom == null) { throw new IllegalArgumentException("whereFrom must be descriptive."); } int lockId = _nextRebootLockId++; _rebootLocks.put(lockId, whereFrom); return lockId; }
[ "public", "int", "preventReboot", "(", "String", "whereFrom", ")", "{", "if", "(", "whereFrom", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"whereFrom must be descriptive.\"", ")", ";", "}", "int", "lockId", "=", "_nextRebootLockId",...
Called by an entity that would like to prevent a reboot.
[ "Called", "by", "an", "entity", "that", "would", "like", "to", "prevent", "a", "reboot", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/RebootManager.java#L149-L157
train
threerings/narya
core/src/main/java/com/threerings/presents/server/RebootManager.java
RebootManager.scheduleReboot
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 delay = rebootTime - now; int[] warnings = getWarnings(); int level = -1; // assume we're not yet warning for (int ii = warnings.length - 1; ii >= 0; ii--) { long warnTime = warnings[ii] * (60L * 1000L); if (delay <= warnTime) { level = ii; if (!exact) { rebootTime = now + warnTime; } break; } } // note our new reboot time and its initiator _nextReboot = rebootTime; _initiator = initiator; doWarning(level, (int)((rebootTime - now) / (60L * 1000L))); }
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 delay = rebootTime - now; int[] warnings = getWarnings(); int level = -1; // assume we're not yet warning for (int ii = warnings.length - 1; ii >= 0; ii--) { long warnTime = warnings[ii] * (60L * 1000L); if (delay <= warnTime) { level = ii; if (!exact) { rebootTime = now + warnTime; } break; } } // note our new reboot time and its initiator _nextReboot = rebootTime; _initiator = initiator; doWarning(level, (int)((rebootTime - now) / (60L * 1000L))); }
[ "protected", "void", "scheduleReboot", "(", "long", "rebootTime", ",", "boolean", "exact", ",", "String", "initiator", ")", "{", "// if there's already a reboot scheduled, cancel it", "cancelReboot", "(", ")", ";", "long", "now", "=", "System", ".", "currentTimeMillis...
Schedule a reboot. @param exact if false we round up to the next highest warning time.
[ "Schedule", "a", "reboot", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/RebootManager.java#L193-L219
train
threerings/narya
core/src/main/java/com/threerings/presents/server/RebootManager.java
RebootManager.getRebootMessage
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 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); }
[ "protected", "String", "getRebootMessage", "(", "String", "key", ",", "int", "minutes", ")", "{", "String", "msg", "=", "getCustomRebootMessage", "(", ")", ";", "if", "(", "StringUtil", ".", "isBlank", "(", "msg", ")", ")", "{", "msg", "=", "\"m.reboot_msg...
Composes the given reboot message with the minutes and either the custom or standard details about the pending reboot.
[ "Composes", "the", "given", "reboot", "message", "with", "the", "minutes", "and", "either", "the", "custom", "or", "standard", "details", "about", "the", "pending", "reboot", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/RebootManager.java#L256-L264
train
threerings/narya
core/src/main/java/com/threerings/presents/server/RebootManager.java
RebootManager.doWarning
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 automatic server reboot/shutdown, as scheduled by: " + _initiator); broadcast("m.rebooting_now"); // wait 1 second, then do it new Interval(Interval.RUN_DIRECT) { @Override public void expired () { _server.queueShutdown(); // this posts a LongRunnable } }.schedule(1000); return; } // issue the warning if (_rebootSoon) { notifyObservers(level); broadcast(getRebootMessage("m.reboot_warning", minutes)); } // schedule the next warning final int nextLevel = level + 1; final int nextMinutes = (nextLevel == warnings.length) ? 0 : warnings[nextLevel]; _interval = _omgr.newInterval(new Runnable() { public void run () { doWarning(nextLevel, nextMinutes); } }); _interval.schedule( Math.max(0L, _nextReboot - (nextMinutes * 60L * 1000L) - System.currentTimeMillis())); }
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 automatic server reboot/shutdown, as scheduled by: " + _initiator); broadcast("m.rebooting_now"); // wait 1 second, then do it new Interval(Interval.RUN_DIRECT) { @Override public void expired () { _server.queueShutdown(); // this posts a LongRunnable } }.schedule(1000); return; } // issue the warning if (_rebootSoon) { notifyObservers(level); broadcast(getRebootMessage("m.reboot_warning", minutes)); } // schedule the next warning final int nextLevel = level + 1; final int nextMinutes = (nextLevel == warnings.length) ? 0 : warnings[nextLevel]; _interval = _omgr.newInterval(new Runnable() { public void run () { doWarning(nextLevel, nextMinutes); } }); _interval.schedule( Math.max(0L, _nextReboot - (nextMinutes * 60L * 1000L) - System.currentTimeMillis())); }
[ "protected", "void", "doWarning", "(", "int", "level", ",", "int", "minutes", ")", "{", "_rebootSoon", "=", "(", "level", ">", "-", "1", ")", ";", "int", "[", "]", "warnings", "=", "getWarnings", "(", ")", ";", "if", "(", "level", "==", "warnings", ...
Do a warning, schedule the next.
[ "Do", "a", "warning", "schedule", "the", "next", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/RebootManager.java#L269-L308
train
threerings/narya
core/src/main/java/com/threerings/presents/server/RebootManager.java
RebootManager.checkLocks
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() { public void run () { doWarning(getWarnings().length, 0); } })).schedule(60 * 1000); return true; }
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() { public void run () { doWarning(getWarnings().length, 0); } })).schedule(60 * 1000); return true; }
[ "protected", "boolean", "checkLocks", "(", ")", "{", "if", "(", "_rebootLocks", ".", "isEmpty", "(", ")", ")", "{", "return", "false", ";", "}", "log", ".", "info", "(", "\"Reboot delayed due to outstanding locks\"", ",", "\"locks\"", ",", "_rebootLocks", ".",...
Check to see if there are outstanding reboot locks that may delay the reboot, returning false if there are none.
[ "Check", "to", "see", "if", "there", "are", "outstanding", "reboot", "locks", "that", "may", "delay", "the", "reboot", "returning", "false", "if", "there", "are", "none", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/RebootManager.java#L314-L328
train
threerings/narya
core/src/main/java/com/threerings/presents/server/RebootManager.java
RebootManager.notifyObservers
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 (PendingShutdownObserver observer) { observer.shutdownPlanned(warningsLeft, msLeft); return true; } }); }
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 (PendingShutdownObserver observer) { observer.shutdownPlanned(warningsLeft, msLeft); return true; } }); }
[ "protected", "void", "notifyObservers", "(", "int", "level", ")", "{", "final", "int", "warningsLeft", "=", "getWarnings", "(", ")", ".", "length", "-", "level", "-", "1", ";", "final", "long", "msLeft", "=", "_nextReboot", "-", "System", ".", "currentTime...
Notify all PendingShutdownObservers of the pending shutdown!
[ "Notify", "all", "PendingShutdownObservers", "of", "the", "pending", "shutdown!" ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/RebootManager.java#L333-L343
train
threerings/narya
core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java
ClientDObjectMgr.registerFlushDelay
public void registerFlushDelay (Class<?> objclass, long delay) { _delays.put(objclass, Long.valueOf(delay)); }
java
public void registerFlushDelay (Class<?> objclass, long delay) { _delays.put(objclass, Long.valueOf(delay)); }
[ "public", "void", "registerFlushDelay", "(", "Class", "<", "?", ">", "objclass", ",", "long", "delay", ")", "{", "_delays", ".", "put", "(", "objclass", ",", "Long", ".", "valueOf", "(", "delay", ")", ")", ";", "}" ]
Registers an object flush delay. @see Client#registerFlushDelay
[ "Registers", "an", "object", "flush", "delay", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java#L159-L162
train
threerings/narya
core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java
ClientDObjectMgr.processMessage
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 message as RunQueue is shutdown", "msg", msg); } }
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 message as RunQueue is shutdown", "msg", msg); } }
[ "public", "void", "processMessage", "(", "Message", "msg", ")", "{", "if", "(", "_client", ".", "getRunQueue", "(", ")", ".", "isRunning", "(", ")", ")", "{", "// append it to our queue", "_actions", ".", "append", "(", "msg", ")", ";", "// and queue ourselv...
Called by the communicator when a message arrives from the network layer. We queue it up for processing and request some processing time on the main thread.
[ "Called", "by", "the", "communicator", "when", "a", "message", "arrives", "from", "the", "network", "layer", ".", "We", "queue", "it", "up", "for", "processing", "and", "request", "some", "processing", "time", "on", "the", "main", "thread", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java#L168-L178
train
threerings/narya
core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java
ClientDObjectMgr.cleanup
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")); } } _penders.clear(); _flusher.cancel(); _flushes.clear(); _dead.clear(); _client.getRunQueue().postRunnable(new Runnable() { public void run () { _ocache.clear(); } }); }
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")); } } _penders.clear(); _flusher.cancel(); _flushes.clear(); _dead.clear(); _client.getRunQueue().postRunnable(new Runnable() { public void run () { _ocache.clear(); } }); }
[ "public", "void", "cleanup", "(", ")", "{", "// tell any pending object subscribers that they're not getting their bits", "for", "(", "PendingRequest", "<", "?", ">", "req", ":", "_penders", ".", "values", "(", ")", ")", "{", "for", "(", "Subscriber", "<", "?", ...
Called when the client is cleaned up due to having disconnected from the server.
[ "Called", "when", "the", "client", "is", "cleaned", "up", "due", "to", "having", "disconnected", "from", "the", "server", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java#L241-L258
train
threerings/narya
core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java
ClientDObjectMgr.dispatchEvent
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.containsKey(remoteOid)) { log.warning("Unable to dispatch event on non-proxied object " + event + "."); } return; } // because we might be acting as a proxy for a remote server, we may need to fiddle with // this event before we dispatch it _client.convertFromRemote(target, event); // if this is a compound event, we need to process its contained events in order if (event instanceof CompoundEvent) { // notify our proxy subscribers in one fell swoop target.notifyProxies(event); // now break the event up and dispatch each event to listeners individually List<DEvent> events = ((CompoundEvent)event).getEvents(); int ecount = events.size(); for (int ii = 0; ii < ecount; ii++) { dispatchEvent(remoteOid, target, events.get(ii)); } } else { // forward to any proxies (or not if we're dispatching part of a compound event) target.notifyProxies(event); // and dispatch the event to regular listeners dispatchEvent(remoteOid, target, event); } }
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.containsKey(remoteOid)) { log.warning("Unable to dispatch event on non-proxied object " + event + "."); } return; } // because we might be acting as a proxy for a remote server, we may need to fiddle with // this event before we dispatch it _client.convertFromRemote(target, event); // if this is a compound event, we need to process its contained events in order if (event instanceof CompoundEvent) { // notify our proxy subscribers in one fell swoop target.notifyProxies(event); // now break the event up and dispatch each event to listeners individually List<DEvent> events = ((CompoundEvent)event).getEvents(); int ecount = events.size(); for (int ii = 0; ii < ecount; ii++) { dispatchEvent(remoteOid, target, events.get(ii)); } } else { // forward to any proxies (or not if we're dispatching part of a compound event) target.notifyProxies(event); // and dispatch the event to regular listeners dispatchEvent(remoteOid, target, event); } }
[ "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", "targ...
Called when a new event arrives from the server that should be dispatched to subscribers here on the client.
[ "Called", "when", "a", "new", "event", "arrives", "from", "the", "server", "that", "should", "be", "dispatched", "to", "subscribers", "here", "on", "the", "client", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java#L277-L314
train
threerings/narya
core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java
ClientDObjectMgr.dispatchEvent
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 instanceof ObjectDestroyedEvent) { // Log.info("Pitching destroyed object [oid=" + remoteOid + // ", class=" + StringUtil.shortClassName(target) + "]."); _ocache.remove(remoteOid); } // have the object pass this event on to its listeners if (notify) { target.notifyListeners(event); } } catch (Exception e) { log.warning("Failure processing event", "event", event, "target", target, e); } }
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 instanceof ObjectDestroyedEvent) { // Log.info("Pitching destroyed object [oid=" + remoteOid + // ", class=" + StringUtil.shortClassName(target) + "]."); _ocache.remove(remoteOid); } // have the object pass this event on to its listeners if (notify) { target.notifyListeners(event); } } catch (Exception e) { log.warning("Failure processing event", "event", event, "target", target, e); } }
[ "protected", "void", "dispatchEvent", "(", "int", "remoteOid", ",", "DObject", "target", ",", "DEvent", "event", ")", "{", "try", "{", "// apply the event to the object", "boolean", "notify", "=", "event", ".", "applyToObject", "(", "target", ")", ";", "// if th...
Dispatches an event on an already resolved target object. @param remoteOid is specified explicitly because we will have already translated the event's target oid into our local object managers oid space if we're acting on behalf of the peer manager.
[ "Dispatches", "an", "event", "on", "an", "already", "resolved", "target", "object", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java#L323-L344
train
threerings/narya
core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java
ClientDObjectMgr.registerObjectAndNotify
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); // let the penders know that the object is available PendingRequest<?> req = _penders.remove(obj.getOid()); if (req == null) { log.warning("Got object, but no one cares?!", "oid", obj.getOid(), "obj", obj); return; } for (int ii = 0; ii < req.targets.size(); ii++) { @SuppressWarnings("unchecked") Subscriber<T> target = (Subscriber<T>)req.targets.get(ii); // add them as a subscriber obj.addSubscriber(target); // and let them know that the object is in target.objectAvailable(obj); } }
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); // let the penders know that the object is available PendingRequest<?> req = _penders.remove(obj.getOid()); if (req == null) { log.warning("Got object, but no one cares?!", "oid", obj.getOid(), "obj", obj); return; } for (int ii = 0; ii < req.targets.size(); ii++) { @SuppressWarnings("unchecked") Subscriber<T> target = (Subscriber<T>)req.targets.get(ii); // add them as a subscriber obj.addSubscriber(target); // and let them know that the object is in target.objectAvailable(obj); } }
[ "protected", "<", "T", "extends", "DObject", ">", "void", "registerObjectAndNotify", "(", "ObjectResponse", "<", "T", ">", "orsp", ")", "{", "// let the object know that we'll be managing it", "T", "obj", "=", "orsp", ".", "getObject", "(", ")", ";", "obj", ".",...
Registers this object in our proxy cache and notifies the subscribers that were waiting for subscription to this object.
[ "Registers", "this", "object", "in", "our", "proxy", "cache", "and", "notifies", "the", "subscribers", "that", "were", "waiting", "for", "subscription", "to", "this", "object", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java#L350-L373
train
threerings/narya
core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java
ClientDObjectMgr.flushObject
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); // ship off an unsubscribe message to the server; we'll remove the object from our table // when we get the unsub ack _comm.postMessage(new UnsubscribeRequest(ooid)); }
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); // ship off an unsubscribe message to the server; we'll remove the object from our table // when we get the unsub ack _comm.postMessage(new UnsubscribeRequest(ooid)); }
[ "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", "(", ")", ";",...
Flushes a distributed object subscription, issuing an unsubscribe request to the server.
[ "Flushes", "a", "distributed", "object", "subscription", "issuing", "an", "unsubscribe", "request", "to", "the", "server", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java#L454-L465
train
threerings/narya
core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java
ClientDObjectMgr.flushObjects
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(); FlushRecord rec = entry.getValue(); if (rec.expire <= now) { iter.remove(); flushObject(rec.object); // Log.info("Flushed object " + oid + "."); } } }
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(); FlushRecord rec = entry.getValue(); if (rec.expire <= now) { iter.remove(); flushObject(rec.object); // Log.info("Flushed object " + oid + "."); } } }
[ "protected", "void", "flushObjects", "(", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "for", "(", "Iterator", "<", "IntMap", ".", "IntEntry", "<", "FlushRecord", ">", ">", "iter", "=", "_flushes", ".", "intEntrySet", ...
Called periodically to flush any objects that have been lingering due to a previously enacted flush delay.
[ "Called", "periodically", "to", "flush", "any", "objects", "that", "have", "been", "lingering", "due", "to", "a", "previously", "enacted", "flush", "delay", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/ClientDObjectMgr.java#L471-L485
train
threerings/narya
core/src/main/java/com/threerings/presents/util/SecureUtil.java
SecureUtil.getAESCipher
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 (GeneralSecurityException gse) { log.warning("Failed to create cipher", gse); } return null; }
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 (GeneralSecurityException gse) { log.warning("Failed to create cipher", gse); } return null; }
[ "public", "static", "Cipher", "getAESCipher", "(", "int", "mode", ",", "byte", "[", "]", "key", ")", "{", "try", "{", "Cipher", "cipher", "=", "Cipher", ".", "getInstance", "(", "\"AES/CBC/PKCS5Padding\"", ")", ";", "SecretKeySpec", "aesKey", "=", "new", "...
Creates our AES cipher.
[ "Creates", "our", "AES", "cipher", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/SecureUtil.java#L54-L65
train
threerings/narya
core/src/main/java/com/threerings/presents/util/SecureUtil.java
SecureUtil.getRSACipher
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); } return null; }
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); } return null; }
[ "public", "static", "Cipher", "getRSACipher", "(", "int", "mode", ",", "Key", "key", ")", "{", "try", "{", "Cipher", "cipher", "=", "Cipher", ".", "getInstance", "(", "\"RSA\"", ")", ";", "cipher", ".", "init", "(", "mode", ",", "key", ")", ";", "ret...
Creates our RSA cipher.
[ "Creates", "our", "RSA", "cipher", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/SecureUtil.java#L86-L96
train
threerings/narya
core/src/main/java/com/threerings/presents/util/SecureUtil.java
SecureUtil.genRSAKeyPair
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); } return null; }
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); } return null; }
[ "public", "static", "KeyPair", "genRSAKeyPair", "(", "int", "bits", ")", "{", "try", "{", "KeyPairGenerator", "kpg", "=", "KeyPairGenerator", ".", "getInstance", "(", "\"RSA\"", ")", ";", "kpg", ".", "initialize", "(", "bits", ")", ";", "return", "kpg", "....
Creates an RSA key pair.
[ "Creates", "an", "RSA", "key", "pair", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/SecureUtil.java#L101-L111
train
threerings/narya
core/src/main/java/com/threerings/presents/util/SecureUtil.java
SecureUtil.stringToRSAPublicKey
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, exp); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(keySpec); } catch (NumberFormatException nfe) { log.warning("Failed to read key from string.", "str", str, nfe); } catch (GeneralSecurityException gse) { log.warning("Failed to read key from string.", "str", str, gse); } return null; }
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, exp); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(keySpec); } catch (NumberFormatException nfe) { log.warning("Failed to read key from string.", "str", str, nfe); } catch (GeneralSecurityException gse) { log.warning("Failed to read key from string.", "str", str, gse); } return null; }
[ "public", "static", "PublicKey", "stringToRSAPublicKey", "(", "String", "str", ")", "{", "try", "{", "BigInteger", "mod", "=", "new", "BigInteger", "(", "str", ".", "substring", "(", "0", ",", "str", ".", "indexOf", "(", "SPLIT", ")", ")", ",", "16", "...
Creates a public key from the supplied string.
[ "Creates", "a", "public", "key", "from", "the", "supplied", "string", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/SecureUtil.java#L154-L168
train
threerings/narya
core/src/main/java/com/threerings/presents/util/SecureUtil.java
SecureUtil.stringToRSAPrivateKey
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, exp); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(keySpec); } catch (NumberFormatException nfe) { log.warning("Failed to read key from string.", "str", str, nfe); } catch (GeneralSecurityException gse) { log.warning("Failed to read key from string.", "str", str, gse); } return null; }
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, exp); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(keySpec); } catch (NumberFormatException nfe) { log.warning("Failed to read key from string.", "str", str, nfe); } catch (GeneralSecurityException gse) { log.warning("Failed to read key from string.", "str", str, gse); } return null; }
[ "public", "static", "PrivateKey", "stringToRSAPrivateKey", "(", "String", "str", ")", "{", "try", "{", "BigInteger", "mod", "=", "new", "BigInteger", "(", "str", ".", "substring", "(", "0", ",", "str", ".", "indexOf", "(", "SPLIT", ")", ")", ",", "16", ...
Creates a private key from the supplied string.
[ "Creates", "a", "private", "key", "from", "the", "supplied", "string", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/SecureUtil.java#L173-L187
train
threerings/narya
core/src/main/java/com/threerings/presents/util/SecureUtil.java
SecureUtil.encryptBytes
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[secret.length + ii] = salt[ii]; } try { return getRSACipher(key).doFinal(encrypt); } catch (GeneralSecurityException gse) { log.warning("Failed to encrypt bytes", gse); } return encrypt; }
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[secret.length + ii] = salt[ii]; } try { return getRSACipher(key).doFinal(encrypt); } catch (GeneralSecurityException gse) { log.warning("Failed to encrypt bytes", gse); } return encrypt; }
[ "public", "static", "byte", "[", "]", "encryptBytes", "(", "PublicKey", "key", ",", "byte", "[", "]", "secret", ",", "byte", "[", "]", "salt", ")", "{", "byte", "[", "]", "encrypt", "=", "new", "byte", "[", "secret", ".", "length", "+", "salt", "."...
Encrypts a secret key and salt with a public key.
[ "Encrypts", "a", "secret", "key", "and", "salt", "with", "a", "public", "key", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/SecureUtil.java#L218-L233
train
threerings/narya
core/src/main/java/com/threerings/presents/util/SecureUtil.java
SecureUtil.decryptBytes
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]) { return null; } } byte[] secret = new byte[decrypted.length - salt.length]; for (int ii = 0; ii < secret.length; ii++) { secret[ii] = decrypted[ii]; } return secret; } catch (GeneralSecurityException gse) { log.warning("Failed to decrypt bytes", gse); } return null; }
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]) { return null; } } byte[] secret = new byte[decrypted.length - salt.length]; for (int ii = 0; ii < secret.length; ii++) { secret[ii] = decrypted[ii]; } return secret; } catch (GeneralSecurityException gse) { log.warning("Failed to decrypt bytes", gse); } return null; }
[ "public", "static", "byte", "[", "]", "decryptBytes", "(", "PrivateKey", "key", ",", "byte", "[", "]", "encrypted", ",", "byte", "[", "]", "salt", ")", "{", "try", "{", "byte", "[", "]", "decrypted", "=", "getRSACipher", "(", "key", ")", ".", "doFina...
Decrypts a secret key and checks for tailing salt. @return the secret key, or null on failure or non-matching salt.
[ "Decrypts", "a", "secret", "key", "and", "checks", "for", "tailing", "salt", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/SecureUtil.java#L240-L258
train
threerings/narya
core/src/main/java/com/threerings/presents/util/SecureUtil.java
SecureUtil.xorBytes
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 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; }
[ "public", "static", "byte", "[", "]", "xorBytes", "(", "byte", "[", "]", "data", ",", "byte", "[", "]", "key", ")", "{", "byte", "[", "]", "xored", "=", "new", "byte", "[", "data", ".", "length", "]", ";", "for", "(", "int", "ii", "=", "0", "...
XORs a byte array against a key.
[ "XORs", "a", "byte", "array", "against", "a", "key", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/SecureUtil.java#L263-L270
train
threerings/narya
core/src/main/java/com/threerings/presents/dobj/CompoundEvent.java
CompoundEvent.commit
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: // no point in being compound _omgr.postEvent(_events.get(0)); break; default: // now we're talking _transport = _events.get(0).getTransport(); for (int ii = 1; ii < size; ii++) { _transport = _events.get(ii).getTransport().combine(_transport); } _omgr.postEvent(this); break; } }
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: // no point in being compound _omgr.postEvent(_events.get(0)); break; default: // now we're talking _transport = _events.get(0).getTransport(); for (int ii = 1; ii < size; ii++) { _transport = _events.get(ii).getTransport().combine(_transport); } _omgr.postEvent(this); break; } }
[ "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", "...
Commits this transaction by posting this event to the distributed object event queue. All participating dobjects will have their transaction references cleared and will go back to normal operation.
[ "Commits", "this", "transaction", "by", "posting", "this", "event", "to", "the", "distributed", "object", "event", "queue", ".", "All", "participating", "dobjects", "will", "have", "their", "transaction", "references", "cleared", "and", "will", "go", "back", "to...
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/dobj/CompoundEvent.java#L86-L108
train
threerings/narya
core/src/main/java/com/threerings/crowd/server/LocationManager.java
LocationManager.moveTo
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", source.who(), "placeOid", placeOid); throw new InvocationException(NO_SUCH_PLACE); } // if they're already in the location they're asking to move to, just give them the config // because we don't need to update anything in distributed object world Place place = pmgr.getLocation(); if (place.equals(source.location)) { log.debug("Going along with client request to move to where they already are", "source", source.who(), "place", place); return pmgr.getConfig(); } // make sure they have access to the specified place String errmsg; if ((errmsg = pmgr.ratifyBodyEntry(source)) != null) { throw new InvocationException(errmsg); } // acquire a lock on the body object to avoid breakage by rapid fire moveTo requests if (!source.acquireLock("moveToLock")) { // if we're still locked, a previous moveTo request hasn't been fully processed throw new InvocationException(MOVE_IN_PROGRESS); } // configure the client accordingly if the place uses a custom class loader PresentsSession client = _clmgr.getClient(source.username); if (client != null) { client.setClassLoader(pmgr.getClass().getClassLoader()); } try { source.startTransaction(); try { // remove them from any previous location leaveOccupiedPlace(source); // let the place manager know that we're coming in pmgr.bodyWillEnter(source); // let the body object know that it's going in source.willEnterPlace(place, pmgr.getPlaceObject()); } finally { source.commitTransaction(); } } finally { // and finally queue up an event to release the lock once these events are processed source.releaseLock("moveToLock"); } return pmgr.getConfig(); }
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", source.who(), "placeOid", placeOid); throw new InvocationException(NO_SUCH_PLACE); } // if they're already in the location they're asking to move to, just give them the config // because we don't need to update anything in distributed object world Place place = pmgr.getLocation(); if (place.equals(source.location)) { log.debug("Going along with client request to move to where they already are", "source", source.who(), "place", place); return pmgr.getConfig(); } // make sure they have access to the specified place String errmsg; if ((errmsg = pmgr.ratifyBodyEntry(source)) != null) { throw new InvocationException(errmsg); } // acquire a lock on the body object to avoid breakage by rapid fire moveTo requests if (!source.acquireLock("moveToLock")) { // if we're still locked, a previous moveTo request hasn't been fully processed throw new InvocationException(MOVE_IN_PROGRESS); } // configure the client accordingly if the place uses a custom class loader PresentsSession client = _clmgr.getClient(source.username); if (client != null) { client.setClassLoader(pmgr.getClass().getClassLoader()); } try { source.startTransaction(); try { // remove them from any previous location leaveOccupiedPlace(source); // let the place manager know that we're coming in pmgr.bodyWillEnter(source); // let the body object know that it's going in source.willEnterPlace(place, pmgr.getPlaceObject()); } finally { source.commitTransaction(); } } finally { // and finally queue up an event to release the lock once these events are processed source.releaseLock("moveToLock"); } return pmgr.getConfig(); }
[ "public", "PlaceConfig", "moveTo", "(", "BodyObject", "source", ",", "int", "placeOid", ")", "throws", "InvocationException", "{", "// make sure the place in question actually exists", "PlaceManager", "pmgr", "=", "_plreg", ".", "getPlaceManager", "(", "placeOid", ")", ...
Moves the specified body from whatever location they currently occupy to the location identified by the supplied place oid. @return the config object for the new location. @exception InvocationException thrown if the move was not successful for some reason (which will be communicated as an error code in the exception's message data).
[ "Moves", "the", "specified", "body", "from", "whatever", "location", "they", "currently", "occupy", "to", "the", "location", "identified", "by", "the", "supplied", "place", "oid", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/server/LocationManager.java#L81-L141
train
threerings/narya
core/src/main/java/com/threerings/crowd/server/LocationManager.java
LocationManager.leaveOccupiedPlace
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) { log.warning("Body requested to leave no longer existent place?", "boid", source.getOid(), "place", oldloc); return; } // tell the place manager that they're on the way out pmgr.bodyWillLeave(source); // clear out their location source.didLeavePlace(pmgr.getPlaceObject()); }
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) { log.warning("Body requested to leave no longer existent place?", "boid", source.getOid(), "place", oldloc); return; } // tell the place manager that they're on the way out pmgr.bodyWillLeave(source); // clear out their location source.didLeavePlace(pmgr.getPlaceObject()); }
[ "public", "void", "leaveOccupiedPlace", "(", "BodyObject", "source", ")", "{", "Place", "oldloc", "=", "source", ".", "location", ";", "if", "(", "oldloc", "==", "null", ")", "{", "return", ";", "// nothing to do if they weren't previously in some location", "}", ...
Removes the specified body from the place object they currently occupy. Does nothing if the body is not currently in a place.
[ "Removes", "the", "specified", "body", "from", "the", "place", "object", "they", "currently", "occupy", ".", "Does", "nothing", "if", "the", "body", "is", "not", "currently", "in", "a", "place", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/server/LocationManager.java#L147-L166
train
threerings/narya
core/src/main/java/com/threerings/presents/data/InvocationMarshaller.java
InvocationMarshaller.init
public void init (int invOid, int invCode, InvocationDirector invDir) { _invOid = invOid; _invCode = invCode; _invdir = invDir; }
java
public void init (int invOid, int invCode, InvocationDirector invDir) { _invOid = invOid; _invCode = invCode; _invdir = invDir; }
[ "public", "void", "init", "(", "int", "invOid", ",", "int", "invCode", ",", "InvocationDirector", "invDir", ")", "{", "_invOid", "=", "invOid", ";", "_invCode", "=", "invCode", ";", "_invdir", "=", "invDir", ";", "}" ]
Initializes this invocation marshaller instance with the requisite information to allow it to operate in the wide world. This is called by the invocation manager when an invocation provider is registered and should not be called otherwise.
[ "Initializes", "this", "invocation", "marshaller", "instance", "with", "the", "requisite", "information", "to", "allow", "it", "to", "operate", "in", "the", "wide", "world", ".", "This", "is", "called", "by", "the", "invocation", "manager", "when", "an", "invo...
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/data/InvocationMarshaller.java#L227-L232
train
threerings/narya
core/src/main/java/com/threerings/presents/data/InvocationMarshaller.java
InvocationMarshaller.sendRequest
protected void sendRequest (int methodId, Object[] args, Transport transport) { _invdir.sendRequest(_invOid, _invCode, methodId, args, transport); }
java
protected void sendRequest (int methodId, Object[] args, Transport transport) { _invdir.sendRequest(_invOid, _invCode, methodId, args, transport); }
[ "protected", "void", "sendRequest", "(", "int", "methodId", ",", "Object", "[", "]", "args", ",", "Transport", "transport", ")", "{", "_invdir", ".", "sendRequest", "(", "_invOid", ",", "_invCode", ",", "methodId", ",", "args", ",", "transport", ")", ";", ...
Called by generated invocation marshaller code; packages up and sends the specified invocation service request.
[ "Called", "by", "generated", "invocation", "marshaller", "code", ";", "packages", "up", "and", "sends", "the", "specified", "invocation", "service", "request", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/data/InvocationMarshaller.java#L293-L296
train
threerings/narya
core/src/main/java/com/threerings/io/FieldMarshaller.java
FieldMarshaller.getFieldMarshaller
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 = createMarshallers(); } // if necessary (we're running in a sandbox), look for custom field accessors if (useFieldAccessors()) { Method reader = null, writer = null; try { reader = field.getDeclaringClass().getMethod( getReaderMethodName(field.getName()), READER_ARGS); } catch (NoSuchMethodException nsme) { // no problem } try { writer = field.getDeclaringClass().getMethod( getWriterMethodName(field.getName()), WRITER_ARGS); } catch (NoSuchMethodException nsme) { // no problem } if (reader != null && writer != null) { return new MethodFieldMarshaller(reader, writer); } if ((reader == null && writer != null) || (writer == null && reader != null)) { log.warning("Class contains one but not both custom field reader and writer", "class", field.getDeclaringClass().getName(), "field", field.getName(), "reader", reader, "writer", writer); // fall through to using reflection on the fields... } } Class<?> ftype = field.getType(); // use the intern marshaller for pooled strings if (ftype == String.class && field.isAnnotationPresent(Intern.class)) { return _internMarshaller; } // if we have an exact match, use that FieldMarshaller fm = _marshallers.get(ftype); if (fm == null) { Class<?> collClass = Streamer.getCollectionClass(ftype); if (collClass != null && !collClass.equals(ftype)) { log.warning("Specific field types are discouraged " + "for Iterables/Collections and Maps. The implementation type may not be " + "recreated on the other side.", "class", field.getDeclaringClass(), "field", field.getName(), "type", ftype, "shouldBe", collClass); fm = _marshallers.get(collClass); } // otherwise if the class is a pure interface or streamable, // use the streamable marshaller if (fm == null && (ftype.isInterface() || Streamer.isStreamable(ftype))) { fm = _marshallers.get(Streamable.class); } } return fm; }
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 = createMarshallers(); } // if necessary (we're running in a sandbox), look for custom field accessors if (useFieldAccessors()) { Method reader = null, writer = null; try { reader = field.getDeclaringClass().getMethod( getReaderMethodName(field.getName()), READER_ARGS); } catch (NoSuchMethodException nsme) { // no problem } try { writer = field.getDeclaringClass().getMethod( getWriterMethodName(field.getName()), WRITER_ARGS); } catch (NoSuchMethodException nsme) { // no problem } if (reader != null && writer != null) { return new MethodFieldMarshaller(reader, writer); } if ((reader == null && writer != null) || (writer == null && reader != null)) { log.warning("Class contains one but not both custom field reader and writer", "class", field.getDeclaringClass().getName(), "field", field.getName(), "reader", reader, "writer", writer); // fall through to using reflection on the fields... } } Class<?> ftype = field.getType(); // use the intern marshaller for pooled strings if (ftype == String.class && field.isAnnotationPresent(Intern.class)) { return _internMarshaller; } // if we have an exact match, use that FieldMarshaller fm = _marshallers.get(ftype); if (fm == null) { Class<?> collClass = Streamer.getCollectionClass(ftype); if (collClass != null && !collClass.equals(ftype)) { log.warning("Specific field types are discouraged " + "for Iterables/Collections and Maps. The implementation type may not be " + "recreated on the other side.", "class", field.getDeclaringClass(), "field", field.getName(), "type", ftype, "shouldBe", collClass); fm = _marshallers.get(collClass); } // otherwise if the class is a pure interface or streamable, // use the streamable marshaller if (fm == null && (ftype.isInterface() || Streamer.isStreamable(ftype))) { fm = _marshallers.get(Streamable.class); } } return fm; }
[ "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 co...
Returns a field marshaller appropriate for the supplied field or null if no marshaller exists for the type contained by the field in question.
[ "Returns", "a", "field", "marshaller", "appropriate", "for", "the", "supplied", "field", "or", "null", "if", "no", "marshaller", "exists", "for", "the", "type", "contained", "by", "the", "field", "in", "question", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/io/FieldMarshaller.java#L78-L140
train
threerings/narya
core/src/main/java/com/threerings/nio/conman/ConnectionManager.java
ConnectionManager.sendOutgoingMessages
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 _oflowqs via the connectionFailed() code path for (OverflowQueue oq : _oflowqs.values().toArray(new OverflowQueue[_oflowqs.size()])) { try { // try writing the messages in this overflow queue if (oq.writeOverflowMessages(iterStamp)) { // if they were all written, we can remove it _oflowqs.remove(oq.conn); } } catch (IOException ioe) { oq.conn.networkFailure(ioe); } } } // then send any new messages Tuple<Connection, byte[]> tup; while ((tup = _outq.getNonBlocking()) != null) { Connection conn = tup.left; // if an overflow queue exists for this client, go ahead and slap the message on there // because we can't send it until all other messages in their queue have gone out OverflowQueue oqueue = _oflowqs.get(conn); if (oqueue != null) { int size = oqueue.size(); if ((size > 500) && (size % 50 == 0)) { log.warning("Aiya, big overflow queue for " + conn + "", "size", size, "bytes", tup.right.length); } oqueue.add(tup.right); continue; } // otherwise write the message out to the client directly writeMessage(conn, tup.right, _oflowHandler); } }
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 _oflowqs via the connectionFailed() code path for (OverflowQueue oq : _oflowqs.values().toArray(new OverflowQueue[_oflowqs.size()])) { try { // try writing the messages in this overflow queue if (oq.writeOverflowMessages(iterStamp)) { // if they were all written, we can remove it _oflowqs.remove(oq.conn); } } catch (IOException ioe) { oq.conn.networkFailure(ioe); } } } // then send any new messages Tuple<Connection, byte[]> tup; while ((tup = _outq.getNonBlocking()) != null) { Connection conn = tup.left; // if an overflow queue exists for this client, go ahead and slap the message on there // because we can't send it until all other messages in their queue have gone out OverflowQueue oqueue = _oflowqs.get(conn); if (oqueue != null) { int size = oqueue.size(); if ((size > 500) && (size % 50 == 0)) { log.warning("Aiya, big overflow queue for " + conn + "", "size", size, "bytes", tup.right.length); } oqueue.add(tup.right); continue; } // otherwise write the message out to the client directly writeMessage(conn, tup.right, _oflowHandler); } }
[ "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 of...
Writes all queued overflow and normal messages to their respective sockets. Connections that already have established overflow queues will have their messages appended to their overflow queue instead so that they are delivered in the proper order.
[ "Writes", "all", "queued", "overflow", "and", "normal", "messages", "to", "their", "respective", "sockets", ".", "Connections", "that", "already", "have", "established", "overflow", "queues", "will", "have", "their", "messages", "appended", "to", "their", "overflo...
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/nio/conman/ConnectionManager.java#L292-L333
train
threerings/narya
core/src/main/java/com/threerings/nio/conman/ConnectionManager.java
ConnectionManager.writeMessage
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 things to tell them; such is life in a fully asynchronous distributed system if (conn.isClosed()) { return true; } // if this is an asynchronous close request, queue the connection up for death if (data == ASYNC_CLOSE_REQUEST) { closeConnection(conn); return true; } // sanity check the message size if (data.length > 1024 * 1024) { log.warning("Refusing to write very large message", "conn", conn, "size", data.length); return true; } // expand our output buffer if needed to accomodate this message if (data.length > _outbuf.capacity()) { // increase the buffer size in large increments int ncapacity = Math.max(_outbuf.capacity() << 1, data.length); log.info("Expanding output buffer size", "nsize", ncapacity); _outbuf = ByteBuffer.allocateDirect(ncapacity); } boolean fully = true; try { // log.info("Writing " + data.length + " byte message to " + conn + "."); // first copy the data into our "direct" output buffer _outbuf.put(data); _outbuf.flip(); // if the connection to which we're writing is not yet ready, the whole message is // "leftover", so we pass it to the partial write handler SocketChannel sochan = conn.getChannel(); if (sochan.isConnectionPending()) { pwh.handlePartialWrite(conn, _outbuf); return false; } // then write the data to the socket int wrote = sochan.write(_outbuf); noteWrite(1, wrote); // if we didn't write our entire message, deal with the leftover bytes if (_outbuf.remaining() > 0) { fully = false; pwh.handlePartialWrite(conn, _outbuf); } } catch (NotYetConnectedException nyce) { // this should be caught by isConnectionPending() but awesomely it's not pwh.handlePartialWrite(conn, _outbuf); return false; } catch (IOException ioe) { conn.networkFailure(ioe); // instruct the connection to deal with its failure } finally { _outbuf.clear(); } return fully; }
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 things to tell them; such is life in a fully asynchronous distributed system if (conn.isClosed()) { return true; } // if this is an asynchronous close request, queue the connection up for death if (data == ASYNC_CLOSE_REQUEST) { closeConnection(conn); return true; } // sanity check the message size if (data.length > 1024 * 1024) { log.warning("Refusing to write very large message", "conn", conn, "size", data.length); return true; } // expand our output buffer if needed to accomodate this message if (data.length > _outbuf.capacity()) { // increase the buffer size in large increments int ncapacity = Math.max(_outbuf.capacity() << 1, data.length); log.info("Expanding output buffer size", "nsize", ncapacity); _outbuf = ByteBuffer.allocateDirect(ncapacity); } boolean fully = true; try { // log.info("Writing " + data.length + " byte message to " + conn + "."); // first copy the data into our "direct" output buffer _outbuf.put(data); _outbuf.flip(); // if the connection to which we're writing is not yet ready, the whole message is // "leftover", so we pass it to the partial write handler SocketChannel sochan = conn.getChannel(); if (sochan.isConnectionPending()) { pwh.handlePartialWrite(conn, _outbuf); return false; } // then write the data to the socket int wrote = sochan.write(_outbuf); noteWrite(1, wrote); // if we didn't write our entire message, deal with the leftover bytes if (_outbuf.remaining() > 0) { fully = false; pwh.handlePartialWrite(conn, _outbuf); } } catch (NotYetConnectedException nyce) { // this should be caught by isConnectionPending() but awesomely it's not pwh.handlePartialWrite(conn, _outbuf); return false; } catch (IOException ioe) { conn.networkFailure(ioe); // instruct the connection to deal with its failure } finally { _outbuf.clear(); } return fully; }
[ "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, ...
Writes a message out to a connection, passing the buck to the partial write handler if the entire message could not be written. @return true if the message was fully written, false if it was partially written (in which case the partial message handler will have been invoked).
[ "Writes", "a", "message", "out", "to", "a", "connection", "passing", "the", "buck", "to", "the", "partial", "write", "handler", "if", "the", "entire", "message", "could", "not", "be", "written", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/nio/conman/ConnectionManager.java#L342-L410
train
threerings/narya
core/src/main/java/com/threerings/nio/conman/ConnectionManager.java
ConnectionManager.connectionFailed
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.remove(conn); synchronized (this) { _stats.disconnects++; } }
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.remove(conn); synchronized (this) { _stats.disconnects++; } }
[ "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", ".", ...
Called by a connection if it experiences a network failure.
[ "Called", "by", "a", "connection", "if", "it", "experiences", "a", "network", "failure", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/nio/conman/ConnectionManager.java#L435-L445
train
threerings/narya
core/src/main/java/com/threerings/nio/conman/ConnectionManager.java
ConnectionManager.connectionClosed
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); synchronized (this) { _stats.closes++; } }
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); synchronized (this) { _stats.closes++; } }
[ "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", ")", ";", "_conne...
Called by a connection when it discovers that it's closed.
[ "Called", "by", "a", "connection", "when", "it", "discovers", "that", "it", "s", "closed", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/nio/conman/ConnectionManager.java#L450-L460
train
threerings/narya
core/src/main/java/com/threerings/util/StreamableHashMap.java
StreamableHashMap.newMap
public static <K, V> StreamableHashMap<K, V> newMap (Map<? extends K, ? extends V> map) { return new StreamableHashMap<K, V>(map); }
java
public static <K, V> StreamableHashMap<K, V> newMap (Map<? extends K, ? extends V> map) { return new StreamableHashMap<K, V>(map); }
[ "public", "static", "<", "K", ",", "V", ">", "StreamableHashMap", "<", "K", ",", "V", ">", "newMap", "(", "Map", "<", "?", "extends", "K", ",", "?", "extends", "V", ">", "map", ")", "{", "return", "new", "StreamableHashMap", "<", "K", ",", "V", "...
Creates StreamableHashMap populated with the same values as the provided Map.
[ "Creates", "StreamableHashMap", "populated", "with", "the", "same", "values", "as", "the", "provided", "Map", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/util/StreamableHashMap.java#L58-L61
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/client/MuteDirector.java
MuteDirector.shutdown
public void shutdown () { if (_chatdir != null) { _chatdir.removeChatFilter(this); _chatdir = null; } _ctx.getClient().removeClientObserver(this); }
java
public void shutdown () { if (_chatdir != null) { _chatdir.removeChatFilter(this); _chatdir = null; } _ctx.getClient().removeClientObserver(this); }
[ "public", "void", "shutdown", "(", ")", "{", "if", "(", "_chatdir", "!=", "null", ")", "{", "_chatdir", ".", "removeChatFilter", "(", "this", ")", ";", "_chatdir", "=", "null", ";", "}", "_ctx", ".", "getClient", "(", ")", ".", "removeClientObserver", ...
Called to shut down the mute director.
[ "Called", "to", "shut", "down", "the", "mute", "director", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/MuteDirector.java#L79-L86
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/client/MuteDirector.java
MuteDirector.setMuted
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"; } // always give some feedback to the user _chatdir.displayFeedback(null, MessageBundle.tcompose(feedback, username)); // if the mutelist actually changed, notify observers if (changed) { notifyObservers(username, mute); } }
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"; } // always give some feedback to the user _chatdir.displayFeedback(null, MessageBundle.tcompose(feedback, username)); // if the mutelist actually changed, notify observers if (changed) { notifyObservers(username, mute); } }
[ "public", "void", "setMuted", "(", "Name", "username", ",", "boolean", "mute", ")", "{", "boolean", "changed", "=", "mute", "?", "_mutelist", ".", "add", "(", "username", ")", ":", "_mutelist", ".", "remove", "(", "username", ")", ";", "String", "feedbac...
Mute or unmute the specified user.
[ "Mute", "or", "unmute", "the", "specified", "user", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/MuteDirector.java#L126-L143
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/client/MuteDirector.java
MuteDirector.filter
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 // silently drop if (outgoing) { _chatdir.displayFeedback(null, "m.no_tell_mute"); } return null; } return msg; }
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 // silently drop if (outgoing) { _chatdir.displayFeedback(null, "m.no_tell_mute"); } return null; } return msg; }
[ "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", ")", "&&", "isMut...
documentation inherited from interface ChatFilter
[ "documentation", "inherited", "from", "interface", "ChatFilter" ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/MuteDirector.java#L156-L170
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/client/MuteDirector.java
MuteDirector.notifyObservers
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
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; } }); }
[ "protected", "void", "notifyObservers", "(", "final", "Name", "username", ",", "final", "boolean", "muted", ")", "{", "_observers", ".", "apply", "(", "new", "ObserverList", ".", "ObserverOp", "<", "MuteObserver", ">", "(", ")", "{", "public", "boolean", "ap...
Notify our observers of a change in the mutelist.
[ "Notify", "our", "observers", "of", "a", "change", "in", "the", "mutelist", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/MuteDirector.java#L175-L183
train
threerings/narya
core/src/main/java/com/threerings/presents/server/InvocationManager.java
InvocationManager.clearDispatcher
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()) == null) { log.warning("Requested to remove unregistered marshaller?", "marsh", marsh, new Exception()); } }
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()) == null) { log.warning("Requested to remove unregistered marshaller?", "marsh", marsh, new Exception()); } }
[ "public", "void", "clearDispatcher", "(", "InvocationMarshaller", "<", "?", ">", "marsh", ")", "{", "_omgr", ".", "requireEventThread", "(", ")", ";", "// sanity check", "if", "(", "marsh", "==", "null", ")", "{", "log", ".", "warning", "(", "\"Refusing to u...
Clears out a dispatcher registration. This should be called to free up resources when an invocation service is no longer going to be used.
[ "Clears", "out", "a", "dispatcher", "registration", ".", "This", "should", "be", "called", "to", "free", "up", "resources", "when", "an", "invocation", "service", "is", "no", "longer", "going", "to", "be", "used", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/InvocationManager.java#L297-L310
train
threerings/narya
core/src/main/java/com/threerings/presents/server/InvocationManager.java
InvocationManager.getBootstrapServices
public List<InvocationMarshaller<?>> getBootstrapServices (String[] bootGroups) { List<InvocationMarshaller<?>> services = Lists.newArrayList(); for (String group : bootGroups) { services.addAll(_bootlists.get(group)); } return services; }
java
public List<InvocationMarshaller<?>> getBootstrapServices (String[] bootGroups) { List<InvocationMarshaller<?>> services = Lists.newArrayList(); for (String group : bootGroups) { services.addAll(_bootlists.get(group)); } return services; }
[ "public", "List", "<", "InvocationMarshaller", "<", "?", ">", ">", "getBootstrapServices", "(", "String", "[", "]", "bootGroups", ")", "{", "List", "<", "InvocationMarshaller", "<", "?", ">", ">", "services", "=", "Lists", ".", "newArrayList", "(", ")", ";...
Constructs a list of all bootstrap services registered in any of the supplied groups.
[ "Constructs", "a", "list", "of", "all", "bootstrap", "services", "registered", "in", "any", "of", "the", "supplied", "groups", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/InvocationManager.java#L315-L322
train
threerings/narya
core/src/main/java/com/threerings/presents/server/InvocationManager.java
InvocationManager.getDispatcherClass
public Class<?> getDispatcherClass (int invCode) { Object dispatcher = _dispatchers.get(invCode); return (dispatcher == null) ? null : dispatcher.getClass(); }
java
public Class<?> getDispatcherClass (int invCode) { Object dispatcher = _dispatchers.get(invCode); return (dispatcher == null) ? null : dispatcher.getClass(); }
[ "public", "Class", "<", "?", ">", "getDispatcherClass", "(", "int", "invCode", ")", "{", "Object", "dispatcher", "=", "_dispatchers", ".", "get", "(", "invCode", ")", ";", "return", "(", "dispatcher", "==", "null", ")", "?", "null", ":", "dispatcher", "....
Get the class that is being used to dispatch the specified invocation code, for informational purposes. @return the Class, or null if no dispatcher is registered with the specified code.
[ "Get", "the", "class", "that", "is", "being", "used", "to", "dispatch", "the", "specified", "invocation", "code", "for", "informational", "purposes", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/InvocationManager.java#L331-L335
train
threerings/narya
core/src/main/java/com/threerings/presents/server/InvocationManager.java
InvocationManager.dispatchRequest
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 for invocation request", "clientOid", clientOid, "code", invCode, "methId", methodId, "args", args); return; } // look up the dispatcher Dispatcher disp = _dispatchers.get(invCode); if (disp == null) { log.info("Received invocation request but dispatcher registration was already cleared", "code", invCode, "methId", methodId, "args", args, "marsh", _recentRegServices.get(Integer.valueOf(invCode))); return; } // scan the args, initializing any listeners and keeping track of the "primary" listener ListenerMarshaller rlist = null; int acount = args.length; for (int ii = 0; ii < acount; ii++) { Object arg = args[ii]; if (arg instanceof ListenerMarshaller) { ListenerMarshaller list = (ListenerMarshaller)arg; list.callerOid = clientOid; list.omgr = _omgr; list.transport = transport; // keep track of the listener we'll inform if anything // goes horribly awry if (rlist == null) { rlist = list; } } } log.debug("Dispatching invreq", "caller", source.who(), "provider", disp.getProvider(), "methId", methodId, "args", args); // dispatch the request try { if (rlist != null) { rlist.setInvocationId( StringUtil.shortClassName(disp.getProvider()) + ", methodId=" + methodId); } disp.dispatchRequest(source, methodId, args); } catch (InvocationException ie) { if (rlist != null) { rlist.requestFailed(ie.getMessage()); } else { log.warning("Service request failed but we've got no listener to inform of " + "the failure", "caller", source.who(), "code", invCode, "provider", disp.getProvider(), "methodId", methodId, "args", args, "error", ie); } } catch (Throwable t) { log.warning("Dispatcher choked", "provider", disp.getProvider(), "caller", source.who(), "methId", methodId, "args", args, t); // avoid logging an error when the listener notices that it's been ignored. if (rlist != null) { rlist.setNoResponse(); } } }
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 for invocation request", "clientOid", clientOid, "code", invCode, "methId", methodId, "args", args); return; } // look up the dispatcher Dispatcher disp = _dispatchers.get(invCode); if (disp == null) { log.info("Received invocation request but dispatcher registration was already cleared", "code", invCode, "methId", methodId, "args", args, "marsh", _recentRegServices.get(Integer.valueOf(invCode))); return; } // scan the args, initializing any listeners and keeping track of the "primary" listener ListenerMarshaller rlist = null; int acount = args.length; for (int ii = 0; ii < acount; ii++) { Object arg = args[ii]; if (arg instanceof ListenerMarshaller) { ListenerMarshaller list = (ListenerMarshaller)arg; list.callerOid = clientOid; list.omgr = _omgr; list.transport = transport; // keep track of the listener we'll inform if anything // goes horribly awry if (rlist == null) { rlist = list; } } } log.debug("Dispatching invreq", "caller", source.who(), "provider", disp.getProvider(), "methId", methodId, "args", args); // dispatch the request try { if (rlist != null) { rlist.setInvocationId( StringUtil.shortClassName(disp.getProvider()) + ", methodId=" + methodId); } disp.dispatchRequest(source, methodId, args); } catch (InvocationException ie) { if (rlist != null) { rlist.requestFailed(ie.getMessage()); } else { log.warning("Service request failed but we've got no listener to inform of " + "the failure", "caller", source.who(), "code", invCode, "provider", disp.getProvider(), "methodId", methodId, "args", args, "error", ie); } } catch (Throwable t) { log.warning("Dispatcher choked", "provider", disp.getProvider(), "caller", source.who(), "methId", methodId, "args", args, t); // avoid logging an error when the listener notices that it's been ignored. if (rlist != null) { rlist.setNoResponse(); } } }
[ "protected", "void", "dispatchRequest", "(", "int", "clientOid", ",", "int", "invCode", ",", "int", "methodId", ",", "Object", "[", "]", "args", ",", "Transport", "transport", ")", "{", "// make sure the client is still around", "ClientObject", "source", "=", "(",...
Called when we receive an invocation request message. Dispatches the request to the appropriate invocation provider via the registered invocation dispatcher.
[ "Called", "when", "we", "receive", "an", "invocation", "request", "message", ".", "Dispatches", "the", "request", "to", "the", "appropriate", "invocation", "provider", "via", "the", "registered", "invocation", "dispatcher", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/InvocationManager.java#L353-L422
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/data/ChatMessage.java
ChatMessage.setClientInfo
public void setClientInfo (String msg, String ltype) { message = msg; localtype = ltype; bundle = null; timestamp = System.currentTimeMillis(); }
java
public void setClientInfo (String msg, String ltype) { message = msg; localtype = ltype; bundle = null; timestamp = System.currentTimeMillis(); }
[ "public", "void", "setClientInfo", "(", "String", "msg", ",", "String", "ltype", ")", "{", "message", "=", "msg", ";", "localtype", "=", "ltype", ";", "bundle", "=", "null", ";", "timestamp", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "}" ]
Once this message reaches the client, the information contained within is changed around a bit.
[ "Once", "this", "message", "reaches", "the", "client", "the", "information", "contained", "within", "is", "changed", "around", "a", "bit", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/data/ChatMessage.java#L63-L69
train
criccomini/ezdb
ezdb-api/src/main/java/ezdb/comparator/SerdeComparator.java
SerdeComparator.innerCompare
protected int innerCompare(Comparable<Object> co1, Comparable<Object> co2) { return co1.compareTo(co2); }
java
protected int innerCompare(Comparable<Object> co1, Comparable<Object> co2) { return co1.compareTo(co2); }
[ "protected", "int", "innerCompare", "(", "Comparable", "<", "Object", ">", "co1", ",", "Comparable", "<", "Object", ">", "co2", ")", "{", "return", "co1", ".", "compareTo", "(", "co2", ")", ";", "}" ]
Override this to customize the comparation itself. E.g. inversing it.
[ "Override", "this", "to", "customize", "the", "comparation", "itself", ".", "E", ".", "g", ".", "inversing", "it", "." ]
2adaccee179614f01e1c7e5af82a4f731e4e72cc
https://github.com/criccomini/ezdb/blob/2adaccee179614f01e1c7e5af82a4f731e4e72cc/ezdb-api/src/main/java/ezdb/comparator/SerdeComparator.java#L37-L39
train
threerings/narya
tools/src/main/java/com/threerings/presents/tools/InstrumentStreamableTask.java
InstrumentStreamableTask.processClass
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); return; } finally { StreamUtil.close(in); } try { if (clazz.subtypeOf(_streamable)) { processStreamable(source, clazz); } } catch (NotFoundException nfe) { System.err.println("Error processing class [class=" + clazz.getName() + ", error=" + nfe + "]."); } }
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); return; } finally { StreamUtil.close(in); } try { if (clazz.subtypeOf(_streamable)) { processStreamable(source, clazz); } } catch (NotFoundException nfe) { System.err.println("Error processing class [class=" + clazz.getName() + ", error=" + nfe + "]."); } }
[ "protected", "void", "processClass", "(", "File", "source", ")", "{", "CtClass", "clazz", ";", "InputStream", "in", "=", "null", ";", "try", "{", "clazz", "=", "_pool", ".", "makeClass", "(", "in", "=", "new", "BufferedInputStream", "(", "new", "FileInputS...
Processes a class file.
[ "Processes", "a", "class", "file", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/tools/src/main/java/com/threerings/presents/tools/InstrumentStreamableTask.java#L122-L143
train
threerings/narya
core/src/main/java/com/threerings/bureau/client/BureauDirector.java
BureauDirector.createAgent
protected synchronized void createAgent (int agentId) { Subscriber<AgentObject> delegator = new Subscriber<AgentObject>() { public void objectAvailable (AgentObject agentObject) { BureauDirector.this.objectAvailable(agentObject); } public void requestFailed (int oid, ObjectAccessException cause) { BureauDirector.this.requestFailed(oid, cause); } }; log.info("Subscribing to object " + agentId); SafeSubscriber<AgentObject> subscriber = new SafeSubscriber<AgentObject>(agentId, delegator); _subscribers.put(agentId, subscriber); subscriber.subscribe(_ctx.getDObjectManager()); }
java
protected synchronized void createAgent (int agentId) { Subscriber<AgentObject> delegator = new Subscriber<AgentObject>() { public void objectAvailable (AgentObject agentObject) { BureauDirector.this.objectAvailable(agentObject); } public void requestFailed (int oid, ObjectAccessException cause) { BureauDirector.this.requestFailed(oid, cause); } }; log.info("Subscribing to object " + agentId); SafeSubscriber<AgentObject> subscriber = new SafeSubscriber<AgentObject>(agentId, delegator); _subscribers.put(agentId, subscriber); subscriber.subscribe(_ctx.getDObjectManager()); }
[ "protected", "synchronized", "void", "createAgent", "(", "int", "agentId", ")", "{", "Subscriber", "<", "AgentObject", ">", "delegator", "=", "new", "Subscriber", "<", "AgentObject", ">", "(", ")", "{", "public", "void", "objectAvailable", "(", "AgentObject", ...
Creates a new agent when the server requests it.
[ "Creates", "a", "new", "agent", "when", "the", "server", "requests", "it", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/bureau/client/BureauDirector.java#L65-L82
train
threerings/narya
core/src/main/java/com/threerings/bureau/client/BureauDirector.java
BureauDirector.destroyAgent
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) { log.warning("Stopping an agent caused an exception", t); } SafeSubscriber<AgentObject> subscriber = _subscribers.remove(agentId); if (subscriber == null) { log.warning("Lost a subscriber for agent " + agent); } else { subscriber.unsubscribe(_ctx.getDObjectManager()); } _bureauService.agentDestroyed(agentId); } }
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) { log.warning("Stopping an agent caused an exception", t); } SafeSubscriber<AgentObject> subscriber = _subscribers.remove(agentId); if (subscriber == null) { log.warning("Lost a subscriber for agent " + agent); } else { subscriber.unsubscribe(_ctx.getDObjectManager()); } _bureauService.agentDestroyed(agentId); } }
[ "protected", "synchronized", "void", "destroyAgent", "(", "int", "agentId", ")", "{", "Agent", "agent", "=", "null", ";", "agent", "=", "_agents", ".", "remove", "(", "agentId", ")", ";", "if", "(", "agent", "==", "null", ")", "{", "log", ".", "warning...
Destroys an agent at the server's request.
[ "Destroys", "an", "agent", "at", "the", "server", "s", "request", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/bureau/client/BureauDirector.java#L87-L108
train
threerings/narya
core/src/main/java/com/threerings/bureau/client/BureauDirector.java
BureauDirector.objectAvailable
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(); } catch (Throwable t) { log.warning("Could not create agent", "obj", agentObject, t); _bureauService.agentCreationFailed(oid); return; } _agents.put(oid, agent); _bureauService.agentCreated(oid); }
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(); } catch (Throwable t) { log.warning("Could not create agent", "obj", agentObject, t); _bureauService.agentCreationFailed(oid); return; } _agents.put(oid, agent); _bureauService.agentCreated(oid); }
[ "protected", "synchronized", "void", "objectAvailable", "(", "AgentObject", "agentObject", ")", "{", "int", "oid", "=", "agentObject", ".", "getOid", "(", ")", ";", "log", ".", "info", "(", "\"Object \"", "+", "oid", "+", "\" now available\"", ")", ";", "Age...
Callback for when the a request to subscribe to an object finishes and the object is available.
[ "Callback", "for", "when", "the", "a", "request", "to", "subscribe", "to", "an", "object", "finishes", "and", "the", "object", "is", "available", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/bureau/client/BureauDirector.java#L114-L133
train
threerings/narya
core/src/main/java/com/threerings/presents/util/PersistingUnit.java
PersistingUnit.handleSuccess
public void handleSuccess () { if (_listener instanceof InvocationService.ConfirmListener) { reportRequestProcessed(); } else if (_listener instanceof InvocationService.ResultListener && _resultSet) { reportRequestProcessed(_result); } }
java
public void handleSuccess () { if (_listener instanceof InvocationService.ConfirmListener) { reportRequestProcessed(); } else if (_listener instanceof InvocationService.ResultListener && _resultSet) { reportRequestProcessed(_result); } }
[ "public", "void", "handleSuccess", "(", ")", "{", "if", "(", "_listener", "instanceof", "InvocationService", ".", "ConfirmListener", ")", "{", "reportRequestProcessed", "(", ")", ";", "}", "else", "if", "(", "_listener", "instanceof", "InvocationService", ".", "...
Handles the success case, which by default posts a response to a ConfirmListener. If you need something else, or to repond to a ResultListener, you'll need to override this.
[ "Handles", "the", "success", "case", "which", "by", "default", "posts", "a", "response", "to", "a", "ConfirmListener", ".", "If", "you", "need", "something", "else", "or", "to", "repond", "to", "a", "ResultListener", "you", "ll", "need", "to", "override", ...
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/PersistingUnit.java#L78-L85
train
threerings/narya
core/src/main/java/com/threerings/presents/util/PersistingUnit.java
PersistingUnit.handleFailure
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 { log.warning(getFailureMessage(), error); } _listener.requestFailed(InvocationCodes.INTERNAL_ERROR); } }
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 { log.warning(getFailureMessage(), error); } _listener.requestFailed(InvocationCodes.INTERNAL_ERROR); } }
[ "public", "void", "handleFailure", "(", "Exception", "error", ")", "{", "if", "(", "error", "instanceof", "InvocationException", ")", "{", "_listener", ".", "requestFailed", "(", "error", ".", "getMessage", "(", ")", ")", ";", "}", "else", "{", "if", "(", ...
Handles the failure case by logging the error and reporting an internal error to the listener.
[ "Handles", "the", "failure", "case", "by", "logging", "the", "error", "and", "reporting", "an", "internal", "error", "to", "the", "listener", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/PersistingUnit.java#L91-L103
train
threerings/narya
core/src/main/java/com/threerings/presents/server/ShutdownManager.java
ShutdownManager.addConstraint
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, Lifecycle.Constraint.RUNS_AFTER, rhs); break; } }
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, Lifecycle.Constraint.RUNS_AFTER, rhs); break; } }
[ "public", "void", "addConstraint", "(", "Shutdowner", "lhs", ",", "Constraint", "constraint", ",", "Shutdowner", "rhs", ")", "{", "switch", "(", "constraint", ")", "{", "case", "RUNS_BEFORE", ":", "_cycle", ".", "addShutdownConstraint", "(", "lhs", ",", "Lifec...
Adds a constraint that a certain shutdowner must be run before another.
[ "Adds", "a", "constraint", "that", "a", "certain", "shutdowner", "must", "be", "run", "before", "another", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/ShutdownManager.java#L64-L74
train