Convert Narya (most of the way) over to a Maven Ant task based build. The

ActionScript bits remain belligerent, but the Java stuff is mostly shipshape.


git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@6222 542714f4-19e9-0310-aa3c-eee0fc999fb1
This commit is contained in:
Michael Bayne
2010-10-22 21:12:29 +00:00
parent 555b865bbf
commit 9d2ca42eac
434 changed files with 163 additions and 208 deletions
@@ -0,0 +1,54 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation that controls ActionScript code generation.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD,
ElementType.METHOD, ElementType.TYPE})
public @interface ActionScript
{
/**
* Indicates whether this field, method or class should be omitted from the ActionScript
* translation.
*/
boolean omit () default false;
/**
* Indicates a custom name to be used for the ActionScript version of this field, method or
* class.
*/
String name () default "";
/**
* Indicates a custom type to be used for the ActionScript version of this field. Ignored if
* used on a method or class.
*/
String type () default "";
}
@@ -0,0 +1,129 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import com.google.common.base.Function;
import com.google.common.collect.ForwardingMap;
import com.google.common.collect.Maps;
/**
* Provides a map implementation that automatically creates, and inserts into the map, a default
* value for any value retrieved via the {@link #fetch} method which has no entry for that key.
*/
public class DefaultMap<K, V> extends ForwardingMap<K, V>
{
/**
* Creates a default map backed by a {@link HashMap} that creates instances of the supplied
* class (using its no-args constructor) as defaults.
*/
public static <K, V> DefaultMap<K, V> newInstanceHashMap (Class<V> clazz)
{
return newInstanceMap(Maps.<K, V>newHashMap(), clazz);
}
/**
* Creates a default map backed by the supplied map that creates instances of the supplied
* class (using its no-args constructor) as defaults.
*/
public static <K, V> DefaultMap<K, V> newInstanceMap (Map<K, V> delegate, Class<V> clazz)
{
Function<K, V> creator = newInstanceCreator(clazz);
return newMap(delegate, creator);
}
/**
* Returns a Function that makes instances of the supplied class (using its no-args
* constructor) as default values.
*/
public static <K, V> Function<K, V> newInstanceCreator (Class<V> clazz) {
final Constructor<V> ctor;
try {
ctor = clazz.getConstructor();
} catch (NoSuchMethodException nsme) {
throw new IllegalArgumentException(clazz + " must have a no-args constructor.");
}
return new Function<K, V>() {
public V apply (K key) {
try {
return ctor.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
/**
* Creates a default map backed by a {@link HashMap} using the supplied default creator.
*/
public static <K, V> DefaultMap<K, V> newHashMap (Function<K, V> creator)
{
return newMap(Maps.<K, V>newHashMap(), creator);
}
/**
* Creates a default map backed by the supplied map using the supplied default creator.
*/
public static <K, V> DefaultMap<K, V> newMap (Map<K, V> delegate, Function<K, V> creator)
{
return new DefaultMap<K, V>(delegate, creator);
}
/**
* Looks up the supplied key in the map, returning the value to which it is mapped. If the key
* has no mapping, a default value will be obtained for the requested key and placed into the
* map. The current and subsequent lookups will return that value.
*/
public V fetch (K key)
{
V value = get(key);
// null is a valid value, so we check containsKey() before creating a default
if (value == null && !containsKey(key)) {
put(key, value = _creator.apply(key));
}
return value;
}
/**
* Creates a default map backed by the supplied map using the supplied default creator.
*/
protected DefaultMap (Map<K, V> delegate, Function<K, V> creator)
{
_delegate = delegate;
_creator = creator;
}
@Override // from ForwardingMap
protected Map<K, V> delegate()
{
return _delegate;
}
protected final Map<K, V> _delegate;
protected final Function<K, V> _creator;
}
@@ -0,0 +1,413 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Enumeration;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import com.samskivert.text.MessageUtil;
import com.samskivert.util.StringUtil;
import static com.threerings.NaryaLog.log;
/**
* A message bundle provides an easy mechanism by which to obtain translated message strings from
* a resource bundle. It uses the {@link MessageFormat} class to substitute arguments into the
* translation strings. Message bundles would generally be obtained via the {@link MessageManager},
* but could be constructed individually if so desired.
*/
public class MessageBundle
{
/**
* Call this to "taint" any string that has been entered by an entity outside the application
* so that the translation code knows not to attempt to translate this string when doing
* recursive translations (see {@link #xlate}).
*/
public static String taint (Object text)
{
return MessageUtil.taint(text);
}
/**
* Composes a message key with a single argument. The message can subsequently be translated
* in a single call using {@link #xlate}.
*/
public static String compose (String key, Object arg)
{
return MessageUtil.compose(key, new Object[] { arg });
}
/**
* Composes a message key with an array of arguments. The message can subsequently be
* translated in a single call using {@link #xlate}.
*/
public static String compose (String key, Object... args)
{
return MessageUtil.compose(key, args);
}
/**
* Composes a message key with an array of arguments. The message can subsequently be
* translated in a single call using {@link #xlate}.
*/
public static String compose (String key, String... args)
{
return MessageUtil.compose(key, args);
}
/**
* A convenience method for calling {@link #compose(String,Object[])} with an array of
* arguments that will be automatically tainted (see {@link #taint}).
*/
public static String tcompose (String key, Object... args)
{
return MessageUtil.tcompose(key, args);
}
/**
* Required for backwards compatibility. Alas.
*/
public static String tcompose (String key, Object arg)
{
return MessageUtil.tcompose(key, new Object[] { arg });
}
/**
* Required for backwards compatibility. Alas.
*/
public static String tcompose (String key, Object arg1, Object arg2)
{
return MessageUtil.tcompose(key, new Object[] { arg1, arg2 });
}
/**
* A convenience method for calling {@link #compose(String,String[])} with an array of
* arguments that will be automatically tainted (see {@link #taint}).
*/
public static String tcompose (String key, String... args)
{
return MessageUtil.tcompose(key, args);
}
/**
* Returns a fully qualified message key which, when translated by some other bundle, will
* know to resolve and utilize the supplied bundle to translate this particular key.
*/
public static String qualify (String bundle, String key)
{
return MessageUtil.qualify(bundle, key);
}
/**
* Returns the bundle name from a fully qualified message key.
*
* @see #qualify
*/
public static String getBundle (String qualifiedKey)
{
return MessageUtil.getBundle(qualifiedKey);
}
/**
* Returns the unqualified portion of the key from a fully qualified message key.
*
* @see #qualify
*/
public static String getUnqualifiedKey (String qualifiedKey)
{
return MessageUtil.getUnqualifiedKey(qualifiedKey);
}
/**
* Initializes the message bundle which will obtain localized messages from the supplied
* resource bundle. The path is provided purely for reporting purposes.
*/
public void init (MessageManager msgmgr, String path,
ResourceBundle bundle, MessageBundle parent)
{
_msgmgr = msgmgr;
_path = path;
_bundle = bundle;
_parent = parent;
}
/**
* Obtains the translation for the specified message key. No arguments are substituted into
* the translated string. If a translation message does not exist for the specified key, an
* error is logged and the key itself is returned so that the caller need not worry about
* handling a null response.
*/
public String get (String key)
{
// if this string is tainted, we don't translate it, instead we
// simply remove the taint character and return it to the caller
if (MessageUtil.isTainted(key)) {
return MessageUtil.untaint(key);
}
String msg = getResourceString(key);
return (msg != null) ? msg : key;
}
/**
* Adds all messages whose key starts with the specified prefix to the supplied collection.
*
* @param includeParent if true, messages from our parent bundle (and its parent bundle, all
* the way up the chain will be included).
*/
public void getAll (String prefix, Collection<String> messages, boolean includeParent)
{
Enumeration<String> iter = _bundle.getKeys();
while (iter.hasMoreElements()) {
String key = iter.nextElement();
if (key.startsWith(prefix)) {
messages.add(get(key));
}
}
if (includeParent && _parent != null) {
_parent.getAll(prefix, messages, includeParent);
}
}
/**
* Adds all keys for messages whose key starts with the specified prefix to the supplied
* collection.
*
* @param includeParent if true, messages from our parent bundle (and its parent bundle, all
* the way up the chain will be included).
*/
public void getAllKeys (String prefix, Collection<String> keys, boolean includeParent)
{
Enumeration<String> iter = _bundle.getKeys();
while (iter.hasMoreElements()) {
String key = iter.nextElement();
if (key.startsWith(prefix)) {
keys.add(key);
}
}
if (includeParent && _parent != null) {
_parent.getAllKeys(prefix, keys, includeParent);
}
}
/**
* Returns true if we have a translation mapping for the supplied key, false if not.
*/
public boolean exists (String key)
{
return getResourceString(key, false) != null;
}
/**
* Get a String from the resource bundle, or null if there was an error.
*/
public String getResourceString (String key)
{
return getResourceString(key, true);
}
/**
* Get a String from the resource bundle, or null if there was an error.
*
* @param key the resource key.
* @param reportMissing whether or not the method should log an error if the resource didn't
* exist.
*/
public String getResourceString (String key, boolean reportMissing)
{
try {
if (_bundle != null) {
return _bundle.getString(key);
}
} catch (MissingResourceException mre) {
// fall through and try the parent
}
// if we have a parent, try getting the string from them
if (_parent != null) {
String value = _parent.getResourceString(key, false);
if (value != null) {
return value;
}
// if we didn't find it in our parent, we want to fall
// through and report missing appropriately
}
if (reportMissing) {
log.warning("Missing translation message", "bundle", _path, "key", key, new Exception());
}
return null;
}
/**
* Obtains the translation for the specified message key. The specified arguments are
* substituted into the translated string.
*
* <p> If the first argument in the array is an {@link Integer} object, a translation will be
* selected accounting for plurality in the following manner. Assume a message key of
* <code>m.widgets</code>, the following translations should be defined: <pre> m.widgets.0 =
* no widgets. m.widgets.1 = {0} widget. m.widgets.n = {0} widgets. </pre>
*
* The specified argument is substituted into the translated string as appropriate. Consider
* using:
*
* <pre> m.widgets.n = {0,number,integer} widgets. </pre>
*
* to obtain proper insertion of commas and dots as appropriate for the locale.
*
* <p> See {@link MessageFormat} for more information on how the substitution is performed. If
* a translation message does not exist for the specified key, an error is logged and the key
* itself (plus the arguments) is returned so that the caller need not worry about handling a
* null response.
*/
public String get (String key, Object... args)
{
// if this is a qualified key, we need to pass the buck to the
// appropriate message bundle
if (key.startsWith(MessageUtil.QUAL_PREFIX)) {
MessageBundle qbundle = _msgmgr.getBundle(getBundle(key));
return qbundle.get(getUnqualifiedKey(key), args);
}
// Select the proper suffix if our first argument can be coaxed into an integer
String suffix = getSuffix(args);
String msg = getResourceString(key + suffix, false);
if (msg == null) {
// Playing with fire: This only works because it's the same "" reference we return
// from getSuffix()
// Don't try this at home. Keep out of reach of children. If swallowed, consult
// StringUtil.isBlank()
if (suffix != "") {
// Try the original key
msg = getResourceString(key, false);
}
if (msg == null) {
log.warning("Missing translation message", "bundle", _path, "key", key,
new Exception());
// return something bogus
return (key + StringUtil.toString(args));
}
}
return MessageFormat.format(MessageUtil.escape(msg), args);
}
/**
* Obtains the translation for the specified message key. The specified arguments are
* substituted into the translated string.
*/
public String get (String key, String... args)
{
return get(key, (Object[]) args);
}
/**
* A helper function for {@link #get(String,Object[])} that allows us to automatically perform
* plurality processing if our first argument can be coaxed to an {@link Integer}.
*/
public String getSuffix (Object[] args)
{
if (args.length > 0 && args[0] != null) {
try {
int count = (args[0] instanceof Integer) ? (Integer)args[0] :
Integer.parseInt(args[0].toString());
switch (count) {
case 0: return ".0";
case 1: return ".1";
default: return ".n";
}
} catch (NumberFormatException e) {
// Fall out
}
}
return "";
}
/**
* Obtains the translation for the specified compound message key. A compound key contains the
* message key followed by a tab separated list of message arguments which will be substituted
* into the translation string.
*
* <p> See {@link MessageFormat} for more information on how the substitution is performed. If
* a translation message does not exist for the specified key, an error is logged and the key
* itself (plus the arguments) is returned so that the caller need not worry about handling a
* null response.
*/
public String xlate (String compoundKey)
{
// if this is a qualified key, we need to pass the buck to the appropriate message bundle;
// we have to do it here because we want the compound arguments of this key to be
// translated in the context of the containing message bundle qualification
if (compoundKey.startsWith(MessageUtil.QUAL_PREFIX)) {
MessageBundle qbundle = _msgmgr.getBundle(getBundle(compoundKey));
return qbundle.xlate(getUnqualifiedKey(compoundKey));
}
// to be more efficient about creating unnecessary objects, we
// do some checking before splitting
int tidx = compoundKey.indexOf('|');
if (tidx == -1) {
return get(compoundKey);
} else {
String key = compoundKey.substring(0, tidx);
String argstr = compoundKey.substring(tidx+1);
String[] args = StringUtil.split(argstr, "|");
// unescape and translate the arguments
for (int ii = 0; ii < args.length; ii++) {
// if the argument is tainted, do no further translation
// (it might contain |s or other fun stuff)
if (MessageUtil.isTainted(args[ii])) {
args[ii] = MessageUtil.unescape(MessageUtil.untaint(args[ii]));
} else {
args[ii] = xlate(MessageUtil.unescape(args[ii]));
}
}
return get(key, (Object[]) args);
}
}
@Override
public String toString ()
{
return "[bundle=" + _bundle + ", path=" + _path + "]";
}
/** The message manager via whom we'll resolve fully qualified translation strings. */
protected MessageManager _msgmgr;
/** The path that identifies the resource bundle we are using to obtain our messages. */
protected String _path;
/** The resource bundle from which we obtain our messages. */
protected ResourceBundle _bundle;
/** Our parent bundle if we're not the global bundle. */
protected MessageBundle _parent;
}
@@ -0,0 +1,228 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.util.HashMap;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import com.google.common.collect.Maps;
import com.samskivert.util.StringUtil;
import static com.threerings.NaryaLog.log;
/**
* The message manager provides a thin wrapper around Java's built-in localization support,
* supporting a policy of dividing up localization resources into logical units, all of the
* translations for which are contained in a single messages file.
*
* <p> The message manager assumes that the locale remains constant for the duration of its
* operation. If the locale were to change during the operation of the client, a call to
* {@link #setLocale} should be made to inform the message manager of the new locale (which will
* clear the message bundle cache).
*/
public class MessageManager
{
/**
* The name of the global resource bundle (which other bundles revert to if they can't locate
* a message within themselves). It must be named <code>global.properties</code> and live at
* the top of the bundle hierarchy.
*/
public static final String GLOBAL_BUNDLE = "global";
/**
* Constructs a message manager with the supplied resource prefix and the default locale. The
* prefix will be prepended to the path of all resource bundles prior to their resolution. For
* example, if a prefix of <code>rsrc.messages</code> was provided and a message bundle with
* the name <code>game.chess</code> was later requested, the message manager would attempt to
* load a resource bundle with the path <code>rsrc.messages.game.chess</code> and would
* eventually search for a file in the classpath with the path
* <code>rsrc/messages/game/chess.properties</code>.
*
* <p> See the documentation for {@link ResourceBundle#getBundle(String,Locale,ClassLoader)}
* for a more detailed explanation of how resource bundle paths are resolved.
*/
public MessageManager (String resourcePrefix)
{
// keep the prefix
_prefix = resourcePrefix;
// use the default locale
_locale = Locale.getDefault();
log.debug("Using locale: " + _locale + ".");
// make sure the prefix ends with a dot
if (!_prefix.endsWith(".")) {
_prefix += ".";
}
// load up the global bundle
_global = getBundle(GLOBAL_BUNDLE);
}
/**
* Get the locale that is being used to translate messages. This may be useful if using
* standard translations, for example new SimpleDateFormat("EEEE", getLocale()) to get the
* name of a weekday that matches the language being used for all other client translations.
*/
public Locale getLocale ()
{
return _locale;
}
/**
* Sets the locale to the specified locale. Subsequent message bundles fetched via the message
* manager will use the new locale. The message bundle cache will also be cleared.
*/
public void setLocale (Locale locale)
{
_locale = locale;
_cache.clear();
}
/**
* Sets the appropriate resource prefix for where to find subsequent message bundles.
*/
public void setPrefix (String resourcePrefix)
{
_prefix = resourcePrefix;
// Need to reget the global bundle at the new prefix location.
_global = getBundle(GLOBAL_BUNDLE);
}
/**
* Allows a custom classloader to be configured for locating translation resources.
*/
public void setClassLoader (ClassLoader loader)
{
_loader = loader;
}
/**
* Fetches the message bundle for the specified path. If no bundle can be located with the
* specified path, a special bundle is returned that returns the untranslated message
* identifiers instead of an associated translation. This is done so that error code to handle
* a failed bundle load need not be replicated wherever bundles are used. Instead an error
* will be logged and the requesting service can continue to function in an impaired state.
*/
public MessageBundle getBundle (String path)
{
// first look in the cache
MessageBundle bundle = _cache.get(path);
if (bundle != null) {
return bundle;
}
// if it's not cached, we'll need to resolve it
ResourceBundle rbundle = loadBundle(_prefix + path);
// if the resource bundle contains a special resource, we'll interpret that as a derivation
// of MessageBundle to instantiate for handling that class
MessageBundle customBundle = null;
if (rbundle != null) {
String mbclass = null;
try {
mbclass = rbundle.getString(MBUNDLE_CLASS_KEY).trim();
if (!StringUtil.isBlank(mbclass)) {
customBundle = (MessageBundle)Class.forName(mbclass).newInstance();
}
} catch (MissingResourceException mre) {
// nothing to worry about
} catch (Throwable t) {
log.warning("Failure instantiating custom message bundle", "mbclass", mbclass,
"error", t);
}
}
// initialize our message bundle, cache it and return it (if we couldn't resolve the
// bundle, the message bundle will cope with its null resource bundle)
bundle = createBundle(path, rbundle, customBundle);
_cache.put(path, bundle);
return bundle;
}
/**
* Returns the bundle to use for the given path and resource bundle. If customBundle is
* non-null, it's an instance of the bundle class specified by the bundle itself and should be
* used as part of the created bundle.
*/
protected MessageBundle createBundle (String path, ResourceBundle rbundle,
MessageBundle customBundle)
{
// if there was no custom class, or we failed to instantiate the custom class, use a
// standard message bundle
if (customBundle == null) {
customBundle = new MessageBundle();
}
initBundle(customBundle, path, rbundle);
return customBundle;
}
/**
* Initializes the given bundle with this manager and the given path and resource bundle.
*/
protected void initBundle (MessageBundle bundle, String path, ResourceBundle rbundle)
{
bundle.init(this, path, rbundle, _global);
}
/**
* Loads a bundle from the given path, or returns null if it can't be found.
*/
protected ResourceBundle loadBundle (String path)
{
try {
if (_loader != null) {
return ResourceBundle.getBundle(path, _locale, _loader);
}
return ResourceBundle.getBundle(path, _locale);
} catch (MissingResourceException mre) {
log.warning("Unable to resolve resource bundle", "path", path, "locale", _locale,
mre);
return null;
}
}
/** The prefix we prepend to resource paths prior to loading. */
protected String _prefix;
/** The locale for which we're obtaining message bundles. */
protected Locale _locale;
/** A custom class loader that we use to load resource bundles. */
protected ClassLoader _loader;
/** A cache of instantiated message bundles. */
protected HashMap<String, MessageBundle> _cache = Maps.newHashMap();
/** Our top-level message bundle, from which others obtain messages if
* they can't find them within themselves. */
protected MessageBundle _global;
/** A key that can contain the classname of a custom message bundle
* class to be used to handle messages for a particular bundle. */
protected static final String MBUNDLE_CLASS_KEY = "msgbundle_class";
}
@@ -0,0 +1,338 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.util.Map;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.samskivert.util.StringUtil;
import static com.threerings.NaryaLog.log;
/**
* Records the times that it takes to call methods. Allows one simultaneous method call per thread
* (no nested calls). Uses java's nano second timer. Results are logged by method name.
*/
public class MethodProfiler
{
/**
* The results of sampling for a single method.
*/
public static class Result
{
/**
* Creates a new result with the given values.
*/
Result (int numSamples, double average, double stdDev)
{
this.numSamples = numSamples;
this.averageTime = average;
this.standardDeviation = stdDev;
}
/** Number of method calls sampled. */
public final int numSamples;
/** Average time spent in the method. */
public final double averageTime;
/** Standard deviation from the average. */
public final double standardDeviation;
// from Object
@Override
public String toString ()
{
return StringUtil.fieldsToString(this);
}
}
/**
* Runs some very basic tests of the method profiler.
*/
public static void main (String args[])
throws InterruptedException
{
int testNum = 0;
if (args.length > 0) {
testNum = Integer.parseInt(args[0]);
}
switch (testNum) {
case 0: // rum some rpc threads
MethodProfiler test = new MethodProfiler();
Thread t1 = test.new TestThread("testm1", 100, 50);
Thread t2 = test.new TestThread("testm2", 100, 50);
t1.start();
t2.start();
t1.join();
t2.join();
for (Map.Entry<String, Result> method : test.getResults().entrySet()) {
log.info(method.getKey(), "result", method.getValue());
}
break;
case 1:
simpleSampleTest("Single", 100);
break;
case 2:
simpleSampleTest("Triple", 100, 0, 200);
break;
case 3:
simpleSampleTest("Multi", 0, 25, 50, 100, 125, 150, 175, 200, 112.5, 112.5, 112.5);
break;
case 4:
MethodProfiler test4 = new MethodProfiler();
test4.enter("L1a");
test4.enter("L2a");
test4.swap("L2b");
test4.enter("L3a");
test4.exit(null);
test4.exit(null);
test4.swap("L1b");
test4.swap("L1c");
test4.exit(null);
for (Map.Entry<String, Result> result : test4.getResults().entrySet()) {
log.info("Results", "name", result.getKey(), "value", result.getValue());
}
break;
}
}
/**
* Gets all method results so far.
*/
public Map<String, Result> getResults ()
{
Map<String, Result> results = Maps.newHashMapWithExpectedSize(_profiles.size());
for (Map.Entry<String, RunningStats> entry : _profiles.entrySet()) {
synchronized (entry.getValue()) {
results.put(entry.getKey(), toResult(entry.getValue()));
}
}
return results;
}
/**
* Notes that the calling thread has entered the given method and records the time stamp.
*/
public void enter (String methodName)
{
Method method = _stack.get().push();
method.name = methodName;
method.entryTime = System.nanoTime();
}
/**
* Notes that the calling thread has exited the given method and records the time delta since
* entry. The method parameter is not strictly necessary but allows some error checking. If not
* null, it must match the most recent value given to {@link #enter} for the calling thread.
*/
public void exit (String methodName)
{
long nanos = System.nanoTime();
Method method = _stack.get().pop();
if (method == null || (methodName != null && !methodName.equals(method.name))) {
// TODO: warn, but only once
return;
}
long elapsed = nanos - method.entryTime;
recordTime(method.fullName(), (double)elapsed / 1000000);
method.name = null;
// Clear the ThreadLocal after we've profiled our whole stack to prevent our class loader
// from hanging around
if (_stack.get().size() == 0) {
_stack.remove();
}
}
/**
* Transition to a new method or segment. Exits the current one and enters the given one.
*/
public void swap (String methodName)
{
exit(null);
enter(methodName);
}
/**
* Clears out the profile for the current thread, and invokes the exit of the top-level method.
* This allows callers to use one try... finally block in their top-level method without skewing
* the results for nested methods that may have thrown exceptions and/or not called
* {@link #exit}.
*/
public void exitAndClear (String methodName)
{
Stack stack = _stack.get();
while (stack.size() > 1) {
stack.pop();
}
if (stack.size() > 0) {
exit(methodName);
}
}
/**
* Clears all recorded methods and times.
*/
public void reset ()
{
_profiles.clear();
}
/**
* Adds a sample to our profile of the given method.
*/
protected void recordTime (String method, double elapsedMs)
{
RunningStats stats = _profiles.get(method);
synchronized (stats) {
stats.addSample(elapsedMs);
}
}
/**
* For testing, just calls the {@link #enter} and {@link #exit} methods at a fixed interval
* for a given number of times.
*/
protected class TestThread extends Thread
{
public TestThread (String method, int methodCount, long sleep)
{
_method = method;
_methodCount = methodCount;
_sleep = sleep;
}
// from Runnable
@Override public void run ()
{
try {
for (int ii = 0; ii < _methodCount; ++ii) {
MethodProfiler.this.enter(_method);
Thread.sleep(_sleep);
MethodProfiler.this.exit(_method);
}
} catch (InterruptedException ie) {
}
}
protected int _methodCount;
protected String _method;
protected long _sleep;
}
/**
* Describes what we know about an in-progress method call.
*/
protected static class Method
{
/** The name of the entered method. */
public String name;
/** The time the method was entered. */
public long entryTime;
/** The parent of the method. */
public Method caller;
/**
* Gets this method's name, prefixed with all parent method names separated by dots.
*/
public String fullName ()
{
if (caller != null) {
return caller.fullName() + "." + name;
}
return name;
}
}
/**
* Describes what we know about a nested set of in progress method calls. This is a fake stack
* that avoid reallocating entries, i.e. pop() == push() and push() == pop().
*/
protected static class Stack
{
public Method push ()
{
if (_size == _methods.length) {
Method []realloc = new Method[_size + 1];
System.arraycopy(_methods, 0, realloc, 0, _size);
_methods = realloc;
_methods[_size] = new Method();
}
_methods[_size].name = null;
_methods[_size].caller = _size > 0 ? _methods[_size - 1] : null;
return _methods[_size++];
}
public Method pop ()
{
if (_size == 0) {
return null;
}
return _methods[--_size];
}
public int size ()
{
return _size;
}
protected int _size;
protected Method[] _methods = {new Method()};
}
/**
* Runs the method profile stat collection with the given samples and logs the result.
*/
protected static void simpleSampleTest (String name, double... samples)
{
RunningStats stats = new RunningStats();
for (double sample : samples) {
stats.addSample(sample);
}
log.info(name, "results", toResult(stats));
}
/**
* Calculates the results of the the profile.
*/
protected static Result toResult (RunningStats stats)
{
return new Result(stats.getNumSamples(), stats.getMean(), stats.getStandardDeviation());
}
/** Set of active methods in the current thread. */
protected ThreadLocal<Stack> _stack = new ThreadLocal<Stack>() {
@Override protected Stack initialValue () {
return new Stack();
}
};
/** Stats by method name. */
protected final Map<String, RunningStats> _profiles =
new MapMaker().makeComputingMap(DefaultMap.newInstanceCreator(RunningStats.class));
}
+161
View File
@@ -0,0 +1,161 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import com.threerings.io.SimpleStreamableObject;
/**
* Contains the name of an entity. Provides a means by which names can be
* efficiently loosely compared rather than relying on humans to type
* things exactly or the challenge of inserting code to normalize names
* everywhere they are compared.
*/
public class Name extends SimpleStreamableObject
implements Comparable<Name>
{
/** A blank name for use in situations where it is needed.
* <em>Note:</em> because names are used in distributed applications
* you cannot assume that a reference check against blank is
* sufficient. You must use <code>BLANK.equals(targetName)</code>. */
public static final Name BLANK = new Name("");
/**
* Returns true if this name is null or blank, false if it contains
* useful data. This works on derived classes as well.
*/
public static boolean isBlank (Name name)
{
return (name == null || name.toString().equals(BLANK.toString()));
}
/** Creates a blank instance for unserialization. */
public Name ()
{
}
/**
* Creates a name instance with the supplied name.
*/
public Name (String name)
{
_name = (name == null) ? "" : name;
}
/**
* Returns the normalized version of this name.
*/
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;
}
/**
* Returns true if this name is valid. Derived classes can provide
* more interesting requirements for name validity than the default
* which is that it is non-blank.
*/
public boolean isValid ()
{
return !isBlank();
}
/**
* Returns true if this name is blank, false if it contains data.
*/
public boolean isBlank ()
{
return isBlank(this);
}
/**
* Returns the unprocessed name as a string.
*/
@Override
public String toString ()
{
return _name;
}
@Override
public int hashCode ()
{
return getNormal().hashCode();
}
@Override
public boolean equals (Object other)
{
if (other != null) {
Class<?> c = getClass();
Class<?> oc = other.getClass();
// we have to be of the same derived class but we don't want to
// wig out if the classes were loaded from different class loaders
if (c == oc || c.getName().equals(oc.getName())) {
return getNormal().equals(((Name)other).getNormal());
}
}
return false;
}
// from interface Comparable<Name>
public int compareTo (Name other)
{
Class<?> c = getClass();
Class<?> oc = other.getClass();
if (c == oc || c.getName().equals(oc.getName())) {
return getNormal().compareTo(other.getNormal());
} else {
return c.getName().compareTo(oc.getName());
}
}
/**
* Returns a normalized version of the supplied name. The default
* implementation is case and space insensitive.
*/
protected String normalize (String name)
{
name = name.toLowerCase();
// Originally we removed whitespace as part of normalization, but
// that ran aground when a player was named "Badbob" and an npp
// was named "Bad Bob". -RG
//name = _compactor.matcher(name).replaceAll("");
return name;
}
/** The raw name text. */
protected String _name;
/** The normalized name text. */
protected transient String _normal;
/** Used to strip spaces from names. */
//protected static Pattern _compactor = Pattern.compile("\\s");
}
@@ -0,0 +1,153 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
/**
* Maintained for backwards compatibility with old Game Gardens games.
*
* @deprecated moved to {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public class RandomUtil
{
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static int getInt (int high)
{
return com.samskivert.util.RandomUtil.getInt(high);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static int getInt (int high, int low)
{
return com.samskivert.util.RandomUtil.getInt(high, low);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static float getFloat (float high)
{
return com.samskivert.util.RandomUtil.getFloat(high);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static int getWeightedIndex (int[] weights)
{
return com.samskivert.util.RandomUtil.getWeightedIndex(weights);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static int getWeightedIndex (float[] weights)
{
return com.samskivert.util.RandomUtil.getWeightedIndex(weights);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static <T> T pickRandom (T[] values)
{
return com.samskivert.util.RandomUtil.pickRandom(values);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static <T> T pickRandom (T[] values, T skip)
{
return com.samskivert.util.RandomUtil.pickRandom(values, skip);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static <T> T pickRandom (Collection<T> values)
{
return com.samskivert.util.RandomUtil.pickRandom(values);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static <T> T pickRandom (List<T> values)
{
return com.samskivert.util.RandomUtil.pickRandom(values);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static <T> T pickRandom (List<T> values, T skip)
{
return com.samskivert.util.RandomUtil.pickRandom(values, skip);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static <T> T pickRandom (List<T> values, T skip, Random r)
{
return com.samskivert.util.RandomUtil.pickRandom(values, skip, r);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static <T> T pickRandom (Iterator<T> iter, int count)
{
return com.samskivert.util.RandomUtil.pickRandom(iter, count);
}
/**
* @deprecated use {@link com.samskivert.util.RandomUtil}.
*/
@Deprecated
public static <T> T pickRandom (Iterator<T> iter, int count, T skip)
{
return com.samskivert.util.RandomUtil.pickRandom(iter, count, skip);
}
}
@@ -0,0 +1,94 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
/**
* Calculates live values for the mean, variance and standard deviation of a set of samples.
* <em>Not thread safe!</em>
*/
public class RunningStats
{
/**
* Adds a new sample.
*/
public void addSample (double sample)
{
// From http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm
_numSamples++;
double deltaToOld = sample - _mean;
_mean += deltaToOld / _numSamples;
double deltaToNew = sample - _mean;
_varianceSum += deltaToOld * deltaToNew;
if (sample < _min) {
_min = sample;
}
if (sample > _max) {
_max = sample;
}
}
/**
* Returns the minimum sample added or {@link Double#POSITIVE_INFINITY} if no samples have
* been added.
*/
public double getMin ()
{
return _min;
}
/**
* Returns the maximum sample added or {@link Double#NEGATIVE_INFINITY} if no samples have
* been added.
*/
public double getMax ()
{
return _max;
}
public double getVariance ()
{
if (getNumSamples() == 0) {
return 0;
}
return _varianceSum / getNumSamples();
}
public int getNumSamples ()
{
return _numSamples;
}
public double getMean ()
{
return _mean;
}
public double getStandardDeviation ()
{
return Math.sqrt(getVariance());
}
protected int _numSamples;
protected double _mean;
protected double _varianceSum;
protected double _max = Double.NEGATIVE_INFINITY, _min = Double.POSITIVE_INFINITY;
}
@@ -0,0 +1,80 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.io.IOException;
import com.samskivert.util.ArrayIntSet;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
/**
* A {@link ArrayIntSet} extension that can be streamed.
*/
public class StreamableArrayIntSet extends ArrayIntSet
implements Streamable
{
// documentation inherited
public StreamableArrayIntSet (int[] values)
{
super(values);
}
// documentation inherited
public StreamableArrayIntSet (int initialCapacity)
{
super(initialCapacity);
}
// documentation inherited
public StreamableArrayIntSet ()
{
super();
}
/**
* Writes our custom streamable fields.
*/
public void writeObject (ObjectOutputStream out)
throws IOException
{
out.writeInt(_size);
for (int ii = 0; ii < _size; ii++) {
out.writeInt(_values[ii]);
}
}
/**
* Reads our custom streamable fields.
*/
public void readObject (ObjectInputStream in)
throws IOException, ClassNotFoundException
{
_size = in.readInt();
_values = new int[Math.max(_size, DEFAULT_CAPACITY)];
for (int ii = 0; ii < _size; ii++) {
_values[ii] = in.readInt();
}
}
}
@@ -0,0 +1,79 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.util.ArrayList;
import java.io.IOException;
import com.samskivert.annotation.ReplacedBy;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
/**
* An {@link ArrayList} extension that can be streamed. The contents of the list must also be of
* streamable types.
*
* @see Streamable
* @param <E> the type of elements stored in this list.
*/
@ReplacedBy("java.util.List")
public class StreamableArrayList<E> extends ArrayList<E>
implements Streamable
{
/**
* Creates an empty StreamableArrayList.
*/
public static <E> StreamableArrayList<E> newList ()
{
return new StreamableArrayList<E>();
}
/**
* Writes our custom streamable fields.
*/
public void writeObject (ObjectOutputStream out)
throws IOException
{
int ecount = size();
out.writeInt(ecount);
for (int ii = 0; ii < ecount; ii++) {
out.writeObject(get(ii));
}
}
/**
* Reads our custom streamable fields.
*/
public void readObject (ObjectInputStream in)
throws IOException, ClassNotFoundException
{
int ecount = in.readInt();
ensureCapacity(ecount);
for (int ii = 0; ii < ecount; ii++) {
@SuppressWarnings("unchecked") E elem = (E)in.readObject();
add(elem);
}
}
}
@@ -0,0 +1,323 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.EnumSet;
import java.util.Iterator;
import java.io.IOException;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
/**
* An {@link EnumSet} equivalent (not a subclass, because EnumSet's implementation is private)
* that can be streamed.
*
* @see Streamable
* @param <E> the type of enum being stored in this set.
*/
public class StreamableEnumSet<E extends Enum<E>> extends AbstractSet<E>
implements Cloneable, Streamable
{
/**
* Creates an empty set of the specified type.
*/
public static <E extends Enum<E>> StreamableEnumSet<E> noneOf (Class<E> elementType)
{
return new StreamableEnumSet<E>(elementType);
}
/**
* Creates a set containing all elements of the specified type.
*/
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;
}
/**
* Creates a set containing all elements in the collection provided (which must have at least
* one element, unless it is a <code>StreamableEnumSet</code>).
*/
public static <E extends Enum<E>> StreamableEnumSet<E> copyOf (Collection<E> s)
{
if (s instanceof StreamableEnumSet<?>) {
StreamableEnumSet<E> set = (StreamableEnumSet<E>)s;
return copyOf(set);
}
if (s.isEmpty()) {
throw new IllegalArgumentException("Collection must have at least one element.");
}
StreamableEnumSet<E> set = new StreamableEnumSet<E>(
s.iterator().next().getDeclaringClass());
set.addAll(s);
return set;
}
/**
* Creates a set containing all elements in the set provided.
*/
public static <E extends Enum<E>> StreamableEnumSet<E> copyOf (StreamableEnumSet<E> s)
{
return s.clone();
}
/**
* Creates a set containing all elements <em>not</em> in the set provided.
*/
public static <E extends Enum<E>> StreamableEnumSet<E> complementOf (StreamableEnumSet<E> s)
{
Class<E> elementType = s._elementType;
StreamableEnumSet<E> set = new StreamableEnumSet<E>(elementType);
for (E constant : elementType.getEnumConstants()) {
if (!s.contains(constant)) {
set.add(constant);
}
}
return set;
}
/**
* Creates a set consisting of the specified elements.
*/
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;
}
/**
* Creates a set that includes all enum constants in the specified (inclusive) range.
*/
public static <E extends Enum<E>> StreamableEnumSet<E> range (E from, E to)
{
Class<E> elementType = from.getDeclaringClass();
StreamableEnumSet<E> set = new StreamableEnumSet<E>(elementType);
E[] constants = elementType.getEnumConstants();
for (int ii = from.ordinal(), last = to.ordinal(); ii <= last; ii++) {
set.add(constants[ii]);
}
return set;
}
/**
* Creates a new, empty enum set for storing elements of the specified class.
*/
public StreamableEnumSet (Class<E> elementType)
{
_elementType = elementType;
initContents();
}
/**
* No-arg constructor for deserialization.
*/
public StreamableEnumSet ()
{
}
@Override
public Iterator<E> iterator ()
{
return new Iterator<E>() {
public boolean hasNext () {
checkConcurrentModification();
return _count < _size;
}
public E next () {
checkConcurrentModification();
do {
_idx += (++_bit >> 3);
_bit &= 0x07;
} while ((_contents[_idx] & (1 << _bit)) == 0);
_count++;
return _elementType.getEnumConstants()[(_idx << 3) | _bit];
}
public void remove () {
checkConcurrentModification();
_contents[_idx] &= ~(1 << _bit);
_size--;
_count--;
_omodcount = ++_modcount;
}
protected void checkConcurrentModification () {
if (_modcount != _omodcount) {
throw new ConcurrentModificationException();
}
}
protected int _idx, _bit = -1;
protected int _count;
protected int _omodcount = _modcount;
};
}
@Override
public int size ()
{
return _size;
}
@Override
public boolean contains (Object o)
{
if (!_elementType.isInstance(o)) {
return false;
}
int ordinal = ((Enum<?>)o).ordinal();
int idx = ordinal >> 3, mask = 1 << (ordinal & 0x07);
return (_contents[idx] & mask) != 0;
}
@Override
public boolean add (E o)
{
int ordinal = _elementType.cast(o).ordinal();
int idx = ordinal >> 3, mask = 1 << (ordinal & 0x07);
if ((_contents[idx] & mask) == 0) {
_contents[idx] |= mask;
_size++;
_modcount++;
return true;
}
return false;
}
@Override
public boolean remove (Object o)
{
if (!_elementType.isInstance(o)) {
return false;
}
int ordinal = ((Enum<?>)o).ordinal();
int idx = ordinal >> 3, mask = 1 << (ordinal & 0x07);
if ((_contents[idx] & mask) != 0) {
_contents[idx] &= ~mask;
_size--;
_modcount++;
return true;
}
return false;
}
@Override
public void clear ()
{
Arrays.fill(_contents, (byte)0);
_size = 0;
_modcount++;
}
@Override
public StreamableEnumSet<E> clone ()
{
try {
// make a deep clone of the contents
@SuppressWarnings("unchecked")
StreamableEnumSet<E> cset = (StreamableEnumSet<E>)super.clone();
cset._contents = _contents.clone();
return cset;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e); // won't happen
}
}
/**
* Writes our custom streamable fields.
*/
public void writeObject (ObjectOutputStream out)
throws IOException
{
if (!classDefinesElementType()) {
out.writeUTF(_elementType.getName());
}
out.write(_contents);
}
/**
* Reads our custom streamable fields.
*/
public void readObject (ObjectInputStream in)
throws IOException, ClassNotFoundException
{
if (!classDefinesElementType()) {
@SuppressWarnings("unchecked") Class<E> elementType =
(Class<E>)Class.forName(in.readUTF());
_elementType = elementType;
} else if (_elementType == null) {
throw new RuntimeException("No element type defined in constructor.");
}
initContents();
in.read(_contents);
// count set bits to initialize size
for (byte b : _contents) {
_size += Integer.bitCount(b & 0xFF);
}
}
/**
* Subclasses that only store elements of a single enum type (initialized in their no-arg
* constructors) can return <code>true</code> here to avoid the overhead of streaming the
* enum type for each instance.
*/
protected boolean classDefinesElementType ()
{
return false;
}
/**
* Creates the contents array.
*/
protected void initContents ()
{
int constants = _elementType.getEnumConstants().length;
_contents = new byte[(constants >> 3) + ((constants & 0x07) == 0 ? 0 : 1)];
}
/** The element type. */
protected Class<E> _elementType;
/** A byte array with bits set for each element in the set. */
protected byte[] _contents;
/** The number of elements in the set. */
protected int _size;
/** The modification count (used to detect concurrent modifications). */
protected int _modcount;
}
@@ -0,0 +1,86 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.io.IOException;
import com.samskivert.util.HashIntMap;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
/**
* A {@link HashIntMap} extension that can be streamed. The keys and values in the map must also
* be of streamable types.
*
* @see Streamable
* @param <V> the type of value stored in this map.
*/
public class StreamableHashIntMap<V> extends HashIntMap<V>
implements Streamable
{
/**
* Constructs an empty hash int map with the specified number of hash buckets.
*/
public StreamableHashIntMap (int buckets, float loadFactor)
{
super(buckets, loadFactor);
}
/**
* Constructs an empty hash int map with the default number of hash buckets.
*/
public StreamableHashIntMap ()
{
super();
}
/**
* Writes our custom streamable fields.
*/
public void writeObject (ObjectOutputStream out)
throws IOException
{
int ecount = size();
out.writeInt(ecount);
for (IntEntry<V> entry : intEntrySet()) {
out.writeInt(entry.getIntKey());
out.writeObject(entry.getValue());
}
}
/**
* Reads our custom streamable fields.
*/
public void readObject (ObjectInputStream in)
throws IOException, ClassNotFoundException
{
int ecount = in.readInt();
ensureCapacity(ecount);
for (int ii = 0; ii < ecount; ii++) {
int key = in.readInt();
@SuppressWarnings("unchecked") V value = (V)in.readObject();
put(key, value);
}
}
}
@@ -0,0 +1,115 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.util.HashMap;
import java.util.Map;
import java.io.IOException;
import com.samskivert.annotation.ReplacedBy;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
/**
* A {@link HashMap} extension that can be streamed. The keys and values in the map must also be
* of streamable types.
*
* @see Streamable
* @param <K> the type of key stored in this map.
* @param <V> the type of value stored in this map.
*/
@ReplacedBy("java.util.Map")
public class StreamableHashMap<K, V> extends HashMap<K, V>
implements Streamable
{
/**
* Creates an empty StreamableHashMap.
*/
public static <K, V> StreamableHashMap<K, V> newMap ()
{
return new StreamableHashMap<K, V>();
}
/**
* Creates StreamableHashMap populated with the same values as the provided Map.
*/
public static <K, V> StreamableHashMap<K, V> newMap (Map<? extends K, ? extends V> map)
{
return new StreamableHashMap<K, V>(map);
}
/**
* Constructs an empty hash map with the specified number of hash buckets.
*/
public StreamableHashMap (int buckets, float loadFactor)
{
super(buckets, loadFactor);
}
/**
* Constructs an empty hash map with the default number of hash buckets.
*/
public StreamableHashMap ()
{
super();
}
/**
* Constructs a hash map with the default number of hash buckets, populated with the same
* values as the provided Map.
*/
public StreamableHashMap (Map<? extends K, ? extends V> map)
{
super(map);
}
/**
* Writes our custom streamable fields.
*/
public void writeObject (ObjectOutputStream out)
throws IOException
{
int ecount = size();
out.writeInt(ecount);
for (Map.Entry<K, V> entry : entrySet()) {
out.writeObject(entry.getKey());
out.writeObject(entry.getValue());
}
}
/**
* Reads our custom streamable fields.
*/
public void readObject (ObjectInputStream in)
throws IOException, ClassNotFoundException
{
int ecount = in.readInt();
for (int ii = 0; ii < ecount; ii++) {
@SuppressWarnings("unchecked") K key = (K)in.readObject();
@SuppressWarnings("unchecked") V value = (V)in.readObject();
put(key, value);
}
}
}
@@ -0,0 +1,90 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.util.HashSet;
import java.io.IOException;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
/**
* A {@link HashSet} extension that can be streamed. The values in the set must also be of
* streamable types.
*
* @see Streamable
* @param <E> the type of element stored in this set.
*/
public class StreamableHashSet<E> extends HashSet<E>
implements Streamable
{
/**
* Creates an empty StreamableHashSet with the default number of hash buckets.
*/
public static <E> StreamableHashSet<E> newSet ()
{
return new StreamableHashSet<E>();
}
/**
* Constructs an empty hash set with the specified number of hash buckets.
*/
public StreamableHashSet (int buckets, float loadFactor)
{
super(buckets, loadFactor);
}
/**
* Constructs an empty hash set with the default number of hash buckets.
*/
public StreamableHashSet ()
{
super();
}
/**
* Writes our custom streamable fields.
*/
public void writeObject (ObjectOutputStream out)
throws IOException
{
out.writeInt(size());
for (E value : this) {
out.writeObject(value);
}
}
/**
* Reads our custom streamable fields.
*/
public void readObject (ObjectInputStream in)
throws IOException, ClassNotFoundException
{
int ecount = in.readInt();
for (int ii = 0; ii < ecount; ii++) {
@SuppressWarnings("unchecked") E value = (E)in.readObject();
add(value);
}
}
}
@@ -0,0 +1,86 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.io.IOException;
import com.samskivert.util.IntIntMap;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
/**
* A {@link IntIntMap} extension that can be streamed. The keys and
* values in the map must also be of streamable types.
*
* @see Streamable
*/
public class StreamableIntIntMap extends IntIntMap
implements Streamable
{
/**
* Constructs an empty int int map with the specified number of
* buckets.
*/
public StreamableIntIntMap (int buckets)
{
super(buckets);
}
/**
* Constructs an empty hash int map with the default number of hash
* buckets.
*/
public StreamableIntIntMap ()
{
super();
}
/**
* Writes our custom streamable fields.
*/
public void writeObject (ObjectOutputStream out)
throws IOException
{
int ecount = size();
out.writeInt(ecount);
for (IntIntEntry entry : entrySet()) {
out.writeInt(entry.getIntKey());
out.writeInt(entry.getIntValue());
}
}
/**
* Reads our custom streamable fields.
*/
public void readObject (ObjectInputStream in)
throws IOException, ClassNotFoundException
{
int ecount = in.readInt();
ensureCapacity(ecount);
for (int ii = 0; ii < ecount; ii++) {
int key = in.readInt();
put(key, in.readInt());
}
}
}
@@ -0,0 +1,50 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.awt.Point;
import com.threerings.io.Streamable;
/**
* A point that can be sent over the network.
*/
public class StreamablePoint extends Point
implements Streamable
{
// Some handy constructors
public StreamablePoint ()
{
super();
}
public StreamablePoint (int x, int y)
{
super(x, y);
}
public StreamablePoint (Point p)
{
super(p);
}
}
@@ -0,0 +1,56 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.awt.Rectangle;
import com.threerings.io.Streamable;
/**
* A {@link Rectangle} extension that can be streamed.
*/
public class StreamableRectangle extends Rectangle
implements Streamable
{
/**
* Creates a rectangle with the specified coordinates.
*/
public StreamableRectangle (int x, int y, int width, int height)
{
super(x, y, width, height);
}
/**
* Copy constructor.
*/
public StreamableRectangle (Rectangle rect)
{
super(rect);
}
/**
* No-arg constructor for deserialization.
*/
public StreamableRectangle ()
{
}
}
@@ -0,0 +1,62 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import com.samskivert.util.Tuple;
import com.threerings.io.Streamable;
/**
* A {@link Tuple} extension that can be streamed. The contents of the tuple
* must also be of streamable types.
*
* @see Streamable
* @param <L> the type of the left-hand side of this tuple.
* @param <R> the type of the right-hand side of this tuple.
*/
public class StreamableTuple<L, R> extends Tuple<L, R>
implements Streamable
{
/**
* Creates a tuple with the specified two objects.
*/
public static <L, R> StreamableTuple<L, R> newTuple (L left, R right)
{
return new StreamableTuple<L, R>(left, right);
}
/**
* Constructs a tuple with the two specified objects.
*/
public StreamableTuple (L left, R right)
{
super(left, right);
}
/**
* Don't use this constructor! It's only for unstreaming.
*/
public StreamableTuple ()
{
super(null, null);
}
}
@@ -0,0 +1,186 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util;
import java.util.ArrayList;
import com.google.common.collect.Lists;
/**
* Utility for times.
*/
public class TimeUtil
{
/** Time unit constant. */
public static final byte MILLISECOND = 0;
/** Time unit constant. */
public static final byte SECOND = 1;
/** Time unit constant. */
public static final byte MINUTE = 2;
/** Time unit constant. */
public static final byte HOUR = 3;
/** Time unit constant. */
public static final byte DAY = 4;
// TODO: Weeks?, months?
protected static final byte MAX_UNIT = DAY;
/**
* Returns (in seconds) the time elapsed between the supplied start and end timestamps (which
* must be in milliseconds). Partial seconds are truncated, not rounded.
*/
public static int elapsedSeconds (long startStamp, long endStamp)
{
if (endStamp < startStamp) {
throw new IllegalArgumentException("End time must be after start time " +
"[start=" + startStamp + ", end=" + endStamp + "]");
}
return (int)((endStamp - startStamp)/1000L);
}
/**
* Get a translatable string specifying the magnitude of the specified duration. Results will
* be between "1 second" and "X hours", with all times rounded to the nearest unit. "0 units"
* will never be displayed, the minimum is 1.
*/
public static String getTimeOrderString (long duration, byte minUnit)
{
return getTimeOrderString(duration, minUnit, MAX_UNIT);
}
/**
* Get a translatable string specifying the magnitude of the specified duration, with the units
* of time bounded between the minimum and maximum specified. "0 units" will never be returned,
* the minimum is 1.
*/
public static String getTimeOrderString (long duration, byte minUnit, byte maxUnit)
{
// enforce sanity
minUnit = (byte) Math.min(minUnit, maxUnit);
maxUnit = (byte) Math.min(maxUnit, MAX_UNIT);
for (byte uu = MILLISECOND; uu <= MAX_UNIT; uu++) {
int quantity = getQuantityPerUnit(uu);
if ((minUnit <= uu) && (duration < quantity || maxUnit == uu)) {
duration = Math.max(1, duration);
return MessageBundle.tcompose(getTransKey(uu), String.valueOf(duration));
}
duration = Math.round(duration / quantity);
}
// will not happen, because eventually gg will be MAX_UNIT
Thread.dumpStack();
return null;
}
/**
* Get a translatable string specifying the duration, down to the minimum granularity.
*/
public static String getTimeString (long duration, byte minUnit)
{
return getTimeString(duration, minUnit, false);
}
/**
* Get a translatable string specifying the duration, down to the minimum granularity.
*
* Normally rounds down to the nearest minUnit, but optionally rounds up.
*/
public static String getTimeString (long duration, byte minUnit, boolean roundUp)
{
// sanity
minUnit = (byte) Math.min(minUnit, MAX_UNIT);
duration = Math.abs(duration);
if (roundUp) {
long quantity = 1;
for (byte uu = MILLISECOND; uu < MAX_UNIT - 1; uu++) {
quantity *= getQuantityPerUnit(uu);
}
if (duration % quantity > 0) {
duration += quantity;
}
}
ArrayList<String> list = Lists.newArrayList();
int parts = 0; // how many parts are in the translation string?
for (byte uu = MILLISECOND; uu <= MAX_UNIT; uu++) {
int quantity = getQuantityPerUnit(uu);
if (minUnit <= uu) {
long amt = duration % quantity;
if (amt != 0) {
list.add(MessageBundle.tcompose(getTransKey(uu), String.valueOf(amt)));
parts++;
}
}
duration /= quantity;
if (duration <= 0 && parts > 0) {
break;
}
}
if (parts == 0) {
// Wow, we didn't get ANYTHING? Okay, I guess that means it's zero of our minUnit
return MessageBundle.tcompose(getTransKey(minUnit), 0);
} else if (parts == 1) {
return list.get(0);
} else {
return MessageBundle.compose("m.times_" + parts, list.toArray());
}
}
/**
* Internal method to get the quantity for the specified unit. (Not very OO)
*/
protected static int getQuantityPerUnit (byte unit)
{
switch (unit) {
case MILLISECOND: return 1000;
case SECOND: case MINUTE: return 60;
case HOUR: return 24;
case DAY: return Integer.MAX_VALUE;
default: return -1;
}
}
/**
* Internal method to get the translation key for the specified unit. (Not very OO)
*/
protected static String getTransKey (byte unit)
{
switch (unit) {
case MILLISECOND: return "m.millisecond";
case SECOND: return "m.second";
case MINUTE: return "m.minute";
case HOUR: return "m.hour";
case DAY: return "m.day";
default: return null;
}
}
}
@@ -0,0 +1,45 @@
#
# $Id$
#
# Executable definitions
CC=gcc
RM=rm
CP=cp
MKDIR=mkdir
#
# Directory definitions
ROOT=../../../../../../..
LIBRARIES_PATH=
OSINCDIR!=uname -s | tr 'A-Z' 'a-z'
INSTALL_PATH=${ROOT}/dist/lib/i386-FreeBSD
#
# Parameter and file definitions
INCLUDES=-I.. -I${JAVA_HOME}/include -I${JAVA_HOME}/include/${OSINCDIR}
LIBRARIES=
TARGET=libsignal.so
#
# Target definitions
all: ${TARGET}
install:
@${MKDIR} -p ${INSTALL_PATH}
cp ${TARGET} ${INSTALL_PATH}
${TARGET}: com_threerings_util_signal_SignalManager.c
@echo "Compiling SignalManager.c"
@${CC} ${INCLUDES} -c com_threerings_util_signal_SignalManager.c \
-o com_threerings_util_signal_SignalManager.o
@echo "Creating libsignal.so"
@${CC} -o ${TARGET} com_threerings_util_signal_SignalManager.o \
${LIBRARIES} ${LIBRARIES_PATH} -shared
clean:
-${RM} -f *.o ${TARGET}
@@ -0,0 +1,96 @@
/**
* $Id$
*/
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <jni.h>
#include "com_threerings_util_signal_SignalManager.h"
static int writefd;
typedef void (*sighandler_t)(int);
static sighandler_t old_handlers[64];
static sighandler_t handlers[64];
static void
signal_handler (int signo)
{
write(writefd, &signo, sizeof(signo));
signal(SIGINT, signal_handler);
}
/**
* Class: com_threerings_util_signal_SignalManager
* Method: activateHandler
* Signature: (I)V
*/
JNIEXPORT void JNICALL
Java_com_threerings_util_signal_SignalManager_activateHandler (
JNIEnv* env, jclass clazz, jint signo)
{
old_handlers[signo] = signal(signo, signal_handler);
if (old_handlers[signo] == SIG_ERR) {
fprintf(stderr, "Error setting signal handler (%d): %s\n",
signo, strerror(errno));
old_handlers[signo] = 0;
} else {
handlers[signo] = signal_handler;
}
}
/**
* Class: com_threerings_util_signal_SignalManager
* Method: deactivateHandler
* Signature: (I)V
*/
JNIEXPORT void JNICALL
Java_com_threerings_util_signal_SignalManager_deactivateHandler (
JNIEnv* env, jclass clazz, jint signo)
{
if (old_handlers[signo] != 0) {
signal(signo, old_handlers[signo]);
old_handlers[signo] = 0;
handlers[signo] = 0;
}
}
/**
* Class: com_threerings_util_signal_SignalManager
* Method: dispatchSignals
* Signature: ()V
*/
JNIEXPORT void JNICALL
Java_com_threerings_util_signal_SignalManager_dispatchSignals (
JNIEnv* env, jclass clazz)
{
int filedes[2], readfd;
jint signo;
jmethodID mid = (*env)->GetStaticMethodID(
env, clazz, "signalReceived", "(I)V");
if (pipe(filedes) < 0) {
fprintf(stderr, "Failed to create signal pipe: %s\n", strerror(errno));
return;
}
readfd = filedes[0];
writefd = filedes[1];
while (1) {
int got = read(readfd, &signo, sizeof(int));
if (got < 0) {
fprintf(stderr, "Signal pipe read failed: %s\n", strerror(errno));
} else if (got == 0) {
fprintf(stderr, "Signal pipe read returned zero bytes.\n");
} else {
if (signo < 0 || signo >= 64 || handlers[signo] == 0) {
fprintf(stderr, "Received bogus signal (%d).\n", signo);
} else {
(*env)->CallStaticVoidMethod(env, clazz, mid, signo);
}
}
}
}
Binary file not shown.
@@ -0,0 +1,45 @@
#
# $Id: Makefile 3328 2005-02-03 01:16:12Z mdb $
#
# Executable definitions
CC=gcc
RM=rm
CP=cp
MKDIR=mkdir
#
# Directory definitions
ROOT=../../../../../../..
LIBRARIES_PATH=
OSINCDIR:=$(shell uname -s | tr 'A-Z' 'a-z')
INSTALL_PATH=${ROOT}/dist/lib/i686-Linux
#
# Parameter and file definitions
INCLUDES=-I.. -I${JAVA_HOME}/include -I${JAVA_HOME}/include/${OSINCDIR}
LIBRARIES=
TARGET=libsignal.so
#
# Target definitions
all: ${TARGET}
install:
@${MKDIR} -p ${INSTALL_PATH}
cp ${TARGET} ${INSTALL_PATH}
${TARGET}: com_threerings_util_signal_SignalManager.c
@echo "Compiling SignalManager.c"
@${CC} ${INCLUDES} -c com_threerings_util_signal_SignalManager.c \
-o com_threerings_util_signal_SignalManager.o
@echo "Creating libsignal.so"
@${CC} -o ${TARGET} com_threerings_util_signal_SignalManager.o \
${LIBRARIES} ${LIBRARIES_PATH} -shared
clean:
-${RM} -f *.o ${TARGET}
@@ -0,0 +1 @@
../FreeBSD/com_threerings_util_signal_SignalManager.c
Binary file not shown.
@@ -0,0 +1,45 @@
#
# $Id: Makefile 3332 2005-02-03 01:30:33Z mdb $
#
# Executable definitions
CC=gcc
RM=rm
CP=cp
MKDIR=mkdir
#
# Directory definitions
ROOT=../../../../../../..
LIBRARIES_PATH=
OSINCDIR!=uname -s | tr 'A-Z' 'a-z'
INSTALL_PATH=${ROOT}/dist/lib/`uname -m`-Darwin
#
# Parameter and file definitions
INCLUDES=-I.. -I/System/Library/Frameworks/JavaVM.framework/Headers
LIBRARIES=
TARGET=libsignal.jnilib
#
# Target definitions
all: ${TARGET}
install:
@${MKDIR} -p ${INSTALL_PATH}
cp ${TARGET} ${INSTALL_PATH}
${TARGET}: com_threerings_util_signal_SignalManager.c
@echo "Compiling $<"
@${CC} ${INCLUDES} -c com_threerings_util_signal_SignalManager.c \
-o com_threerings_util_signal_SignalManager.o
@echo "Creating $@"
@${CC} -o ${TARGET} com_threerings_util_signal_SignalManager.o \
${LIBRARIES} ${LIBRARIES_PATH} -dynamiclib
clean:
-${RM} -f *.o ${TARGET}
@@ -0,0 +1 @@
../FreeBSD/com_threerings_util_signal_SignalManager.c
Binary file not shown.
@@ -0,0 +1,277 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util.signal;
import com.samskivert.util.HashIntMap;
import com.samskivert.util.ObserverList;
import static com.threerings.NaryaLog.log;
/**
* Uses native code to catch Unix signals and invoke callbacks on a separate signal handler thread.
* If the native library cannot be loaded, signal handlers will be allowed to be registered but
* will never be called.
*/
public class SignalManager
{
/* Hangup (POSIX). */
public static final int SIGHUP = 1;
/* Interrupt (ANSI). */
public static final int SIGINT = 2;
/* Quit (POSIX). */
public static final int SIGQUIT = 3;
/* Illegal instruction (ANSI). */
public static final int SIGILL = 4;
/* Trace trap (POSIX). */
public static final int SIGTRAP = 5;
/* Abort (ANSI). */
public static final int SIGABRT = 6;
/* IOT trap (4.2 BSD). */
public static final int SIGIOT = 6;
/* BUS error (4.2 BSD). */
public static final int SIGBUS = 7;
/* Floating-point exception (ANSI). */
public static final int SIGFPE = 8;
/* Kill, unblockable (POSIX). */
public static final int SIGKILL = 9;
/* User-defined signal 1 (POSIX). */
public static final int SIGUSR1 = 10;
/* Segmentation violation (ANSI). */
public static final int SIGSEGV = 11;
/* User-defined signal 2 (POSIX). */
public static final int SIGUSR2 = 12;
/* Broken pipe (POSIX). */
public static final int SIGPIPE = 13;
/* Alarm clock (POSIX). */
public static final int SIGALRM = 14;
/* Termination (ANSI). */
public static final int SIGTERM = 15;
/* Stack fault. */
public static final int SIGSTKFLT = 16;
/* Child status has changed (POSIX). */
public static final int SIGCHLD = 17;
/* Continue (POSIX). */
public static final int SIGCONT = 18;
/* Stop, unblockable (POSIX). */
public static final int SIGSTOP = 19;
/* Keyboard stop (POSIX). */
public static final int SIGTSTP = 20;
/* Background read from tty (POSIX). */
public static final int SIGTTIN = 21;
/* Background write to tty (POSIX). */
public static final int SIGTTOU = 22;
/* Urgent condition on socket (4.2 BSD). */
public static final int SIGURG = 23;
/* CPU limit exceeded (4.2 BSD). */
public static final int SIGXCPU = 24;
/* File size limit exceeded (4.2 BSD). */
public static final int SIGXFSZ = 25;
/* Virtual alarm clock (4.2 BSD). */
public static final int SIGVTALRM = 26;
/* Profiling alarm clock (4.2 BSD). */
public static final int SIGPROF = 27;
/* Window size change (4.3 BSD, Sun). */
public static final int SIGWINCH = 28;
/* I/O now possible (4.2 BSD). */
public static final int SIGIO = 29;
/* Pollable event occurred (System V). */
public static final int SIGPOLL = SIGIO;
/* Power failure restart (System V). */
public static final int SIGPWR = 30;
/* Bad system call. */
public static final int SIGSYS = 31;
/** Used to dispatch signal notifications. */
public static interface SignalHandler
{
/**
* Called when the specified signal is received.
*
* @return true if the signal handler should remain registered, false if it should be
* removed.
*/
boolean signalReceived (int signal);
}
/**
* Returns true if signal dispatching services are available, false if we could not load our
* native library.
*/
public static boolean servicesAvailable ()
{
return _haveLibrary;
}
/**
* Registers a signal handler for the specified signal.
*/
public synchronized static void registerSignalHandler (int signal, SignalHandler handler)
{
ObserverList<SignalHandler> list = _handlers.get(signal);
if (list == null) {
_handlers.put(signal, list = new ObserverList<SignalHandler>(
ObserverList.SAFE_IN_ORDER_NOTIFY));
if (_haveLibrary) {
activateHandler(signal);
}
}
list.add(handler);
// make sure the signal dispatcher thread is started
if (_haveLibrary && _sigdis == null) {
_sigdis = new Thread("SignalDispatcher") {
@Override
public void run () {
log.info("Dispatching signals...");
dispatchSignals();
}
};
_sigdis.setDaemon(true);
_sigdis.start();
}
}
/**
* Removes the registration for the specified signal handler.
*/
public synchronized static void removeSignalHandler (int signal, SignalHandler handler)
{
ObserverList<SignalHandler> list = _handlers.get(signal);
if (list == null || !list.contains(handler)) {
log.warning("Requested to remove non-registered handler", "signal", signal,
"handler", handler);
return;
}
list.remove(handler);
checkEmpty(signal);
}
/**
* Called by native code when a signal is received.
*/
protected synchronized static void signalReceived (final int signal)
{
// this is hack, but we seem to get a call to our signal handler for each thread if the
// user presses ctrl-c in the terminal, so we "collapse" those into one call back
long now = System.currentTimeMillis();
if (signal == SIGINT) {
if (now - _lastINTed < 10) {
return;
} else {
_lastINTed = now;
}
}
ObserverList<SignalHandler> list = _handlers.get(signal);
if (list != null) {
list.apply(new ObserverList.ObserverOp<SignalHandler>() {
public boolean apply (SignalHandler handler) {
return handler.signalReceived(signal);
}
});
}
checkEmpty(signal);
}
/**
* Called when a signal handler is removed.
*/
protected static void checkEmpty (int signal)
{
ObserverList<SignalHandler> list = _handlers.get(signal);
if (list != null && list.size() == 0) {
_handlers.remove(signal);
if (_haveLibrary) {
deactivateHandler(signal);
}
}
}
/**
* Activates the signal handler for the specified signal.
*/
protected static native void activateHandler (int signal);
/**
* Deactivates the signal handler for the specified signal.
*/
protected static native void deactivateHandler (int signal);
/**
* Consigns a Java thread to the task of dispatching signal handler callbacks.
*/
protected static native void dispatchSignals ();
/** A mapping from signal number to a list of handlers. */
protected static HashIntMap<ObserverList<SignalHandler>> _handlers =
new HashIntMap<ObserverList<SignalHandler>>();
/** Our signal dispatcher thread. */
protected static Thread _sigdis;
/** Set to true if we successfully load our native library. */
protected static boolean _haveLibrary;
/** Used to collapse bogus multiple delivery of SIGINT when the user pressed ctrl-c in the
* console. */
protected static long _lastINTed = 0L;
static {
try {
System.loadLibrary("signal");
_haveLibrary = true;
} catch (Throwable t) {
log.info("Could not load libsignal.so; signal handling disabled.");
}
}
}
@@ -0,0 +1,104 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_threerings_util_signal_SignalManager */
#ifndef _Included_com_threerings_util_signal_SignalManager
#define _Included_com_threerings_util_signal_SignalManager
#ifdef __cplusplus
extern "C" {
#endif
#undef com_threerings_util_signal_SignalManager_SIGHUP
#define com_threerings_util_signal_SignalManager_SIGHUP 1L
#undef com_threerings_util_signal_SignalManager_SIGINT
#define com_threerings_util_signal_SignalManager_SIGINT 2L
#undef com_threerings_util_signal_SignalManager_SIGQUIT
#define com_threerings_util_signal_SignalManager_SIGQUIT 3L
#undef com_threerings_util_signal_SignalManager_SIGILL
#define com_threerings_util_signal_SignalManager_SIGILL 4L
#undef com_threerings_util_signal_SignalManager_SIGTRAP
#define com_threerings_util_signal_SignalManager_SIGTRAP 5L
#undef com_threerings_util_signal_SignalManager_SIGABRT
#define com_threerings_util_signal_SignalManager_SIGABRT 6L
#undef com_threerings_util_signal_SignalManager_SIGIOT
#define com_threerings_util_signal_SignalManager_SIGIOT 6L
#undef com_threerings_util_signal_SignalManager_SIGBUS
#define com_threerings_util_signal_SignalManager_SIGBUS 7L
#undef com_threerings_util_signal_SignalManager_SIGFPE
#define com_threerings_util_signal_SignalManager_SIGFPE 8L
#undef com_threerings_util_signal_SignalManager_SIGKILL
#define com_threerings_util_signal_SignalManager_SIGKILL 9L
#undef com_threerings_util_signal_SignalManager_SIGUSR1
#define com_threerings_util_signal_SignalManager_SIGUSR1 10L
#undef com_threerings_util_signal_SignalManager_SIGSEGV
#define com_threerings_util_signal_SignalManager_SIGSEGV 11L
#undef com_threerings_util_signal_SignalManager_SIGUSR2
#define com_threerings_util_signal_SignalManager_SIGUSR2 12L
#undef com_threerings_util_signal_SignalManager_SIGPIPE
#define com_threerings_util_signal_SignalManager_SIGPIPE 13L
#undef com_threerings_util_signal_SignalManager_SIGALRM
#define com_threerings_util_signal_SignalManager_SIGALRM 14L
#undef com_threerings_util_signal_SignalManager_SIGTERM
#define com_threerings_util_signal_SignalManager_SIGTERM 15L
#undef com_threerings_util_signal_SignalManager_SIGSTKFLT
#define com_threerings_util_signal_SignalManager_SIGSTKFLT 16L
#undef com_threerings_util_signal_SignalManager_SIGCHLD
#define com_threerings_util_signal_SignalManager_SIGCHLD 17L
#undef com_threerings_util_signal_SignalManager_SIGCONT
#define com_threerings_util_signal_SignalManager_SIGCONT 18L
#undef com_threerings_util_signal_SignalManager_SIGSTOP
#define com_threerings_util_signal_SignalManager_SIGSTOP 19L
#undef com_threerings_util_signal_SignalManager_SIGTSTP
#define com_threerings_util_signal_SignalManager_SIGTSTP 20L
#undef com_threerings_util_signal_SignalManager_SIGTTIN
#define com_threerings_util_signal_SignalManager_SIGTTIN 21L
#undef com_threerings_util_signal_SignalManager_SIGTTOU
#define com_threerings_util_signal_SignalManager_SIGTTOU 22L
#undef com_threerings_util_signal_SignalManager_SIGURG
#define com_threerings_util_signal_SignalManager_SIGURG 23L
#undef com_threerings_util_signal_SignalManager_SIGXCPU
#define com_threerings_util_signal_SignalManager_SIGXCPU 24L
#undef com_threerings_util_signal_SignalManager_SIGXFSZ
#define com_threerings_util_signal_SignalManager_SIGXFSZ 25L
#undef com_threerings_util_signal_SignalManager_SIGVTALRM
#define com_threerings_util_signal_SignalManager_SIGVTALRM 26L
#undef com_threerings_util_signal_SignalManager_SIGPROF
#define com_threerings_util_signal_SignalManager_SIGPROF 27L
#undef com_threerings_util_signal_SignalManager_SIGWINCH
#define com_threerings_util_signal_SignalManager_SIGWINCH 28L
#undef com_threerings_util_signal_SignalManager_SIGIO
#define com_threerings_util_signal_SignalManager_SIGIO 29L
#undef com_threerings_util_signal_SignalManager_SIGPOLL
#define com_threerings_util_signal_SignalManager_SIGPOLL 29L
#undef com_threerings_util_signal_SignalManager_SIGPWR
#define com_threerings_util_signal_SignalManager_SIGPWR 30L
#undef com_threerings_util_signal_SignalManager_SIGSYS
#define com_threerings_util_signal_SignalManager_SIGSYS 31L
/* Inaccessible static: _handlers */
/*
* Class: com_threerings_util_signal_SignalManager
* Method: activateHandler
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_threerings_util_signal_SignalManager_activateHandler
(JNIEnv *, jclass, jint);
/*
* Class: com_threerings_util_signal_SignalManager
* Method: deactivateHandler
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_threerings_util_signal_SignalManager_deactivateHandler
(JNIEnv *, jclass, jint);
/*
* Class: com_threerings_util_signal_SignalManager
* Method: dispatchSignals
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_threerings_util_signal_SignalManager_dispatchSignals
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif