code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
public static void runServer (Module... modules)
{
Injector injector = Guice.createInjector(modules);
PresentsServer server = injector.getInstance(PresentsServer.class);
try {
// initialize the server
server.init(injector);
// check to see if we should lo... | java |
public void run ()
{
// wait till everything in the dobjmgr queue and invokers are processed and then start the
// connection manager
((PresentsInvoker)_invoker).postRunnableWhenEmpty(new Runnable() {
public void run () {
// Take as long as you like opening to the... | java |
protected void openToThePublic ()
{
if (getListenPorts().length != 0 && !_socketAcceptor.bind()) {
queueShutdown();
} else {
_datagramReader.bind();
_conmgr.start();
}
} | java |
public void readFrom (File source)
throws IOException
{
// slurp our source file into newline separated strings
_lines = Lists.newArrayList();
BufferedReader bin = new BufferedReader(new FileReader(source));
String line = null;
while ((line = bin.readLine()) != null) ... | java |
public boolean containsString (String text)
{
for (int ii = 0, nn = _lines.size(); ii < nn; ii++) {
// don't look inside the autogenerated areas
if (!(ii >= _nstart && ii < _nend) && !(ii >= _mstart && ii < _mend) &&
_lines.get(ii).contains(text)) {
... | java |
public String generate (String fsection, String msection)
throws IOException
{
StringWriter writer = new StringWriter();
BufferedWriter bout = new BufferedWriter(writer);
addOrRemoveGeneratedImport(StringUtil.deNull(fsection).contains("@Generated(") ||
StringUtil.deNull(m... | java |
protected void check (File source, String mname, int mline, String fname, int fline)
throws IOException
{
if (mline == -1 && fline != -1) {
throw new IOException(
"Found " + fname + " marker (at line " + (fline+1) + ") but no " + mname +
" marker in '" + s... | java |
protected void writeln (BufferedWriter bout, String line)
throws IOException
{
bout.write(line);
bout.newLine();
} | java |
protected void addOrRemoveGeneratedImport (boolean add)
{
final String IMPORT = "import javax.annotation.Generated;";
int packageLine = -1;
int importLine = -1;
int lastJavaImport = -1;
int firstNonJavaImport = -1;
for (int ii = 0, nn = _lines.size(); ii < nn; ii++) ... | java |
protected void updateBorder (boolean modified)
{
if (modified) {
setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
} else {
setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
}
} | java |
public void addListener (ChangeListener listener, boolean weak)
{
// only add the listener if they're not already there
int idx = getListenerIndex(listener);
if (idx == -1) {
_listeners = ListUtil.add(_listeners,
weak ? new WeakReference<Object>(listener) : listen... | java |
public void removeListener (ChangeListener listener)
{
int idx = getListenerIndex(listener);
if (idx != -1) {
_listeners[idx] = null;
}
} | java |
public final <T extends DSet.Entry> DSet<T> getSet (String setName)
{
@SuppressWarnings("unchecked") DSet<T> casted = (DSet<T>)getAccessor(setName).get(this);
return casted;
} | java |
public <T extends DSet.Entry> void addToSet (String setName, T entry)
{
requestEntryAdd(setName, getSet(setName), entry);
} | java |
public void updateSet (String setName, DSet.Entry entry)
{
requestEntryUpdate(setName, getSet(setName), entry);
} | java |
public void removeFromSet (String setName, Comparable<?> key)
{
requestEntryRemove(setName, getSet(setName), key);
} | java |
public void notifyListeners (DEvent event)
{
if (_listeners == null) {
return;
}
for (int ii = 0, ll = _listeners.length; ii < ll; ii++) {
Object listener = _listeners[ii];
if (listener == null) {
continue;
}
if (li... | java |
public void notifyProxies (DEvent event)
{
if (_subs == null || event.isPrivate()) {
return;
}
for (Object sub : _subs) {
try {
if (sub != null && sub instanceof ProxySubscriber) {
((ProxySubscriber)sub).eventReceived(event);
... | java |
public void changeAttribute (String name, Object value)
{
Accessor acc = getAccessor(name);
requestAttributeChange(name, value, acc.get(this));
acc.set(this, value);
} | java |
public void postEvent (DEvent event)
{
if (_tevent != null) {
_tevent.postEvent(event);
} else if (_omgr != null) {
_omgr.postEvent(event);
} else {
log.info("Dropping event for non- or no longer managed object", "oid", getOid(),
"cl... | java |
protected void which (StringBuilder buf)
{
buf.append(StringUtil.shortClassName(this));
buf.append(":").append(_oid);
} | java |
public void commitTransaction ()
{
if (_tevent == null) {
String errmsg = "Cannot commit: not involved in a transaction [dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
// if we are nested, we decrement our nesting count rather than committing the tra... | java |
public void cancelTransaction ()
{
if (_tevent == null) {
String errmsg = "Cannot cancel: not involved in a transaction [dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
// if we're in a nested transaction, make a note that it is to be cancelled when a... | java |
protected void requestOidAdd (String name, OidList list, int oid)
{
// if we're on the authoritative server, we update the set immediately
boolean applyImmediately = isAuthoritative();
if (applyImmediately) {
list.add(oid);
}
postEvent(new ObjectAddedEvent(_oid, n... | java |
protected void requestOidRemove (String name, OidList list, int oid)
{
// if we're on the authoritative server, we update the set immediately
boolean applyImmediately = isAuthoritative();
if (applyImmediately) {
list.remove(oid);
}
// dispatch an object removed ev... | java |
protected <T extends DSet.Entry> void requestEntryAdd (String name, DSet<T> set, T entry)
{
// if we're on the authoritative server, we update the set immediately
boolean applyImmediately = isAuthoritative();
if (applyImmediately) {
set.add(entry);
}
// dispatch a... | java |
protected <T extends DSet.Entry> void requestEntryRemove (
String name, DSet<T> set, Comparable<?> key)
{
// if we're on the authoritative server, we update the set immediately
T oldEntry = null;
if (isAuthoritative()) {
oldEntry = set.removeKey(key);
if (oldE... | java |
protected Accessor[] createAccessors ()
{
Field[] fields = getClass().getFields();
// assume we have one static field for every non-static field
List<Accessor> accs = Lists.newArrayListWithExpectedSize(fields.length/2);
for (Field field : fields) {
if (!Modifier.isStatic(... | java |
protected int getListenerIndex (ChangeListener listener)
{
if (_listeners == null) {
return -1;
}
for (int ii = 0, ll = _listeners.length; ii < ll; ii++) {
Object olistener = _listeners[ii];
if (olistener == listener || (olistener instanceof WeakReference<... | java |
public void getConfigInfo (ClientObject caller, AdminService.ConfigInfoListener listener)
throws InvocationException
{
// we don't have to validate the request because the user can't do anything with the keys
// or oids unless they're an admin (we put the burden of doing that checking on the... | java |
protected static String createAuthToken (String clientId, String sharedSecret)
{
return StringUtil.md5hex(clientId + sharedSecret);
} | java |
public boolean bind ()
{
// open our TCP listening ports
int successes = 0;
for (int port : _ports) {
try {
acceptConnections(port);
successes++;
} catch (IOException ioe) {
log.warning("Failure listening to socket", "ho... | java |
public void shutdown ()
{
for (ServerSocketChannel ssocket : _ssockets) {
try {
ssocket.socket().close();
} catch (IOException ioe) {
log.warning("Failed to close listening socket: " + ssocket, ioe);
}
}
} | java |
public ServiceMethod createAndGatherImports (Method method, ImportSet imports)
{
ServiceMethod sm = new ServiceMethod(method);
sm.gatherImports(imports);
return sm;
} | java |
protected long getDelta (long timeStamp, long maxValue)
{
boolean even = (evenBase > oddBase);
long base = even ? evenBase : oddBase;
long delta = timeStamp - base;
// make sure this timestamp is not sufficiently old that we can't
// generate a delta time with it
if ... | java |
public String checkAccess (Permission perm, Object context)
{
if (_permPolicy == null) {
_permPolicy = createPermissionPolicy();
}
return _permPolicy.checkAccess(perm, context);
} | java |
public MarcValueTransformers setMarcValueTransformer(String fieldKey, MarcValueTransformer transformer) {
// split into tag + indicator and subfield IDs
int pos = fieldKey.lastIndexOf('$');
String tagind = pos > 0 ? fieldKey.substring(0, pos) : fieldKey;
String subs = pos > 0 ? fieldKey... | java |
public MarcField transformValue(MarcField field) {
String key = field.toTagIndicatorKey();
if (marcValueTransformerMap.isEmpty()) {
return field;
}
final MarcValueTransformer transformer = marcValueTransformerMap.containsKey(key) ?
marcValueTransformerMap.get(... | java |
protected final void expand (int needed)
{
int ocapacity = _buffer.capacity();
int ncapacity = _buffer.position() + needed;
if (ncapacity > ocapacity) {
// increase the buffer size in large increments
ncapacity = Math.max(ocapacity << 1, ncapacity);
ByteBu... | java |
public static UserSystemMessage create (Name sender, String message, String bundle)
{
return new UserSystemMessage(sender, message, bundle, INFO);
} | java |
public void setLine(int... points) {
double[] pd = new double[points.length];
for (int i = 0; i < points.length; i++) {
pd[i] = points[i];
}
setLine(pd);
} | java |
public void setLine(Point2D[] points) {
double[] pd = new double[points.length * 2];
for (int i = 0; i < points.length; i++) {
Point2D p = points[i];
pd[i * 2] = p.getX();
pd[i * 2 + 1] = p.getY();
}
setLine(pd);
} | java |
public void addClientObserver (ClientObserver observer)
{
_clobservers.add(observer);
if (observer instanceof DetailedClientObserver) {
_dclobservers.add((DetailedClientObserver)observer);
}
} | java |
public void applyToClient (Name username, final ClientOp clop)
{
resolveClientObject(username, new ClientResolutionListener() {
public void clientResolved (Name username, ClientObject clobj) {
try {
clop.apply(clobj);
} catch (Exception e) {
... | java |
public void shutdown ()
{
log.info("Client manager shutting down", "ccount", _usermap.size());
// inform all of our clients that they are being shut down
synchronized (_usermap) {
for (PresentsSession pc : _usermap.values()) {
try {
pc.shutdow... | java |
public synchronized void clientResolved (Name username, ClientObject clobj)
{
// because we added ourselves as a client resolution listener, the client object reference
// count was increased, but we're not a real resolver (who would have to call
// releaseClientObject() to release their ref... | java |
public synchronized void connectionEstablished (
PresentsConnection conn, Name authname, AuthRequest req, AuthResponse rsp)
{
String type = authname.getClass().getSimpleName();
// see if a session is already registered with this name
PresentsSession session = getClient(authname);
... | java |
public synchronized void connectionFailed (Connection conn, IOException fault)
{
// remove the session from the connection map
PresentsSession session = _conmap.remove(conn);
if (session != null) {
log.info("Unmapped failed session", "session", session, "conn", conn, "fault", fau... | java |
public synchronized void connectionClosed (Connection conn)
{
// remove the session from the connection map
PresentsSession session = _conmap.remove(conn);
if (session != null) {
log.debug("Unmapped session", "session", session, "conn", conn);
// let the session know ... | java |
public void appendReport (StringBuilder report, long now, long sinceLast, boolean reset)
{
report.append("* presents.ClientManager:\n");
report.append("- Sessions: ");
synchronized (_usermap) {
report.append(_usermap.size()).append(" total, ");
}
report.append(_co... | java |
@EventThread
protected void clientSessionWillEnd (final PresentsSession session)
{
// notify the observers that the session is ended
_dclobservers.apply(new ObserverList.ObserverOp<DetailedClientObserver>() {
public boolean apply (DetailedClientObserver observer) {
ob... | java |
@EventThread
protected void clientSessionDidEnd (final PresentsSession session)
{
// notify the observers that the session is ended
_clobservers.apply(new ObserverList.ObserverOp<ClientObserver>() {
public boolean apply (ClientObserver observer) {
observer.clientSessi... | java |
protected void clearSession (PresentsSession session)
{
// remove the session from the username map
PresentsSession rc;
synchronized (_usermap) {
rc = _usermap.remove(session.getAuthName());
}
// sanity check just because we can
if (rc == null) {
... | java |
protected void flushSessions ()
{
List<PresentsSession> victims = Lists.newArrayList();
long now = System.currentTimeMillis();
// first build a list of our victims
synchronized (_usermap) {
for (PresentsSession session : _usermap.values()) {
if (session.c... | java |
protected String getLabel(ArgumentComponent argumentComponent, Token token)
{
StringBuilder sb = new StringBuilder(argumentComponent.getClass().getSimpleName());
if ("BIO".equals(this.codingGranularity)) {
// Does the component begin here?
if (argumentComponent.getBegin() ==... | java |
protected synchronized boolean clearPPI (boolean cancel)
{
if (_prefPortInterval != null) {
if (cancel) {
_prefPortInterval.cancel();
_prefPortInterval.failed();
}
_prefPortInterval = null;
return true;
}
return ... | java |
@Override
public CacheManagerPeerProvider createCachePeerProvider (
CacheManager cacheManager, Properties properties)
{
if (_instance == null) {
_instance = new Provider(cacheManager);
}
return _instance;
} | java |
@Override
public Stream<Chunk<byte[], BytesReference>> chunks() {
Iterator<Chunk<byte[], BytesReference>> iterator = new Iterator<Chunk<byte[], BytesReference>>() {
Chunk<byte[], BytesReference> nextData = null;
@Override
public boolean hasNext() {
if (ne... | java |
public void decrypt (byte[] key)
throws IOException, ClassNotFoundException
{
if (_clearCreds != null) {
return;
}
_key = key;
try {
_contents = SecureUtil.getAESCipher(Cipher.DECRYPT_MODE, _key).doFinal(_contents);
} catch (GeneralSecurityExcep... | java |
public void writeObject (ObjectOutputStream out)
throws IOException
{
out.defaultWriteObject();
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream oOut = new ObjectOutputStream(byteOut);
oOut.writeObject(_clearCreds);
try {
byt... | java |
@Override
public void readObject (ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
_contents = new byte[in.readInt()];
in.read(_contents);
} | java |
protected synchronized void connectionFailed (final IOException ioe)
{
// make sure the socket isn't already closed down (meaning we've already dealt with the
// failed connection)
if (_channel == null) {
return;
}
log.info("Connection failed", ioe);
// ... | java |
protected synchronized void readerDidExit ()
{
// clear out our reader reference
_reader = null;
if (_writer == null) {
// there's no writer during authentication, so we may be responsible for closing the
// socket channel
closeChannel();
// ... | java |
protected synchronized void writerDidExit ()
{
// clear out our writer reference
_writer = null;
log.debug("Writer thread exited.");
// let the client observers know that we're logged off
notifyClientObservers(new ObserverOps.Session(_client) {
@Override protecte... | java |
protected void closeDatagramChannel ()
{
if (_selector != null) {
try {
_selector.close();
} catch (IOException ioe) {
log.warning("Error closing selector: " + ioe);
}
_selector = null;
}
if (_datagramChannel != ... | java |
protected void sendMessage (UpstreamMessage msg)
throws IOException
{
if (debugLogMessages()) {
log.info("SEND " + msg);
}
// first we write the message so that we can measure it's length
_oout.writeObject(msg);
_oout.flush();
// then write the f... | java |
protected void sendDatagram (UpstreamMessage msg)
throws IOException
{
// reset the stream and write our connection id and hash placeholder
_bout.reset();
_uout.writeInt(_client.getConnectionId());
_uout.writeLong(0L);
// write the datagram through the sequencer
... | java |
protected void throttleOutgoingMessage ()
{
Throttle throttle = _client.getOutgoingMessageThrottle();
synchronized(throttle) {
while (throttle.throttleOp()) {
try {
Thread.sleep(2);
} catch (InterruptedException ie) {
... | java |
private String interpolate(MarcField marcField, String value) {
if (value == null) {
return null;
}
Matcher m = REP.matcher(value);
if (m.find()) {
return m.replaceAll(Integer.toString(repeatCounter));
}
m = NREP.matcher(value);
if (m.find(... | java |
public PlaceController createController ()
{
Class<?> cclass = getControllerClass();
if (cclass == null) {
throw new RuntimeException(
"PlaceConfig.createController() must be overridden.");
}
log.warning("Providing backwards compatibility. PlaceConfig." +... | java |
protected void addWhoData (StringBuilder buf)
{
buf.append(getOid());
if (status != OccupantInfo.ACTIVE) {
buf.append(" ").append(getStatusTranslation());
}
} | java |
public static void init (InvocationManager invmgr, RootDObjectManager omgr)
{
// we'll need these later
_invmgr = invmgr;
_omgr = omgr;
// register a provider instance
invmgr.registerProvider(new TimeBaseProvider(), TimeBaseMarshaller.class, GLOBAL_GROUP);
} | java |
public static TimeBaseObject createTimeBase (String timeBase)
{
TimeBaseObject object = _omgr.registerObject(new TimeBaseObject());
_timeBases.put(timeBase, object);
return object;
} | java |
public void getTimeOid (ClientObject source, String timeBase,
TimeBaseService.GotTimeBaseListener listener)
throws InvocationException
{
// look up the time base object in question
TimeBaseObject time = getTimeBase(timeBase);
if (time == null) {
... | java |
public Iterable<NodeObject> getNodeObjects ()
{
return Iterables.filter(
Iterables.concat(Collections.singleton(_nodeobj),
Iterables.transform(_peers.values(), GET_NODE_OBJECT)),
Predicates.notNull());
} | java |
public ClientInfo locateClient (final Name key)
{
return lookupNodeDatum(new Function<NodeObject,ClientInfo>() {
public ClientInfo apply (NodeObject nodeobj) {
return nodeobj.clients.get(key);
}
});
} | java |
public void invokeNodeAction (final NodeAction action, final Runnable onDropped)
{
// if we're not on the dobjmgr thread, get there
if (!_omgr.isDispatchThread()) {
_omgr.postRunnable(new Runnable() {
public void run () {
invokeNodeAction(action, onDro... | java |
public <T> void invokeNodeRequest (
final NodeRequest request, final NodeRequestsListener<T> listener)
{
// if we're not on the dobjmgr thread, get there
if (!_omgr.isDispatchThread()) {
_omgr.postRunnable(new Runnable() {
public void run () {
... | java |
public void invokeNodeRequest (String nodeName, NodeRequest request,
InvocationService.ResultListener listener)
{
invokeNodeRequest(nodeName, flattenRequest(request), listener);
} | java |
public <T extends DObject> void proxyRemoteObject (
String nodeName, final int remoteOid, final ResultListener<Integer> listener)
{
proxyRemoteObject(new DObjectAddress(nodeName, remoteOid), listener);
} | java |
public void unproxyRemoteObject (DObjectAddress addr)
{
Tuple<Subscriber<?>, DObject> bits = _proxies.remove(addr);
if (bits == null) {
log.warning("Requested to clear unknown proxy", "addr", addr);
return;
}
// If it's local, just remove the subscriber we ad... | java |
public String getPeerPublicHostName (String nodeName)
{
if (Objects.equal(_nodeName, nodeName)) {
return _self.publicHostName;
}
PeerNode peer = _peers.get(nodeName);
return (peer == null) ? null : peer.getPublicHostName();
} | java |
public String getPeerInternalHostName (String nodeName)
{
if (Objects.equal(_nodeName, nodeName)) {
return _self.hostName;
}
PeerNode peer = _peers.get(nodeName);
return (peer == null) ? null : peer.getInternalHostName();
} | java |
public int getPeerPort (String nodeName)
{
if (Objects.equal(_nodeName, nodeName)) {
return _self.port;
}
PeerNode peer = _peers.get(nodeName);
return (peer == null) ? -1 : peer.getPort();
} | java |
public void acquireLock (final NodeObject.Lock lock, final ResultListener<String> listener)
{
// wait until any pending resolution is complete
queryLock(lock, new ChainedResultListener<String, String>(listener) {
public void requestCompleted (String result) {
if (result =... | java |
public void queryLock (NodeObject.Lock lock, ResultListener<String> listener)
{
// if it's being resolved, add the listener to the list
LockHandler handler = _locks.get(lock);
if (handler != null) {
handler.listeners.add(listener);
return;
}
// otherw... | java |
public void addStaleCacheObserver (String cache, StaleCacheObserver observer)
{
ObserverList<StaleCacheObserver> list = _cacheobs.get(cache);
if (list == null) {
list = ObserverList.newFastUnsafe();
_cacheobs.put(cache, list);
}
list.add(observer);
} | java |
public void removeStaleCacheObserver (String cache, StaleCacheObserver observer)
{
ObserverList<StaleCacheObserver> list = _cacheobs.get(cache);
if (list == null) {
return;
}
list.remove(observer);
if (list.isEmpty()) {
_cacheobs.remove(cache);
... | java |
public void broadcastStaleCacheData (String cache, Streamable data)
{
_nodeobj.setCacheData(new NodeObject.CacheData(cache, data));
} | java |
protected void refreshPeer (NodeRecord record)
{
PeerNode peer = _peers.get(record.nodeName);
if (peer == null) {
peer = _injector.getInstance(getPeerNodeClass());
_peers.put(record.nodeName, peer);
peer.init(record);
}
peer.refresh(record);
} | java |
protected void changedCacheData (String cache, final Streamable data)
{
// see if we have any observers
ObserverList<StaleCacheObserver> list = _cacheobs.get(cache);
if (list == null) {
return;
}
// if so, notify them
list.apply(new ObserverList.ObserverOp... | java |
protected void droppedLock (final NodeObject.Lock lock)
{
_nodeobj.removeFromLocks(lock);
_stats.locksHijacked++;
_dropobs.apply(new ObserverList.ObserverOp<DroppedLockObserver>() {
public boolean apply (DroppedLockObserver observer) {
observer.droppedLock(lock);
... | java |
protected void clientLoggedOn (String nodeName, ClientInfo clinfo)
{
PresentsSession session = _clmgr.getClient(clinfo.username);
if (session != null) {
log.info("Booting user that has connected on another node",
"username", clinfo.username, "otherNode", nodeName);
... | java |
protected void peerAcquiringLock (PeerNode peer, NodeObject.Lock lock)
{
// refuse to ratify if we believe someone else owns the lock
String owner = queryLock(lock);
if (owner != null) {
log.warning("Refusing to ratify lock acquisition.", "lock", lock,
"node", pee... | java |
protected void peerReleasingLock (PeerNode peer, NodeObject.Lock lock)
{
// refuse to ratify if we don't believe they own the lock
String owner = queryLock(lock);
if (!peer.getNodeName().equals(owner)) {
log.warning("Refusing to ratify lock release.", "lock", lock,
... | java |
protected void peerAddedLock (String nodeName, NodeObject.Lock lock)
{
// check for hijacking
if (_nodeobj.locks.contains(lock)) {
log.warning("Client hijacked lock owned by this node", "lock", lock, "node", nodeName);
droppedLock(lock);
}
// notify the handl... | java |
protected void peerUpdatedLock (String nodeName, NodeObject.Lock lock)
{
// notify the handler, if any
LockHandler handler = _locks.get(lock);
if (handler != null) {
handler.peerUpdatedLock(nodeName);
}
} | java |
protected byte[] flattenAction (NodeAction action)
{
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject(action);
return bout.toByteArray();
} catch (Exception e) {
... | java |
protected byte[] flattenRequest (NodeRequest request)
{
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject(request);
return bout.toByteArray();
} catch (Exception e) ... | java |
protected static String propertiesToString(Properties properties)
{
StringWriter stringWriter = new StringWriter();
String comments = Properties.class.getName();
try {
properties.store(stringWriter, comments);
}
catch (IOException e) {
throw new Runti... | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.