diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/org/python/util/jython.java b/src/org/python/util/jython.java
index daf46c6d..e619e9b3 100644
--- a/src/org/python/util/jython.java
+++ b/src/org/python/util/jython.java
@@ -1,547 +1,547 @@
// Copyright (c) Corporation for National Research Initiatives
package org.python.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.python.Version;
import org.python.core.CodeFlag;
import org.python.core.CompileMode;
import org.python.core.Options;
import org.python.core.Py;
import org.python.core.PyCode;
import org.python.core.PyException;
import org.python.core.PyFile;
import org.python.core.PyList;
import org.python.core.PyString;
import org.python.core.PyStringMap;
import org.python.core.PySystemState;
import org.python.core.imp;
import org.python.core.util.RelativeFile;
import org.python.modules._systemrestart;
import org.python.modules.posix.PosixModule;
import org.python.modules.thread.thread;
public class jython {
private static final String COPYRIGHT =
"Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.";
static final String usageHeader =
"usage: jython [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
private static final String usage = usageHeader +
"Options and arguments:\n" + //(and corresponding environment variables):\n" +
"-c cmd : program passed in as string (terminates option list)\n" +
//"-d : debug output from parser (also PYTHONDEBUG=x)\n" +
"-Dprop=v : Set the property `prop' to value `v'\n"+
//"-E : ignore environment variables (such as PYTHONPATH)\n" +
"-C codec : Use a different codec when reading from the console.\n"+
"-h : print this help message and exit (also --help)\n" +
"-i : inspect interactively after running script\n" + //, (also PYTHONINSPECT=x)\n" +
" and force prompts, even if stdin does not appear to be a terminal\n" +
"-jar jar : program read from __run__.py in jar file\n"+
"-m mod : run library module as a script (terminates option list)\n" +
//"-O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)\n" +
//"-OO : remove doc-strings in addition to the -O optimizations\n" +
"-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew\n" +
"-S : don't imply 'import site' on initialization\n" +
//"-t : issue warnings about inconsistent tab usage (-tt: issue errors)\n" +
"-u : unbuffered binary stdout and stderr\n" + // (also PYTHONUNBUFFERED=x)\n" +
//" see man page for details on internal buffering relating to '-u'\n" +
"-v : verbose (trace import statements)\n" + // (also PYTHONVERBOSE=x)\n" +
"-V : print the Python version number and exit (also --version)\n" +
"-W arg : warning control (arg is action:message:category:module:lineno)\n" +
//"-x : skip first line of source, allowing use of non-Unix forms of #!cmd\n" +
"file : program read from script file\n" +
"- : program read from stdin (default; interactive mode if a tty)\n" +
"arg ... : arguments passed to program in sys.argv[1:]\n" +
"Other environment variables:\n" +
"JYTHONPATH: '" + File.pathSeparator +
"'-separated list of directories prefixed to the default module\n" +
" search path. The result is sys.path.";
public static boolean shouldRestart;
/**
* Runs a JAR file, by executing the code found in the file __run__.py,
* which should be in the root of the JAR archive.
*
* Note that the __name__ is set to the base name of the JAR file and not
* to "__main__" (for historic reasons).
*
* This method do NOT handle exceptions. the caller SHOULD handle any
* (Py)Exceptions thrown by the code.
*
* @param filename The path to the filename to run.
*/
public static void runJar(String filename) {
// TBD: this is kind of gross because a local called `zipfile' just magically
// shows up in the module's globals. Either `zipfile' should be called
// `__zipfile__' or (preferrably, IMO), __run__.py should be imported and a main()
// function extracted. This function should be called passing zipfile in as an
// argument.
//
// Probably have to keep this code around for backwards compatibility (?)
try {
ZipFile zip = new ZipFile(filename);
ZipEntry runit = zip.getEntry("__run__.py");
if (runit == null) {
throw Py.ValueError("jar file missing '__run__.py'");
}
PyStringMap locals = new PyStringMap();
// Stripping the stuff before the last File.separator fixes Bug #931129 by
// keeping illegal characters out of the generated proxy class name
int beginIndex;
if ((beginIndex = filename.lastIndexOf(File.separator)) != -1) {
filename = filename.substring(beginIndex + 1);
}
locals.__setitem__("__name__", new PyString(filename));
locals.__setitem__("zipfile", Py.java2py(zip));
InputStream file = zip.getInputStream(runit);
PyCode code;
try {
code = Py.compile(file, "__run__", CompileMode.exec);
} finally {
file.close();
}
Py.runCode(code, locals, locals);
} catch (IOException e) {
throw Py.IOError(e);
}
}
public static void main(String[] args) {
do {
shouldRestart = false;
run(args);
} while (shouldRestart);
}
public static void run(String[] args) {
// Parse the command line options
CommandLineOptions opts = new CommandLineOptions();
if (!opts.parse(args)) {
if (opts.version) {
System.err.println("Jython " + Version.PY_VERSION);
System.exit(0);
}
if (!opts.runCommand && !opts.runModule) {
System.err.println(usage);
}
int exitcode = opts.help ? 0 : -1;
System.exit(exitcode);
}
// Setup the basic python system state from these options
PySystemState.initialize(PySystemState.getBaseProperties(), opts.properties, opts.argv);
PyList warnoptions = new PyList();
for (String wopt : opts.warnoptions) {
warnoptions.append(new PyString(wopt));
}
Py.getSystemState().setWarnoptions(warnoptions);
PySystemState systemState = Py.getSystemState();
// Decide if stdin is interactive
- if (!opts.fixInteractive && opts.interactive) {
+ if (!opts.fixInteractive || opts.interactive) {
opts.interactive = ((PyFile)Py.defaultSystemState.stdin).isatty();
if (!opts.interactive) {
systemState.ps1 = systemState.ps2 = Py.EmptyString;
}
}
// Now create an interpreter
InteractiveConsole interp = newInterpreter(opts.interactive);
systemState.__setattr__("_jy_interpreter", Py.java2py(interp));
// Print banner and copyright information (or not)
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(InteractiveConsole.getDefaultBanner());
}
if (Options.importSite) {
try {
imp.load("site");
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(COPYRIGHT);
}
} catch (PyException pye) {
if (!pye.match(Py.ImportError)) {
System.err.println("error importing site");
Py.printException(pye);
System.exit(-1);
}
}
}
if (opts.division != null) {
if ("old".equals(opts.division)) {
Options.divisionWarning = 0;
} else if ("warn".equals(opts.division)) {
Options.divisionWarning = 1;
} else if ("warnall".equals(opts.division)) {
Options.divisionWarning = 2;
} else if ("new".equals(opts.division)) {
Options.Qnew = true;
interp.cflags.setFlag(CodeFlag.CO_FUTURE_DIVISION);
}
}
// was there a filename on the command line?
if (opts.filename != null) {
String path;
try {
path = new File(opts.filename).getCanonicalFile().getParent();
} catch (IOException ioe) {
path = new File(opts.filename).getAbsoluteFile().getParent();
}
if (path == null) {
path = "";
}
Py.getSystemState().path.insert(0, new PyString(path));
if (opts.jar) {
try {
runJar(opts.filename);
} catch (Throwable t) {
Py.printException(t);
System.exit(-1);
}
} else if (opts.filename.equals("-")) {
try {
interp.globals.__setitem__(new PyString("__file__"), new PyString("<stdin>"));
interp.execfile(System.in, "<stdin>");
} catch (Throwable t) {
Py.printException(t);
}
} else {
try {
interp.globals.__setitem__(new PyString("__file__"),
new PyString(opts.filename));
FileInputStream file;
try {
file = new FileInputStream(new RelativeFile(opts.filename));
} catch (FileNotFoundException e) {
throw Py.IOError(e);
}
try {
if (PosixModule.getPOSIX().isatty(file.getFD())) {
opts.interactive = true;
interp.interact(null, new PyFile(file));
System.exit(0);
} else {
interp.execfile(file, opts.filename);
}
} finally {
file.close();
}
} catch (Throwable t) {
if (t instanceof PyException
&& ((PyException)t).match(_systemrestart.SystemRestart)) {
// Shutdown this instance...
shouldRestart = true;
shutdownInterpreter();
interp.cleanup();
// ..reset the state...
Py.setSystemState(new PySystemState());
// ...and start again
return;
} else {
Py.printException(t);
if (!opts.interactive) {
interp.cleanup();
System.exit(-1);
}
}
}
}
}
else {
// if there was no file name on the command line, then "" is the first element
// on sys.path. This is here because if there /was/ a filename on the c.l.,
// and say the -i option was given, sys.path[0] will have gotten filled in
// with the dir of the argument filename.
Py.getSystemState().path.insert(0, Py.EmptyString);
if (opts.command != null) {
try {
interp.exec(opts.command);
} catch (Throwable t) {
Py.printException(t);
System.exit(1);
}
}
if (opts.moduleName != null) {
// PEP 338 - Execute module as a script
try {
interp.exec("import runpy");
interp.set("name", Py.newString(opts.moduleName));
interp.exec("runpy.run_module(name, run_name='__main__', alter_sys=True)");
interp.cleanup();
System.exit(0);
} catch (Throwable t) {
Py.printException(t);
interp.cleanup();
System.exit(-1);
}
}
}
if (opts.fixInteractive || (opts.filename == null && opts.command == null)) {
if (opts.encoding == null) {
opts.encoding = PySystemState.registry.getProperty("python.console.encoding");
}
if (opts.encoding != null) {
if (!Charset.isSupported(opts.encoding)) {
System.err.println(opts.encoding
+ " is not a supported encoding on this JVM, so it can't "
+ "be used in python.console.encoding.");
System.exit(1);
}
interp.cflags.encoding = opts.encoding;
}
try {
interp.interact(null, null);
} catch (Throwable t) {
Py.printException(t);
}
}
interp.cleanup();
if (opts.fixInteractive || opts.interactive) {
System.exit(0);
}
}
/**
* Returns a new python interpreter using the InteractiveConsole subclass from the
* <tt>python.console</tt> registry key.
* <p>
* When stdin is interactive the default is {@link JLineConsole}. Otherwise the
* featureless {@link InteractiveConsole} is always used as alternative consoles cause
* unexpected behavior with the std file streams.
*/
private static InteractiveConsole newInterpreter(boolean interactiveStdin) {
if (!interactiveStdin) {
return new InteractiveConsole();
}
String interpClass = PySystemState.registry.getProperty("python.console", "");
if (interpClass.length() > 0) {
try {
return (InteractiveConsole)Class.forName(interpClass).newInstance();
} catch (Throwable t) {
// fall through
}
}
return new JLineConsole();
}
/**
* Run any finalizations on the current interpreter in preparation for a SytemRestart.
*/
public static void shutdownInterpreter() {
// Stop all the active threads and signal the SystemRestart
thread.interruptAllThreads();
Py.getSystemState()._systemRestart = true;
// Close all sockets -- not all of their operations are stopped by
// Thread.interrupt (in particular pre-nio sockets)
try {
imp.load("socket").__findattr__("_closeActiveSockets").__call__();
} catch (PyException pye) {
// continue
}
}
}
class CommandLineOptions {
public String filename;
public boolean jar, interactive, notice;
public boolean runCommand, runModule;
public boolean fixInteractive;
public boolean help, version;
public String[] argv;
public Properties properties;
public String command;
public List<String> warnoptions = Generic.list();
public String encoding;
public String division;
public String moduleName;
public CommandLineOptions() {
filename = null;
jar = fixInteractive = false;
interactive = notice = true;
runModule = false;
properties = new Properties();
help = version = false;
}
public void setProperty(String key, String value) {
properties.put(key, value);
try {
System.setProperty(key, value);
} catch (SecurityException e) {
// continue
}
}
public boolean parse(String[] args) {
int index = 0;
while (index < args.length && args[index].startsWith("-")) {
String arg = args[index];
if (arg.equals("-h") || arg.equals("-?") || arg.equals("--help")) {
help = true;
return false;
} else if (arg.equals("-V") || arg.equals("--version")) {
version = true;
return false;
} else if (arg.equals("-")) {
if (!fixInteractive) {
interactive = false;
}
filename = "-";
} else if (arg.equals("-i")) {
fixInteractive = true;
interactive = true;
} else if (arg.equals("-jar")) {
jar = true;
if (!fixInteractive) {
interactive = false;
}
} else if (arg.equals("-u")) {
Options.unbuffered = true;
} else if (arg.equals("-v")) {
Options.verbose++;
} else if (arg.equals("-vv")) {
Options.verbose += 2;
} else if (arg.equals("-vvv")) {
Options.verbose +=3 ;
} else if (arg.equals("-S")) {
Options.importSite = false;
} else if (arg.equals("-c")) {
runCommand = true;
if (arg.length() > 2) {
command = arg.substring(2);
} else if ((index + 1) < args.length) {
command = args[++index];
} else {
System.err.println("Argument expected for the -c option");
System.err.print(jython.usageHeader);
System.err.println("Try `jython -h' for more information.");
return false;
}
if (!fixInteractive) {
interactive = false;
}
index++;
break;
} else if (arg.equals("-W")) {
warnoptions.add(args[++index]);
} else if (arg.equals("-C")) {
encoding = args[++index];
setProperty("python.console.encoding", encoding);
} else if (arg.equals("-E")) {
// XXX: accept -E (ignore environment variables) to be compatiable with
// CPython. do nothing for now (we could ignore the registry)
} else if (arg.startsWith("-D")) {
String key = null;
String value = null;
int equals = arg.indexOf("=");
if (equals == -1) {
String arg2 = args[++index];
key = arg.substring(2, arg.length());
value = arg2;
} else {
key = arg.substring(2, equals);
value = arg.substring(equals + 1, arg.length());
}
setProperty(key, value);
} else if (arg.startsWith("-Q")) {
if (arg.length() > 2) {
division = arg.substring(2);
} else {
division = args[++index];
}
} else if (arg.startsWith("-m")) {
runModule = true;
if (arg.length() > 2) {
moduleName = arg.substring(2);
} else if ((index + 1) < args.length) {
moduleName = args[++index];
} else {
System.err.println("Argument expected for the -m option");
System.err.print(jython.usageHeader);
System.err.println("Try `jython -h' for more information.");
return false;
}
if (!fixInteractive) {
interactive = false;
}
index++;
int n = args.length - index + 1;
argv = new String[n];
argv[0] = moduleName;
for (int i = 1; index < args.length; i++, index++) {
argv[i] = args[index];
}
return true;
} else {
String opt = args[index];
if (opt.startsWith("--")) {
opt = opt.substring(2);
} else if (opt.startsWith("-")) {
opt = opt.substring(1);
}
System.err.println("Unknown option: " + opt);
return false;
}
index += 1;
}
notice = interactive;
if (filename == null && index < args.length && command == null) {
filename = args[index++];
if (!fixInteractive) {
interactive = false;
}
notice = false;
}
if (command != null) {
notice = false;
}
int n = args.length - index + 1;
argv = new String[n];
if (filename != null) {
argv[0] = filename;
} else if (command != null) {
argv[0] = "-c";
} else {
argv[0] = "";
}
for (int i = 1; i < n; i++, index++) {
argv[i] = args[index];
}
return true;
}
}
| true | true | public static void run(String[] args) {
// Parse the command line options
CommandLineOptions opts = new CommandLineOptions();
if (!opts.parse(args)) {
if (opts.version) {
System.err.println("Jython " + Version.PY_VERSION);
System.exit(0);
}
if (!opts.runCommand && !opts.runModule) {
System.err.println(usage);
}
int exitcode = opts.help ? 0 : -1;
System.exit(exitcode);
}
// Setup the basic python system state from these options
PySystemState.initialize(PySystemState.getBaseProperties(), opts.properties, opts.argv);
PyList warnoptions = new PyList();
for (String wopt : opts.warnoptions) {
warnoptions.append(new PyString(wopt));
}
Py.getSystemState().setWarnoptions(warnoptions);
PySystemState systemState = Py.getSystemState();
// Decide if stdin is interactive
if (!opts.fixInteractive && opts.interactive) {
opts.interactive = ((PyFile)Py.defaultSystemState.stdin).isatty();
if (!opts.interactive) {
systemState.ps1 = systemState.ps2 = Py.EmptyString;
}
}
// Now create an interpreter
InteractiveConsole interp = newInterpreter(opts.interactive);
systemState.__setattr__("_jy_interpreter", Py.java2py(interp));
// Print banner and copyright information (or not)
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(InteractiveConsole.getDefaultBanner());
}
if (Options.importSite) {
try {
imp.load("site");
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(COPYRIGHT);
}
} catch (PyException pye) {
if (!pye.match(Py.ImportError)) {
System.err.println("error importing site");
Py.printException(pye);
System.exit(-1);
}
}
}
if (opts.division != null) {
if ("old".equals(opts.division)) {
Options.divisionWarning = 0;
} else if ("warn".equals(opts.division)) {
Options.divisionWarning = 1;
} else if ("warnall".equals(opts.division)) {
Options.divisionWarning = 2;
} else if ("new".equals(opts.division)) {
Options.Qnew = true;
interp.cflags.setFlag(CodeFlag.CO_FUTURE_DIVISION);
}
}
// was there a filename on the command line?
if (opts.filename != null) {
String path;
try {
path = new File(opts.filename).getCanonicalFile().getParent();
} catch (IOException ioe) {
path = new File(opts.filename).getAbsoluteFile().getParent();
}
if (path == null) {
path = "";
}
Py.getSystemState().path.insert(0, new PyString(path));
if (opts.jar) {
try {
runJar(opts.filename);
} catch (Throwable t) {
Py.printException(t);
System.exit(-1);
}
} else if (opts.filename.equals("-")) {
try {
interp.globals.__setitem__(new PyString("__file__"), new PyString("<stdin>"));
interp.execfile(System.in, "<stdin>");
} catch (Throwable t) {
Py.printException(t);
}
} else {
try {
interp.globals.__setitem__(new PyString("__file__"),
new PyString(opts.filename));
FileInputStream file;
try {
file = new FileInputStream(new RelativeFile(opts.filename));
} catch (FileNotFoundException e) {
throw Py.IOError(e);
}
try {
if (PosixModule.getPOSIX().isatty(file.getFD())) {
opts.interactive = true;
interp.interact(null, new PyFile(file));
System.exit(0);
} else {
interp.execfile(file, opts.filename);
}
} finally {
file.close();
}
} catch (Throwable t) {
if (t instanceof PyException
&& ((PyException)t).match(_systemrestart.SystemRestart)) {
// Shutdown this instance...
shouldRestart = true;
shutdownInterpreter();
interp.cleanup();
// ..reset the state...
Py.setSystemState(new PySystemState());
// ...and start again
return;
} else {
Py.printException(t);
if (!opts.interactive) {
interp.cleanup();
System.exit(-1);
}
}
}
}
}
else {
// if there was no file name on the command line, then "" is the first element
// on sys.path. This is here because if there /was/ a filename on the c.l.,
// and say the -i option was given, sys.path[0] will have gotten filled in
// with the dir of the argument filename.
Py.getSystemState().path.insert(0, Py.EmptyString);
if (opts.command != null) {
try {
interp.exec(opts.command);
} catch (Throwable t) {
Py.printException(t);
System.exit(1);
}
}
if (opts.moduleName != null) {
// PEP 338 - Execute module as a script
try {
interp.exec("import runpy");
interp.set("name", Py.newString(opts.moduleName));
interp.exec("runpy.run_module(name, run_name='__main__', alter_sys=True)");
interp.cleanup();
System.exit(0);
} catch (Throwable t) {
Py.printException(t);
interp.cleanup();
System.exit(-1);
}
}
}
if (opts.fixInteractive || (opts.filename == null && opts.command == null)) {
if (opts.encoding == null) {
opts.encoding = PySystemState.registry.getProperty("python.console.encoding");
}
if (opts.encoding != null) {
if (!Charset.isSupported(opts.encoding)) {
System.err.println(opts.encoding
+ " is not a supported encoding on this JVM, so it can't "
+ "be used in python.console.encoding.");
System.exit(1);
}
interp.cflags.encoding = opts.encoding;
}
try {
interp.interact(null, null);
} catch (Throwable t) {
Py.printException(t);
}
}
interp.cleanup();
if (opts.fixInteractive || opts.interactive) {
System.exit(0);
}
}
| public static void run(String[] args) {
// Parse the command line options
CommandLineOptions opts = new CommandLineOptions();
if (!opts.parse(args)) {
if (opts.version) {
System.err.println("Jython " + Version.PY_VERSION);
System.exit(0);
}
if (!opts.runCommand && !opts.runModule) {
System.err.println(usage);
}
int exitcode = opts.help ? 0 : -1;
System.exit(exitcode);
}
// Setup the basic python system state from these options
PySystemState.initialize(PySystemState.getBaseProperties(), opts.properties, opts.argv);
PyList warnoptions = new PyList();
for (String wopt : opts.warnoptions) {
warnoptions.append(new PyString(wopt));
}
Py.getSystemState().setWarnoptions(warnoptions);
PySystemState systemState = Py.getSystemState();
// Decide if stdin is interactive
if (!opts.fixInteractive || opts.interactive) {
opts.interactive = ((PyFile)Py.defaultSystemState.stdin).isatty();
if (!opts.interactive) {
systemState.ps1 = systemState.ps2 = Py.EmptyString;
}
}
// Now create an interpreter
InteractiveConsole interp = newInterpreter(opts.interactive);
systemState.__setattr__("_jy_interpreter", Py.java2py(interp));
// Print banner and copyright information (or not)
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(InteractiveConsole.getDefaultBanner());
}
if (Options.importSite) {
try {
imp.load("site");
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(COPYRIGHT);
}
} catch (PyException pye) {
if (!pye.match(Py.ImportError)) {
System.err.println("error importing site");
Py.printException(pye);
System.exit(-1);
}
}
}
if (opts.division != null) {
if ("old".equals(opts.division)) {
Options.divisionWarning = 0;
} else if ("warn".equals(opts.division)) {
Options.divisionWarning = 1;
} else if ("warnall".equals(opts.division)) {
Options.divisionWarning = 2;
} else if ("new".equals(opts.division)) {
Options.Qnew = true;
interp.cflags.setFlag(CodeFlag.CO_FUTURE_DIVISION);
}
}
// was there a filename on the command line?
if (opts.filename != null) {
String path;
try {
path = new File(opts.filename).getCanonicalFile().getParent();
} catch (IOException ioe) {
path = new File(opts.filename).getAbsoluteFile().getParent();
}
if (path == null) {
path = "";
}
Py.getSystemState().path.insert(0, new PyString(path));
if (opts.jar) {
try {
runJar(opts.filename);
} catch (Throwable t) {
Py.printException(t);
System.exit(-1);
}
} else if (opts.filename.equals("-")) {
try {
interp.globals.__setitem__(new PyString("__file__"), new PyString("<stdin>"));
interp.execfile(System.in, "<stdin>");
} catch (Throwable t) {
Py.printException(t);
}
} else {
try {
interp.globals.__setitem__(new PyString("__file__"),
new PyString(opts.filename));
FileInputStream file;
try {
file = new FileInputStream(new RelativeFile(opts.filename));
} catch (FileNotFoundException e) {
throw Py.IOError(e);
}
try {
if (PosixModule.getPOSIX().isatty(file.getFD())) {
opts.interactive = true;
interp.interact(null, new PyFile(file));
System.exit(0);
} else {
interp.execfile(file, opts.filename);
}
} finally {
file.close();
}
} catch (Throwable t) {
if (t instanceof PyException
&& ((PyException)t).match(_systemrestart.SystemRestart)) {
// Shutdown this instance...
shouldRestart = true;
shutdownInterpreter();
interp.cleanup();
// ..reset the state...
Py.setSystemState(new PySystemState());
// ...and start again
return;
} else {
Py.printException(t);
if (!opts.interactive) {
interp.cleanup();
System.exit(-1);
}
}
}
}
}
else {
// if there was no file name on the command line, then "" is the first element
// on sys.path. This is here because if there /was/ a filename on the c.l.,
// and say the -i option was given, sys.path[0] will have gotten filled in
// with the dir of the argument filename.
Py.getSystemState().path.insert(0, Py.EmptyString);
if (opts.command != null) {
try {
interp.exec(opts.command);
} catch (Throwable t) {
Py.printException(t);
System.exit(1);
}
}
if (opts.moduleName != null) {
// PEP 338 - Execute module as a script
try {
interp.exec("import runpy");
interp.set("name", Py.newString(opts.moduleName));
interp.exec("runpy.run_module(name, run_name='__main__', alter_sys=True)");
interp.cleanup();
System.exit(0);
} catch (Throwable t) {
Py.printException(t);
interp.cleanup();
System.exit(-1);
}
}
}
if (opts.fixInteractive || (opts.filename == null && opts.command == null)) {
if (opts.encoding == null) {
opts.encoding = PySystemState.registry.getProperty("python.console.encoding");
}
if (opts.encoding != null) {
if (!Charset.isSupported(opts.encoding)) {
System.err.println(opts.encoding
+ " is not a supported encoding on this JVM, so it can't "
+ "be used in python.console.encoding.");
System.exit(1);
}
interp.cflags.encoding = opts.encoding;
}
try {
interp.interact(null, null);
} catch (Throwable t) {
Py.printException(t);
}
}
interp.cleanup();
if (opts.fixInteractive || opts.interactive) {
System.exit(0);
}
}
|
diff --git a/src/org/jwildfire/create/tina/render/GammaCorrectionFilter.java b/src/org/jwildfire/create/tina/render/GammaCorrectionFilter.java
index f4faff68..ec8e5d6b 100644
--- a/src/org/jwildfire/create/tina/render/GammaCorrectionFilter.java
+++ b/src/org/jwildfire/create/tina/render/GammaCorrectionFilter.java
@@ -1,157 +1,159 @@
/*
JWildfire - an image and animation processor written in Java
Copyright (C) 1995-2011 Andreas Maschke
This 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 software 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 software;
if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jwildfire.create.tina.render;
import org.jwildfire.create.tina.base.Flame;
public class GammaCorrectionFilter {
private final Flame flame;
private int vibInt;
private int inverseVibInt;
private double gamma;
private double sclGamma;
private int bgRed, bgGreen, bgBlue;
public GammaCorrectionFilter(Flame pFlame) {
flame = pFlame;
initFilter();
}
private void initFilter() {
gamma = (flame.getGamma() == 0.0) ? flame.getGamma() : 1.0 / flame.getGamma();
vibInt = (int) (flame.getVibrancy() * 256.0 + 0.5);
inverseVibInt = 256 - vibInt;
sclGamma = 0.0;
if (flame.getGammaThreshold() != 0) {
sclGamma = Math.pow(flame.getGammaThreshold(), gamma - 1);
}
bgRed = flame.getBGColorRed();
bgGreen = flame.getBGColorGreen();
bgBlue = flame.getBGColorBlue();
}
public void transformPoint(LogDensityPoint logDensityPnt, GammaCorrectedRGBPoint pRGBPoint) {
double logScl;
int inverseAlphaInt;
if (logDensityPnt.intensity > 0.0) {
// gamma linearization
double alpha;
if (logDensityPnt.intensity <= flame.getGammaThreshold()) {
double frac = logDensityPnt.intensity / flame.getGammaThreshold();
alpha = (1.0 - frac) * logDensityPnt.intensity * sclGamma + frac * Math.pow(logDensityPnt.intensity, gamma);
}
else {
alpha = Math.pow(logDensityPnt.intensity, gamma);
}
logScl = vibInt * alpha / logDensityPnt.intensity;
int alphaInt = (int) (alpha * 256 + 0.5);
if (alphaInt < 0)
alphaInt = 0;
else if (alphaInt > 255)
alphaInt = 255;
inverseAlphaInt = 255 - alphaInt;
}
else {
pRGBPoint.red = bgRed;
pRGBPoint.green = bgGreen;
pRGBPoint.blue = bgBlue;
return;
}
int red, green, blue;
if (inverseVibInt > 0) {
red = (int) (logScl * logDensityPnt.red + inverseVibInt * Math.pow(logDensityPnt.red, gamma) + 0.5);
green = (int) (logScl * logDensityPnt.green + inverseVibInt * Math.pow(logDensityPnt.green, gamma) + 0.5);
blue = (int) (logScl * logDensityPnt.blue + inverseVibInt * Math.pow(logDensityPnt.blue, gamma) + 0.5);
}
else {
red = (int) (logScl * logDensityPnt.red + 0.5);
green = (int) (logScl * logDensityPnt.green + 0.5);
blue = (int) (logScl * logDensityPnt.blue + 0.5);
}
red = red + ((inverseAlphaInt * bgRed) >> 8);
if (red < 0)
red = 0;
else if (red > 255)
red = 255;
green = green + ((inverseAlphaInt * bgGreen) >> 8);
if (green < 0)
green = 0;
else if (green > 255)
green = 255;
blue = blue + ((inverseAlphaInt * bgBlue) >> 8);
if (blue < 0)
blue = 0;
+ else if (blue > 255)
+ blue = 255;
pRGBPoint.red = red;
pRGBPoint.green = green;
pRGBPoint.blue = blue;
}
public void transformPointSimple(LogDensityPoint logDensityPnt, GammaCorrectedRGBPoint pRGBPoint) {
double logScl;
int inverseAlphaInt;
if (logDensityPnt.intensity > 0.0) {
// gamma linearization
double alpha = Math.pow(logDensityPnt.intensity, gamma);
logScl = vibInt * alpha / logDensityPnt.intensity;
int alphaInt = (int) (alpha * 256 + 0.5);
if (alphaInt < 0)
alphaInt = 0;
else if (alphaInt > 255)
alphaInt = 255;
inverseAlphaInt = 255 - alphaInt;
}
else {
pRGBPoint.red = bgRed;
pRGBPoint.green = bgGreen;
pRGBPoint.blue = bgBlue;
return;
}
int red, green, blue;
red = (int) (logScl * logDensityPnt.red + 0.5);
green = (int) (logScl * logDensityPnt.green + 0.5);
blue = (int) (logScl * logDensityPnt.blue + 0.5);
red = red + ((inverseAlphaInt * bgRed) >> 8);
if (red < 0)
red = 0;
else if (red > 255)
red = 255;
green = green + ((inverseAlphaInt * bgGreen) >> 8);
if (green < 0)
green = 0;
else if (green > 255)
green = 255;
blue = blue + ((inverseAlphaInt * bgBlue) >> 8);
if (blue < 0)
blue = 0;
pRGBPoint.red = red;
pRGBPoint.green = green;
pRGBPoint.blue = blue;
}
}
| true | true | public void transformPoint(LogDensityPoint logDensityPnt, GammaCorrectedRGBPoint pRGBPoint) {
double logScl;
int inverseAlphaInt;
if (logDensityPnt.intensity > 0.0) {
// gamma linearization
double alpha;
if (logDensityPnt.intensity <= flame.getGammaThreshold()) {
double frac = logDensityPnt.intensity / flame.getGammaThreshold();
alpha = (1.0 - frac) * logDensityPnt.intensity * sclGamma + frac * Math.pow(logDensityPnt.intensity, gamma);
}
else {
alpha = Math.pow(logDensityPnt.intensity, gamma);
}
logScl = vibInt * alpha / logDensityPnt.intensity;
int alphaInt = (int) (alpha * 256 + 0.5);
if (alphaInt < 0)
alphaInt = 0;
else if (alphaInt > 255)
alphaInt = 255;
inverseAlphaInt = 255 - alphaInt;
}
else {
pRGBPoint.red = bgRed;
pRGBPoint.green = bgGreen;
pRGBPoint.blue = bgBlue;
return;
}
int red, green, blue;
if (inverseVibInt > 0) {
red = (int) (logScl * logDensityPnt.red + inverseVibInt * Math.pow(logDensityPnt.red, gamma) + 0.5);
green = (int) (logScl * logDensityPnt.green + inverseVibInt * Math.pow(logDensityPnt.green, gamma) + 0.5);
blue = (int) (logScl * logDensityPnt.blue + inverseVibInt * Math.pow(logDensityPnt.blue, gamma) + 0.5);
}
else {
red = (int) (logScl * logDensityPnt.red + 0.5);
green = (int) (logScl * logDensityPnt.green + 0.5);
blue = (int) (logScl * logDensityPnt.blue + 0.5);
}
red = red + ((inverseAlphaInt * bgRed) >> 8);
if (red < 0)
red = 0;
else if (red > 255)
red = 255;
green = green + ((inverseAlphaInt * bgGreen) >> 8);
if (green < 0)
green = 0;
else if (green > 255)
green = 255;
blue = blue + ((inverseAlphaInt * bgBlue) >> 8);
if (blue < 0)
blue = 0;
pRGBPoint.red = red;
pRGBPoint.green = green;
pRGBPoint.blue = blue;
}
| public void transformPoint(LogDensityPoint logDensityPnt, GammaCorrectedRGBPoint pRGBPoint) {
double logScl;
int inverseAlphaInt;
if (logDensityPnt.intensity > 0.0) {
// gamma linearization
double alpha;
if (logDensityPnt.intensity <= flame.getGammaThreshold()) {
double frac = logDensityPnt.intensity / flame.getGammaThreshold();
alpha = (1.0 - frac) * logDensityPnt.intensity * sclGamma + frac * Math.pow(logDensityPnt.intensity, gamma);
}
else {
alpha = Math.pow(logDensityPnt.intensity, gamma);
}
logScl = vibInt * alpha / logDensityPnt.intensity;
int alphaInt = (int) (alpha * 256 + 0.5);
if (alphaInt < 0)
alphaInt = 0;
else if (alphaInt > 255)
alphaInt = 255;
inverseAlphaInt = 255 - alphaInt;
}
else {
pRGBPoint.red = bgRed;
pRGBPoint.green = bgGreen;
pRGBPoint.blue = bgBlue;
return;
}
int red, green, blue;
if (inverseVibInt > 0) {
red = (int) (logScl * logDensityPnt.red + inverseVibInt * Math.pow(logDensityPnt.red, gamma) + 0.5);
green = (int) (logScl * logDensityPnt.green + inverseVibInt * Math.pow(logDensityPnt.green, gamma) + 0.5);
blue = (int) (logScl * logDensityPnt.blue + inverseVibInt * Math.pow(logDensityPnt.blue, gamma) + 0.5);
}
else {
red = (int) (logScl * logDensityPnt.red + 0.5);
green = (int) (logScl * logDensityPnt.green + 0.5);
blue = (int) (logScl * logDensityPnt.blue + 0.5);
}
red = red + ((inverseAlphaInt * bgRed) >> 8);
if (red < 0)
red = 0;
else if (red > 255)
red = 255;
green = green + ((inverseAlphaInt * bgGreen) >> 8);
if (green < 0)
green = 0;
else if (green > 255)
green = 255;
blue = blue + ((inverseAlphaInt * bgBlue) >> 8);
if (blue < 0)
blue = 0;
else if (blue > 255)
blue = 255;
pRGBPoint.red = red;
pRGBPoint.green = green;
pRGBPoint.blue = blue;
}
|
diff --git a/src/org/balau/fakedawn/DawnSound.java b/src/org/balau/fakedawn/DawnSound.java
index f01a7df..f373c37 100644
--- a/src/org/balau/fakedawn/DawnSound.java
+++ b/src/org/balau/fakedawn/DawnSound.java
@@ -1,236 +1,236 @@
/**
* Copyright 2012 Francesco Balducci
*
* This file is part of FakeDawn.
*
* FakeDawn is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FakeDawn 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FakeDawn. If not, see <http://www.gnu.org/licenses/>.
*/
package org.balau.fakedawn;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.Log;
/**
* @author francesco
*
*/
public class DawnSound extends Service implements OnPreparedListener, OnCompletionListener, OnErrorListener {
public static final String EXTRA_SOUND_URI = "org.balau.fakedawn.DawnSound.EXTRA_SOUND_URI";
public static final String EXTRA_SOUND_START_MILLIS = "org.balau.fakedawn.DawnSound.EXTRA_SOUND_START_MILLIS";
public static final String EXTRA_SOUND_END_MILLIS = "org.balau.fakedawn.DawnSound.EXTRA_SOUND_END_MILLIS";
public static final String EXTRA_SOUND_VOLUME = "org.balau.fakedawn.DawnSound.EXTRA_SOUND_VOLUME";
public static final String EXTRA_VIBRATE = "org.balau.fakedawn.DawnSound.EXTRA_VIBRATE";
private static int TIMER_TICK_SECONDS = 10;
private Timer m_timer = null;
private long m_soundStartMillis;
private long m_soundEndMillis;
private MediaPlayer m_player = new MediaPlayer();
private boolean m_soundInitialized = false;
private Vibrator m_vibrator = null;
private boolean m_vibrate = false;
private long[] m_vibratePattern = {0, 1000, 1000};
/* (non-Javadoc)
* @see android.app.Service#onBind(android.content.Intent)
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
/* (non-Javadoc)
* @see android.app.Service#onDestroy()
*/
@Override
public void onDestroy() {
super.onDestroy();
if(m_soundInitialized)
{
m_soundInitialized = false;
if(m_player.isPlaying())
{
m_player.stop();
}
}
if(m_timer != null)
m_timer.cancel();
if(m_vibrate)
{
m_vibrate = false;
m_vibrator.cancel();
}
}
/* (non-Javadoc)
* @see android.app.Service#onStartCommand(android.content.Intent, int, int)
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!m_soundInitialized)
{
m_player.setOnPreparedListener(this);
m_player.setOnCompletionListener(this);
m_player.setOnErrorListener(this);
m_player.setAudioStreamType(AudioManager.STREAM_ALARM);
m_player.reset();
m_soundStartMillis = intent.getLongExtra(EXTRA_SOUND_START_MILLIS, 0);
m_soundEndMillis = intent.getLongExtra(EXTRA_SOUND_END_MILLIS, 0);
String sound = intent.getStringExtra(EXTRA_SOUND_URI);
if(sound.isEmpty())
{
Log.d("FakeDawn", "Silent.");
}
else
{
Uri soundUri = Uri.parse(sound);
if(soundUri != null)
{
AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_ALARM);
int volume = intent.getIntExtra(EXTRA_SOUND_VOLUME, maxVolume/2);
if(volume < 0) volume = 0;
if(volume > maxVolume) volume = maxVolume;
am.setStreamVolume(AudioManager.STREAM_ALARM, volume, 0);
try {
m_player.setDataSource(this, soundUri);
m_soundInitialized = true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
m_vibrate = intent.getBooleanExtra(EXTRA_VIBRATE, false);
if(m_vibrate)
{
m_vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if(m_vibrator == null)
{
m_vibrate = false;
}
}
m_timer = new Timer();
m_timer.schedule(
new TimerTask() {
@Override
public void run() {
if(m_soundInitialized)
{
if(!m_player.isPlaying())
{
m_player.prepareAsync();
}
}
if(m_vibrate)
{
m_vibrator.vibrate(m_vibratePattern, 0);
}
}
}, new Date(m_soundStartMillis));
Log.d("FakeDawn", "Sound scheduled.");
}
}
- return START_STICKY;
+ return START_REDELIVER_INTENT;
}
private void updateVolume(long currentTimeMillis)
{
float volume;
long millis_from_start;
long soundRiseDurationMillis;
millis_from_start = currentTimeMillis - m_soundStartMillis;
soundRiseDurationMillis = m_soundEndMillis - m_soundStartMillis;
if(soundRiseDurationMillis > 0)
{
volume = Math.max(
0.0F,
Math.min(
1.0F,
((float)millis_from_start)/((float)soundRiseDurationMillis))
);
}
else
{
volume = (millis_from_start >= 0)?1.0F:0.0F;
}
m_player.setVolume(volume, volume);
}
@Override
public void onPrepared(MediaPlayer mp) {
m_player.setLooping(true);
updateVolume(System.currentTimeMillis());
m_player.start();
m_timer = new Timer();
m_timer.schedule(
new TimerTask() {
@Override
public void run() {
if(m_player.isPlaying())
{
updateVolume(System.currentTimeMillis());
}
else
{
m_timer.cancel();
}
}
}, TIMER_TICK_SECONDS*1000, TIMER_TICK_SECONDS*1000);
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e("FakeDawn", String.format("MediaPlayer error. what: %d, extra: %d", what, extra));
m_player.reset();
m_soundInitialized = false;
return true;
}
@Override
public void onCompletion(MediaPlayer mp) {
Log.w("FakeDawn", "Sound completed even if looping.");
m_player.stop();
}
}
| true | true | public int onStartCommand(Intent intent, int flags, int startId) {
if(!m_soundInitialized)
{
m_player.setOnPreparedListener(this);
m_player.setOnCompletionListener(this);
m_player.setOnErrorListener(this);
m_player.setAudioStreamType(AudioManager.STREAM_ALARM);
m_player.reset();
m_soundStartMillis = intent.getLongExtra(EXTRA_SOUND_START_MILLIS, 0);
m_soundEndMillis = intent.getLongExtra(EXTRA_SOUND_END_MILLIS, 0);
String sound = intent.getStringExtra(EXTRA_SOUND_URI);
if(sound.isEmpty())
{
Log.d("FakeDawn", "Silent.");
}
else
{
Uri soundUri = Uri.parse(sound);
if(soundUri != null)
{
AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_ALARM);
int volume = intent.getIntExtra(EXTRA_SOUND_VOLUME, maxVolume/2);
if(volume < 0) volume = 0;
if(volume > maxVolume) volume = maxVolume;
am.setStreamVolume(AudioManager.STREAM_ALARM, volume, 0);
try {
m_player.setDataSource(this, soundUri);
m_soundInitialized = true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
m_vibrate = intent.getBooleanExtra(EXTRA_VIBRATE, false);
if(m_vibrate)
{
m_vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if(m_vibrator == null)
{
m_vibrate = false;
}
}
m_timer = new Timer();
m_timer.schedule(
new TimerTask() {
@Override
public void run() {
if(m_soundInitialized)
{
if(!m_player.isPlaying())
{
m_player.prepareAsync();
}
}
if(m_vibrate)
{
m_vibrator.vibrate(m_vibratePattern, 0);
}
}
}, new Date(m_soundStartMillis));
Log.d("FakeDawn", "Sound scheduled.");
}
}
return START_STICKY;
}
| public int onStartCommand(Intent intent, int flags, int startId) {
if(!m_soundInitialized)
{
m_player.setOnPreparedListener(this);
m_player.setOnCompletionListener(this);
m_player.setOnErrorListener(this);
m_player.setAudioStreamType(AudioManager.STREAM_ALARM);
m_player.reset();
m_soundStartMillis = intent.getLongExtra(EXTRA_SOUND_START_MILLIS, 0);
m_soundEndMillis = intent.getLongExtra(EXTRA_SOUND_END_MILLIS, 0);
String sound = intent.getStringExtra(EXTRA_SOUND_URI);
if(sound.isEmpty())
{
Log.d("FakeDawn", "Silent.");
}
else
{
Uri soundUri = Uri.parse(sound);
if(soundUri != null)
{
AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_ALARM);
int volume = intent.getIntExtra(EXTRA_SOUND_VOLUME, maxVolume/2);
if(volume < 0) volume = 0;
if(volume > maxVolume) volume = maxVolume;
am.setStreamVolume(AudioManager.STREAM_ALARM, volume, 0);
try {
m_player.setDataSource(this, soundUri);
m_soundInitialized = true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
m_vibrate = intent.getBooleanExtra(EXTRA_VIBRATE, false);
if(m_vibrate)
{
m_vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if(m_vibrator == null)
{
m_vibrate = false;
}
}
m_timer = new Timer();
m_timer.schedule(
new TimerTask() {
@Override
public void run() {
if(m_soundInitialized)
{
if(!m_player.isPlaying())
{
m_player.prepareAsync();
}
}
if(m_vibrate)
{
m_vibrator.vibrate(m_vibratePattern, 0);
}
}
}, new Date(m_soundStartMillis));
Log.d("FakeDawn", "Sound scheduled.");
}
}
return START_REDELIVER_INTENT;
}
|
diff --git a/java/com/couchbase/cblite/testapp/tests/Replicator.java b/java/com/couchbase/cblite/testapp/tests/Replicator.java
index 2944af86..fd5f6322 100644
--- a/java/com/couchbase/cblite/testapp/tests/Replicator.java
+++ b/java/com/couchbase/cblite/testapp/tests/Replicator.java
@@ -1,286 +1,286 @@
package com.couchbase.cblite.testapp.tests;
import java.io.IOException;
import java.net.URL;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.CountDownLatch;
import junit.framework.Assert;
import android.os.AsyncTask;
import android.util.Log;
import com.couchbase.cblite.CBLBody;
import com.couchbase.cblite.CBLDatabase;
import com.couchbase.cblite.CBLRevision;
import com.couchbase.cblite.CBLStatus;
import com.couchbase.cblite.replicator.CBLPusher;
import com.couchbase.cblite.replicator.CBLReplicator;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
public class Replicator extends CBLiteTestCase {
public static final String TAG = "Replicator";
public String testPusher() throws Throwable {
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
URL remote = getReplicationURL();
String docIdTimestamp = Long.toString(System.currentTimeMillis());
// Create some documents:
Map<String, Object> documentProperties = new HashMap<String, Object>();
final String doc1Id = String.format("doc1-%s", docIdTimestamp);
documentProperties.put("_id", doc1Id);
documentProperties.put("foo", 1);
documentProperties.put("bar", false);
CBLBody body = new CBLBody(documentProperties);
- CBLRevision rev1 = new CBLRevision(body);
+ CBLRevision rev1 = new CBLRevision(body, database);
CBLStatus status = new CBLStatus();
rev1 = database.putRevision(rev1, null, false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
documentProperties.put("_rev", rev1.getRevId());
documentProperties.put("UPDATED", true);
@SuppressWarnings("unused")
- CBLRevision rev2 = database.putRevision(new CBLRevision(documentProperties), rev1.getRevId(), false, status);
+ CBLRevision rev2 = database.putRevision(new CBLRevision(documentProperties, database), rev1.getRevId(), false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
documentProperties = new HashMap<String, Object>();
String doc2Id = String.format("doc2-%s", docIdTimestamp);
documentProperties.put("_id", doc2Id);
documentProperties.put("baz", 666);
documentProperties.put("fnord", true);
- database.putRevision(new CBLRevision(documentProperties), null, false, status);
+ database.putRevision(new CBLRevision(documentProperties, database), null, false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
final CBLReplicator repl = database.getReplicator(remote, true, false, server.getWorkExecutor());
((CBLPusher)repl).setCreateTarget(true);
AsyncTask replicationTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
// Push them to the remote:
repl.start();
Assert.assertTrue(repl.isRunning());
return null;
}
};
replicationTask.execute();
ReplicationObserver replicationObserver = new ReplicationObserver(replicationDoneSignal);
repl.addObserver(replicationObserver);
Log.d(TAG, "Waiting for replicator to finish");
try {
replicationDoneSignal.await();
Log.d(TAG, "replicator finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
// make sure doc1 is there
// TODO: make sure doc2 is there (refactoring needed)
URL replicationUrlTrailing = new URL(String.format("%s/", remote.toExternalForm()));
final URL pathToDoc = new URL(replicationUrlTrailing, doc1Id);
Log.d(TAG, "Send http request to " + pathToDoc);
final CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
AsyncTask getDocTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(pathToDoc.toExternalForm()));
StatusLine statusLine = response.getStatusLine();
Assert.assertTrue(statusLine.getStatusCode() == HttpStatus.SC_OK);
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Assert.assertTrue(responseString.contains(doc1Id));
Log.d(TAG, "result: " + responseString);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Assert.assertNull("Got ClientProtocolException: " + e.getLocalizedMessage(), e);
} catch (IOException e) {
Assert.assertNull("Got IOException: " + e.getLocalizedMessage(), e);
}
httpRequestDoneSignal.countDown();
return null;
}
};
getDocTask.execute();
Log.d(TAG, "Waiting for http request to finish");
try {
httpRequestDoneSignal.await();
Log.d(TAG, "http request finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "testPusher() finished");
return docIdTimestamp;
}
public void testPuller() throws Throwable {
String docIdTimestamp = Long.toString(System.currentTimeMillis());
final String doc1Id = String.format("doc1-%s", docIdTimestamp);
// push a document to server
final String json = String.format("{\"foo\":1,\"bar\":false}", doc1Id);
URL replicationUrlTrailing = new URL(String.format("%s/%s", getReplicationURL().toExternalForm(), doc1Id));
final URL pathToDoc = new URL(replicationUrlTrailing, doc1Id);
Log.d(TAG, "Send http request to " + pathToDoc);
final CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
AsyncTask getDocTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
HttpPut post = new HttpPut(pathToDoc.toExternalForm());
StringEntity se = new StringEntity( json.toString() );
se.setContentType(new BasicHeader("content_type", "application/json"));
post.setEntity(se);
response = httpclient.execute(post);
StatusLine statusLine = response.getStatusLine();
Log.d(TAG, "Got response: " + statusLine);
Assert.assertTrue(statusLine.getStatusCode() == HttpStatus.SC_CREATED);
} catch (ClientProtocolException e) {
Assert.assertNull("Got ClientProtocolException: " + e.getLocalizedMessage(), e);
} catch (IOException e) {
Assert.assertNull("Got IOException: " + e.getLocalizedMessage(), e);
}
httpRequestDoneSignal.countDown();
return null;
}
};
getDocTask.execute();
Log.d(TAG, "Waiting for http request to finish");
try {
httpRequestDoneSignal.await();
Log.d(TAG, "http request finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
URL remote = getReplicationURL();
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
final CBLReplicator repl = database.getReplicator(remote, false, false, server.getWorkExecutor());
AsyncTask replicationTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
// Push them to the remote:
repl.start();
Assert.assertTrue(repl.isRunning());
return null;
}
};
replicationTask.execute();
ReplicationObserver replicationObserver = new ReplicationObserver(replicationDoneSignal);
repl.addObserver(replicationObserver);
Log.d(TAG, "Waiting for replicator to finish");
try {
replicationDoneSignal.await();
Log.d(TAG, "replicator finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
CBLRevision doc = database.getDocumentWithIDAndRev(doc1Id, null, EnumSet.noneOf(CBLDatabase.TDContentOptions.class));
Assert.assertNotNull(doc);
Assert.assertTrue(doc.getRevId().startsWith("1-"));
Assert.assertEquals(1, doc.getProperties().get("foo"));
Log.d(TAG, "testPuller() finished");
}
class ReplicationObserver implements Observer {
public boolean replicationFinished = false;
private CountDownLatch doneSignal;
public ReplicationObserver(CountDownLatch doneSignal) {
super();
this.doneSignal = doneSignal;
}
@Override
public void update(Observable observable, Object data) {
Log.d(TAG, "ReplicationObserver.update called. observable: " + observable);
CBLReplicator replicator = (CBLReplicator) observable;
if (!replicator.isRunning()) {
replicationFinished = true;
String msg = String.format("myobserver.update called, set replicationFinished to: %b", replicationFinished);
Log.d(TAG, msg);
doneSignal.countDown();
}
else {
String msg = String.format("myobserver.update called, but replicator still running, so ignore it");
Log.d(TAG, msg);
}
}
boolean isReplicationFinished() {
return replicationFinished;
}
}
}
| false | true | public String testPusher() throws Throwable {
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
URL remote = getReplicationURL();
String docIdTimestamp = Long.toString(System.currentTimeMillis());
// Create some documents:
Map<String, Object> documentProperties = new HashMap<String, Object>();
final String doc1Id = String.format("doc1-%s", docIdTimestamp);
documentProperties.put("_id", doc1Id);
documentProperties.put("foo", 1);
documentProperties.put("bar", false);
CBLBody body = new CBLBody(documentProperties);
CBLRevision rev1 = new CBLRevision(body);
CBLStatus status = new CBLStatus();
rev1 = database.putRevision(rev1, null, false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
documentProperties.put("_rev", rev1.getRevId());
documentProperties.put("UPDATED", true);
@SuppressWarnings("unused")
CBLRevision rev2 = database.putRevision(new CBLRevision(documentProperties), rev1.getRevId(), false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
documentProperties = new HashMap<String, Object>();
String doc2Id = String.format("doc2-%s", docIdTimestamp);
documentProperties.put("_id", doc2Id);
documentProperties.put("baz", 666);
documentProperties.put("fnord", true);
database.putRevision(new CBLRevision(documentProperties), null, false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
final CBLReplicator repl = database.getReplicator(remote, true, false, server.getWorkExecutor());
((CBLPusher)repl).setCreateTarget(true);
AsyncTask replicationTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
// Push them to the remote:
repl.start();
Assert.assertTrue(repl.isRunning());
return null;
}
};
replicationTask.execute();
ReplicationObserver replicationObserver = new ReplicationObserver(replicationDoneSignal);
repl.addObserver(replicationObserver);
Log.d(TAG, "Waiting for replicator to finish");
try {
replicationDoneSignal.await();
Log.d(TAG, "replicator finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
// make sure doc1 is there
// TODO: make sure doc2 is there (refactoring needed)
URL replicationUrlTrailing = new URL(String.format("%s/", remote.toExternalForm()));
final URL pathToDoc = new URL(replicationUrlTrailing, doc1Id);
Log.d(TAG, "Send http request to " + pathToDoc);
final CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
AsyncTask getDocTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(pathToDoc.toExternalForm()));
StatusLine statusLine = response.getStatusLine();
Assert.assertTrue(statusLine.getStatusCode() == HttpStatus.SC_OK);
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Assert.assertTrue(responseString.contains(doc1Id));
Log.d(TAG, "result: " + responseString);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Assert.assertNull("Got ClientProtocolException: " + e.getLocalizedMessage(), e);
} catch (IOException e) {
Assert.assertNull("Got IOException: " + e.getLocalizedMessage(), e);
}
httpRequestDoneSignal.countDown();
return null;
}
};
getDocTask.execute();
Log.d(TAG, "Waiting for http request to finish");
try {
httpRequestDoneSignal.await();
Log.d(TAG, "http request finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "testPusher() finished");
return docIdTimestamp;
}
| public String testPusher() throws Throwable {
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
URL remote = getReplicationURL();
String docIdTimestamp = Long.toString(System.currentTimeMillis());
// Create some documents:
Map<String, Object> documentProperties = new HashMap<String, Object>();
final String doc1Id = String.format("doc1-%s", docIdTimestamp);
documentProperties.put("_id", doc1Id);
documentProperties.put("foo", 1);
documentProperties.put("bar", false);
CBLBody body = new CBLBody(documentProperties);
CBLRevision rev1 = new CBLRevision(body, database);
CBLStatus status = new CBLStatus();
rev1 = database.putRevision(rev1, null, false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
documentProperties.put("_rev", rev1.getRevId());
documentProperties.put("UPDATED", true);
@SuppressWarnings("unused")
CBLRevision rev2 = database.putRevision(new CBLRevision(documentProperties, database), rev1.getRevId(), false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
documentProperties = new HashMap<String, Object>();
String doc2Id = String.format("doc2-%s", docIdTimestamp);
documentProperties.put("_id", doc2Id);
documentProperties.put("baz", 666);
documentProperties.put("fnord", true);
database.putRevision(new CBLRevision(documentProperties, database), null, false, status);
Assert.assertEquals(CBLStatus.CREATED, status.getCode());
final CBLReplicator repl = database.getReplicator(remote, true, false, server.getWorkExecutor());
((CBLPusher)repl).setCreateTarget(true);
AsyncTask replicationTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
// Push them to the remote:
repl.start();
Assert.assertTrue(repl.isRunning());
return null;
}
};
replicationTask.execute();
ReplicationObserver replicationObserver = new ReplicationObserver(replicationDoneSignal);
repl.addObserver(replicationObserver);
Log.d(TAG, "Waiting for replicator to finish");
try {
replicationDoneSignal.await();
Log.d(TAG, "replicator finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
// make sure doc1 is there
// TODO: make sure doc2 is there (refactoring needed)
URL replicationUrlTrailing = new URL(String.format("%s/", remote.toExternalForm()));
final URL pathToDoc = new URL(replicationUrlTrailing, doc1Id);
Log.d(TAG, "Send http request to " + pathToDoc);
final CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
AsyncTask getDocTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... aParams) {
org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(pathToDoc.toExternalForm()));
StatusLine statusLine = response.getStatusLine();
Assert.assertTrue(statusLine.getStatusCode() == HttpStatus.SC_OK);
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Assert.assertTrue(responseString.contains(doc1Id));
Log.d(TAG, "result: " + responseString);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Assert.assertNull("Got ClientProtocolException: " + e.getLocalizedMessage(), e);
} catch (IOException e) {
Assert.assertNull("Got IOException: " + e.getLocalizedMessage(), e);
}
httpRequestDoneSignal.countDown();
return null;
}
};
getDocTask.execute();
Log.d(TAG, "Waiting for http request to finish");
try {
httpRequestDoneSignal.await();
Log.d(TAG, "http request finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "testPusher() finished");
return docIdTimestamp;
}
|
diff --git a/App/src/com/dozuki/ifixit/view/ui/TopicViewFragment.java b/App/src/com/dozuki/ifixit/view/ui/TopicViewFragment.java
index f1d1e66a..e442e8d2 100644
--- a/App/src/com/dozuki/ifixit/view/ui/TopicViewFragment.java
+++ b/App/src/com/dozuki/ifixit/view/ui/TopicViewFragment.java
@@ -1,285 +1,285 @@
package com.dozuki.ifixit.view.ui;
import java.net.URLEncoder;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.dozuki.ifixit.MainApplication;
import com.dozuki.ifixit.R;
import com.dozuki.ifixit.util.APIService;
import com.dozuki.ifixit.view.model.TopicLeaf;
import com.dozuki.ifixit.view.model.TopicNode;
import com.ifixit.android.imagemanager.ImageManager;
public class TopicViewFragment extends SherlockFragment
implements ActionBar.TabListener {
private static final int GUIDES_TAB = 0;
private static final int ANSWERS_TAB = 1;
private static final int MORE_INFO_TAB = 2;
private static final String CURRENT_PAGE = "CURRENT_PAGE";
private static final String CURRENT_TOPIC_LEAF = "CURRENT_TOPIC_LEAF";
private static final String CURRENT_TOPIC_NODE = "CURRENT_TOPIC_NODE";
private TopicNode mTopicNode;
private TopicLeaf mTopicLeaf;
private ImageManager mImageManager;
private ActionBar mActionBar;
private int mSelectedTab = -1;
private BroadcastReceiver mApiReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
APIService.Result result = (APIService.Result)
intent.getExtras().getSerializable(APIService.RESULT);
if (!result.hasError()) {
setTopicLeaf((TopicLeaf)result.getResult());
} else {
APIService.getErrorDialog(getActivity(),
result.getError(),
APIService.getTopicIntent(getActivity(),
mTopicNode.getName())).show();
}
}
};
public boolean isDisplayingTopic() {
return mTopicLeaf != null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mImageManager == null) {
mImageManager = ((MainApplication)getActivity().getApplication()).
getImageManager();
}
if (savedInstanceState != null) {
mSelectedTab = savedInstanceState.getInt(CURRENT_PAGE);
mTopicNode = (TopicNode)savedInstanceState.getSerializable(
CURRENT_TOPIC_NODE);
TopicLeaf topicLeaf = (TopicLeaf)savedInstanceState.getSerializable(
CURRENT_TOPIC_LEAF);
if (topicLeaf != null) {
setTopicLeaf(topicLeaf);
} else if (mTopicNode != null) {
getTopicLeaf(mTopicNode.getName());
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.topic_view_fragment, container,
false);
return view;
}
@Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(APIService.ACTION_TOPIC);
getActivity().registerReceiver(mApiReceiver, filter);
}
@Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(mApiReceiver);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActionBar = ((SherlockFragmentActivity)activity).getSupportActionBar();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(CURRENT_PAGE, mActionBar.getSelectedNavigationIndex());
outState.putSerializable(CURRENT_TOPIC_LEAF, mTopicLeaf);
outState.putSerializable(CURRENT_TOPIC_NODE, mTopicNode);
}
public void setTopicNode(TopicNode topicNode) {
if (topicNode == null) {
mTopicNode = null;
mTopicLeaf = null;
return;
}
if (mTopicNode == null || !mTopicNode.equals(topicNode)) {
getTopicLeaf(topicNode.getName());
} else {
selectDefaultTab();
}
mTopicNode = topicNode;
}
public void setTopicLeaf(TopicLeaf topicLeaf) {
if (getActivity() == null) {
return;
}
if (mTopicLeaf != null && topicLeaf != null) {
if (mTopicLeaf.equals(topicLeaf)) {
selectDefaultTab();
return;
- } else if (!mTopicLeaf.getName().equals(mTopicNode.getName())) {
+ } else if (!topicLeaf.getName().equals(mTopicNode.getName())) {
// Not the most recently selected topic... wait for another.
return;
}
}
mTopicLeaf = topicLeaf;
mActionBar.removeAllTabs();
if (mTopicLeaf == null) {
// display error message
return;
}
mActionBar.setTitle(mTopicLeaf.getName());
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab = mActionBar.newTab();
tab.setText(getActivity().getString(R.string.guides));
tab.setTabListener(this);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(getActivity().getString(R.string.answers));
tab.setTabListener(this);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(getActivity().getString(R.string.info));
tab.setTabListener(this);
mActionBar.addTab(tab);
if (mSelectedTab != -1) {
mActionBar.setSelectedNavigationItem(mSelectedTab);
} else {
selectDefaultTab();
}
}
private void displayLoading() {
mActionBar.removeAllTabs();
FragmentTransaction ft = getActivity().getSupportFragmentManager().
beginTransaction();
ft.replace(R.id.topic_view_page_fragment, new LoadingFragment());
ft.commit();
}
private void selectDefaultTab() {
int tab;
if (mTopicLeaf == null) {
return;
}
if (mTopicLeaf.getGuides().size() == 0) {
tab = MORE_INFO_TAB;
} else {
tab = GUIDES_TAB;
}
mActionBar.setSelectedNavigationItem(tab);
}
private void getTopicLeaf(String topicName) {
displayLoading();
mTopicLeaf = null;
mSelectedTab = -1;
getActivity().startService(
APIService.getTopicIntent(getActivity(),
topicName));
}
public TopicLeaf getTopicLeaf() {
return mTopicLeaf;
}
public TopicNode getTopicNode() {
return mTopicNode;
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
int position = tab.getPosition();
Fragment selectedFragment;
ft = getActivity().getSupportFragmentManager().beginTransaction();
if (mTopicLeaf == null) {
Log.w("iFixit", "Trying to get Fragment at bad position");
return;
}
if (position == GUIDES_TAB) {
if (mTopicLeaf.getGuides().size() == 0) {
selectedFragment = new NoGuidesFragment();
} else {
selectedFragment = new TopicGuideListFragment(mImageManager, mTopicLeaf);
}
} else if (position == ANSWERS_TAB) {
WebViewFragment webView = new WebViewFragment();
webView.loadUrl(mTopicLeaf.getSolutionsUrl());
selectedFragment = webView;
} else if (position == MORE_INFO_TAB) {
WebViewFragment webView = new WebViewFragment();
try {
webView.loadUrl("http://www.ifixit.com/c/" +
URLEncoder.encode(mTopicLeaf.getName(), "UTF-8"));
} catch (Exception e) {
Log.w("iFixit", "Encoding error: " + e.getMessage());
}
selectedFragment = webView;
} else {
Log.w("iFixit", "Too many tabs!");
return;
}
ft.replace(R.id.topic_view_page_fragment, selectedFragment);
ft.commit();
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
| true | true | public void setTopicLeaf(TopicLeaf topicLeaf) {
if (getActivity() == null) {
return;
}
if (mTopicLeaf != null && topicLeaf != null) {
if (mTopicLeaf.equals(topicLeaf)) {
selectDefaultTab();
return;
} else if (!mTopicLeaf.getName().equals(mTopicNode.getName())) {
// Not the most recently selected topic... wait for another.
return;
}
}
mTopicLeaf = topicLeaf;
mActionBar.removeAllTabs();
if (mTopicLeaf == null) {
// display error message
return;
}
mActionBar.setTitle(mTopicLeaf.getName());
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab = mActionBar.newTab();
tab.setText(getActivity().getString(R.string.guides));
tab.setTabListener(this);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(getActivity().getString(R.string.answers));
tab.setTabListener(this);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(getActivity().getString(R.string.info));
tab.setTabListener(this);
mActionBar.addTab(tab);
if (mSelectedTab != -1) {
mActionBar.setSelectedNavigationItem(mSelectedTab);
} else {
selectDefaultTab();
}
}
| public void setTopicLeaf(TopicLeaf topicLeaf) {
if (getActivity() == null) {
return;
}
if (mTopicLeaf != null && topicLeaf != null) {
if (mTopicLeaf.equals(topicLeaf)) {
selectDefaultTab();
return;
} else if (!topicLeaf.getName().equals(mTopicNode.getName())) {
// Not the most recently selected topic... wait for another.
return;
}
}
mTopicLeaf = topicLeaf;
mActionBar.removeAllTabs();
if (mTopicLeaf == null) {
// display error message
return;
}
mActionBar.setTitle(mTopicLeaf.getName());
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab = mActionBar.newTab();
tab.setText(getActivity().getString(R.string.guides));
tab.setTabListener(this);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(getActivity().getString(R.string.answers));
tab.setTabListener(this);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(getActivity().getString(R.string.info));
tab.setTabListener(this);
mActionBar.addTab(tab);
if (mSelectedTab != -1) {
mActionBar.setSelectedNavigationItem(mSelectedTab);
} else {
selectDefaultTab();
}
}
|
diff --git a/src/main/java/org/basex/query/item/FElem.java b/src/main/java/org/basex/query/item/FElem.java
index 0569745f9..e3f3df21b 100644
--- a/src/main/java/org/basex/query/item/FElem.java
+++ b/src/main/java/org/basex/query/item/FElem.java
@@ -1,235 +1,234 @@
package org.basex.query.item;
import static org.basex.query.QueryTokens.*;
import java.io.IOException;
import org.basex.data.Serializer;
import org.basex.query.iter.NodIter;
import org.basex.query.util.NSGlobal;
import org.basex.util.Atts;
import org.basex.util.Token;
import org.basex.util.TokenBuilder;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Element node fragment.
*
* @author Workgroup DBIS, University of Konstanz 2005-10, ISC License
* @author Christian Gruen
*/
public final class FElem extends FNode {
/** Namespaces. */
private final Atts ns;
/** Tag name. */
private final QNm name;
/** Base URI. */
private final byte[] base;
/**
* Constructor.
* @param n tag name
* @param b base uri
* @param p parent
*/
public FElem(final QNm n, final byte[] b, final Nod p) {
this(n, new NodIter(), new NodIter(), b, null, p);
}
/**
* Constructor.
* @param n tag name
* @param ch children
* @param at attributes
* @param b base uri
* @param nsp namespaces
* @param p parent
*/
public FElem(final QNm n, final NodIter ch, final NodIter at,
final byte[] b, final Atts nsp, final Nod p) {
super(Type.ELM);
name = n;
children = ch;
atts = at;
base = b;
ns = nsp;
par = p;
}
/**
* Constructor for DOM nodes (partial).
* Provided by Erdal Karaca.
* @param node DOM node
* @param p parent reference
*/
FElem(final Node node, final Nod p) {
super(Type.ELM);
final NodeList ch = node.getChildNodes();
final int s = ch.getLength();
final Nod[] childArr = new Nod[s];
final NamedNodeMap at = node.getAttributes();
final int as = at.getLength();
final Nod[] attArr = new Nod[as];
name = new QNm(Token.token(node.getNodeName()));
children = new NodIter(childArr, childArr.length);
atts = new NodIter(attArr, attArr.length);
base = Token.EMPTY;
ns = null;
par = p;
for(int i = 0; i < at.getLength(); i++) {
attArr[i] = new FAttr(at.item(i), this);
}
for(int i = 0; i < ch.getLength(); i++) {
final Node child = ch.item(i);
switch(child.getNodeType()) {
case Node.TEXT_NODE:
childArr[i] = new FTxt(child, this); break;
case Node.COMMENT_NODE:
childArr[i] = new FComm(child, this); break;
case Node.PROCESSING_INSTRUCTION_NODE:
childArr[i] = new FPI(child, this); break;
case Node.ELEMENT_NODE:
childArr[i] = new FElem(child, this); break;
default:
break;
}
}
}
@Override
public byte[] base() {
return base;
}
@Override
public QNm qname() {
return name;
}
@Override
public byte[] nname() {
return name.str();
}
@Override
public Atts ns() {
return ns;
}
@Override
public byte[] str() {
final TokenBuilder tb = new TokenBuilder();
for(int n = 0; n < children.size(); n++) {
final Nod c = children.get(n);
if(c.type == Type.ELM || c.type == Type.TXT) tb.add(c.str());
}
return tb.finish();
}
@Override
public void serialize(final Serializer ser) throws IOException {
final byte[] tag = name.str();
final byte[] uri = name.uri.str();
ser.openElement(tag);
// remember top level namespace
final byte[] dn = ser.dn;
boolean xmlns = false;
// serialize all namespaces at top level...
if(ser.level() == 1) {
final Atts nns = nsScope();
for(int a = 0; a < nns.size; a++) {
if(nns.key[a].length == 0) {
xmlns = true;
if(Token.eq(ser.dn, nns.val[a])) continue;
// reset default namespace
ser.dn = nns.val[a];
}
ser.namespace(nns.key[a], nns.val[a]);
}
// serialize default namespace if not done yet
for(int p = ser.ns.size - 1; p >= 0 && !xmlns; p--) {
if(ser.ns.key[p].length != 0) continue;
xmlns = true;
ser.dn = ser.ns.val[p];
ser.namespace(Token.EMPTY, ser.ns.val[p]);
}
} else {
if(ns != null) {
for(int p = ns.size - 1; p >= 0; p--) {
final byte[] key = ns.key[p];
final int i = ser.ns.get(key);
if(i == -1 || !Token.eq(ser.ns.val[i], uri)) {
ser.namespace(key, ns.val[p]);
xmlns |= key.length == 0;
}
}
}
}
- if(!xmlns && !name.ns() && !Token.eq(uri, ser.dn)) {
+ if(!xmlns && !name.ns() && !Token.eq(uri, ser.dn))
ser.namespace(Token.EMPTY, uri);
- ser.dn = uri;
- }
+ ser.dn = uri;
// serialize attributes
for(int n = 0; n < atts.size(); n++) {
final Nod nod = atts.get(n);
final QNm atn = nod.qname();
if(atn.ns()) {
if(!NSGlobal.standard(atn.uri.str())) {
final byte[] pre = atn.pref();
final int i = ser.ns.get(pre);
if(i == -1) ser.namespace(pre, atn.uri.str());
}
}
ser.attribute(atn.str(), nod.str());
}
// serialize children
for(int n = 0; n < children.size(); n++) children.get(n).serialize(ser);
ser.closeElement();
// reset top level namespace
ser.dn = dn;
}
@Override
public FElem copy() {
final NodIter ch = new NodIter();
final NodIter at = new NodIter();
final FElem node = new FElem(name, ch, at, base, ns, par);
for(int c = 0; c < children.size(); c++) {
ch.add(children.get(c).copy());
ch.get(c).parent(node);
}
for(int c = 0; c < atts.size(); c++) {
at.add(atts.get(c).copy());
at.get(c).parent(node);
}
return node;
}
@Override
public void plan(final Serializer ser) throws IOException {
ser.emptyElement(this, NAM, name.str());
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("<");
sb.append(Token.string(name.str()));
if(atts.size() != 0 || ns != null && ns.size != 0 || children.size() != 0)
sb.append(" ...");
return sb.append("/>").toString();
}
}
| false | true | public void serialize(final Serializer ser) throws IOException {
final byte[] tag = name.str();
final byte[] uri = name.uri.str();
ser.openElement(tag);
// remember top level namespace
final byte[] dn = ser.dn;
boolean xmlns = false;
// serialize all namespaces at top level...
if(ser.level() == 1) {
final Atts nns = nsScope();
for(int a = 0; a < nns.size; a++) {
if(nns.key[a].length == 0) {
xmlns = true;
if(Token.eq(ser.dn, nns.val[a])) continue;
// reset default namespace
ser.dn = nns.val[a];
}
ser.namespace(nns.key[a], nns.val[a]);
}
// serialize default namespace if not done yet
for(int p = ser.ns.size - 1; p >= 0 && !xmlns; p--) {
if(ser.ns.key[p].length != 0) continue;
xmlns = true;
ser.dn = ser.ns.val[p];
ser.namespace(Token.EMPTY, ser.ns.val[p]);
}
} else {
if(ns != null) {
for(int p = ns.size - 1; p >= 0; p--) {
final byte[] key = ns.key[p];
final int i = ser.ns.get(key);
if(i == -1 || !Token.eq(ser.ns.val[i], uri)) {
ser.namespace(key, ns.val[p]);
xmlns |= key.length == 0;
}
}
}
}
if(!xmlns && !name.ns() && !Token.eq(uri, ser.dn)) {
ser.namespace(Token.EMPTY, uri);
ser.dn = uri;
}
// serialize attributes
for(int n = 0; n < atts.size(); n++) {
final Nod nod = atts.get(n);
final QNm atn = nod.qname();
if(atn.ns()) {
if(!NSGlobal.standard(atn.uri.str())) {
final byte[] pre = atn.pref();
final int i = ser.ns.get(pre);
if(i == -1) ser.namespace(pre, atn.uri.str());
}
}
ser.attribute(atn.str(), nod.str());
}
// serialize children
for(int n = 0; n < children.size(); n++) children.get(n).serialize(ser);
ser.closeElement();
// reset top level namespace
ser.dn = dn;
}
| public void serialize(final Serializer ser) throws IOException {
final byte[] tag = name.str();
final byte[] uri = name.uri.str();
ser.openElement(tag);
// remember top level namespace
final byte[] dn = ser.dn;
boolean xmlns = false;
// serialize all namespaces at top level...
if(ser.level() == 1) {
final Atts nns = nsScope();
for(int a = 0; a < nns.size; a++) {
if(nns.key[a].length == 0) {
xmlns = true;
if(Token.eq(ser.dn, nns.val[a])) continue;
// reset default namespace
ser.dn = nns.val[a];
}
ser.namespace(nns.key[a], nns.val[a]);
}
// serialize default namespace if not done yet
for(int p = ser.ns.size - 1; p >= 0 && !xmlns; p--) {
if(ser.ns.key[p].length != 0) continue;
xmlns = true;
ser.dn = ser.ns.val[p];
ser.namespace(Token.EMPTY, ser.ns.val[p]);
}
} else {
if(ns != null) {
for(int p = ns.size - 1; p >= 0; p--) {
final byte[] key = ns.key[p];
final int i = ser.ns.get(key);
if(i == -1 || !Token.eq(ser.ns.val[i], uri)) {
ser.namespace(key, ns.val[p]);
xmlns |= key.length == 0;
}
}
}
}
if(!xmlns && !name.ns() && !Token.eq(uri, ser.dn))
ser.namespace(Token.EMPTY, uri);
ser.dn = uri;
// serialize attributes
for(int n = 0; n < atts.size(); n++) {
final Nod nod = atts.get(n);
final QNm atn = nod.qname();
if(atn.ns()) {
if(!NSGlobal.standard(atn.uri.str())) {
final byte[] pre = atn.pref();
final int i = ser.ns.get(pre);
if(i == -1) ser.namespace(pre, atn.uri.str());
}
}
ser.attribute(atn.str(), nod.str());
}
// serialize children
for(int n = 0; n < children.size(); n++) children.get(n).serialize(ser);
ser.closeElement();
// reset top level namespace
ser.dn = dn;
}
|
diff --git a/ldt-core/src/test/java/com/farpost/ldt/PojoTaskTest.java b/ldt-core/src/test/java/com/farpost/ldt/PojoTaskTest.java
index 28be258..0481a69 100644
--- a/ldt-core/src/test/java/com/farpost/ldt/PojoTaskTest.java
+++ b/ldt-core/src/test/java/com/farpost/ldt/PojoTaskTest.java
@@ -1,70 +1,70 @@
package com.farpost.ldt;
import org.testng.annotations.Test;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import static com.farpost.ldt.TestUtils.near;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class PojoTaskTest {
@Test
public void taskShouldAbleToInjectParameters() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {
PojoTask<SomeTask> task = new PojoTask<SomeTask>(SomeTask.class, "doWork");
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("string", "foo");
parameters.put("integer", "6");
task.setParameters(parameters);
SomeTask t = task.getTaskObject();
assertThat(t.getString(), equalTo("foo"));
assertThat(t.getInteger(), equalTo(6));
}
@Test
public void pojoTaskCanBeRunWithTestRunner()
throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException,
InterruptedException {
PojoTask<?> task = new PojoTask(SleepTask.class, "execute");
TestRunner runner = new TestRunner();
runner.setConcurrencyLevel(2);
- runner.setThreadSamplesCount(50);
+ runner.setThreadSamplesCount(5);
Map<String, String> parameters = new HashMap<String, String>();
- parameters.put("delay", "20");
+ parameters.put("delay", "200");
task.setParameters(parameters);
TestResult result = runner.run(task);
- assertThat(result.getThroughput(), near(100f, 5));
+ assertThat(result.getThroughput(), near(10f, 2f));
}
public static class SomeTask {
private String string;
private int integer;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public int getInteger() {
return integer;
}
public void setInteger(int integer) {
this.integer = integer;
}
public void doWork() {}
}
}
| false | true | public void pojoTaskCanBeRunWithTestRunner()
throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException,
InterruptedException {
PojoTask<?> task = new PojoTask(SleepTask.class, "execute");
TestRunner runner = new TestRunner();
runner.setConcurrencyLevel(2);
runner.setThreadSamplesCount(50);
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("delay", "20");
task.setParameters(parameters);
TestResult result = runner.run(task);
assertThat(result.getThroughput(), near(100f, 5));
}
| public void pojoTaskCanBeRunWithTestRunner()
throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException,
InterruptedException {
PojoTask<?> task = new PojoTask(SleepTask.class, "execute");
TestRunner runner = new TestRunner();
runner.setConcurrencyLevel(2);
runner.setThreadSamplesCount(5);
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("delay", "200");
task.setParameters(parameters);
TestResult result = runner.run(task);
assertThat(result.getThroughput(), near(10f, 2f));
}
|
diff --git a/src/com/android/gallery3d/ui/CustomMenu.java b/src/com/android/gallery3d/ui/CustomMenu.java
index f1a4a46..dd8e6ab 100644
--- a/src/com/android/gallery3d/ui/CustomMenu.java
+++ b/src/com/android/gallery3d/ui/CustomMenu.java
@@ -1,93 +1,91 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gallery3d.ui;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import com.android.gallery3d.R;
import java.util.ArrayList;
public class CustomMenu implements OnMenuItemClickListener {
@SuppressWarnings("unused")
private static final String TAG = "FilterMenu";
public static class DropDownMenu {
private Button mButton;
private PopupMenu mPopupMenu;
private Menu mMenu;
public DropDownMenu(Context context, Button button, int menuId,
OnMenuItemClickListener listener) {
mButton = button;
- mButton.setBackgroundDrawable(context.getResources().getDrawable(
- R.drawable.dropdown_normal_holo_dark));
mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu();
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
mPopupMenu.setOnMenuItemClickListener(listener);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
}
});
}
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
public void setTitle(CharSequence title) {
mButton.setText(title);
}
}
private Context mContext;
private ArrayList<DropDownMenu> mMenus;
private OnMenuItemClickListener mListener;
public CustomMenu(Context context) {
mContext = context;
mMenus = new ArrayList<DropDownMenu>();
}
public DropDownMenu addDropDownMenu(Button button, int menuId) {
DropDownMenu menu = new DropDownMenu(mContext, button, menuId, this);
mMenus.add(menu);
return menu;
}
public void setOnMenuItemClickListener(OnMenuItemClickListener listener) {
mListener = listener;
}
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
return mListener.onMenuItemClick(item);
}
return false;
}
}
| true | true | public DropDownMenu(Context context, Button button, int menuId,
OnMenuItemClickListener listener) {
mButton = button;
mButton.setBackgroundDrawable(context.getResources().getDrawable(
R.drawable.dropdown_normal_holo_dark));
mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu();
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
mPopupMenu.setOnMenuItemClickListener(listener);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
}
});
}
| public DropDownMenu(Context context, Button button, int menuId,
OnMenuItemClickListener listener) {
mButton = button;
mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu();
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
mPopupMenu.setOnMenuItemClickListener(listener);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
}
});
}
|
diff --git a/Server/VoiceServer.java b/Server/VoiceServer.java
index f022aca..0ba4c4a 100644
--- a/Server/VoiceServer.java
+++ b/Server/VoiceServer.java
@@ -1,82 +1,81 @@
import java.util.*;
import java.io.*;
import java.net.*;
public class VoiceServer implements Runnable
{
private int _port = 0;
ArrayList<VoiceServerConnection> _connections = null;
VoiceServer(int port)
{
_port = port;
_connections = new ArrayList<VoiceServerConnection>();
}
public void run()
{
System.out.println("Voice Server started.");
try
{
// create a socket for handling incoming requests
DatagramSocket serverSocket = new DatagramSocket(_port);
while(true)
{
// receive the incoming packet
byte[] buffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(receivePacket);
// extract the byte stream data
buffer = receivePacket.getData();
// extract the IP address and port number
InetAddress ipAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
// if this is a new connection, store it in our list
VoiceServerConnection target = null;
for (VoiceServerConnection c : _connections)
{
- if ((c.getIPAddress() == ipAddress) &&
+ if ((c.getIPAddress().toString(ipAddress)) &&
(c.getPort() == port))
{
target = c;
break;
}
}
if (target == null)
{
VoiceServerConnection vsc = new VoiceServerConnection(ipAddress, port);
_connections.add(vsc);
}
// send the packet data
for (VoiceServerConnection c : _connections)
{
try
{
- if ((c.getIPAddress() != ipAddress) ||
- (c.getPort() != port)) // we don't need to hear our own audio
+ if (!(c.getIPAddress().toString(ipAddress))) // we don't need to hear our own audio
{
DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, c.getIPAddress(), c.getPort());
serverSocket.send(sendPacket);
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
}
| false | true | public void run()
{
System.out.println("Voice Server started.");
try
{
// create a socket for handling incoming requests
DatagramSocket serverSocket = new DatagramSocket(_port);
while(true)
{
// receive the incoming packet
byte[] buffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(receivePacket);
// extract the byte stream data
buffer = receivePacket.getData();
// extract the IP address and port number
InetAddress ipAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
// if this is a new connection, store it in our list
VoiceServerConnection target = null;
for (VoiceServerConnection c : _connections)
{
if ((c.getIPAddress() == ipAddress) &&
(c.getPort() == port))
{
target = c;
break;
}
}
if (target == null)
{
VoiceServerConnection vsc = new VoiceServerConnection(ipAddress, port);
_connections.add(vsc);
}
// send the packet data
for (VoiceServerConnection c : _connections)
{
try
{
if ((c.getIPAddress() != ipAddress) ||
(c.getPort() != port)) // we don't need to hear our own audio
{
DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, c.getIPAddress(), c.getPort());
serverSocket.send(sendPacket);
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
| public void run()
{
System.out.println("Voice Server started.");
try
{
// create a socket for handling incoming requests
DatagramSocket serverSocket = new DatagramSocket(_port);
while(true)
{
// receive the incoming packet
byte[] buffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(receivePacket);
// extract the byte stream data
buffer = receivePacket.getData();
// extract the IP address and port number
InetAddress ipAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
// if this is a new connection, store it in our list
VoiceServerConnection target = null;
for (VoiceServerConnection c : _connections)
{
if ((c.getIPAddress().toString(ipAddress)) &&
(c.getPort() == port))
{
target = c;
break;
}
}
if (target == null)
{
VoiceServerConnection vsc = new VoiceServerConnection(ipAddress, port);
_connections.add(vsc);
}
// send the packet data
for (VoiceServerConnection c : _connections)
{
try
{
if (!(c.getIPAddress().toString(ipAddress))) // we don't need to hear our own audio
{
DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, c.getIPAddress(), c.getPort());
serverSocket.send(sendPacket);
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
}
}
catch (IOException ex)
{
// TODO: handle this exception
}
}
|
diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java
index 082a8ecb7..ee064a594 100644
--- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java
+++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java
@@ -1,684 +1,684 @@
/*
* FeedServlet.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.servlet;
import com.sun.syndication.feed.rss.Channel;
import com.sun.syndication.feed.rss.Description;
import com.sun.syndication.feed.rss.Image;
import com.sun.syndication.feed.rss.TextInput;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.WireFeedOutput;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowserScope;
import org.dspace.sort.SortOption;
import org.dspace.sort.SortException;
import org.dspace.content.Bitstream;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.search.Harvest;
import org.dspace.uri.ResolvableIdentifier;
import org.dspace.uri.IdentifierFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
/**
* Servlet for handling requests for a syndication feed. The URI of the collection
* or community is extracted from the URL, e.g: <code>/feed/rss_1.0/xyz:1234/5678</code>.
* Currently supports only RSS feed formats.
*
* @author Ben Bosman, Richard Rodgers, James Rutherford
* @version $Revision$
*/
public class FeedServlet extends DSpaceServlet
{
// key for site-wide feed
public static final String SITE_FEED_KEY = "site";
// one hour in milliseconds
private static final long HOUR_MSECS = 60 * 60 * 1000;
/** log4j category */
private static Logger log = Logger.getLogger(FeedServlet.class);
private String clazz = "org.dspace.app.webui.servlet.FeedServlet";
// are syndication feeds enabled?
private static boolean enabled = false;
// number of DSpace items per feed
private static int itemCount = 0;
// optional cache of feeds
private static Map feedCache = null;
// maximum size of cache - 0 means caching disabled
private static int cacheSize = 0;
// how many days to keep a feed in cache before checking currency
private static int cacheAge = 0;
// supported syndication formats
private static List formats = null;
// localized resource bundle
private static ResourceBundle labels = null;
//default fields to display in item description
private static String defaultDescriptionFields = "dc.title, dc.contributor.author, dc.contributor.editor, dc.description.abstract, dc.description";
static
{
enabled = ConfigurationManager.getBooleanProperty("webui.feed.enable");
}
public void init()
{
// read rest of config info if enabled
if (enabled)
{
String fmtsStr = ConfigurationManager.getProperty("webui.feed.formats");
if ( fmtsStr != null )
{
formats = new ArrayList();
String[] fmts = fmtsStr.split(",");
for (int i = 0; i < fmts.length; i++)
{
formats.add(fmts[i]);
}
}
itemCount = ConfigurationManager.getIntProperty("webui.feed.items");
cacheSize = ConfigurationManager.getIntProperty("webui.feed.cache.size");
if (cacheSize > 0)
{
feedCache = new HashMap();
cacheAge = ConfigurationManager.getIntProperty("webui.feed.cache.age");
}
}
}
protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
String path = request.getPathInfo();
String feedType = null;
String uri = null;
if(labels==null)
{
// Get access to the localized resource bundle
Locale locale = request.getLocale();
labels = ResourceBundle.getBundle("Messages", locale);
}
if (path != null)
{
// substring(1) is to remove initial '/'
path = path.substring(1);
int split = path.indexOf("/");
if (split != -1)
{
feedType = path.substring(0,split);
uri = path.substring(split+1);
}
}
DSpaceObject dso = null;
//as long as this is not a site wide feed,
//attempt to retrieve the Collection or Community object
if(!uri.equals(SITE_FEED_KEY))
{
// Determine if the URI is a valid reference
ResolvableIdentifier di = IdentifierFactory.resolve(context, uri);
//ExternalIdentifierDAO dao = ExternalIdentifierDAOFactory.getInstance(context);
//ExternalIdentifier identifier = dao.retrieve(uri);
//ObjectIdentifier oi = identifier.getObjectIdentifier();
dso = di.getObject(context);
}
if (! enabled || (dso != null &&
(dso.getType() != Constants.COLLECTION && dso.getType() != Constants.COMMUNITY)) )
{
log.info(LogManager.getHeader(context, "invalid_id", "path=" + path));
JSPManager.showInvalidIDError(request, response, path, -1);
return;
}
// Determine if requested format is supported
if( feedType == null || ! formats.contains( feedType ) )
{
log.info(LogManager.getHeader(context, "invalid_syndformat", "path=" + path));
JSPManager.showInvalidIDError(request, response, path, -1);
return;
}
// Lookup or generate the feed
Channel channel = null;
if (feedCache != null)
{
// Cache key is URI
CacheFeed cFeed = (CacheFeed)feedCache.get(uri);
if (cFeed != null) // cache hit, but...
{
// Is the feed current?
boolean cacheFeedCurrent = false;
if (cFeed.timeStamp + (cacheAge * HOUR_MSECS) < System.currentTimeMillis())
{
cacheFeedCurrent = true;
}
// Not current, but have any items changed since feed was created/last checked?
else if ( ! itemsChanged(context, dso, cFeed.timeStamp))
{
// no items have changed, re-stamp feed and use it
cFeed.timeStamp = System.currentTimeMillis();
cacheFeedCurrent = true;
}
if (cacheFeedCurrent)
{
channel = cFeed.access();
}
}
}
// either not caching, not found in cache, or feed in cache not current
if (channel == null)
{
channel = generateFeed(context, dso);
if (feedCache != null)
{
cache(uri, new CacheFeed(channel));
}
}
// set the feed to the requested type & return it
channel.setFeedType(feedType);
WireFeedOutput feedWriter = new WireFeedOutput();
try
{
response.setContentType("text/xml; charset=UTF-8");
feedWriter.output(channel, response.getWriter());
}
catch( FeedException fex )
{
throw new IOException(fex.getMessage());
}
}
private boolean itemsChanged(Context context, DSpaceObject dso, long timeStamp)
throws SQLException
{
// construct start and end dates
DCDate dcStartDate = new DCDate( new Date(timeStamp) );
DCDate dcEndDate = new DCDate( new Date(System.currentTimeMillis()) );
// convert dates to ISO 8601, stripping the time
String startDate = dcStartDate.toString().substring(0, 10);
String endDate = dcEndDate.toString().substring(0, 10);
// this invocation should return a non-empty list if even 1 item has changed
try {
return (Harvest.harvest(context, dso, startDate, endDate,
0, 1, false, false, false).size() > 0);
}
catch (ParseException pe)
{
// This should never get thrown as we have generated the dates ourselves
return false;
}
}
/**
* Generate a syndication feed for a collection or community
* or community
*
* @param context the DSpace context object
*
* @param dso DSpace object - collection or community
*
* @return an object representing the feed
*/
private Channel generateFeed(Context context, DSpaceObject dso)
throws IOException, SQLException
{
try
{
// container-level elements
String dspaceUrl = ConfigurationManager.getProperty("dspace.url");
String type = null;
String description = null;
String title = null;
Bitstream logo = null;
// browse scope
// BrowseScope scope = new BrowseScope(context);
// new method of doing the browse:
String idx = ConfigurationManager.getProperty("recent.submissions.sort-option");
if (idx == null)
{
throw new IOException("There is no configuration supplied for: recent.submissions.sort-option");
}
BrowseIndex bix = BrowseIndex.getItemBrowseIndex();
if (bix == null)
{
throw new IOException("There is no browse index with the name: " + idx);
}
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bix);
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(idx))
scope.setSortBy(so.getNumber());
}
scope.setOrder(SortOption.DESCENDING);
// the feed
Channel channel = new Channel();
//Special Case: if DSpace Object passed in is null,
//generate a feed for the entire DSpace site!
if(dso == null)
{
channel.setTitle(ConfigurationManager.getProperty("dspace.name"));
channel.setLink(dspaceUrl);
channel.setDescription(labels.getString(clazz + ".general-feed.description"));
}
else //otherwise, this is a Collection or Community specific feed
{
if (dso.getType() == Constants.COLLECTION)
{
type = labels.getString(clazz + ".feed-type.collection");
Collection col = (Collection)dso;
description = col.getMetadata("short_description");
title = col.getMetadata("name");
logo = col.getLogo();
// scope.setScope(col);
scope.setBrowseContainer(col);
}
else if (dso.getType() == Constants.COMMUNITY)
{
type = labels.getString(clazz + ".feed-type.community");
Community comm = (Community)dso;
description = comm.getMetadata("short_description");
title = comm.getMetadata("name");
logo = comm.getLogo();
// scope.setScope(comm);
scope.setBrowseContainer(comm);
}
String objectUrl = "";
if (dso.getExternalIdentifier() != null)
{
objectUrl = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? IdentifierFactory.getURL(dso).toString()
: dso.getExternalIdentifier().getURI().toString();
}
else
{
// If no external identifier is available, use the local URL
objectUrl = IdentifierFactory.getURL(dso).toString();
}
// put in container-level data
channel.setDescription(description);
channel.setLink(objectUrl);
//build channel title by passing in type and title
String channelTitle = MessageFormat.format(labels.getString(clazz + ".feed.title"),
new Object[]{type, title});
channel.setTitle(channelTitle);
//if collection or community has a logo
if (logo != null)
{
// we use the path to the logo for this, the logo itself cannot
// be contained in the rdf. Not all RSS-viewers show this logo.
Image image = new Image();
image.setLink(objectUrl);
image.setTitle(labels.getString(clazz + ".logo.title"));
image.setUrl(dspaceUrl + "/retrieve/" + logo.getID());
channel.setImage(image);
}
}
// this is a direct link to the search-engine of dspace. It searches
// in the current collection. Since the current version of DSpace
// can't search within collections anymore, this works only in older
// version until this bug is fixed.
TextInput input = new TextInput();
input.setLink(dspaceUrl + "/simple-search");
input.setDescription( labels.getString(clazz + ".search.description") );
String searchTitle = "";
//if a "type" of feed was specified, build search title off that
if(type!=null)
{
searchTitle = MessageFormat.format(labels.getString(clazz + ".search.title"),
new Object[]{type});
}
else //otherwise, default to a more generic search title
{
searchTitle = labels.getString(clazz + ".search.title.default");
}
input.setTitle(searchTitle);
input.setName(labels.getString(clazz + ".search.name"));
channel.setTextInput(input);
// gather & add items to the feed.
scope.setResultsPerPage(itemCount);
BrowseEngine be = new BrowseEngine(context);
BrowseInfo bi = be.browseMini(scope);
Item[] results = bi.getBrowseItemResults(context);
List items = new ArrayList();
for (int i = 0; i < results.length; i++)
{
items.add(itemFromDSpaceItem(context, results[i]));
}
channel.setItems(items);
// If the description is null, replace it with an empty string
// to avoid a FeedException
if (channel.getDescription() == null)
channel.setDescription("");
return channel;
}
catch (SortException se)
{
log.error("caught exception: ", se);
- throw new IOException(se);
+ throw new IOException(se.getMessage());
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new IOException(e.getMessage());
}
}
/**
* The metadata fields of the given item will be added to the given feed.
*
* @param context DSpace context object
*
* @param dspaceItem DSpace Item
*
* @return an object representing a feed entry
*/
private com.sun.syndication.feed.rss.Item itemFromDSpaceItem(Context context,
Item dspaceItem)
throws SQLException
{
com.sun.syndication.feed.rss.Item rssItem =
new com.sun.syndication.feed.rss.Item();
//get the title and date fields
String titleField = ConfigurationManager.getProperty("webui.feed.item.title");
if (titleField == null)
{
titleField = "dc.title";
}
String dateField = ConfigurationManager.getProperty("webui.feed.item.date");
if (dateField == null)
{
dateField = "dc.date.issued";
}
//Set item URI
String link = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? IdentifierFactory.getURL(dspaceItem).toString()
: dspaceItem.getExternalIdentifier().getURI().toString();
rssItem.setLink(link);
//get first title
String title = null;
try
{
title = dspaceItem.getMetadata(titleField)[0].value;
}
catch (ArrayIndexOutOfBoundsException e)
{
title = labels.getString(clazz + ".notitle");
}
rssItem.setTitle(title);
// We put some metadata in the description field. This field is
// displayed by most RSS viewers
String descriptionFields = ConfigurationManager
.getProperty("webui.feed.item.description");
if (descriptionFields == null)
{
descriptionFields = defaultDescriptionFields;
}
//loop through all the metadata fields to put in the description
StringBuffer descBuf = new StringBuffer();
StringTokenizer st = new StringTokenizer(descriptionFields, ",");
while (st.hasMoreTokens())
{
String field = st.nextToken().trim();
boolean isDate = false;
// Find out if the field should rendered as a date
if (field.indexOf("(date)") > 0)
{
field = field.replaceAll("\\(date\\)", "");
isDate = true;
}
//print out this field, along with its value(s)
DCValue[] values = dspaceItem.getMetadata(field);
if(values != null && values.length>0)
{
//as long as there is already something in the description
//buffer, print out a few line breaks before the next field
if(descBuf.length() > 0)
{
descBuf.append("\n<br/>");
descBuf.append("\n<br/>");
}
String fieldLabel = null;
try
{
fieldLabel = labels.getString("metadata." + field);
}
catch(java.util.MissingResourceException e) {}
if(fieldLabel !=null && fieldLabel.length()>0)
descBuf.append(fieldLabel + ": ");
for(int i=0; i<values.length; i++)
{
String fieldValue = values[i].value;
if(isDate)
fieldValue = (new DCDate(fieldValue)).toString();
descBuf.append(fieldValue);
if (i < values.length - 1)
{
descBuf.append("; ");
}
}
}
}//end while
Description descrip = new Description();
descrip.setValue(descBuf.toString());
rssItem.setDescription(descrip);
// set date field
String dcDate = null;
try
{
dcDate = dspaceItem.getMetadata(dateField)[0].value;
}
catch (ArrayIndexOutOfBoundsException e)
{
}
if (dcDate != null)
{
rssItem.setPubDate((new DCDate(dcDate)).toDate());
}
return rssItem;
}
/************************************************
* private cache management classes and methods *
************************************************/
/**
* Add a feed to the cache - reducing the size of the cache by 1 to make room if
* necessary. The removed entry has an access count equal to the minumum in the cache.
* @param feedKey
* The cache key for the feed
* @param newFeed
* The CacheFeed feed to be cached
*/
private static void cache(String feedKey, CacheFeed newFeed)
{
// remove older feed to make room if cache full
if (feedCache.size() >= cacheSize)
{
// cache profiling data
int total = 0;
String minKey = null;
CacheFeed minFeed = null;
CacheFeed maxFeed = null;
Iterator iter = feedCache.keySet().iterator();
while (iter.hasNext())
{
String key = (String)iter.next();
CacheFeed feed = (CacheFeed)feedCache.get(key);
if (minKey != null)
{
if (feed.hits < minFeed.hits)
{
minKey = key;
minFeed = feed;
}
if (feed.hits >= maxFeed.hits)
{
maxFeed = feed;
}
}
else
{
minKey = key;
minFeed = maxFeed = feed;
}
total += feed.hits;
}
// log a profile of the cache to assist administrator in tuning it
int avg = total / feedCache.size();
String logMsg = "feedCache() - size: " + feedCache.size() +
" Hits - total: " + total + " avg: " + avg +
" max: " + maxFeed.hits + " min: " + minFeed.hits;
log.info(logMsg);
// remove minimum hits entry
feedCache.remove(minKey);
}
// add feed to cache
feedCache.put(feedKey, newFeed);
}
/**
* Class to instrument accesses & currency of a given feed in cache
*/
private class CacheFeed
{
// currency timestamp
public long timeStamp = 0L;
// access count
public int hits = 0;
// the feed
private Channel feed = null;
public CacheFeed(Channel feed)
{
this.feed = feed;
timeStamp = System.currentTimeMillis();
}
public Channel access()
{
++hits;
return feed;
}
}
}
| true | true | private Channel generateFeed(Context context, DSpaceObject dso)
throws IOException, SQLException
{
try
{
// container-level elements
String dspaceUrl = ConfigurationManager.getProperty("dspace.url");
String type = null;
String description = null;
String title = null;
Bitstream logo = null;
// browse scope
// BrowseScope scope = new BrowseScope(context);
// new method of doing the browse:
String idx = ConfigurationManager.getProperty("recent.submissions.sort-option");
if (idx == null)
{
throw new IOException("There is no configuration supplied for: recent.submissions.sort-option");
}
BrowseIndex bix = BrowseIndex.getItemBrowseIndex();
if (bix == null)
{
throw new IOException("There is no browse index with the name: " + idx);
}
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bix);
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(idx))
scope.setSortBy(so.getNumber());
}
scope.setOrder(SortOption.DESCENDING);
// the feed
Channel channel = new Channel();
//Special Case: if DSpace Object passed in is null,
//generate a feed for the entire DSpace site!
if(dso == null)
{
channel.setTitle(ConfigurationManager.getProperty("dspace.name"));
channel.setLink(dspaceUrl);
channel.setDescription(labels.getString(clazz + ".general-feed.description"));
}
else //otherwise, this is a Collection or Community specific feed
{
if (dso.getType() == Constants.COLLECTION)
{
type = labels.getString(clazz + ".feed-type.collection");
Collection col = (Collection)dso;
description = col.getMetadata("short_description");
title = col.getMetadata("name");
logo = col.getLogo();
// scope.setScope(col);
scope.setBrowseContainer(col);
}
else if (dso.getType() == Constants.COMMUNITY)
{
type = labels.getString(clazz + ".feed-type.community");
Community comm = (Community)dso;
description = comm.getMetadata("short_description");
title = comm.getMetadata("name");
logo = comm.getLogo();
// scope.setScope(comm);
scope.setBrowseContainer(comm);
}
String objectUrl = "";
if (dso.getExternalIdentifier() != null)
{
objectUrl = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? IdentifierFactory.getURL(dso).toString()
: dso.getExternalIdentifier().getURI().toString();
}
else
{
// If no external identifier is available, use the local URL
objectUrl = IdentifierFactory.getURL(dso).toString();
}
// put in container-level data
channel.setDescription(description);
channel.setLink(objectUrl);
//build channel title by passing in type and title
String channelTitle = MessageFormat.format(labels.getString(clazz + ".feed.title"),
new Object[]{type, title});
channel.setTitle(channelTitle);
//if collection or community has a logo
if (logo != null)
{
// we use the path to the logo for this, the logo itself cannot
// be contained in the rdf. Not all RSS-viewers show this logo.
Image image = new Image();
image.setLink(objectUrl);
image.setTitle(labels.getString(clazz + ".logo.title"));
image.setUrl(dspaceUrl + "/retrieve/" + logo.getID());
channel.setImage(image);
}
}
// this is a direct link to the search-engine of dspace. It searches
// in the current collection. Since the current version of DSpace
// can't search within collections anymore, this works only in older
// version until this bug is fixed.
TextInput input = new TextInput();
input.setLink(dspaceUrl + "/simple-search");
input.setDescription( labels.getString(clazz + ".search.description") );
String searchTitle = "";
//if a "type" of feed was specified, build search title off that
if(type!=null)
{
searchTitle = MessageFormat.format(labels.getString(clazz + ".search.title"),
new Object[]{type});
}
else //otherwise, default to a more generic search title
{
searchTitle = labels.getString(clazz + ".search.title.default");
}
input.setTitle(searchTitle);
input.setName(labels.getString(clazz + ".search.name"));
channel.setTextInput(input);
// gather & add items to the feed.
scope.setResultsPerPage(itemCount);
BrowseEngine be = new BrowseEngine(context);
BrowseInfo bi = be.browseMini(scope);
Item[] results = bi.getBrowseItemResults(context);
List items = new ArrayList();
for (int i = 0; i < results.length; i++)
{
items.add(itemFromDSpaceItem(context, results[i]));
}
channel.setItems(items);
// If the description is null, replace it with an empty string
// to avoid a FeedException
if (channel.getDescription() == null)
channel.setDescription("");
return channel;
}
catch (SortException se)
{
log.error("caught exception: ", se);
throw new IOException(se);
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new IOException(e.getMessage());
}
}
| private Channel generateFeed(Context context, DSpaceObject dso)
throws IOException, SQLException
{
try
{
// container-level elements
String dspaceUrl = ConfigurationManager.getProperty("dspace.url");
String type = null;
String description = null;
String title = null;
Bitstream logo = null;
// browse scope
// BrowseScope scope = new BrowseScope(context);
// new method of doing the browse:
String idx = ConfigurationManager.getProperty("recent.submissions.sort-option");
if (idx == null)
{
throw new IOException("There is no configuration supplied for: recent.submissions.sort-option");
}
BrowseIndex bix = BrowseIndex.getItemBrowseIndex();
if (bix == null)
{
throw new IOException("There is no browse index with the name: " + idx);
}
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bix);
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(idx))
scope.setSortBy(so.getNumber());
}
scope.setOrder(SortOption.DESCENDING);
// the feed
Channel channel = new Channel();
//Special Case: if DSpace Object passed in is null,
//generate a feed for the entire DSpace site!
if(dso == null)
{
channel.setTitle(ConfigurationManager.getProperty("dspace.name"));
channel.setLink(dspaceUrl);
channel.setDescription(labels.getString(clazz + ".general-feed.description"));
}
else //otherwise, this is a Collection or Community specific feed
{
if (dso.getType() == Constants.COLLECTION)
{
type = labels.getString(clazz + ".feed-type.collection");
Collection col = (Collection)dso;
description = col.getMetadata("short_description");
title = col.getMetadata("name");
logo = col.getLogo();
// scope.setScope(col);
scope.setBrowseContainer(col);
}
else if (dso.getType() == Constants.COMMUNITY)
{
type = labels.getString(clazz + ".feed-type.community");
Community comm = (Community)dso;
description = comm.getMetadata("short_description");
title = comm.getMetadata("name");
logo = comm.getLogo();
// scope.setScope(comm);
scope.setBrowseContainer(comm);
}
String objectUrl = "";
if (dso.getExternalIdentifier() != null)
{
objectUrl = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? IdentifierFactory.getURL(dso).toString()
: dso.getExternalIdentifier().getURI().toString();
}
else
{
// If no external identifier is available, use the local URL
objectUrl = IdentifierFactory.getURL(dso).toString();
}
// put in container-level data
channel.setDescription(description);
channel.setLink(objectUrl);
//build channel title by passing in type and title
String channelTitle = MessageFormat.format(labels.getString(clazz + ".feed.title"),
new Object[]{type, title});
channel.setTitle(channelTitle);
//if collection or community has a logo
if (logo != null)
{
// we use the path to the logo for this, the logo itself cannot
// be contained in the rdf. Not all RSS-viewers show this logo.
Image image = new Image();
image.setLink(objectUrl);
image.setTitle(labels.getString(clazz + ".logo.title"));
image.setUrl(dspaceUrl + "/retrieve/" + logo.getID());
channel.setImage(image);
}
}
// this is a direct link to the search-engine of dspace. It searches
// in the current collection. Since the current version of DSpace
// can't search within collections anymore, this works only in older
// version until this bug is fixed.
TextInput input = new TextInput();
input.setLink(dspaceUrl + "/simple-search");
input.setDescription( labels.getString(clazz + ".search.description") );
String searchTitle = "";
//if a "type" of feed was specified, build search title off that
if(type!=null)
{
searchTitle = MessageFormat.format(labels.getString(clazz + ".search.title"),
new Object[]{type});
}
else //otherwise, default to a more generic search title
{
searchTitle = labels.getString(clazz + ".search.title.default");
}
input.setTitle(searchTitle);
input.setName(labels.getString(clazz + ".search.name"));
channel.setTextInput(input);
// gather & add items to the feed.
scope.setResultsPerPage(itemCount);
BrowseEngine be = new BrowseEngine(context);
BrowseInfo bi = be.browseMini(scope);
Item[] results = bi.getBrowseItemResults(context);
List items = new ArrayList();
for (int i = 0; i < results.length; i++)
{
items.add(itemFromDSpaceItem(context, results[i]));
}
channel.setItems(items);
// If the description is null, replace it with an empty string
// to avoid a FeedException
if (channel.getDescription() == null)
channel.setDescription("");
return channel;
}
catch (SortException se)
{
log.error("caught exception: ", se);
throw new IOException(se.getMessage());
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new IOException(e.getMessage());
}
}
|
diff --git a/modules/activiti-spring/src/main/java/org/activiti/spring/components/scope/ProcessScope.java b/modules/activiti-spring/src/main/java/org/activiti/spring/components/scope/ProcessScope.java
index ebd99bdff..00dfa05c1 100644
--- a/modules/activiti-spring/src/main/java/org/activiti/spring/components/scope/ProcessScope.java
+++ b/modules/activiti-spring/src/main/java/org/activiti/spring/components/scope/ProcessScope.java
@@ -1,242 +1,242 @@
/*
* Copyright 2010 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.spring.components.scope;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.spring.components.aop.util.Scopifier;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.scope.ScopedObject;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* binds variables to a currently executing Activiti business process (a {@link org.activiti.engine.runtime.ProcessInstance}).
* <p/>
* Parts of this code are lifted wholesale from Dave Syer's work on the Spring 3.1 RefreshScope.
*
* @author Josh Long
* @since 5.3
*/
public class ProcessScope implements Scope, InitializingBean, BeanFactoryPostProcessor, DisposableBean {
/**
* Map of the processVariables. Supports correct, scoped access to process variables so that
* <code>
*
* @Value("#{ processVariables['customerId'] }") long customerId;
* </code>
* <p/>
* works in any bean - scoped or not
*/
public final static String PROCESS_SCOPE_PROCESS_VARIABLES_SINGLETON = "processVariables";
public final static String PROCESS_SCOPE_NAME = "process";
private ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
private boolean proxyTargetClass = true;
private Logger logger = LoggerFactory.getLogger(getClass());
private ProcessEngine processEngine;
private RuntimeService runtimeService;
// set through Namespace reflection if nothing else
@SuppressWarnings("unused")
public void setProcessEngine(ProcessEngine processEngine) {
this.processEngine = processEngine;
}
public Object get(String name, ObjectFactory<?> objectFactory) {
ExecutionEntity executionEntity = null;
try {
logger.debug("returning scoped object having beanName '{}' for conversation ID '{}'.", name, this.getConversationId());
ProcessInstance processInstance = Context.getExecutionContext().getProcessInstance();
executionEntity = (ExecutionEntity) processInstance;
Object scopedObject = executionEntity.getVariable(name);
if (scopedObject == null) {
scopedObject = objectFactory.getObject();
if (scopedObject instanceof ScopedObject) {
ScopedObject sc = (ScopedObject) scopedObject;
scopedObject = sc.getTargetObject();
logger.debug("de-referencing {}#targetObject before persisting variable", ScopedObject.class.getName());
}
persistVariable(name, scopedObject);
}
return createDirtyCheckingProxy(name, scopedObject);
} catch (Throwable th) {
- logger.warn("couldn't return value from process scope! {}",ExceptionUtils.getFullStackTrace(th));
+ logger.warn("couldn't return value from process scope! {}", ExceptionUtils.getStackTrace(th));
} finally {
if (executionEntity != null) {
logger.debug("set variable '{}' on executionEntity#{}", name, executionEntity.getId());
}
}
return null;
}
public void registerDestructionCallback(String name, Runnable callback) {
logger.debug("no support for registering descruction callbacks implemented currently. registerDestructionCallback('{}',callback) will do nothing.", name);
}
private String getExecutionId() {
return Context.getExecutionContext().getExecution().getId();
}
public Object remove(String name) {
logger.debug("remove '{}'", name);
return runtimeService.getVariable(getExecutionId(), name);
}
public Object resolveContextualObject(String key) {
if ("executionId".equalsIgnoreCase(key))
return Context.getExecutionContext().getExecution().getId();
if ("processInstance".equalsIgnoreCase(key))
return Context.getExecutionContext().getProcessInstance();
if ("processInstanceId".equalsIgnoreCase(key))
return Context.getExecutionContext().getProcessInstance().getId();
return null;
}
/**
* creates a proxy that dispatches invocations to the currently bound {@link ProcessInstance}
*
* @return shareable {@link ProcessInstance}
*/
private Object createSharedProcessInstance() {
ProxyFactory proxyFactoryBean = new ProxyFactory(ProcessInstance.class, new MethodInterceptor() {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
String methodName = methodInvocation.getMethod().getName() ;
logger.info("method invocation for {}.", methodName);
if(methodName.equals("toString"))
return "SharedProcessInstance";
ProcessInstance processInstance = Context.getExecutionContext().getProcessInstance();
Method method = methodInvocation.getMethod();
Object[] args = methodInvocation.getArguments();
Object result = method.invoke(processInstance, args);
return result;
}
});
return proxyFactoryBean.getProxy(this.classLoader);
}
public String getConversationId() {
return getExecutionId();
}
private final ConcurrentHashMap<String, Object> processVariablesMap = new ConcurrentHashMap<String, Object>() {
@Override
public java.lang.Object get(java.lang.Object o) {
Assert.isInstanceOf(String.class, o, "the 'key' must be a String");
String varName = (String) o;
ProcessInstance processInstance = Context.getExecutionContext().getProcessInstance();
ExecutionEntity executionEntity = (ExecutionEntity) processInstance;
if (executionEntity.getVariableNames().contains(varName)) {
return executionEntity.getVariable(varName);
}
throw new RuntimeException("no processVariable by the name of '" + varName + "' is available!");
}
};
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.registerScope(ProcessScope.PROCESS_SCOPE_NAME, this);
Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory, "BeanFactory was not a BeanDefinitionRegistry, so ProcessScope cannot be used.");
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
// Replace this or any of its inner beans with scoped proxy if it has this scope
boolean scoped = PROCESS_SCOPE_NAME.equals(definition.getScope());
Scopifier scopifier = new Scopifier(registry, PROCESS_SCOPE_NAME, proxyTargetClass, scoped);
scopifier.visitBeanDefinition(definition);
if (scoped) {
Scopifier.createScopedProxy(beanName, definition, registry, proxyTargetClass);
}
}
beanFactory.registerSingleton(ProcessScope.PROCESS_SCOPE_PROCESS_VARIABLES_SINGLETON, this.processVariablesMap);
beanFactory.registerResolvableDependency(ProcessInstance.class, createSharedProcessInstance());
}
public void destroy() throws Exception {
logger.info("{}#destroy() called ...", ProcessScope.class.getName());
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.processEngine, "the 'processEngine' must not be null!");
this.runtimeService = this.processEngine.getRuntimeService();
}
private Object createDirtyCheckingProxy(final String name, final Object scopedObject) throws Throwable {
ProxyFactory proxyFactoryBean = new ProxyFactory(scopedObject);
proxyFactoryBean.setProxyTargetClass(this.proxyTargetClass);
proxyFactoryBean.addAdvice(new MethodInterceptor() {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Object result = methodInvocation.proceed();
persistVariable(name, scopedObject);
return result;
}
});
return proxyFactoryBean.getProxy(this.classLoader);
}
private void persistVariable(String variableName, Object scopedObject) {
ProcessInstance processInstance = Context.getExecutionContext().getProcessInstance();
ExecutionEntity executionEntity = (ExecutionEntity) processInstance;
Assert.isTrue(scopedObject instanceof Serializable, "the scopedObject is not " + Serializable.class.getName() + "!");
executionEntity.setVariable(variableName, scopedObject);
}
}
| true | true | public Object get(String name, ObjectFactory<?> objectFactory) {
ExecutionEntity executionEntity = null;
try {
logger.debug("returning scoped object having beanName '{}' for conversation ID '{}'.", name, this.getConversationId());
ProcessInstance processInstance = Context.getExecutionContext().getProcessInstance();
executionEntity = (ExecutionEntity) processInstance;
Object scopedObject = executionEntity.getVariable(name);
if (scopedObject == null) {
scopedObject = objectFactory.getObject();
if (scopedObject instanceof ScopedObject) {
ScopedObject sc = (ScopedObject) scopedObject;
scopedObject = sc.getTargetObject();
logger.debug("de-referencing {}#targetObject before persisting variable", ScopedObject.class.getName());
}
persistVariable(name, scopedObject);
}
return createDirtyCheckingProxy(name, scopedObject);
} catch (Throwable th) {
logger.warn("couldn't return value from process scope! {}",ExceptionUtils.getFullStackTrace(th));
} finally {
if (executionEntity != null) {
logger.debug("set variable '{}' on executionEntity#{}", name, executionEntity.getId());
}
}
return null;
}
| public Object get(String name, ObjectFactory<?> objectFactory) {
ExecutionEntity executionEntity = null;
try {
logger.debug("returning scoped object having beanName '{}' for conversation ID '{}'.", name, this.getConversationId());
ProcessInstance processInstance = Context.getExecutionContext().getProcessInstance();
executionEntity = (ExecutionEntity) processInstance;
Object scopedObject = executionEntity.getVariable(name);
if (scopedObject == null) {
scopedObject = objectFactory.getObject();
if (scopedObject instanceof ScopedObject) {
ScopedObject sc = (ScopedObject) scopedObject;
scopedObject = sc.getTargetObject();
logger.debug("de-referencing {}#targetObject before persisting variable", ScopedObject.class.getName());
}
persistVariable(name, scopedObject);
}
return createDirtyCheckingProxy(name, scopedObject);
} catch (Throwable th) {
logger.warn("couldn't return value from process scope! {}", ExceptionUtils.getStackTrace(th));
} finally {
if (executionEntity != null) {
logger.debug("set variable '{}' on executionEntity#{}", name, executionEntity.getId());
}
}
return null;
}
|
diff --git a/store/infinispan/src/main/java/org/commonjava/shelflife/store/infinispan/InfinispanExpirationManager.java b/store/infinispan/src/main/java/org/commonjava/shelflife/store/infinispan/InfinispanExpirationManager.java
index 9332bde..2046391 100644
--- a/store/infinispan/src/main/java/org/commonjava/shelflife/store/infinispan/InfinispanExpirationManager.java
+++ b/store/infinispan/src/main/java/org/commonjava/shelflife/store/infinispan/InfinispanExpirationManager.java
@@ -1,492 +1,496 @@
package org.commonjava.shelflife.store.infinispan;
import static org.commonjava.shelflife.expire.ExpirationEventType.CANCEL;
import static org.commonjava.shelflife.expire.ExpirationEventType.EXPIRE;
import static org.commonjava.shelflife.expire.ExpirationEventType.SCHEDULE;
import static org.commonjava.shelflife.store.infinispan.BlockKeyUtils.generateCurrentBlockKey;
import static org.commonjava.shelflife.store.infinispan.BlockKeyUtils.generateNextBlockKey;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import org.commonjava.shelflife.expire.ExpirationEvent;
import org.commonjava.shelflife.expire.ExpirationManager;
import org.commonjava.shelflife.expire.ExpirationManagerException;
import org.commonjava.shelflife.expire.match.ExpirationMatcher;
import org.commonjava.shelflife.model.Expiration;
import org.commonjava.shelflife.model.ExpirationKey;
import org.commonjava.shelflife.store.infinispan.inject.ShelflifeCache;
import org.commonjava.shelflife.store.infinispan.inject.ShelflifeCaches;
import org.commonjava.util.logging.Logger;
import org.infinispan.Cache;
@javax.enterprise.context.ApplicationScoped
public class InfinispanExpirationManager
implements ExpirationManager
{
public static final int NEXT_EXPIRATION_OFFSET_MINUTES = 5;
private static final long NEXT_EXPIRATION_BATCH_OFFSET =
TimeUnit.MILLISECONDS.convert( NEXT_EXPIRATION_OFFSET_MINUTES, TimeUnit.MINUTES );
private static final long MIN_PURGE_PERIOD = 500;
public static final String BLOCK_CACHE_NAME = "shelflife-blocks";
public static final String DATA_CACHE_NAME = "shelflife-data";
private final Logger logger = new Logger( getClass() );
private final Timer timer = new Timer( true );
private final LinkedHashMap<ExpirationKey, Expiration> currentExpirations =
new LinkedHashMap<ExpirationKey, Expiration>();
@Inject
private Event<ExpirationEvent> eventQueue;
@Inject
@ShelflifeCache( ShelflifeCaches.BLOCKS )
// @Named( BLOCK_CACHE_NAME )
private transient Cache<String, Set<ExpirationKey>> expirationBlocks;
@Inject
@ShelflifeCache( ShelflifeCaches.DATA )
// @Named( DATA_CACHE_NAME )
private transient Cache<ExpirationKey, Expiration> expirationCache;
@PostConstruct
protected void init()
{
timer.schedule( new LoadNextExpirationsTask(), 0, NEXT_EXPIRATION_BATCH_OFFSET );
timer.schedule( new PurgeExpiredTask(), 0 );
}
@PreDestroy
protected void stopLoader()
{
timer.cancel();
}
@Override
public synchronized void schedule( final Expiration expiration )
throws ExpirationManagerException
{
if ( contains( expiration ) )
{
logger.info( "SKIPPING SCHEDULE: %s. Already scheduled!", expiration.getKey() );
return;
}
final long expires = expiration.getExpires();
final long expiresOffset = expires - System.currentTimeMillis();
if ( expiresOffset < NEXT_EXPIRATION_BATCH_OFFSET )
{
synchronized ( currentExpirations )
{
currentExpirations.put( expiration.getKey(), expiration );
currentExpirations.notifyAll();
}
// timer.schedule( new ExpirationTask( expiration ), expires );
}
final String blockKey = generateNextBlockKey( expires );
Set<ExpirationKey> keySet = expirationBlocks.get( blockKey );
if ( keySet == null )
{
keySet = new HashSet<ExpirationKey>();
expirationBlocks.put( blockKey, keySet );
}
keySet.add( expiration.getKey() );
expirationCache.put( expiration.getKey(), expiration );
logger.info( "\n\n[%s] SCHEDULED %s, expires: %s\nCurrent time: %s\n\n", System.currentTimeMillis(),
expiration.getKey(), new Date( expiration.getExpires() ), new Date() );
eventQueue.fire( new ExpirationEvent( expiration, SCHEDULE ) );
}
@Override
public void cancel( final Expiration expiration )
throws ExpirationManagerException
{
logger.info( "\n\n[%s] ATTEMPTING CANCEL: %s\n\n", System.currentTimeMillis(), expiration.getKey() );
logger.debug( "Is expiration still active? If not, skip cancellation! %s", expiration.isActive() );
if ( expiration.isActive() && contains( expiration ) )
{
logger.debug( "doing cancel: %s", expiration );
expiration.cancel();
remove( expiration );
logger.info( "\n\n[%s] CANCELED %s at: %s\n\n", System.currentTimeMillis(), expiration.getKey(), new Date() );
eventQueue.fire( new ExpirationEvent( expiration, CANCEL ) );
}
}
@Override
public void cancel( final ExpirationKey key )
throws ExpirationManagerException
{
final Expiration expiration = expirationCache.get( key );
if ( expiration != null )
{
cancel( expiration );
}
}
private synchronized void remove( final Expiration expiration )
{
final String blockKey = generateNextBlockKey( expiration.getExpires() );
final Set<ExpirationKey> keySet = expirationBlocks.get( blockKey );
if ( keySet != null )
{
keySet.remove( expiration );
if ( keySet.isEmpty() )
{
expirationBlocks.remove( blockKey );
}
}
synchronized ( currentExpirations )
{
currentExpirations.remove( expiration.getKey() );
}
expirationCache.remove( expiration.getKey() );
}
@Override
public void trigger( final Expiration expiration )
throws ExpirationManagerException
{
logger.info( "\n\n[%s] ATTEMPTING TRIGGER: %s\n\n", System.currentTimeMillis(), expiration.getKey() );
// logger.debug( "Is expiration still active? If not, skip trigger! %s", expiration.isActive() );
if ( expiration.isActive() && contains( expiration ) )
{
expiration.expire();
remove( expiration );
logger.info( "\n\n[%s] TRIGGERED %s at: %s\n\n", System.currentTimeMillis(), expiration.getKey(),
new Date() );
eventQueue.fire( new ExpirationEvent( expiration, EXPIRE ) );
}
}
@Override
public void trigger( final ExpirationKey key )
throws ExpirationManagerException
{
final Expiration expiration = expirationCache.get( key );
if ( expiration != null )
{
trigger( expiration );
}
}
@Override
public void triggerAll()
throws ExpirationManagerException
{
logger.debug( "[TRIGGER] ALL" );
for ( final Expiration exp : all() )
{
trigger( exp );
}
}
@Override
public void triggerAll( final ExpirationMatcher matcher )
throws ExpirationManagerException
{
logger.debug( "[TRIGGER] ALL" );
for ( final Expiration exp : getMatching( matcher ) )
{
if ( matcher.matches( exp ) )
{
trigger( exp );
}
}
}
@Override
public void cancelAll()
throws ExpirationManagerException
{
final Set<Expiration> all = all();
logger.debug( "[CANCEL] ALL(%s)", all.size() );
for ( final Expiration exp : all )
{
logger.info( "[%s] Canceling: %s", System.currentTimeMillis(), exp );
cancel( exp );
}
}
@Override
public void cancelAll( final ExpirationMatcher matcher )
throws ExpirationManagerException
{
for ( final Expiration exp : getMatching( matcher ) )
{
cancel( exp );
}
}
@Override
public void loadedFromStorage( final Collection<Expiration> expirations )
throws ExpirationManagerException
{
for ( final Expiration expiration : expirations )
{
if ( expiration.getExpires() <= System.currentTimeMillis() )
{
trigger( expiration );
}
else
{
this.currentExpirations.put( expiration.getKey(), expiration );
}
synchronized ( currentExpirations )
{
currentExpirations.notifyAll();
}
}
}
@Override
public boolean contains( final Expiration expiration )
{
return currentExpirations.containsKey( expiration.getKey() )
|| expirationCache.containsKey( expiration.getKey() );
}
private Set<Expiration> getMatching( final ExpirationMatcher matcher )
{
final Set<Expiration> matching = new LinkedHashSet<Expiration>();
for ( final Expiration exp : all() )
{
if ( matcher.matches( exp ) )
{
matching.add( exp );
}
}
return matching;
}
private Set<Expiration> all()
{
final Set<Expiration> result = new HashSet<Expiration>();
for ( final Entry<ExpirationKey, Expiration> entry : expirationCache.entrySet() )
{
result.add( entry.getValue() );
}
return result;
}
public final class PurgeExpiredTask
extends TimerTask
{
private final Logger logger = new Logger( getClass() );
@Override
public void run()
{
// logger.info( "Purging expired entries." );
synchronized ( currentExpirations )
{
while ( currentExpirations.isEmpty() )
{
try
{
// logger.info( "Purge task waiting for expirations..." );
currentExpirations.wait( TimeUnit.MILLISECONDS.convert( 10, TimeUnit.SECONDS ) );
}
catch ( final InterruptedException e )
{
logger.info( "Expiration purge task interrupted." );
return;
}
}
}
Map<ExpirationKey, Expiration> current;
synchronized ( currentExpirations )
{
current = new HashMap<ExpirationKey, Expiration>( currentExpirations );
}
for ( final Map.Entry<ExpirationKey, Expiration> entry : new HashSet<Map.Entry<ExpirationKey, Expiration>>(
current.entrySet() ) )
{
final ExpirationKey key = entry.getKey();
final Expiration exp = entry.getValue();
+ if ( exp == null )
+ {
+ continue;
+ }
// logger.info( "Handling expiration for: %s", key );
boolean cancel = false;
if ( !exp.isActive() )
{
// logger.info( "Expiration no longer active: %s", exp );
cancel = true;
return;
}
boolean expired = false;
if ( !cancel )
{
expired = exp.getExpires() <= System.currentTimeMillis();
// logger.info( "Checking expiration: %s vs current time: %s. Expired? %s", exp.getExpires(),
// System.currentTimeMillis(), expired );
if ( expired )
{
try
{
// logger.info( "\n\n\n [%s] TRIGGERING: %s (expiration timeout: %s)\n\n\n",
// System.currentTimeMillis(), exp, exp.getExpires() );
trigger( exp );
}
catch ( final ExpirationManagerException e )
{
logger.error( "Failed to trigger expiration: %s. Reason: %s", e, key, e.getMessage() );
cancel = true;
}
}
}
if ( cancel )
{
// logger.info( "Canceling: %s", key );
try
{
InfinispanExpirationManager.this.cancel( exp );
}
catch ( final ExpirationManagerException e )
{
logger.error( "Failed to cancel expiration: %s. Reason: %s", e, key, e.getMessage() );
}
}
if ( cancel || expired )
{
synchronized ( currentExpirations )
{
// logger.info( "Removing handled expiration: %s", key );
remove( exp );
current.remove( key );
}
}
}
if ( !current.isEmpty() )
{
final List<Expiration> remaining = new ArrayList<Expiration>( current.values() );
// logger.info( "Sorting %d remaining expirations", remaining.size() );
Collections.sort( remaining, new Comparator<Expiration>()
{
@Override
public int compare( final Expiration one, final Expiration two )
{
return Long.valueOf( one.getExpires() )
.compareTo( two.getExpires() );
}
} );
boolean scheduled = false;
for ( final Expiration exp : remaining )
{
if ( exp.getExpires() > ( System.currentTimeMillis() + MIN_PURGE_PERIOD ) )
{
final long offset = exp.getExpires() - System.currentTimeMillis();
logger.info( "Next purge in %d seconds.",
TimeUnit.SECONDS.convert( offset, TimeUnit.MILLISECONDS ) );
timer.schedule( new PurgeExpiredTask(), offset );
scheduled = true;
break;
}
}
if ( !scheduled )
{
logger.info( "Next purge in: %d seconds.",
TimeUnit.SECONDS.convert( MIN_PURGE_PERIOD, TimeUnit.MILLISECONDS ) );
timer.schedule( new PurgeExpiredTask(), MIN_PURGE_PERIOD );
}
}
}
}
public final class LoadNextExpirationsTask
extends TimerTask
{
private final Logger logger = new Logger( getClass() );
@Override
public void run()
{
final String key = generateCurrentBlockKey();
logger.info( "Loading batch of expirations for: %s", key );
final Set<ExpirationKey> expirationKeys = expirationBlocks.get( key );
if ( expirationKeys != null )
{
synchronized ( currentExpirations )
{
int added = 0;
for ( final ExpirationKey expirationKey : expirationKeys )
{
final Expiration expiration = expirationCache.get( expirationKey );
if ( !currentExpirations.containsKey( expiration ) )
{
currentExpirations.put( expirationKey, expiration );
added++;
}
}
if ( added > 0 )
{
currentExpirations.notifyAll();
}
}
}
}
}
}
| true | true | public void run()
{
// logger.info( "Purging expired entries." );
synchronized ( currentExpirations )
{
while ( currentExpirations.isEmpty() )
{
try
{
// logger.info( "Purge task waiting for expirations..." );
currentExpirations.wait( TimeUnit.MILLISECONDS.convert( 10, TimeUnit.SECONDS ) );
}
catch ( final InterruptedException e )
{
logger.info( "Expiration purge task interrupted." );
return;
}
}
}
Map<ExpirationKey, Expiration> current;
synchronized ( currentExpirations )
{
current = new HashMap<ExpirationKey, Expiration>( currentExpirations );
}
for ( final Map.Entry<ExpirationKey, Expiration> entry : new HashSet<Map.Entry<ExpirationKey, Expiration>>(
current.entrySet() ) )
{
final ExpirationKey key = entry.getKey();
final Expiration exp = entry.getValue();
// logger.info( "Handling expiration for: %s", key );
boolean cancel = false;
if ( !exp.isActive() )
{
// logger.info( "Expiration no longer active: %s", exp );
cancel = true;
return;
}
boolean expired = false;
if ( !cancel )
{
expired = exp.getExpires() <= System.currentTimeMillis();
// logger.info( "Checking expiration: %s vs current time: %s. Expired? %s", exp.getExpires(),
// System.currentTimeMillis(), expired );
if ( expired )
{
try
{
// logger.info( "\n\n\n [%s] TRIGGERING: %s (expiration timeout: %s)\n\n\n",
// System.currentTimeMillis(), exp, exp.getExpires() );
trigger( exp );
}
catch ( final ExpirationManagerException e )
{
logger.error( "Failed to trigger expiration: %s. Reason: %s", e, key, e.getMessage() );
cancel = true;
}
}
}
if ( cancel )
{
// logger.info( "Canceling: %s", key );
try
{
InfinispanExpirationManager.this.cancel( exp );
}
catch ( final ExpirationManagerException e )
{
logger.error( "Failed to cancel expiration: %s. Reason: %s", e, key, e.getMessage() );
}
}
if ( cancel || expired )
{
synchronized ( currentExpirations )
{
// logger.info( "Removing handled expiration: %s", key );
remove( exp );
current.remove( key );
}
}
}
if ( !current.isEmpty() )
{
final List<Expiration> remaining = new ArrayList<Expiration>( current.values() );
// logger.info( "Sorting %d remaining expirations", remaining.size() );
Collections.sort( remaining, new Comparator<Expiration>()
{
@Override
public int compare( final Expiration one, final Expiration two )
{
return Long.valueOf( one.getExpires() )
.compareTo( two.getExpires() );
}
} );
boolean scheduled = false;
for ( final Expiration exp : remaining )
{
if ( exp.getExpires() > ( System.currentTimeMillis() + MIN_PURGE_PERIOD ) )
{
final long offset = exp.getExpires() - System.currentTimeMillis();
logger.info( "Next purge in %d seconds.",
TimeUnit.SECONDS.convert( offset, TimeUnit.MILLISECONDS ) );
timer.schedule( new PurgeExpiredTask(), offset );
scheduled = true;
break;
}
}
if ( !scheduled )
{
logger.info( "Next purge in: %d seconds.",
TimeUnit.SECONDS.convert( MIN_PURGE_PERIOD, TimeUnit.MILLISECONDS ) );
timer.schedule( new PurgeExpiredTask(), MIN_PURGE_PERIOD );
}
}
}
| public void run()
{
// logger.info( "Purging expired entries." );
synchronized ( currentExpirations )
{
while ( currentExpirations.isEmpty() )
{
try
{
// logger.info( "Purge task waiting for expirations..." );
currentExpirations.wait( TimeUnit.MILLISECONDS.convert( 10, TimeUnit.SECONDS ) );
}
catch ( final InterruptedException e )
{
logger.info( "Expiration purge task interrupted." );
return;
}
}
}
Map<ExpirationKey, Expiration> current;
synchronized ( currentExpirations )
{
current = new HashMap<ExpirationKey, Expiration>( currentExpirations );
}
for ( final Map.Entry<ExpirationKey, Expiration> entry : new HashSet<Map.Entry<ExpirationKey, Expiration>>(
current.entrySet() ) )
{
final ExpirationKey key = entry.getKey();
final Expiration exp = entry.getValue();
if ( exp == null )
{
continue;
}
// logger.info( "Handling expiration for: %s", key );
boolean cancel = false;
if ( !exp.isActive() )
{
// logger.info( "Expiration no longer active: %s", exp );
cancel = true;
return;
}
boolean expired = false;
if ( !cancel )
{
expired = exp.getExpires() <= System.currentTimeMillis();
// logger.info( "Checking expiration: %s vs current time: %s. Expired? %s", exp.getExpires(),
// System.currentTimeMillis(), expired );
if ( expired )
{
try
{
// logger.info( "\n\n\n [%s] TRIGGERING: %s (expiration timeout: %s)\n\n\n",
// System.currentTimeMillis(), exp, exp.getExpires() );
trigger( exp );
}
catch ( final ExpirationManagerException e )
{
logger.error( "Failed to trigger expiration: %s. Reason: %s", e, key, e.getMessage() );
cancel = true;
}
}
}
if ( cancel )
{
// logger.info( "Canceling: %s", key );
try
{
InfinispanExpirationManager.this.cancel( exp );
}
catch ( final ExpirationManagerException e )
{
logger.error( "Failed to cancel expiration: %s. Reason: %s", e, key, e.getMessage() );
}
}
if ( cancel || expired )
{
synchronized ( currentExpirations )
{
// logger.info( "Removing handled expiration: %s", key );
remove( exp );
current.remove( key );
}
}
}
if ( !current.isEmpty() )
{
final List<Expiration> remaining = new ArrayList<Expiration>( current.values() );
// logger.info( "Sorting %d remaining expirations", remaining.size() );
Collections.sort( remaining, new Comparator<Expiration>()
{
@Override
public int compare( final Expiration one, final Expiration two )
{
return Long.valueOf( one.getExpires() )
.compareTo( two.getExpires() );
}
} );
boolean scheduled = false;
for ( final Expiration exp : remaining )
{
if ( exp.getExpires() > ( System.currentTimeMillis() + MIN_PURGE_PERIOD ) )
{
final long offset = exp.getExpires() - System.currentTimeMillis();
logger.info( "Next purge in %d seconds.",
TimeUnit.SECONDS.convert( offset, TimeUnit.MILLISECONDS ) );
timer.schedule( new PurgeExpiredTask(), offset );
scheduled = true;
break;
}
}
if ( !scheduled )
{
logger.info( "Next purge in: %d seconds.",
TimeUnit.SECONDS.convert( MIN_PURGE_PERIOD, TimeUnit.MILLISECONDS ) );
timer.schedule( new PurgeExpiredTask(), MIN_PURGE_PERIOD );
}
}
}
|
diff --git a/src/minecraft/basiccomponents/common/container/ContainerBatteryBox.java b/src/minecraft/basiccomponents/common/container/ContainerBatteryBox.java
index e31360c..0739ec4 100644
--- a/src/minecraft/basiccomponents/common/container/ContainerBatteryBox.java
+++ b/src/minecraft/basiccomponents/common/container/ContainerBatteryBox.java
@@ -1,101 +1,101 @@
package basiccomponents.common.container;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import universalelectricity.core.implement.IItemElectric;
import universalelectricity.prefab.SlotElectricItem;
import basiccomponents.common.tileentity.TileEntityBatteryBox;
public class ContainerBatteryBox extends Container
{
private TileEntityBatteryBox tileEntity;
public ContainerBatteryBox(InventoryPlayer par1InventoryPlayer, TileEntityBatteryBox batteryBox)
{
this.tileEntity = batteryBox;
// Top slot for battery output
this.addSlotToContainer(new SlotElectricItem(batteryBox, 0, 33, 24));
// Bottom slot for batter input
this.addSlotToContainer(new SlotElectricItem(batteryBox, 1, 33, 48));
int var3;
for (var3 = 0; var3 < 3; ++var3)
{
for (int var4 = 0; var4 < 9; ++var4)
{
this.addSlotToContainer(new Slot(par1InventoryPlayer, var4 + var3 * 9 + 9, 8 + var4 * 18, 84 + var3 * 18));
}
}
for (var3 = 0; var3 < 9; ++var3)
{
this.addSlotToContainer(new Slot(par1InventoryPlayer, var3, 8 + var3 * 18, 142));
}
tileEntity.openChest();
}
public void onCraftGuiClosed(EntityPlayer entityplayer)
{
super.onCraftGuiClosed(entityplayer);
tileEntity.closeChest();
}
@Override
public boolean canInteractWith(EntityPlayer par1EntityPlayer)
{
return this.tileEntity.isUseableByPlayer(par1EntityPlayer);
}
/**
* Called to transfer a stack from one inventory to the other eg. when shift clicking.
*/
@Override
public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par1)
{
ItemStack var2 = null;
Slot var3 = (Slot) this.inventorySlots.get(par1);
if (var3 != null && var3.getHasStack())
{
ItemStack var4 = var3.getStack();
var2 = var4.copy();
if (par1 != 0 && par1 != 1)
{
- if (var4.getItem() instanceof IItemElectric)
+ if (this.getSlot(0).isItemValid(var4))
{
if (((IItemElectric) var4.getItem()).canProduceElectricity())
{
if (!this.mergeItemStack(var4, 1, 2, false)) { return null; }
}
else
{
if (!this.mergeItemStack(var4, 0, 1, false)) { return null; }
}
}
else if (par1 >= 30 && par1 < 38 && !this.mergeItemStack(var4, 3, 30, false)) { return null; }
}
else if (!this.mergeItemStack(var4, 3, 38, false)) { return null; }
if (var4.stackSize == 0)
{
var3.putStack((ItemStack) null);
}
else
{
var3.onSlotChanged();
}
if (var4.stackSize == var2.stackSize) { return null; }
var3.onPickupFromSlot(par1EntityPlayer, var4);
}
return var2;
}
}
| true | true | public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par1)
{
ItemStack var2 = null;
Slot var3 = (Slot) this.inventorySlots.get(par1);
if (var3 != null && var3.getHasStack())
{
ItemStack var4 = var3.getStack();
var2 = var4.copy();
if (par1 != 0 && par1 != 1)
{
if (var4.getItem() instanceof IItemElectric)
{
if (((IItemElectric) var4.getItem()).canProduceElectricity())
{
if (!this.mergeItemStack(var4, 1, 2, false)) { return null; }
}
else
{
if (!this.mergeItemStack(var4, 0, 1, false)) { return null; }
}
}
else if (par1 >= 30 && par1 < 38 && !this.mergeItemStack(var4, 3, 30, false)) { return null; }
}
else if (!this.mergeItemStack(var4, 3, 38, false)) { return null; }
if (var4.stackSize == 0)
{
var3.putStack((ItemStack) null);
}
else
{
var3.onSlotChanged();
}
if (var4.stackSize == var2.stackSize) { return null; }
var3.onPickupFromSlot(par1EntityPlayer, var4);
}
return var2;
}
| public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par1)
{
ItemStack var2 = null;
Slot var3 = (Slot) this.inventorySlots.get(par1);
if (var3 != null && var3.getHasStack())
{
ItemStack var4 = var3.getStack();
var2 = var4.copy();
if (par1 != 0 && par1 != 1)
{
if (this.getSlot(0).isItemValid(var4))
{
if (((IItemElectric) var4.getItem()).canProduceElectricity())
{
if (!this.mergeItemStack(var4, 1, 2, false)) { return null; }
}
else
{
if (!this.mergeItemStack(var4, 0, 1, false)) { return null; }
}
}
else if (par1 >= 30 && par1 < 38 && !this.mergeItemStack(var4, 3, 30, false)) { return null; }
}
else if (!this.mergeItemStack(var4, 3, 38, false)) { return null; }
if (var4.stackSize == 0)
{
var3.putStack((ItemStack) null);
}
else
{
var3.onSlotChanged();
}
if (var4.stackSize == var2.stackSize) { return null; }
var3.onPickupFromSlot(par1EntityPlayer, var4);
}
return var2;
}
|
diff --git a/src/org/commoncrawl/service/parser/server/ParseWorker.java b/src/org/commoncrawl/service/parser/server/ParseWorker.java
index 8e4a461..3e5693d 100644
--- a/src/org/commoncrawl/service/parser/server/ParseWorker.java
+++ b/src/org/commoncrawl/service/parser/server/ParseWorker.java
@@ -1,594 +1,594 @@
/**
* Copyright 2008 - CommonCrawl Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
**/
package org.commoncrawl.service.parser.server;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.DataOutputBuffer;
import org.commoncrawl.io.NIOHttpHeaders;
import org.commoncrawl.service.parser.Link;
import org.commoncrawl.service.parser.Meta;
import org.commoncrawl.service.parser.ParseResult;
import org.commoncrawl.util.CCStringUtils;
import org.commoncrawl.util.CharsetUtils;
import org.commoncrawl.util.FlexBuffer;
import org.commoncrawl.util.HttpHeaderUtils;
import org.commoncrawl.util.MimeTypeFilter;
import org.commoncrawl.util.HttpHeaderUtils.ContentTypeAndCharset;
import org.commoncrawl.util.MimeTypeFilter.MimeTypeDisposition;
import org.commoncrawl.util.Tuples.Pair;
import org.w3c.dom.Document;
import com.dappit.Dapper.parser.DocumentBuilder;
import com.dappit.Dapper.parser.InstructionsPool;
import com.dappit.Dapper.parser.MozillaParser;
import com.dappit.Dapper.parser.ParserInitializationException;
import com.dappit.Dapper.parser.ParserInstruction;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.ByteProcessor;
import com.google.common.io.ByteStreams;
import com.google.common.io.InputSupplier;
import com.google.gson.JsonObject;
/**
*
* @author rana
*
*/
public class ParseWorker implements DocumentBuilder {
private static final Log LOG = LogFactory.getLog(ParserSlaveServer.class);
URL baseURL = null;
ImmutableMap<String,String> linkTypeToSrcMap
= new ImmutableMap.Builder<String,String>()
.put("a", "href")
.put("area", "href")
.put("frame", "src")
.put("iframe", "src")
.put("script", "src")
.put("link", "href")
.put("img", "src").build();
ImmutableSet<String> ignoreTextTagSet
= new ImmutableSet.Builder<String>()
.add("noscript")
.build();
class LinkUnderConstruction {
public String linkURL = null;
public String type = null;
public JsonObject jsonObject = new JsonObject();
public String linkText = "";
public LinkUnderConstruction(String linkType,BlockObjectInContext blockInContext) {
type = linkType;
jsonObject.addProperty("type", linkType);
/*
if (blockInContext != null) {
JsonObject blockJSONObject = new JsonObject();
blockJSONObject.addProperty("type", blockInContext.type);
blockJSONObject.addProperty("oid", blockInContext.id);
if (blockInContext.htmlId != null)
blockJSONObject.addProperty("id", blockInContext.htmlId);
if (blockInContext.classId != null)
blockJSONObject.addProperty("class", blockInContext.classId);
if (blockInContext.type.equals("table")) {
blockJSONObject.addProperty("t_row", Math.max(0,blockInContext.rowNumber));
blockJSONObject.addProperty("t_cell", Math.max(0,blockInContext.cellNumber));
}
if (blockInContext.parent != null) {
blockJSONObject.addProperty("p_oid", blockInContext.parent.id);
// if (blockInContext.parent.htmlId != null)
// blockJSONObject.addProperty("p_html_id", blockInContext.parent.htmlId);
// if (blockInContext.parent.classId != null)
// blockJSONObject.addProperty("p_class", blockInContext.parent.classId);
}
jsonObject.add("context", blockJSONObject);
}
*/
}
public Link buildLink() {
if (linkURL != null && linkURL.length() != 0 && !linkURL.startsWith("#")) {
try {
URL url = new URL(baseURL,linkURL);
Link link = new Link();
link.setUrl(url.toString());
jsonObject.addProperty("text", linkText);
link.setAttributes(jsonObject.toString());
return link;
} catch (MalformedURLException e) {
//LOG.error(CCStringUtils.stringifyException(e));
}
}
return null;
}
}
private ParseResult activeParseResult;
public void parsePartialHTMLDocument(ParseResult parseResultOut,URL baseURL,String content)throws IOException {
parseResultOut.setParseSuccessful(false);
this.baseURL = baseURL;
try {
// init parser ...
MozillaParser.init(null, "/usr/local/lib");
MozillaParser parser;
try {
parser = new MozillaParser(this);
activeParseResult = parseResultOut;
//LOG.info("Parsing Document");
parser.parse(content.getBytes(Charset.forName("UTF-8")),"utf-8",null);
activeParseResult = null;
// set content type ...
parseResultOut.setContentType("text/html");
parseResultOut.setText(textAccumulator.toString().replaceAll("[\\s]+", " "));
parseResultOut.setParseSuccessful(true);
} catch (ParserInitializationException e) {
LOG.error(CCStringUtils.stringifyException(e));
parseResultOut.setParseFailureReason("Parser Initialization Failed!");
}
catch (Exception e) {
parseResultOut.setParseFailureReason(CCStringUtils.stringifyException(e));
LOG.error(parseResultOut);
}
}
catch (ParserInitializationException e) {
parseResultOut.setParseFailureReason("Parser Initialization Failed!");
LOG.error(CCStringUtils.stringifyException(e));
throw new IOException(e);
}
}
public void parseDocument(ParseResult parseResultOut,long domainId,long documentId,URL baseURL,String rawHeaders, FlexBuffer data)throws IOException {
parseResultOut.setParseSuccessful(false);
this.baseURL = baseURL;
if (data.getCount() != 0) {
try {
// init parser ...
MozillaParser.init(null, "/usr/local/lib");
// load headers ...
NIOHttpHeaders headers = NIOHttpHeaders.parseHttpHeaders(rawHeaders);
// detect content type ...
ContentTypeAndCharset contentTypeInfo = new ContentTypeAndCharset();
HttpHeaderUtils.parseContentType(headers, contentTypeInfo);
//LOG.info("ContentType:" + contentTypeInfo._contentType + " Charset:" + contentTypeInfo._charset);
// ok now extract charset if possible ...
Pair<Integer,Charset> charsetTuple = CharsetUtils.bestEffortDetectCharset(rawHeaders,data.get(),data.getOffset(),data.getCount());
if (charsetTuple == null) {
charsetTuple = new Pair<Integer,Charset>(CharsetUtils.CHARSET_SRC_NO_MATCH,Charset.forName("ISO-8859-1"));
}
// decode bytes ... and convert to utf-8
ByteBuffer utf8Bytes = null;
try {
if (charsetTuple.e1.toString().equalsIgnoreCase("utf-8")) {
//LOG.info("Input Charset is utf-8, transposing source bytes to dest bytes");
if (data.getOffset() == 0) {
utf8Bytes = ByteBuffer.wrap(data.get(), 0, data.getCount());
}
else {
byte[] buffer = new byte[data.getCount()];
System.arraycopy(data.get(), data.getOffset(),buffer, 0, data.getCount());
utf8Bytes = ByteBuffer.wrap(buffer);
}
}
else {
CharBuffer ucs2Chars = charsetTuple.e1.decode(ByteBuffer.wrap(data.get(),data.getOffset(),data.getCount()));
utf8Bytes = Charset.forName("UTF-8").encode(ucs2Chars);
}
} catch (Exception e) {
LOG.error(CCStringUtils.stringifyException(e));
parseResultOut.setParseFailureReason(CCStringUtils.stringifyException(e));
// this should not have happened... we consider this unrecoverable
throw new IOException(e);
}
if (utf8Bytes == null || utf8Bytes.remaining() == 0) {
parseResultOut.setParseFailureReason("Invalid UTF-8 bytes detected for doc:" + baseURL + " detector:" + charsetTuple.e0 + " Charset:" + charsetTuple.e1);
throw new IOException(parseResultOut.getParseFailureReason());
}
//LOG.info("UTF-8 Data Length:" + utf8Bytes.remaining());
MimeTypeDisposition disposition = MimeTypeFilter.checkMimeTypeDisposition(contentTypeInfo._contentType);
//LOG.info("MimeType Disposition:"+ disposition);
if (disposition == MimeTypeDisposition.ACCEPT_HTML) {
// ok ready to send to mozilla ...
MozillaParser parser;
try {
parser = new MozillaParser(this);
activeParseResult = parseResultOut;
//LOG.info("Parsing Document");
parser.parse(utf8Bytes.array(),"utf-8",null);
activeParseResult = null;
// set content type ...
parseResultOut.setContentType(contentTypeInfo._contentType);
parseResultOut.setText(textAccumulator.toString().replaceAll("[\\s]+", " "));
parseResultOut.setParseSuccessful(true);
} catch (ParserInitializationException e) {
LOG.error(CCStringUtils.stringifyException(e));
parseResultOut.setParseFailureReason("Parser Initialization Failed!");
}
catch (Exception e) {
parseResultOut.setParseFailureReason(CCStringUtils.stringifyException(e));
LOG.error(parseResultOut);
}
}
else if (disposition == MimeTypeDisposition.ACCEPT_OTHER) {
}
else {
parseResultOut.setParseFailureReason("Unsupported ContentType:" + contentTypeInfo._contentType);
}
} catch (ParserInitializationException e) {
parseResultOut.setParseFailureReason("Parser Initialization Failed!");
LOG.error(CCStringUtils.stringifyException(e));
throw new IOException(e);
}
}
}
public static void main(String[] args) throws IOException {
String baseURL = "http://unknown.com/";
if (args.length != 0) {
baseURL = args[0];
}
URL baseURLObj;
try {
baseURLObj = new URL(baseURL);
} catch (MalformedURLException e2) {
throw new IOException("Invalid Base Link");
}
final DataOutputBuffer headerBuffer = new DataOutputBuffer();
final DataOutputBuffer contentBuffer = new DataOutputBuffer();
try {
ByteStreams.readBytes(
new InputSupplier<InputStream>() {
@Override
public InputStream getInput() throws IOException {
return System.in;
}
}
,new ByteProcessor<Long>() {
@Override
public Long getResult() {
return 0L;
}
int currLineCharCount = 0;
boolean processingHeaders = true;
@Override
public boolean processBytes(byte[] buf, int start, int length)
throws IOException {
if (processingHeaders) {
int current = start;
int end = current + length;
while (processingHeaders && current != end) {
if (buf[current] != '\r' && buf[current] != '\n') {
currLineCharCount++;
}
else if (buf[current] == '\n') {
if (currLineCharCount == 0){
headerBuffer.write(buf,start,current - start + 1);
processingHeaders = false;
}
currLineCharCount = 0;
}
current++;
}
if (processingHeaders) {
headerBuffer.write(buf,start,length);
}
else {
length -= current-start;
start = current;
}
}
if (!processingHeaders) {
contentBuffer.write(buf,start,length);
}
return true;
}
});
//LOG.info("HEADER LEN:" + headerBuffer.getLength());
// System.out.println(new String(headerBuffer.getData(),0,headerBuffer.getLength(),Charset.forName("UTF-8")));
//LOG.info("CONTENT LEN:" + contentBuffer.getLength());
//System.out.println(new String(contentBuffer.getData(),0,contentBuffer.getLength(),Charset.forName("UTF-8")));
// decode header bytes ...
String header = "";
if (headerBuffer.getLength() != 0) {
try {
header = new String(headerBuffer.getData(),0,headerBuffer.getLength(),Charset.forName("UTF-8"));
}
catch (Exception e) {
LOG.warn(CCStringUtils.stringifyException(e));
header = new String(headerBuffer.getData(),0,headerBuffer.getLength(),Charset.forName("ASCII"));
}
}
//LOG.info("Parsing Document");
ParseWorker worker = new ParseWorker();
ParseResult result = new ParseResult();
worker.parseDocument(result,0L,0L,baseURLObj,header,new FlexBuffer(contentBuffer.getData(),0,contentBuffer.getLength()));
//LOG.info("Parse Result:" + result.getParseSuccessful());
//LOG.info("Parse Data:" + result.toString());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/*
List<String> lines;
try {
lines = IOUtils.readLines(System.in, "UTF-8");
for (String line : lines){
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
int inHeadTag = 0;
int inBase = 0;
int blockId = 0;
int inTable = 0;
LinkUnderConstruction activeLink = null;
BlockObjectInContext blockInConstruction = null;
LinkedList<LinkUnderConstruction> linksUnderConstruction = new LinkedList<LinkUnderConstruction>();
StringBuffer textAccumulator = new StringBuffer();
static class BlockObjectInContext {
public BlockObjectInContext parent;
public String type = "";
public int id;
public int rowNumber=-1;
public int cellNumber=-1;
public String classId=null;
public String htmlId = null;
public BlockObjectInContext(BlockObjectInContext parentObject,String type,int id) {
this.parent= parentObject;
this.type = type;
this.id = id;
}
}
static ImmutableSet<String> validMetaTagKeys = new ImmutableSet.Builder<String>()
.add("name")
.add("property")
.add("http-equiv")
.build();
@Override
public Document buildDocument(InstructionsPool instructionsPool,FileOutputStream optionalOutputStream) throws IOException {
//LOG.info("Build Document Called");
List<Integer> operations = instructionsPool.operations;
List<String> arguments = instructionsPool.arguments;
LinkedList<Integer> nodeStack = new LinkedList<Integer>();
LinkedList<BlockObjectInContext> blockStack = new LinkedList<BlockObjectInContext>();
Meta meta = null;
for (int i=0; i<operations.size(); i++)
{
int domOperation = operations.get(i);
String domArgument = arguments.get(i);
//System.out.println("Operation :" + ParserInstruction.getOperationString(domOperation)+" Arg:~" + domArgument+"~");
switch (domOperation)
{
// Open node :
case ParserInstruction.OpenNode:
case ParserInstruction.AddLeaf: {
activeLink = null;
blockInConstruction = null;
String nodeName = domArgument.toLowerCase();
if (nodeName.equals("meta")) {
meta = new Meta();
}
else if (linkTypeToSrcMap.containsKey(nodeName)) {
//LOG.info("Node:" + nodeName + " is of type Link. Adding to LinksUnderConst");
activeLink = new LinkUnderConstruction(nodeName,blockStack.peek());
linksUnderConstruction.push(activeLink);
}
else if (nodeName.equals("head")) {
inHeadTag++;
}
else if (nodeName.equals("base")) {
if (inHeadTag != 0) {
inBase++;
}
}
else if (nodeName.equals("table") || nodeName.equals("div")) {
blockInConstruction = new BlockObjectInContext(blockStack.peek(),nodeName,++blockId);
blockStack.push(blockInConstruction);
}
else if (nodeName.equals("tr") || nodeName.equals("th")) {
BlockObjectInContext table = blockStack.peek();
if (table != null) {
table.rowNumber++;
table.cellNumber = -1;
}
}
else if (nodeName.equals("td")) {
BlockObjectInContext table = blockStack.peek();
if (table != null) {
table.cellNumber++;
}
}
nodeStack.push(i);
}
break;
// Close node :
case ParserInstruction.CloseNode:
case ParserInstruction.CloseLeaf: {
int arguementPos = nodeStack.pop();
String nodeName = arguments.get(arguementPos).toLowerCase();
//LOG.info("Close Node Called on Node:" + nodeName);
if (nodeName.equals("head")) {
inHeadTag--;
}
else if (nodeName.equals("base")) {
if (inHeadTag != 0) {
inBase--;
}
}
else if (linkTypeToSrcMap.containsKey(nodeName)){
//LOG.info("Node:" + nodeName + " is a Link Type");
LinkUnderConstruction linkPartial = linksUnderConstruction.pop();
if (linkPartial != null) {
//LOG.info("POPed a partial LinkObject of type:" + linkPartial.type);
Link link = linkPartial.buildLink();
if (link != null) {
activeParseResult.getExtractedLinks().add(link);
}
}
}
else if (nodeName.equals("table") || nodeName.equals("div")) {
blockStack.pop();
}
else if (nodeName.equals("meta")) {
if (meta != null) {
activeParseResult.getMetaTags().add(meta);
meta = null;
}
}
if (textAccumulator.length() != 0
&& !Character.isWhitespace(textAccumulator.charAt(textAccumulator.length() - 1))) {
textAccumulator.append(" ");
}
}
break;
case ParserInstruction.AddText: {
Integer arguementPos = nodeStack.peek();
String nodeName = (arguementPos != null) ? arguments.get(arguementPos).toLowerCase() :null;
LinkUnderConstruction link = linksUnderConstruction.peek();
if (link != null) {
if (link.linkText.length() != 0)
link.linkText += " ";
link.linkText += domArgument.trim();
}
if (nodeName == null || !ignoreTextTagSet.contains(nodeName.toLowerCase())) {
textAccumulator.append(domArgument);
}
}break;
// case ParserInstruction.AddContent:
// System.out.println("AddContent:"+domArgument);
// break;
case ParserInstruction.WriteAttributeKey: {
// add an attribute with the next lookahead operation :
String key = domArgument.toLowerCase();
i++;
domOperation = operations.get(i);
String value = arguments.get(i);
if (meta != null) {
if (key.equalsIgnoreCase("content")) {
meta.setValue(value);
}
else if (validMetaTagKeys.contains(key)) {
- meta.setName(key);
+ meta.setName(value);
}
}
if(key.equals("href") && inBase != 0) {
if (value.length() != 0) {
try {
baseURL = new URL(value);
}
catch (Exception e) {
LOG.error(CCStringUtils.stringifyException(e));
throw new IOException(e);
}
}
}
else if (activeLink != null) {
if (linkTypeToSrcMap.get(activeLink.type).equalsIgnoreCase(key)) {
activeLink.linkURL = value;
}
else {
activeLink.jsonObject.addProperty(key, value);
}
}
else if (blockInConstruction != null){
if (key.equals("class")) {
blockInConstruction.classId = value;
}
else if (key.equals("id")) {
blockInConstruction.htmlId = value;
}
}
}
break;
case ParserInstruction.SetTitle: {
activeParseResult.setTitle(domArgument);
}
break;
// case ParserInstruction.AddEntity:
// System.out.println("AddEntity:" + domArgument);
// break;
// case ParserInstruction.AddComment:
// System.out.println("AddComment:" + domArgument);
// break; case ParserInstruction.SetTitle:
// System.out.println("SetTitle:" + domArgument);
// break;
// }
}
}
return null;
}
}
| true | true | public Document buildDocument(InstructionsPool instructionsPool,FileOutputStream optionalOutputStream) throws IOException {
//LOG.info("Build Document Called");
List<Integer> operations = instructionsPool.operations;
List<String> arguments = instructionsPool.arguments;
LinkedList<Integer> nodeStack = new LinkedList<Integer>();
LinkedList<BlockObjectInContext> blockStack = new LinkedList<BlockObjectInContext>();
Meta meta = null;
for (int i=0; i<operations.size(); i++)
{
int domOperation = operations.get(i);
String domArgument = arguments.get(i);
//System.out.println("Operation :" + ParserInstruction.getOperationString(domOperation)+" Arg:~" + domArgument+"~");
switch (domOperation)
{
// Open node :
case ParserInstruction.OpenNode:
case ParserInstruction.AddLeaf: {
activeLink = null;
blockInConstruction = null;
String nodeName = domArgument.toLowerCase();
if (nodeName.equals("meta")) {
meta = new Meta();
}
else if (linkTypeToSrcMap.containsKey(nodeName)) {
//LOG.info("Node:" + nodeName + " is of type Link. Adding to LinksUnderConst");
activeLink = new LinkUnderConstruction(nodeName,blockStack.peek());
linksUnderConstruction.push(activeLink);
}
else if (nodeName.equals("head")) {
inHeadTag++;
}
else if (nodeName.equals("base")) {
if (inHeadTag != 0) {
inBase++;
}
}
else if (nodeName.equals("table") || nodeName.equals("div")) {
blockInConstruction = new BlockObjectInContext(blockStack.peek(),nodeName,++blockId);
blockStack.push(blockInConstruction);
}
else if (nodeName.equals("tr") || nodeName.equals("th")) {
BlockObjectInContext table = blockStack.peek();
if (table != null) {
table.rowNumber++;
table.cellNumber = -1;
}
}
else if (nodeName.equals("td")) {
BlockObjectInContext table = blockStack.peek();
if (table != null) {
table.cellNumber++;
}
}
nodeStack.push(i);
}
break;
// Close node :
case ParserInstruction.CloseNode:
case ParserInstruction.CloseLeaf: {
int arguementPos = nodeStack.pop();
String nodeName = arguments.get(arguementPos).toLowerCase();
//LOG.info("Close Node Called on Node:" + nodeName);
if (nodeName.equals("head")) {
inHeadTag--;
}
else if (nodeName.equals("base")) {
if (inHeadTag != 0) {
inBase--;
}
}
else if (linkTypeToSrcMap.containsKey(nodeName)){
//LOG.info("Node:" + nodeName + " is a Link Type");
LinkUnderConstruction linkPartial = linksUnderConstruction.pop();
if (linkPartial != null) {
//LOG.info("POPed a partial LinkObject of type:" + linkPartial.type);
Link link = linkPartial.buildLink();
if (link != null) {
activeParseResult.getExtractedLinks().add(link);
}
}
}
else if (nodeName.equals("table") || nodeName.equals("div")) {
blockStack.pop();
}
else if (nodeName.equals("meta")) {
if (meta != null) {
activeParseResult.getMetaTags().add(meta);
meta = null;
}
}
if (textAccumulator.length() != 0
&& !Character.isWhitespace(textAccumulator.charAt(textAccumulator.length() - 1))) {
textAccumulator.append(" ");
}
}
break;
case ParserInstruction.AddText: {
Integer arguementPos = nodeStack.peek();
String nodeName = (arguementPos != null) ? arguments.get(arguementPos).toLowerCase() :null;
LinkUnderConstruction link = linksUnderConstruction.peek();
if (link != null) {
if (link.linkText.length() != 0)
link.linkText += " ";
link.linkText += domArgument.trim();
}
if (nodeName == null || !ignoreTextTagSet.contains(nodeName.toLowerCase())) {
textAccumulator.append(domArgument);
}
}break;
// case ParserInstruction.AddContent:
// System.out.println("AddContent:"+domArgument);
// break;
case ParserInstruction.WriteAttributeKey: {
// add an attribute with the next lookahead operation :
String key = domArgument.toLowerCase();
i++;
domOperation = operations.get(i);
String value = arguments.get(i);
if (meta != null) {
if (key.equalsIgnoreCase("content")) {
meta.setValue(value);
}
else if (validMetaTagKeys.contains(key)) {
meta.setName(key);
}
}
if(key.equals("href") && inBase != 0) {
if (value.length() != 0) {
try {
baseURL = new URL(value);
}
catch (Exception e) {
LOG.error(CCStringUtils.stringifyException(e));
throw new IOException(e);
}
}
}
else if (activeLink != null) {
if (linkTypeToSrcMap.get(activeLink.type).equalsIgnoreCase(key)) {
activeLink.linkURL = value;
}
else {
activeLink.jsonObject.addProperty(key, value);
}
}
else if (blockInConstruction != null){
if (key.equals("class")) {
blockInConstruction.classId = value;
}
else if (key.equals("id")) {
blockInConstruction.htmlId = value;
}
}
}
break;
case ParserInstruction.SetTitle: {
activeParseResult.setTitle(domArgument);
}
break;
// case ParserInstruction.AddEntity:
// System.out.println("AddEntity:" + domArgument);
// break;
// case ParserInstruction.AddComment:
// System.out.println("AddComment:" + domArgument);
// break; case ParserInstruction.SetTitle:
// System.out.println("SetTitle:" + domArgument);
// break;
// }
}
}
return null;
}
| public Document buildDocument(InstructionsPool instructionsPool,FileOutputStream optionalOutputStream) throws IOException {
//LOG.info("Build Document Called");
List<Integer> operations = instructionsPool.operations;
List<String> arguments = instructionsPool.arguments;
LinkedList<Integer> nodeStack = new LinkedList<Integer>();
LinkedList<BlockObjectInContext> blockStack = new LinkedList<BlockObjectInContext>();
Meta meta = null;
for (int i=0; i<operations.size(); i++)
{
int domOperation = operations.get(i);
String domArgument = arguments.get(i);
//System.out.println("Operation :" + ParserInstruction.getOperationString(domOperation)+" Arg:~" + domArgument+"~");
switch (domOperation)
{
// Open node :
case ParserInstruction.OpenNode:
case ParserInstruction.AddLeaf: {
activeLink = null;
blockInConstruction = null;
String nodeName = domArgument.toLowerCase();
if (nodeName.equals("meta")) {
meta = new Meta();
}
else if (linkTypeToSrcMap.containsKey(nodeName)) {
//LOG.info("Node:" + nodeName + " is of type Link. Adding to LinksUnderConst");
activeLink = new LinkUnderConstruction(nodeName,blockStack.peek());
linksUnderConstruction.push(activeLink);
}
else if (nodeName.equals("head")) {
inHeadTag++;
}
else if (nodeName.equals("base")) {
if (inHeadTag != 0) {
inBase++;
}
}
else if (nodeName.equals("table") || nodeName.equals("div")) {
blockInConstruction = new BlockObjectInContext(blockStack.peek(),nodeName,++blockId);
blockStack.push(blockInConstruction);
}
else if (nodeName.equals("tr") || nodeName.equals("th")) {
BlockObjectInContext table = blockStack.peek();
if (table != null) {
table.rowNumber++;
table.cellNumber = -1;
}
}
else if (nodeName.equals("td")) {
BlockObjectInContext table = blockStack.peek();
if (table != null) {
table.cellNumber++;
}
}
nodeStack.push(i);
}
break;
// Close node :
case ParserInstruction.CloseNode:
case ParserInstruction.CloseLeaf: {
int arguementPos = nodeStack.pop();
String nodeName = arguments.get(arguementPos).toLowerCase();
//LOG.info("Close Node Called on Node:" + nodeName);
if (nodeName.equals("head")) {
inHeadTag--;
}
else if (nodeName.equals("base")) {
if (inHeadTag != 0) {
inBase--;
}
}
else if (linkTypeToSrcMap.containsKey(nodeName)){
//LOG.info("Node:" + nodeName + " is a Link Type");
LinkUnderConstruction linkPartial = linksUnderConstruction.pop();
if (linkPartial != null) {
//LOG.info("POPed a partial LinkObject of type:" + linkPartial.type);
Link link = linkPartial.buildLink();
if (link != null) {
activeParseResult.getExtractedLinks().add(link);
}
}
}
else if (nodeName.equals("table") || nodeName.equals("div")) {
blockStack.pop();
}
else if (nodeName.equals("meta")) {
if (meta != null) {
activeParseResult.getMetaTags().add(meta);
meta = null;
}
}
if (textAccumulator.length() != 0
&& !Character.isWhitespace(textAccumulator.charAt(textAccumulator.length() - 1))) {
textAccumulator.append(" ");
}
}
break;
case ParserInstruction.AddText: {
Integer arguementPos = nodeStack.peek();
String nodeName = (arguementPos != null) ? arguments.get(arguementPos).toLowerCase() :null;
LinkUnderConstruction link = linksUnderConstruction.peek();
if (link != null) {
if (link.linkText.length() != 0)
link.linkText += " ";
link.linkText += domArgument.trim();
}
if (nodeName == null || !ignoreTextTagSet.contains(nodeName.toLowerCase())) {
textAccumulator.append(domArgument);
}
}break;
// case ParserInstruction.AddContent:
// System.out.println("AddContent:"+domArgument);
// break;
case ParserInstruction.WriteAttributeKey: {
// add an attribute with the next lookahead operation :
String key = domArgument.toLowerCase();
i++;
domOperation = operations.get(i);
String value = arguments.get(i);
if (meta != null) {
if (key.equalsIgnoreCase("content")) {
meta.setValue(value);
}
else if (validMetaTagKeys.contains(key)) {
meta.setName(value);
}
}
if(key.equals("href") && inBase != 0) {
if (value.length() != 0) {
try {
baseURL = new URL(value);
}
catch (Exception e) {
LOG.error(CCStringUtils.stringifyException(e));
throw new IOException(e);
}
}
}
else if (activeLink != null) {
if (linkTypeToSrcMap.get(activeLink.type).equalsIgnoreCase(key)) {
activeLink.linkURL = value;
}
else {
activeLink.jsonObject.addProperty(key, value);
}
}
else if (blockInConstruction != null){
if (key.equals("class")) {
blockInConstruction.classId = value;
}
else if (key.equals("id")) {
blockInConstruction.htmlId = value;
}
}
}
break;
case ParserInstruction.SetTitle: {
activeParseResult.setTitle(domArgument);
}
break;
// case ParserInstruction.AddEntity:
// System.out.println("AddEntity:" + domArgument);
// break;
// case ParserInstruction.AddComment:
// System.out.println("AddComment:" + domArgument);
// break; case ParserInstruction.SetTitle:
// System.out.println("SetTitle:" + domArgument);
// break;
// }
}
}
return null;
}
|
diff --git a/source/RMG/jing/chem/QMTP.java b/source/RMG/jing/chem/QMTP.java
index 61158705..f6aa142b 100644
--- a/source/RMG/jing/chem/QMTP.java
+++ b/source/RMG/jing/chem/QMTP.java
@@ -1,2360 +1,2360 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
package jing.chem;
import java.util.*;
import jing.chemUtil.*;
import jing.param.*;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
//quantum mechanics thermo property estimator; analog of GATP
public class QMTP implements GeneralGAPP {
final protected static double ENTHALPY_HYDROGEN = 52.1; //needed for HBI
private static QMTP INSTANCE = new QMTP(); //## attribute INSTANCE
protected static PrimaryThermoLibrary primaryLibrary;//Note: may be able to separate this out into GeneralGAPP, as this is common to both GATP and QMTP
public static String qmfolder= "QMfiles/";
// protected static HashMap library; //as above, may be able to move this and associated functions to GeneralGAPP (and possibly change from "x implements y" to "x extends y"), as it is common to both GATP and QMTP
protected ThermoGAGroupLibrary thermoLibrary; //needed for HBI
public static String qmprogram= "both";//the qmprogram can be "mopac", "gaussian03", "both" (MOPAC and Gaussian), or "mm4"
public static boolean usePolar = false; //use polar keyword in MOPAC
public static boolean useCanTherm = true; //whether to use CanTherm in MM4 cases for interpreting output via force-constant matrix; this will hopefully avoid zero frequency issues
public static boolean useHindRot = false;//whether to use HinderedRotor scans with MM4 (requires useCanTherm=true)
// Constructors
//## operation QMTP()
private QMTP() {
// initializeLibrary(); //gmagoon 72509: commented out in GATP, so I am mirroring the change here; other library functions below also commented out
initializePrimaryThermoLibrary();
}
//## operation generateThermoData(ChemGraph)
public ThermoData generateThermoData(ChemGraph p_chemGraph) {
//#[ operation generateThermoData(ChemGraph)
//first, check for thermo data in the primary thermo library and library (?); if it is there, use it
ThermoData result = primaryLibrary.getThermoData(p_chemGraph.getGraph());
//System.out.println(result);
if (result != null) {
p_chemGraph.fromprimarythermolibrary = true;
return result;
}
// result = getFromLibrary(p_chemGraph.getChemicalFormula());//gmagoon 72509: commented out in GATP, so I am mirroring the change here
// if (result != null) return result;
result=new ThermoData();
int maxRadNumForQM = Global.maxRadNumForQM;
if (p_chemGraph.getRadicalNumber() > maxRadNumForQM)//use HBI if the molecule has more radicals than maxRadNumForQM; this is helpful because ; also MM4 (and MM3) look like they may have issues with radicals
{//this code is based closely off of GATP saturation (in getGAGroup()), but there are some modifications, particularly for symmetry correction
//find the initial symmetry number
int sigmaRadical = p_chemGraph.getSymmetryNumber();
Graph g = p_chemGraph.getGraph();
HashMap oldCentralNode = (HashMap)(p_chemGraph.getCentralNode()).clone();
// saturate radical site
int max_radNum_molecule = ChemGraph.getMAX_RADICAL_NUM();
int max_radNum_atom = Math.min(8,max_radNum_molecule);
int [] idArray = new int[max_radNum_molecule];
Atom [] atomArray = new Atom[max_radNum_molecule];
Node [][] newnode = new Node[max_radNum_molecule][max_radNum_atom];
int radicalSite = 0;
Iterator iter = p_chemGraph.getNodeList();
FreeElectron satuated = FreeElectron.make("0");
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isRadical()) {
radicalSite ++;
// save the old radical atom
idArray[radicalSite-1] = node.getID().intValue();
atomArray[radicalSite-1] = atom;
// new a satuated atom and replace the old one
Atom newAtom = new Atom(atom.getChemElement(),satuated);
node.setElement(newAtom);
node.updateFeElement();
}
}
// add H to saturate chem graph
Atom H = Atom.make(ChemElement.make("H"),satuated);
Bond S = Bond.make("S");
for (int i=0;i<radicalSite;i++) {
Node node = p_chemGraph.getNodeAt(idArray[i]);
Atom atom = atomArray[i];
int HNum = atom.getRadicalNumber();
for (int j=0;j<HNum;j++) {
newnode[i][j] = g.addNode(H);
g.addArcBetween(node,S,newnode[i][j]);
}
node.updateFgElement();
}
//find the saturated symmetry number
int sigmaSaturated = p_chemGraph.getSymmetryNumber();
// result = generateThermoData(g);//I'm not sure what GATP does, but this recursive calling will use HBIs on saturated species if it exists in PrimaryThermoLibrary
//check the primary thermo library for the saturated graph
result = primaryLibrary.getThermoData(p_chemGraph.getGraph());
//System.out.println(result);
if (result != null) {
p_chemGraph.fromprimarythermolibrary = true;
}
else{
result=generateQMThermoData(p_chemGraph);
}
// find the BDE for all radical groups
if(thermoLibrary == null) initGAGroupLibrary();
for (int i=0; i<radicalSite; i++) {
int id = idArray[i];
Node node = g.getNodeAt(id);
Atom old = (Atom)node.getElement();
node.setElement(atomArray[i]);
node.updateFeElement();
// get rid of the extra H at ith site
int HNum = atomArray[i].getRadicalNumber();
for (int j=0;j<HNum;j++) {
g.removeNode(newnode[i][j]);
}
node.updateFgElement();
p_chemGraph.resetThermoSite(node);
ThermoGAValue thisGAValue = thermoLibrary.findRadicalGroup(p_chemGraph);
if (thisGAValue == null) {
System.err.println("Radical group not found: " + node.getID());
}
else {
//System.out.println(node.getID() + " radical correction: " + thisGAValue.getName() + " "+thisGAValue.toString());
result.plus(thisGAValue);
}
//recover the saturated site for next radical site calculation
node.setElement(old);
node.updateFeElement();
for (int j=0;j<HNum;j++) {
newnode[i][j] = g.addNode(H);
g.addArcBetween(node,S,newnode[i][j]);
}
node.updateFgElement();
}
// recover the chem graph structure
// recover the radical
for (int i=0; i<radicalSite; i++) {
int id = idArray[i];
Node node = g.getNodeAt(id);
node.setElement(atomArray[i]);
node.updateFeElement();
int HNum = atomArray[i].getRadicalNumber();
//get rid of extra H
for (int j=0;j<HNum;j++) {
g.removeNode(newnode[i][j]);
}
node.updateFgElement();
}
// subtract the enthalphy of H from the result
int rad_number = p_chemGraph.getRadicalNumber();
ThermoGAValue enthalpy_H = new ThermoGAValue(ENTHALPY_HYDROGEN * rad_number, 0,0,0,0,0,0,0,0,0,0,0,null);
result.minus(enthalpy_H);
//correct the symmetry number based on the relative radical and saturated symmetry number; this should hopefully sidestep potential complications based on the fact that certain symmetry effects could be included in HBI value itself, and the fact that the symmetry number correction for saturated molecule has already been implemented, and it is likely to be different than symmetry number considered here, since the correction for the saturated molecule will have been external symmetry number, whereas RMG's ChemGraph symmetry number estimator includes both internal and external symmetry contributions; even so, I don't know if this will handle a change from chiral to achiral (or vice versa) properly
ThermoGAValue symmetryNumberCorrection = new ThermoGAValue(0,-1*GasConstant.getCalMolK()*Math.log((double)(sigmaRadical)/(double)(sigmaSaturated)),0,0,0,0,0,0,0,0,0,0,null);
result.plus(symmetryNumberCorrection);
p_chemGraph.setCentralNode(oldCentralNode);
//display corrected thermo to user
String [] InChInames = getQMFileName(p_chemGraph);//determine the filename (InChIKey) and InChI with appended info for triplets, etc.
String name = InChInames[0];
String InChIaug = InChInames[1];
System.out.println("HBI-based thermo for " + name + "("+InChIaug+"): "+ result.toString());//print result, at least for debugging purposes
}
else{
result = generateQMThermoData(p_chemGraph);
}
return result;
//#]
}
public ThermoData generateQMThermoData(ChemGraph p_chemGraph){
//if there is no data in the libraries, calculate the result based on QM or MM calculations; the below steps will be generalized later to allow for other quantum mechanics packages, etc.
String qmProgram = qmprogram;
String qmMethod = "";
if(qmProgram.equals("mm4")){
qmMethod = "mm4";
}
else{
qmMethod="pm3"; //may eventually want to pass this to various functions to choose which "sub-function" to call
}
ThermoData result = new ThermoData();
String [] InChInames = getQMFileName(p_chemGraph);//determine the filename (InChIKey) and InChI with appended info for triplets, etc.
String name = InChInames[0];
String InChIaug = InChInames[1];
String directory = qmfolder;
File dir=new File(directory);
directory = dir.getAbsolutePath();//this and previous three lines get the absolute path for the directory
if(qmMethod.equals("pm3")){
//first, check to see if the result already exists and the job terminated successfully
boolean gaussianResultExists = successfulGaussianResultExistsQ(name,directory,InChIaug);
boolean mopacResultExists = successfulMopacResultExistsQ(name,directory,InChIaug);
if(!gaussianResultExists && !mopacResultExists){//if a successful result doesn't exist from previous run (or from this run), run the calculation; if a successful result exists, we will skip directly to parsing the file
//steps 1 and 2: create 2D and 3D mole files
molFile p_3dfile = create3Dmolfile(name, p_chemGraph);
//3. create the Gaussian or MOPAC input file
directory = qmfolder;
dir=new File(directory);
directory = dir.getAbsolutePath();//this and previous three lines get the absolute path for the directory
int attemptNumber=1;//counter for attempts using different keywords
int successFlag=0;//flag for success of Gaussian run; 0 means it failed, 1 means it succeeded
int maxAttemptNumber=1;
int multiplicity = p_chemGraph.getRadicalNumber()+1; //multiplicity = radical number + 1
while(successFlag==0 && attemptNumber <= maxAttemptNumber){
//IF block to check which program to use
if (qmProgram.equals("gaussian03")){
if(p_chemGraph.getAtomNumber() > 1){
maxAttemptNumber = createGaussianPM3Input(name, directory, p_3dfile, attemptNumber, InChIaug, multiplicity);
}
else{
maxAttemptNumber = createGaussianPM3Input(name, directory, p_3dfile, -1, InChIaug, multiplicity);//use -1 for attemptNumber for monoatomic case
}
//4. run Gaussian
successFlag = runGaussian(name, directory);
}
else if (qmProgram.equals("mopac") || qmProgram.equals("both")){
maxAttemptNumber = createMopacPM3Input(name, directory, p_3dfile, attemptNumber, InChIaug, multiplicity);
successFlag = runMOPAC(name, directory);
}
else{
System.out.println("Unsupported quantum chemistry program");
System.exit(0);
}
//new IF block to check success
if(successFlag==1){
System.out.println("Attempt #"+attemptNumber + " on species " + name + " ("+InChIaug+") succeeded.");
}
else if(successFlag==0){
if(attemptNumber==maxAttemptNumber){//if this is the last possible attempt, and the calculation fails, exit with an error message
if(qmProgram.equals("both")){ //if we are running with "both" option and all keywords fail, try with Gaussian
qmProgram = "gaussian03";
System.out.println("*****Final MOPAC attempt (#" + maxAttemptNumber + ") on species " + name + " ("+InChIaug+") failed. Trying to use Gaussian.");
attemptNumber=0;//this needs to be 0 so that when we increment attemptNumber below, it becomes 1 when returning to the beginning of the for loop
maxAttemptNumber=1;
}
else{
System.out.println("*****Final attempt (#" + maxAttemptNumber + ") on species " + name + " ("+InChIaug+") failed.");
System.out.print(p_chemGraph.toString());
System.exit(0);
// return new ThermoData(1000,0,0,0,0,0,0,0,0,0,0,0,"failed calculation");
}
}
System.out.println("*****Attempt #"+attemptNumber + " on species " + name + " ("+InChIaug+") failed. Will attempt a new keyword.");
attemptNumber++;//try again with new keyword
}
}
}
//5. parse QM output and record as thermo data (function includes symmetry/point group calcs, etc.); if both Gaussian and MOPAC results exist, Gaussian result is used
if (gaussianResultExists || (qmProgram.equals("gaussian03") && !mopacResultExists)){
result = parseGaussianPM3(name, directory, p_chemGraph);
}
else if (mopacResultExists || qmProgram.equals("mopac") || qmProgram.equals("both")){
result = parseMopacPM3(name, directory, p_chemGraph);
}
else{
System.out.println("Unexpected situation in QMTP thermo estimation");
System.exit(0);
}
}
else{//mm4 case
//first, check to see if the result already exists and the job terminated successfully
boolean mm4ResultExists = successfulMM4ResultExistsQ(name,directory,InChIaug);
if(!mm4ResultExists){//if a successful result doesn't exist from previous run (or from this run), run the calculation; if a successful result exists, we will skip directly to parsing the file
//steps 1 and 2: create 2D and 3D mole files
molFile p_3dfile = create3Dmolfile(name, p_chemGraph);
//3. create the MM4 input file
directory = qmfolder;
dir=new File(directory);
directory = dir.getAbsolutePath();//this and previous three lines get the absolute path for the directory
int attemptNumber=1;//counter for attempts using different keywords
int successFlag=0;//flag for success of MM4 run; 0 means it failed, 1 means it succeeded
int maxAttemptNumber=1;
int multiplicity = p_chemGraph.getRadicalNumber()+1; //multiplicity = radical number + 1
while(successFlag==0 && attemptNumber <= maxAttemptNumber){
maxAttemptNumber = createMM4Input(name, directory, p_3dfile, attemptNumber, InChIaug, multiplicity);
//4. run MM4
successFlag = runMM4(name, directory);
//new IF block to check success
if(successFlag==1){
System.out.println("Attempt #"+attemptNumber + " on species " + name + " ("+InChIaug+") succeeded.");
}
else if(successFlag==0){
if(attemptNumber==maxAttemptNumber){//if this is the last possible attempt, and the calculation fails, exit with an error message
System.out.println("*****Final attempt (#" + maxAttemptNumber + ") on species " + name + " ("+InChIaug+") failed.");
System.out.print(p_chemGraph.toString());
System.exit(0);
//return new ThermoData(1000,0,0,0,0,0,0,0,0,0,0,0,"failed calculation");
}
System.out.println("*****Attempt #"+attemptNumber + " on species " + name + " ("+InChIaug+") failed. Will attempt a new keyword.");
attemptNumber++;//try again with new keyword
}
}
}
//5. parse MM4 output and record as thermo data (function includes symmetry/point group calcs, etc.); if both Gaussian and MOPAC results exist, Gaussian result is used
if(!useCanTherm) result = parseMM4(name, directory, p_chemGraph);
else result = parseMM4withForceMat(name, directory, p_chemGraph);
}
return result;
}
protected static QMTP getINSTANCE() {
return INSTANCE;
}
public void initializePrimaryThermoLibrary(){//svp
primaryLibrary = PrimaryThermoLibrary.getINSTANCE();
}
//creates a 3D molFile; for monoatomic species, it just returns the 2D molFile
public molFile create3Dmolfile(String name, ChemGraph p_chemGraph){
//1. create a 2D file
//use the absolute path for directory, so we can easily reference from other directories in command-line paths
//can't use RMG.workingDirectory, since this basically holds the RMG environment variable, not the workingDirectory
String directory = "2Dmolfiles/";
File dir=new File(directory);
directory = dir.getAbsolutePath();
molFile p_2dfile = new molFile(name, directory, p_chemGraph);
molFile p_3dfile = new molFile();//it seems this must be initialized, so we initialize to empty object
//2. convert from 2D to 3D using RDKit if the 2D molfile is for a molecule with 2 or more atoms
int atoms = p_chemGraph.getAtomNumber();
if(atoms > 1){
int distGeomAttempts=1;
if(atoms > 3){//this check prevents the number of attempts from being negative
distGeomAttempts = 5*(p_chemGraph.getAtomNumber()-3); //number of conformer attempts is just a linear scaling with molecule size, due to time considerations; in practice, it is probably more like 3^(n-3) or something like that
}
p_3dfile = embed3D(p_2dfile, distGeomAttempts);
return p_3dfile;
}
else{
return p_2dfile;
}
}
//embed a molecule in 3D, using RDKit
public molFile embed3D(molFile twoDmolFile, int numConfAttempts){
//convert to 3D MOL file using RDKit script
int flag=0;
String directory = "3Dmolfiles/";
File dir=new File(directory);
directory = dir.getAbsolutePath();//this uses the absolute path for the directory
String name = twoDmolFile.getName();
try{
File runningdir=new File(directory);
String command="";
if (System.getProperty("os.name").toLowerCase().contains("windows")){//special windows case where paths can have spaces and are allowed to be surrounded by quotes
command = "python \""+System.getProperty("RMG.workingDirectory")+"/scripts/distGeomScriptMolLowestEnergyConf.py\" ";
String twoDmolpath=twoDmolFile.getPath();
command=command.concat("\""+twoDmolpath+"\" ");
command=command.concat("\""+name+".mol\" ");//this is the target file name; use the same name as the twoDmolFile (but it will be in he 3Dmolfiles folder
command=command.concat("\""+name+".cmol\" ");//this is the target file name for crude coordinates (corresponding to the minimum energy conformation based on UFF refinement); use the same name as the twoDmolFile (but it will be in he 3Dmolfiles folder) and have suffix .cmol
command=command.concat(numConfAttempts + " ");
command=command.concat("\"" + System.getenv("RDBASE")+"\"");//pass the $RDBASE environment variable to the script so it can use the approprate directory when importing rdkit
}
else{//non-Windows case
command = "python "+System.getProperty("RMG.workingDirectory")+"/scripts/distGeomScriptMolLowestEnergyConf.py ";
String twoDmolpath=twoDmolFile.getPath();
command=command.concat(""+twoDmolpath+" ");
command=command.concat(name+".mol ");//this is the target file name; use the same name as the twoDmolFile (but it will be in he 3Dmolfiles folder
command=command.concat(name+".cmol ");//this is the target file name for crude coordinates (corresponding to the minimum energy conformation based on UFF refinement); use the same name as the twoDmolFile (but it will be in he 3Dmolfiles folder) and have suffix .cmol
command=command.concat(numConfAttempts + " ");
command=command.concat(System.getenv("RDBASE"));//pass the $RDBASE environment variable to the script so it can use the approprate directory when importing rdkit
}
Process pythonProc = Runtime.getRuntime().exec(command, null, runningdir);
String killmsg= "Python process for "+twoDmolFile.getName()+" did not complete within 120 seconds, and the process was killed. File was probably not written.";//message to print if the process times out
Thread timeoutThread = new TimeoutKill(pythonProc, killmsg, 120000L); //create a timeout thread to handle cases where the UFF optimization get's locked up (cf. Ch. 16 of "Ivor Horton's Beginning Java 2: JDK 5 Edition"); once we use the updated version of RDKit, we should be able to get rid of this
timeoutThread.start();//start the thread
//check for errors and display the error if there is one
InputStream is = pythonProc.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
line = line.trim();
System.err.println(line);
flag=1;
}
//if there was an error, indicate the file and InChI
if(flag==1){
System.out.println("RDKit received error (see above) on " + twoDmolFile.getName()+". File was probably not written.");
}
int exitValue = pythonProc.waitFor();
if(timeoutThread.isAlive())//if the timeout thread is still alive (indicating that the process has completed in a timely manner), stop the timeout thread
timeoutThread.interrupt();
}
catch (Exception e) {
String err = "Error in running RDKit Python process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
// gmagoon 6/3/09 comment out InChI checking for now; in any case, the code will need to be updated, as it is copied from my testing code
// //check whether the original InChI is reproduced
// if(flag==0){
// try{
// File f=new File("c:/Python25/"+molfilename);
// File newFile= new File("c:/Python25/mol3d.mol");
// if(newFile.exists()){
// newFile.delete();//apparently renaming will not work unless target file does not exist (at least on Vista)
// }
// f.renameTo(newFile);
// String command = "c:/Users/User1/Documents/InChI-1/cInChI-1.exe c:/Python25/mol3d.mol inchi3d.inchi /AuxNone /DoNotAddH";//DoNotAddH used to prevent adding Hs to radicals (this would be a problem for current RDKit output which doesn't use M RAD notation)
// Process inchiProc = Runtime.getRuntime().exec(command);
// // int exitValue = inchiProc.waitFor();
// Thread.sleep(200);//****update: can probably eliminate this using buffered reader
// inchiProc.destroy();
//
// //read output file
// File outputFile = new File("inchi3d.inchi");
// FileReader fr = new FileReader(outputFile);
// BufferedReader br = new BufferedReader(fr);
// String line=null;
// String inchi3d=null;
// while ( (line = br.readLine()) != null) {
// line = line.trim();
// if(line.startsWith("InChI="))
// {
// inchi3d=line;
// }
// }
// fr.close();
//
// //return file to original name:
// File f2=new File("c:/Python25/mol3d.mol");
// File newFile2= new File("c:/Python25/"+molfilename);
// if(newFile2.exists()){
// newFile2.delete();
// }
// f2.renameTo(newFile2);
//
// //compare inchi3d with input inchi and print a message if they don't match
// if(!inchi3d.equals(inchiString)){
// if(inchi3d.startsWith(inchiString)&&inchiString.length()>10){//second condition ensures 1/C does not match 1/CH4; 6 characters for InChI=, 2 characters for 1/, 2 characters for atom layer
// System.out.println("(probably minor) For File: "+ molfilename+" , 3D InChI (" + inchi3d+") begins with, but does not match original InChI ("+inchiString+"). SMILES string: "+ smilesString);
//
// }
// else{
// System.out.println("For File: "+ molfilename+" , 3D InChI (" + inchi3d+") does not match original InChI ("+inchiString+"). SMILES string: "+ smilesString);
// }
// }
// }
// catch (Exception e) {
// String err = "Error in running InChI process \n";
// err += e.toString();
// e.printStackTrace();
// System.exit(0);
// }
// }
//construct molFile pointer to new file (name will be same as 2D mol file
return new molFile(name, directory);
}
//creates Gaussian PM3 input file in directory with filename name.gjf by using OpenBabel to convert p_molfile
//attemptNumber determines which keywords to try
//the function returns the maximum number of keywords that can be attempted; this will be the same throughout the evaluation of the code, so it may be more appropriate to have this as a "constant" attribute of some sort
//attemptNumber=-1 will call a special set of keywords for the monoatomic case
public int createGaussianPM3Input(String name, String directory, molFile p_molfile, int attemptNumber, String InChIaug, int multiplicity){
//write a file with the input keywords
int maxAttemptNumber=18;//update this if additional keyword options are added or removed
try{
File inpKey=new File(directory+"/inputkeywords.txt");
String inpKeyStr="%chk="+directory+"/RMGrunCHKfile.chk\n";
inpKeyStr+="%mem=6MW\n";
inpKeyStr+="%nproc=1\n";
if(attemptNumber==-1) inpKeyStr+="# pm3 freq";//keywords for monoatomic case (still need to use freq keyword to get molecular mass)
else if(attemptNumber==1) inpKeyStr+="# pm3 opt=(verytight,gdiis) freq IOP(2/16=3)";//added IOP option to avoid aborting when symmetry changes; 3 is supposed to be default according to documentation, but it seems that 0 (the default) is the only option that doesn't work from 0-4; also, it is interesting to note that all 4 options seem to work for test case with z-matrix input rather than xyz coords; cf. http://www.ccl.net/cgi-bin/ccl/message-new?2006+10+17+005 for original idea for solution
else if(attemptNumber==2) inpKeyStr+="# pm3 opt=(verytight,gdiis) freq IOP(2/16=3) IOP(4/21=2)";//use different SCF method; this addresses at least one case of failure for a C4H7J species
else if(attemptNumber==3) inpKeyStr+="# pm3 opt=(verytight,calcfc,maxcyc=200) freq IOP(2/16=3) nosymm";//try multiple different options (no gdiis, use calcfc, nosymm); 7/21/09: added maxcyc option to fix case of MPTBUKVAJYJXDE-UHFFFAOYAPmult3 (InChI=1/C4H10O5Si/c1-3-7-9-10(5,6)8-4-2/h4-5H,3H2,1-2H3/mult3) (file manually copied to speed things along)
else if(attemptNumber==4) inpKeyStr+="# pm3 opt=(verytight,calcfc,maxcyc=200) freq=numerical IOP(2/16=3) nosymm";//7/8/09: numerical frequency keyword version of keyword #3; used to address GYFVJYRUZAKGFA-UHFFFAOYALmult3 (InChI=1/C6H14O6Si/c1-3-10-13(8,11-4-2)12-6-5-9-7/h6-7H,3-5H2,1-2H3/mult3) case; (none of the existing Gaussian or MOPAC combinations worked with it)
else if(attemptNumber==5) inpKeyStr+="# pm3 opt=(verytight,gdiis,small) freq IOP(2/16=3)";//7/10/09: somehow, this worked for problematic case of ZGAWAHRALACNPM-UHFFFAOYAF (InChI=1/C8H17O5Si/c1-3-11-14(10,12-4-2)13-8-5-7(9)6-8/h7-9H,3-6H2,1-2H3); (was otherwise giving l402 errors); even though I had a keyword that worked for this case, I manually copied the fixed log file to QMfiles folder to speed things along; note that there are a couple of very low frequencies (~5-6 cm^-1 for this case)
else if(attemptNumber==6) inpKeyStr+="# pm3 opt=(verytight,nolinear,calcfc,small) freq IOP(2/16=3)";//used for troublesome C5H7J2 case (similar error to C5H7J below); calcfc is not necessary for this particular species, but it speeds convergence and probably makes it more robust for other species
else if(attemptNumber==7) inpKeyStr+="# pm3 opt=(verytight,gdiis,maxcyc=200) freq=numerical IOP(2/16=3)"; //use numerical frequencies; this takes a relatively long time, so should only be used as one of the last resorts; this seemed to address at least one case of failure for a C6H10JJ species; 7/15/09: maxcyc=200 added to address GVCMURUDAUQXEY-UHFFFAOYAVmult3 (InChI=1/C3H4O7Si/c1-2(9-6)10-11(7,8)3(4)5/h6-7H,1H2/mult3)...however, result was manually pasted in QMfiles folder to speed things along
else if(attemptNumber==8) inpKeyStr+="# pm3 opt=tight freq IOP(2/16=3)";//7/10/09: this worked for problematic case of SZSSHFMXPBKYPR-UHFFFAOYAF (InChI=1/C7H15O5Si/c1-3-10-13(8,11-4-2)12-7-5-6-9-7/h7H,3-6H2,1-2H3) (otherwise, it had l402.exe errors); corrected log file was manually copied to QMfiles to speed things along; we could also add a freq=numerical version of this keyword combination for added robustness; UPDATE: see below
else if(attemptNumber==9) inpKeyStr+="# pm3 opt=tight freq=numerical IOP(2/16=3)";//7/10/09: used for problematic case of CIKDVMUGTARZCK-UHFFFAOYAImult4 (InChI=1/C8H15O6Si/c1-4-12-15(10,13-5-2)14-7-6-11-8(7,3)9/h7H,3-6H2,1-2H3/mult4 (most other cases had l402.exe errors); corrected log file was manually copied to QMfiles to speed things along
else if(attemptNumber==10) inpKeyStr+="# pm3 opt=(tight,nolinear,calcfc,small,maxcyc=200) freq IOP(2/16=3)";//7/8/09: similar to existing #5, but uses tight rather than verytight; used for ADMPQLGIEMRGAT-UHFFFAOYAUmult3 (InChI=1/C6H14O5Si/c1-4-9-12(8,10-5-2)11-6(3)7/h6-7H,3-5H2,1-2H3/mult3)
else if(attemptNumber==11) inpKeyStr+="# pm3 opt freq IOP(2/16=3)"; //use default (not verytight) convergence criteria; use this as last resort
else if(attemptNumber==12) inpKeyStr+="# pm3 opt=(verytight,gdiis) freq=numerical IOP(2/16=3) IOP(4/21=200)";//to address problematic C10H14JJ case
else if(attemptNumber==13) inpKeyStr+="# pm3 opt=(calcfc,verytight,newton,notrustupdate,small,maxcyc=100,maxstep=100) freq=(numerical,step=10) IOP(2/16=3) nosymm";// added 6/10/09 for very troublesome RRMZRNPRCUANER-UHFFFAOYAQ (InChI=1/C5H7/c1-3-5-4-2/h3H,1-2H3) case...there were troubles with negative frequencies, where I don't think they should have been; step size of numerical frequency was adjusted to give positive result; accuracy of result is questionable; it is possible that not all of these keywords are needed; note that for this and other nearly free rotor cases, I think heat capacity will be overestimated by R/2 (R vs. R/2) (but this is a separate issue)
else if(attemptNumber==14) inpKeyStr+="# pm3 opt=(tight,gdiis,small,maxcyc=200,maxstep=100) freq=numerical IOP(2/16=3) nosymm";// added 6/22/09 for troublesome QDERTVAGQZYPHT-UHFFFAOYAHmult3(InChI=1/C6H14O4Si/c1-4-8-11(7,9-5-2)10-6-3/h4H,5-6H2,1-3H3/mult3); key aspects appear to be tight (rather than verytight) convergence criteria, no calculation of frequencies during optimization, use of numerical frequencies, and probably also the use of opt=small
//gmagoon 7/9/09: commented out since although this produces a "reasonable" result for the problematic case, there is a large amount of spin contamination, apparently introducing 70+ kcal/mol of instability else if(attemptNumber==12) inpKeyStr+="# pm3 opt=(verytight,gdiis,small) freq=numerical IOP(2/16=3) IOP(4/21=200)";//7/9/09: similar to current number 9 with keyword small; this addresses case of VCSJVABXVCFDRA-UHFFFAOYAI (InChI=1/C8H19O5Si/c1-5-10-8(4)13-14(9,11-6-2)12-7-3/h8H,5-7H2,1-4H3)
else if(attemptNumber==15) inpKeyStr+="# pm3 opt=(verytight,gdiis,calcall) IOP(2/16=3)";//used for troublesome C5H7J case; note that before fixing, I got errors like the following: "Incomplete coordinate system. Try restarting with Geom=Check Guess=Read Opt=(ReadFC,NewRedundant) Incomplete coordinate system. Error termination via Lnk1e in l103.exe"; we could try to restart, but it is probably preferrable to have each keyword combination standalone; another keyword that may be helpful if additional problematic cases are encountered is opt=small; 6/9/09 note: originally, this had # pm3 opt=(verytight,gdiis,calcall) freq IOP(2/16=3)" (with freq keyword), but I discovered that in this case, there are two thermochemistry sections and cclib parses frequencies twice, giving twice the number of desired frequencies and hence produces incorrect thermo; this turned up on C5H6JJ isomer
//gmagoon 7/3/09: it is probably best to retire this keyword combination in light of the similar combination below //else if(attemptNumber==6) inpKeyStr+="# pm3 opt=(verytight,gdiis,calcall,small) IOP(2/16=3) IOP(4/21=2)";//6/10/09: worked for OJZYSFFHCAPVGA-UHFFFAOYAK (InChI=1/C5H7/c1-3-5-4-2/h1,4H2,2H3) case; IOP(4/21) keyword was key
else if(attemptNumber==16) inpKeyStr+="# pm3 opt=(verytight,gdiis,calcall,small,maxcyc=200) IOP(2/16=3) IOP(4/21=2) nosymm";//6/29/09: worked for troublesome ketene case: CCGKOQOJPYTBIH-UHFFFAOYAO (InChI=1/C2H2O/c1-2-3/h1H2) (could just increase number of iterations for similar keyword combination above (#6 at the time of this writing), allowing symmetry, but nosymm seemed to reduce # of iterations; I think one of nosymm or higher number of iterations would allow the similar keyword combination to converge; both are included here for robustness)
else if(attemptNumber==17) inpKeyStr+="# pm3 opt=(verytight,gdiis,calcall,small) IOP(2/16=3) nosymm";//7/1/09: added for case of ZWMVZWMBTVHPBS-UHFFFAOYAEmult3 (InChI=1/C4H4O2/c1-3-5-6-4-2/h1-2H2/mult3)
else if(attemptNumber==18) inpKeyStr+="# pm3 opt=(calcall,small,maxcyc=100) IOP(2/16=3)"; //6/10/09: used to address troublesome FILUFGAZMJGNEN-UHFFFAOYAImult3 case (InChI=1/C5H6/c1-3-5-4-2/h3H,1H2,2H3/mult3)
else throw new Exception();//this point should not be reached
// if(multiplicity == 3) inpKeyStr+= " guess=mix"; //assumed to be triplet biradical...use guess=mix to perform unrestricted ; nevermind...I think this would only be for singlet biradicals based on http://www.gaussian.com/g_tech/g_ur/k_guess.htm
if (usePolar) inpKeyStr += " polar";
FileWriter fw = new FileWriter(inpKey);
fw.write(inpKeyStr);
fw.close();
}
catch(Exception e){
String err = "Error in writing inputkeywords.txt \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//call the OpenBabel process (note that this requires OpenBabel environment variable)
try{
File runningdir=new File(directory);
String command=null;
if (System.getProperty("os.name").toLowerCase().contains("windows")){//special windows case
command = "babel -imol \""+ p_molfile.getPath()+ "\" -ogjf \"" + name+".gjf\" -xf inputkeywords.txt --title \""+InChIaug+"\"";
}
else{
command = "babel -imol "+ p_molfile.getPath()+ " -ogjf " + name+".gjf -xf inputkeywords.txt --title "+InChIaug;
}
Process babelProc = Runtime.getRuntime().exec(command, null, runningdir);
//read in output
InputStream is = babelProc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
//do nothing
}
int exitValue = babelProc.waitFor();
}
catch(Exception e){
String err = "Error in running OpenBabel MOL to GJF process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
return maxAttemptNumber;
}
//creates MM4 input file and MM4 batch file in directory with filenames name.mm4 and name.com, respectively using MoleCoor
//attemptNumber determines which keywords to try
//the function returns the maximum number of keywords that can be attempted; this will be the same throughout the evaluation of the code, so it may be more appropriate to have this as a "constant" attribute of some sort
public int createMM4Input(String name, String directory, molFile p_molfile, int attemptNumber, String InChIaug, int multiplicity){
//Step 1: write the script for MM4 batch operation
// Example script file:
// #! /bin/csh
// cp testEthylene.mm4 CPD.MM4
// cp $MM4_DATDIR/BLANK.DAT PARA.MM4
// cp $MM4_DATDIR/CONST.MM4 .
// $MM4_EXEDIR/mm4 <<%
// 1
// 2
// 0
// %
// mv TAPE4.MM4 testEthyleneBatch.out
// mv TAPE9.MM4 testEthyleneBatch.opt
// exit
int scriptAttempts = 2;//the number of script permutations available; update as additional options are added
int maxAttemptNumber=2*scriptAttempts;//we will try a second time with crude coordinates if the UFF refined coordinates do not work
try{
//create batch file with executable permissions: cf. http://java.sun.com/docs/books/tutorial/essential/io/fileAttr.html#posix
File inpKey = new File(directory+"/"+name+".com");
String inpKeyStr="#! /bin/csh\n";
inpKeyStr+="cp "+name+".mm4 CPD.MM4\n";
inpKeyStr+="cp $MM4_DATDIR/BLANK.DAT PARA.MM4\n";
inpKeyStr+="cp $MM4_DATDIR/CONST.MM4 .\n";
inpKeyStr+="$MM4_EXEDIR/mm4 <<%\n";
inpKeyStr+="1\n";//read from first line of .mm4 file
if (!useCanTherm){
if(attemptNumber%scriptAttempts==1) inpKeyStr+="2\n"; //Block-Diagonal Method then Full-Matrix Method
else if(attemptNumber%scriptAttempts==0) inpKeyStr+="3\n"; //Full-Matrix Method only
else throw new Exception();//this point should not be reached
}
else{//CanTherm case: write the FORCE.MAT file
if(attemptNumber%scriptAttempts==1) inpKeyStr+="4\n"; //Block-Diagonal Method then Full-Matrix Method
else if(attemptNumber%scriptAttempts==0) inpKeyStr+="5\n"; //Full-Matrix Method only
else throw new Exception();//this point should not be reached
inpKeyStr+="\n";//<RETURN> for temperature
inpKeyStr+="4\n";//unofficial option 4 for vibrational eigenvector printout to generate Cartesian force constant matrix in FORCE.MAT file
inpKeyStr+="0\n";//no vibrational amplitude printout
}
inpKeyStr+="0\n";//terminate the job
inpKeyStr+="%\n";
inpKeyStr+="mv TAPE4.MM4 "+name+".mm4out\n";
inpKeyStr+="mv TAPE9.MM4 "+name+".mm4opt\n";
if(useCanTherm){
inpKeyStr+="mv FORCE.MAT "+name+".fmat\n";
}
inpKeyStr+="exit\n";
FileWriter fw = new FileWriter(inpKey);
fw.write(inpKeyStr);
fw.close();
}
catch(Exception e){
String err = "Error in writing MM4 script file\n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//Step 2: call the MoleCoor process to create the MM4 input file from the mole file
try{
File runningdir=new File(directory);
//this will only be run on Linux so we don't have to worry about Linux vs. Windows issues
String command = "python "+System.getenv("RMG")+"/scripts/MM4InputFileMaker.py ";
//first argument: input file path; for the first attempts, we will use UFF refined coordinates; if that doesn't work, (e.g. case of cyclopropene, InChI=1/C3H4/c1-2-3-1/h1-2H,3H2 OOXWYYGXTJLWHA-UHFFFAOYAJ) we will try crude coordinates (.cmol suffix)
if(attemptNumber<=scriptAttempts){
command=command.concat(p_molfile.getPath() + " ");
}
else{
command=command.concat(p_molfile.getCrudePath() + " ");
}
//second argument: output path
String inpfilepath=directory+"/"+name+".mm4";
command=command.concat(inpfilepath+ " ");
//third argument: molecule name (the augmented InChI)
command=command.concat(InChIaug+ " ");
//fourth argument: PYTHONPATH
command=command.concat(System.getenv("RMG")+"/source/MoleCoor");//this will pass $RMG/source/MoleCoor to the script (in order to get the appropriate path for importing
Process molecoorProc = Runtime.getRuntime().exec(command, null, runningdir);
//read in output
InputStream is = molecoorProc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
//do nothing
}
int exitValue = molecoorProc.waitFor();
}
catch(Exception e){
String err = "Error in running MoleCoor MOL to .MM4 process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
return maxAttemptNumber;
}
//returns the extra Mopac keywords to use for radical species, given the spin multiplicity (radical number + 1)
public String getMopacRadicalString(int multiplicity){
if(multiplicity==1) return "";
else if (multiplicity==2) return "uhf doublet";
else if (multiplicity==3) return "uhf triplet";
else if (multiplicity==4) return "uhf quartet";
else if (multiplicity==5) return "uhf quintet";
else if (multiplicity==6) return "uhf sextet";
else if (multiplicity==7) return "uhf septet";
else if (multiplicity==8) return "uhf octet";
else if (multiplicity==9) return "uhf nonet";
else{
System.out.println("Invalid multiplicity encountered: "+multiplicity);
System.exit(0);
}
return "this should not be returned: error associated with getMopacRadicalString()";
}
//creates MOPAC PM3 input file in directory with filename name.mop by using OpenBabel to convert p_molfile
//attemptNumber determines which keywords to try
//the function returns the maximum number of keywords that can be attempted; this will be the same throughout the evaluation of the code, so it may be more appropriate to have this as a "constant" attribute of some sort
//unlike createGaussianPM3 input, this requires an additional input specifying the spin multiplicity (radical number + 1) for the species
public int createMopacPM3Input(String name, String directory, molFile p_molfile, int attemptNumber, String InChIaug, int multiplicity){
//write a file with the input keywords
int maxAttemptNumber=5;//update this if additional keyword options are added or removed
String inpKeyStrBoth = "";//this string will be written at both the top (for optimization) and the bottom (for thermo/force calc)
String inpKeyStrTop = "";//this string will be written only at the top
String inpKeyStrBottom = "";//this string will be written at the bottom
String radicalString = getMopacRadicalString(multiplicity);
try{
// File inpKey=new File(directory+"/inputkeywords.txt");
// String inpKeyStr="%chk="+directory+"\\RMGrunCHKfile.chk\n";
// inpKeyStr+="%mem=6MW\n";
// inpKeyStr+="%nproc=1\n";
if(attemptNumber==1){
inpKeyStrBoth="pm3 "+radicalString;
inpKeyStrTop=" precise nosym";
inpKeyStrBottom="oldgeo thermo nosym precise ";//7/10/09: based on a quick review of recent results, keyword combo #1 rarely works, and when it did (CJAINEUZFLXGFA-UHFFFAOYAUmult3 (InChI=1/C8H16O5Si/c1-4-11-14(9,12-5-2)13-8-6-10-7(8)3/h7-8H,3-6H2,1-2H3/mult3)), the grad. norm on the force step was about 1.7 (too large); I manually removed this result and re-ran...the entropy was increased by nearly 20 cal/mol-K...perhaps we should add a check for the "WARNING" that MOPAC prints out when the gradient is high; 7/22/09: for the case of FUGDBSHZYPTWLG-UHFFFAOYADmult3 (InChI=1/C5H8/c1-4-3-5(4)2/h4-5H,1-3H2/mult3), adding nosym seemed to resolve 1. large discrepancies from Gaussian and 2. negative frequencies in mass-weighted coordinates and possibly related issue in discrepancies between regular and mass-weighted coordinate frequencies
}
else if(attemptNumber==2){//7/9/09: used for VCSJVABXVCFDRA-UHFFFAOYAI (InChI=1/C8H19O5Si/c1-5-10-8(4)13-14(9,11-6-2)12-7-3/h8H,5-7H2,1-4H3); all existing Gaussian keywords also failed; the Gaussian result was also rectified, but the resulting molecule was over 70 kcal/mol less stable, probably due to a large amount of spin contamination (~1.75 in fixed Gaussian result vs. 0.754 for MOPAC)
inpKeyStrBoth="pm3 "+radicalString;
inpKeyStrTop=" precise nosym gnorm=0.0 nonr";
inpKeyStrBottom="oldgeo thermo nosym precise ";
}
else if(attemptNumber==3){//7/8/09: used for ADMPQLGIEMRGAT-UHFFFAOYAUmult3 (InChI=1/C6H14O5Si/c1-4-9-12(8,10-5-2)11-6(3)7/h6-7H,3-5H2,1-2H3/mult3); all existing Gaussian keywords also failed; however, the Gaussian result was also rectified, and the resulting conformation was about 1.0 kcal/mol more stable than the one resulting from this, so fixed Gaussian result was manually copied to QMFiles folder
inpKeyStrBoth="pm3 "+radicalString;
inpKeyStrTop=" precise nosym gnorm=0.0";
inpKeyStrBottom="oldgeo thermo nosym precise "; //precise appeared to be necessary for the problematic case (to avoid negative frequencies);
}
else if(attemptNumber==4){//7/8/09: used for GYFVJYRUZAKGFA-UHFFFAOYALmult3 (InChI=1/C6H14O6Si/c1-3-10-13(8,11-4-2)12-6-5-9-7/h6-7H,3-5H2,1-2H3/mult3) case (negative frequency issues in MOPAC) (also, none of the existing Gaussian combinations worked with it); note that the Gaussian result appears to be a different conformation as it is about 0.85 kcal/mol more stable, so the Gaussian result was manually copied to QMFiles directory; note that the MOPAC output included a very low frequency (4-5 cm^-1)
inpKeyStrBoth="pm3 "+radicalString;
inpKeyStrTop=" precise nosym gnorm=0.0 bfgs";
inpKeyStrBottom="oldgeo thermo nosym precise "; //precise appeared to be necessary for the problematic case (to avoid negative frequencies)
}
// else if(attemptNumber==5){
// inpKeyStrBoth="pm3 "+radicalString;
// inpKeyStrTop=" precise nosym gnorm=0.0 ddmin=0.0";
// inpKeyStrBottom="oldgeo thermo nosym precise ";
// }
// else if(attemptNumber==6){
// inpKeyStrBoth="pm3 "+radicalString;
// inpKeyStrTop=" precise nosym gnorm=0.0 nonr ddmin=0.0";
// inpKeyStrBottom="oldgeo thermo nosym precise ";
// }
// else if(attemptNumber==7){
// inpKeyStrBoth="pm3 "+radicalString;
// inpKeyStrTop=" precise nosym bfgs gnorm=0.0 ddmin=0.0";
// inpKeyStrBottom="oldgeo thermo nosym precise ";
// }
else if(attemptNumber==5){//used for troublesome HGRZRPHFLAXXBT-UHFFFAOYAVmult3 (InChI=1/C3H2O4/c4-2(5)1-3(6)7/h1H2/mult3) case (negative frequency and large gradient issues)
inpKeyStrBoth="pm3 "+radicalString;
inpKeyStrTop=" precise nosym recalc=10 dmax=0.10 nonr cycles=2000 t=2000";
inpKeyStrBottom="oldgeo thermo nosym precise ";
}
// else if(attemptNumber==9){//used for troublesome CMARQPBQDRXBTN-UHFFFAOYAAmult3 (InChI=1/C3H2O4/c1-3(5)7-6-2-4/h1H2/mult3) case (negative frequency issues)
// inpKeyStrBoth="pm3 "+radicalString;
// inpKeyStrTop=" precise nosym recalc=1 dmax=0.05 gnorm=0.0 cycles=1000 t=1000";
// inpKeyStrBottom="oldgeo thermo nosym precise ";
// }
// else if(attemptNumber==10){//used for ATCYLHQLTOSVFK-UHFFFAOYAMmult4 (InChI=1/C4H5O5/c1-3(5)8-9-4(2)7-6/h6H,1-2H2/mult4) case (timeout issue; also, negative frequency issues); note that this is very similar to the keyword below, so we may want to consolidate
// inpKeyStrBoth="pm3 "+radicalString;
// inpKeyStrTop=" precise nosym recalc=1 dmax=0.05 gnorm=0.2 cycles=1000 t=1000";
// inpKeyStrBottom="oldgeo thermo nosym precise ";
// }
else throw new Exception();//this point should not be reached
// FileWriter fw = new FileWriter(inpKey);
// fw.write(inpKeyStr);
// fw.close();
}
catch(Exception e){
String err = "Error in writing inputkeywords.txt \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
String polarString = "";
if (usePolar){
if(multiplicity == 1) polarString = System.getProperty("line.separator") + System.getProperty("line.separator") + System.getProperty("line.separator")+ "oldgeo polar nosym precise " + inpKeyStrBoth;
else polarString = System.getProperty("line.separator") + System.getProperty("line.separator") + System.getProperty("line.separator")+ "oldgeo static nosym precise " + inpKeyStrBoth;
}
//call the OpenBabel process (note that this requires OpenBabel environment variable)
try{
File runningdir=new File(directory);
String inpKeyStrTopCombined = inpKeyStrBoth + inpKeyStrTop;
String command = "babel -imol "+ p_molfile.getPath()+ " -omop " + name+".mop -xk \"" + inpKeyStrTopCombined + "\" --title \""+InChIaug+"\"";
Process babelProc = Runtime.getRuntime().exec(command, null, runningdir);
//read in output
InputStream is = babelProc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
//do nothing
}
int exitValue = babelProc.waitFor();
//append the final keywords to the end of the file just written
// File mopacInpFile = new File(directory+"/"+name+".mop");
FileWriter fw = new FileWriter(directory+"/"+name+".mop", true);//filewriter with append = true
fw.write(System.getProperty("line.separator") + inpKeyStrBottom + inpKeyStrBoth + polarString);//on Windows Vista, "\n" appears correctly in WordPad view, but not Notepad view (cf. http://forums.sun.com/thread.jspa?threadID=5386822)
fw.close();
}
catch(Exception e){
String err = "Error in running OpenBabel MOL to MOP process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
return maxAttemptNumber;
}
//name and directory are the name and directory for the input (and output) file;
//input is assumed to be preexisting and have the .gjf suffix
//returns an integer indicating success or failure of the Gaussian calculation: 1 for success, 0 for failure;
public int runGaussian(String name, String directory){
int flag = 0;
int successFlag=0;
try{
String command = "g03 ";
command=command.concat(qmfolder+"/"+name+".gjf ");//specify the input file; space is important
command=command.concat(qmfolder+"/"+name+".log");//specify the output file
Process gaussianProc = Runtime.getRuntime().exec(command);
//check for errors and display the error if there is one
InputStream is = gaussianProc.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
line = line.trim();
System.err.println(line);
flag=1;
}
//if there was an error, indicate that an error was obtained
if(flag==1){
System.out.println("Gaussian process received error (see above) on " + name);
}
int exitValue = gaussianProc.waitFor();
}
catch(Exception e){
String err = "Error in running Gaussian process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//look in the output file to check for the successful termination of the Gaussian calculation
//failed jobs will contain the a line beginning with " Error termination" near the end of the file
int failureFlag=0;
String errorLine = "";//string to store the error
try{
FileReader in = new FileReader(directory+"/"+name+".log");
BufferedReader reader = new BufferedReader(in);
String line=reader.readLine();
while(line!=null){
if (line.startsWith(" Error termination ")){
failureFlag=1;
errorLine = line.trim();
System.out.println("*****Error in Gaussian log file: "+errorLine);//print the error (note that in general, I think two lines will be printed)
}
else if (line.startsWith(" ******")){//also look for imaginary frequencies
if (line.contains("imaginary frequencies")){
System.out.println("*****Imaginary freqencies found:");
failureFlag=1;
}
}
line=reader.readLine();
}
}
catch(Exception e){
String err = "Error in reading Gaussian log file \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//if the failure flag is still 0, the process should have been successful
if (failureFlag==0) successFlag=1;
return successFlag;
}
//name and directory are the name and directory for the input (and output) file;
//input script is assumed to be preexisting and have the .com suffix
//returns an integer indicating success or failure of the calculation: 1 for success, 0 for failure
public int runMM4(String name, String directory){
int successFlag=0;
//int flag = 0;
try{
File runningDirectory = new File(qmfolder);
String command=name+".com";
File script = new File(qmfolder+command);
command = "./"+command;
script.setExecutable(true);
Process mm4Proc = Runtime.getRuntime().exec(command, null, runningDirectory);
//check for errors and display the error if there is one
// InputStream is = mm4Proc.getErrorStream();
// InputStreamReader isr = new InputStreamReader(is);
// BufferedReader br = new BufferedReader(isr);
// String line=null;
// while ( (line = br.readLine()) != null) {
// line = line.trim();
// if(!line.equals("STOP statement executed")){//string listed here seems to be typical
// System.err.println(line);
// flag=1;
// }
// }
InputStream is = mm4Proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
//do nothing
}
//if there was an error, indicate that an error was obtained
// if(flag==1){
// System.out.println("MM4 process received error (see above) on " + name);
// }
int exitValue = mm4Proc.waitFor();
}
catch(Exception e){
String err = "Error in running MM4 process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//look in the output file to check for the successful termination of the MM4 calculation (cf. successfulMM4ResultExistsQ)
File file = new File(directory+"/"+name+".mm4out");
int failureFlag=1;//flag (1 or 0) indicating whether the MM4 job failed
int failureOverrideFlag=0;//flag (1 or 0) to override success as measured by failureFlag
if(file.exists()){//if the file exists, do further checks; otherwise, we will skip to final statement and return false
try{
FileReader in = new FileReader(file);
BufferedReader reader = new BufferedReader(in);
String line=reader.readLine();
while(line!=null){
String trimLine= line.trim();
if (trimLine.equals("STATISTICAL THERMODYNAMICS ANALYSIS")){
failureFlag = 0;
}
else if (trimLine.endsWith("imaginary frequencies,")){//read the number of imaginary frequencies and make sure it is zero
String[] split = trimLine.split("\\s+");
if (Integer.parseInt(split[3])>0){
System.out.println("*****Imaginary freqencies found:");
failureOverrideFlag=1;
}
}
else if (trimLine.contains(" 0.0 (fir )")){
if (useCanTherm){//zero frequencies are only acceptable when CanTherm is used
System.out.println("*****Warning: zero freqencies found (values lower than 7.7 cm^-1 are rounded to zero in MM4 output); CanTherm should hopefully correct this:");
}
else{
System.out.println("*****Zero freqencies found:");
failureOverrideFlag=1;
}
}
line=reader.readLine();
}
}
catch(Exception e){
String err = "Error in reading MM4 output file \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
}
//if the failure flag is still 0, the process should have been successful
if(failureOverrideFlag==1) failureFlag=1; //job will be considered a failure if there are imaginary frequencies or if job terminates to to excess time/cycles
//if the failure flag is 0 and there are no negative frequencies, the process should have been successful
if (failureFlag==0) successFlag=1;
return successFlag;
}
//name and directory are the name and directory for the input (and output) file;
//input is assumed to be preexisting and have the .mop suffix
//returns an integer indicating success or failure of the MOPAC calculation: 1 for success, 0 for failure;
//this function is based on the Gaussian analogue
public int runMOPAC(String name, String directory){
int flag = 0;
int successFlag=0;
try{
String command = System.getenv("MOPAC_LICENSE")+"MOPAC2009.exe ";
command=command.concat(directory+"/"+name+".mop ");//specify the input file; space is important
command=command.concat(directory+"/"+name+".out");//specify the output file
Process mopacProc = Runtime.getRuntime().exec(command);
//check for errors and display the error if there is one
InputStream is = mopacProc.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
line = line.trim();
System.err.println(line);
flag=1;
}
//if there was an error, indicate that an error was obtained
if(flag==1){
System.out.println("MOPAC process received error (see above) on " + name);
}
int exitValue = mopacProc.waitFor();
}
catch(Exception e){
String err = "Error in running MOPAC process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//look in the output file to check for the successful termination of the calculation (this is a trimmed down version of what appears in successfulMOPACResultExistsQ (it doesn't have the InChI check)
File file = new File(directory+"/"+name+".out");
int failureFlag=1;//flag (1 or 0) indicating whether the MOPAC job failed
int failureOverrideFlag=0;//flag (1 or 0) to override success as measured by failureFlag
if(file.exists()){//if the file exists, do further checks; otherwise, we will skip to final statement and return false
try{
FileReader in = new FileReader(file);
BufferedReader reader = new BufferedReader(in);
String line=reader.readLine();
while(line!=null){
String trimLine = line.trim();
if (trimLine.equals("DESCRIPTION OF VIBRATIONS")){//check for this line; if it is here, check for negative frequencies
//if(!MopacFileContainsNegativeFreqsQ(name, directory)) failureFlag=0;
failureFlag=0;
}
//negative frequencies notice example:
// NOTE: SYSTEM IS NOT A GROUND STATE, THEREFORE ZERO POINT
// ENERGY IS NOT MEANINGFULL. ZERO POINT ENERGY PRINTED
// DOES NOT INCLUDE THE 2 IMAGINARY FREQUENCIES
else if (trimLine.endsWith("IMAGINARY FREQUENCIES")){
System.out.println("*****Imaginary freqencies found:");
failureOverrideFlag=1;
}
else if (trimLine.equals("EXCESS NUMBER OF OPTIMIZATION CYCLES")){//exceeding max cycles error
failureOverrideFlag=1;
}
else if (trimLine.equals("NOT ENOUGH TIME FOR ANOTHER CYCLE")){//timeout error
failureOverrideFlag=1;
}
line=reader.readLine();
}
}
catch(Exception e){
String err = "Error in reading MOPAC output file \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
}
if(failureOverrideFlag==1) failureFlag=1; //job will be considered a failure if there are imaginary frequencies or if job terminates to to excess time/cycles
//if the failure flag is 0 and there are no negative frequencies, the process should have been successful
if (failureFlag==0) successFlag=1;
return successFlag;
}
//parse the results using cclib and return a ThermoData object; name and directory indicate the location of the Gaussian .log file
//may want to split this into several functions
public ThermoData parseGaussianPM3(String name, String directory, ChemGraph p_chemGraph){
// //parse the Gaussian file using cclib
// int natoms = 0; //number of atoms from Gaussian file; in principle, this should agree with number of chemGraph atoms
// ArrayList atomicNumber = new ArrayList(); //vector of atomic numbers (integers) (apparently Vector is thread-safe; cf. http://answers.yahoo.com/question/index?qid=20081214065127AArZDT3; ...should I be using this instead?)
// ArrayList x_coor = new ArrayList(); //vectors of x-, y-, and z-coordinates (doubles) (Angstroms) (in order corresponding to above atomic numbers)
// ArrayList y_coor = new ArrayList();
// ArrayList z_coor = new ArrayList();
// double energy = 0; //PM3 energy (Hf298) in Hartree
// double molmass = 0; //molecular mass in amu
// ArrayList freqs = new ArrayList(); //list of frequencies in units of cm^-1
// double rotCons_1 = 0;//rotational constants in (1/s)
// double rotCons_2 = 0;
// double rotCons_3 = 0;
// int gdStateDegen = p_chemGraph.getRadicalNumber()+1;//calculate ground state degeneracy from the number of radicals; this should give the same result as spin multiplicity in Gaussian input file (and output file), but we do not explicitly check this (we could use "mult" which cclib reads in if we wanted to do so); also, note that this is not always correct, as there can apparently be additional spatial degeneracy for non-symmetric linear molecules like OH radical (cf. http://cccbdb.nist.gov/thermo.asp)
// try{
// File runningdir=new File(directory);
// String command = "c:/Python25/python.exe c:/Python25/GaussianPM3ParsingScript.py ";//this should eventually be modified for added generality
// String logfilepath=directory+"/"+name+".log";
// command=command.concat(logfilepath);
// Process cclibProc = Runtime.getRuntime().exec(command, null, runningdir);
// //read the stdout of the process, which should contain the desired information in a particular format
// InputStream is = cclibProc.getInputStream();
// InputStreamReader isr = new InputStreamReader(is);
// BufferedReader br = new BufferedReader(isr);
// String line=null;
// //example output:
//// C:\Python25>python.exe GaussianPM3ParsingScript.py TEOS.out
//// 33
//// [ 6 6 8 14 8 6 6 8 6 6 8 6 6 1 1 1 1 1 1 1 1 1 1 1 1
//// 1 1 1 1 1 1 1 1]
//// [[ 2.049061 -0.210375 3.133106]
//// [ 1.654646 0.321749 1.762752]
//// [ 0.359284 -0.110429 1.471465]
//// [-0.201871 -0.013365 -0.12819 ]
//// [ 0.086307 1.504918 -0.82893 ]
//// [-0.559186 2.619928 -0.284003]
//// [-0.180246 3.839463 -1.113029]
//// [ 0.523347 -1.188305 -1.112765]
//// [ 1.857584 -1.018167 -1.495088]
//// [ 2.375559 -2.344392 -2.033403]
//// [-1.870397 -0.297297 -0.075427]
//// [-2.313824 -1.571765 0.300245]
//// [-3.83427 -1.535927 0.372171]
//// [ 1.360346 0.128852 3.917699]
//// [ 2.053945 -1.307678 3.160474]
//// [ 3.055397 0.133647 3.403037]
//// [ 1.677262 1.430072 1.750899]
//// [ 2.372265 -0.029237 0.985204]
//// [-0.245956 2.754188 0.771433]
//// [-1.656897 2.472855 -0.287156]
//// [-0.664186 4.739148 -0.712606]
//// [-0.489413 3.734366 -2.161038]
//// [ 0.903055 4.016867 -1.112198]
//// [ 1.919521 -0.229395 -2.269681]
//// [ 2.474031 -0.680069 -0.629949]
//// [ 2.344478 -3.136247 -1.273862]
//// [ 1.786854 -2.695974 -2.890647]
//// [ 3.41648 -2.242409 -2.365094]
//// [-1.884889 -1.858617 1.28054 ]
//// [-1.976206 -2.322432 -0.440995]
//// [-4.284706 -1.26469 -0.591463]
//// [-4.225999 -2.520759 0.656131]
//// [-4.193468 -0.809557 1.112677]]
//// -14.1664924726
//// [ 9.9615 18.102 27.0569 31.8459 39.0096 55.0091
//// 66.4992 80.4552 86.4912 123.3551 141.6058 155.5448
//// 159.4747 167.0013 178.5676 207.3738 237.3201 255.3487
//// 264.5649 292.867 309.4248 344.6503 434.8231 470.2074
//// 488.9717 749.1722 834.257 834.6594 837.7292 839.6352
//// 887.9767 892.9538 899.5374 992.1851 1020.6164 1020.8671
//// 1028.3897 1046.7945 1049.1768 1059.4704 1065.1505 1107.4001
//// 1108.1567 1109.0466 1112.6677 1122.7785 1124.4315 1128.4163
//// 1153.3438 1167.6705 1170.9627 1174.9613 1232.1826 1331.8459
//// 1335.3932 1335.8677 1343.9556 1371.37 1372.8127 1375.5428
//// 1396.0344 1402.4082 1402.7554 1403.2463 1403.396 1411.6946
//// 1412.2456 1412.3519 1414.5982 1415.3613 1415.5698 1415.7993
//// 1418.5409 2870.7446 2905.3132 2907.0361 2914.1662 2949.2646
//// 2965.825 2967.7667 2971.5223 3086.3849 3086.3878 3086.6448
//// 3086.687 3089.2274 3089.4105 3089.4743 3089.5841 3186.0753
//// 3186.1375 3186.3511 3186.365 ]
//// [ 0.52729 0.49992 0.42466]
////note: above example has since been updated to print molecular mass; also frequency and atomic number format has been updated
// String [] stringArray;
// natoms = Integer.parseInt(br.readLine());//read line 1: number of atoms
// stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read line 2: the atomic numbers (first removing braces)
// // line = br.readLine().replace("[", "").replace("]","");//read line 2: the atomic numbers (first removing braces)
// // StringTokenizer st = new StringTokenizer(line); //apprently the stringTokenizer class is deprecated, but I am having trouble getting the regular expressions to work properly
// for(int i=0; i < natoms; i++){
// // atomicNumber.add(i,Integer.parseInt(stringArray[i]));
// atomicNumber.add(i,Integer.parseInt(stringArray[i]));
// }
// for(int i=0; i < natoms; i++){
// stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read line 3+: coordinates for atom i; used /s+ for split; using spaces with default limit of 0 was giving empty string
// x_coor.add(i,Double.parseDouble(stringArray[0]));
// y_coor.add(i,Double.parseDouble(stringArray[1]));
// z_coor.add(i,Double.parseDouble(stringArray[2]));
// }
// energy = Double.parseDouble(br.readLine());//read next line: energy
// molmass = Double.parseDouble(br.readLine());//read next line: molecular mass (in amu)
// if (natoms>1){//read additional info for non-monoatomic species
// stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read next line: frequencies
// for(int i=0; i < stringArray.length; i++){
// freqs.add(i,Double.parseDouble(stringArray[i]));
// }
// stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read next line rotational constants (converting from GHz to Hz in the process)
// rotCons_1 = Double.parseDouble(stringArray[0])*1000000000;
// rotCons_2 = Double.parseDouble(stringArray[1])*1000000000;
// rotCons_3 = Double.parseDouble(stringArray[2])*1000000000;
// }
// while ( (line = br.readLine()) != null) {
// //do nothing (there shouldn't be any more information, but this is included to get all the output)
// }
// int exitValue = cclibProc.waitFor();
// }
// catch (Exception e) {
// String err = "Error in running ccLib Python process \n";
// err += e.toString();
// e.printStackTrace();
// System.exit(0);
// }
//
// ThermoData result = calculateThermoFromPM3Calc(natoms, atomicNumber, x_coor, y_coor, z_coor, energy, molmass, freqs, rotCons_1, rotCons_2, rotCons_3, gdStateDegen);
// System.out.println("Thermo for " + name + ": "+ result.toString());//print result, at least for debugging purposes
// return result;
String command = null;
if (System.getProperty("os.name").toLowerCase().contains("windows")){//special windows case where paths can have spaces and are allowed to be surrounded by quotes
command = "python \""+ System.getProperty("RMG.workingDirectory")+"/scripts/GaussianPM3ParsingScript.py\" ";
String logfilepath="\""+directory+"/"+name+".log\"";
command=command.concat(logfilepath);
command=command.concat(" \""+ System.getenv("RMG")+"/source\"");//this will pass $RMG/source to the script (in order to get the appropriate path for importing
}
else{//non-Windows case
command = "python "+ System.getProperty("RMG.workingDirectory")+"/scripts/GaussianPM3ParsingScript.py ";
String logfilepath=directory+"/"+name+".log";
command=command.concat(logfilepath);
command=command.concat(" "+ System.getenv("RMG")+"/source");//this will pass $RMG/source to the script (in order to get the appropriate path for importing
}
ThermoData result = getPM3MM4ThermoDataUsingCCLib(name, directory, p_chemGraph, command);
System.out.println("Thermo for " + name + ": "+ result.toString());//print result, at least for debugging purposes
return result;
}
//parse the results using cclib and return a ThermoData object; name and directory indicate the location of the MM4 .mm4out file
public ThermoData parseMM4(String name, String directory, ChemGraph p_chemGraph){
String command = "python "+System.getProperty("RMG.workingDirectory")+"/scripts/MM4ParsingScript.py ";
String logfilepath=directory+"/"+name+".mm4out";
command=command.concat(logfilepath);
command=command.concat(" "+ System.getenv("RMG")+"/source");//this will pass $RMG/source to the script (in order to get the appropriate path for importing
ThermoData result = getPM3MM4ThermoDataUsingCCLib(name, directory, p_chemGraph, command);
System.out.println("Thermo for " + name + ": "+ result.toString());//print result, at least for debugging purposes
return result;
}
//parse the results using cclib and CanTherm and return a ThermoData object; name and directory indicate the location of the MM4 .mm4out file
public ThermoData parseMM4withForceMat(String name, String directory, ChemGraph p_chemGraph){
//1. parse the MM4 file with cclib to get atomic number vector and geometry
String command = "python "+System.getProperty("RMG.workingDirectory")+"/scripts/MM4ParsingScript.py ";
String logfilepath=directory+"/"+name+".mm4out";
command=command.concat(logfilepath);
command=command.concat(" "+ System.getenv("RMG")+"/source");//this will pass $RMG/source to the script (in order to get the appropriate path for importing
///////////beginning of block taken from the bulk of getPM3MM4ThermoDataUsingCCLib////////////
//parse the file using cclib
int natoms = 0; //number of atoms from Mopac file; in principle, this should agree with number of chemGraph atoms
ArrayList atomicNumber = new ArrayList(); //vector of atomic numbers (integers) (apparently Vector is thread-safe; cf. http://answers.yahoo.com/question/index?qid=20081214065127AArZDT3; ...should I be using this instead?)
ArrayList x_coor = new ArrayList(); //vectors of x-, y-, and z-coordinates (doubles) (Angstroms) (in order corresponding to above atomic numbers)
ArrayList y_coor = new ArrayList();
ArrayList z_coor = new ArrayList();
double energy = 0; // energy (Hf298) in Hartree
double molmass = 0; //molecular mass in amu
ArrayList freqs = new ArrayList(); //list of frequencies in units of cm^-1
double rotCons_1 = 0;//rotational constants in (1/s)
double rotCons_2 = 0;
double rotCons_3 = 0;
int gdStateDegen = p_chemGraph.getRadicalNumber()+1;//calculate ground state degeneracy from the number of radicals; this should give the same result as spin multiplicity in Gaussian input file (and output file), but we do not explicitly check this (we could use "mult" which cclib reads in if we wanted to do so); also, note that this is not always correct, as there can apparently be additional spatial degeneracy for non-symmetric linear molecules like OH radical (cf. http://cccbdb.nist.gov/thermo.asp)
try{
Process cclibProc = Runtime.getRuntime().exec(command);
//read the stdout of the process, which should contain the desired information in a particular format
InputStream is = cclibProc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
//example output:
// C:\Python25>python.exe GaussianPM3ParsingScript.py TEOS.out
// 33
// [ 6 6 8 14 8 6 6 8 6 6 8 6 6 1 1 1 1 1 1 1 1 1 1 1 1
// 1 1 1 1 1 1 1 1]
// [[ 2.049061 -0.210375 3.133106]
// [ 1.654646 0.321749 1.762752]
// [ 0.359284 -0.110429 1.471465]
// [-0.201871 -0.013365 -0.12819 ]
// [ 0.086307 1.504918 -0.82893 ]
// [-0.559186 2.619928 -0.284003]
// [-0.180246 3.839463 -1.113029]
// [ 0.523347 -1.188305 -1.112765]
// [ 1.857584 -1.018167 -1.495088]
// [ 2.375559 -2.344392 -2.033403]
// [-1.870397 -0.297297 -0.075427]
// [-2.313824 -1.571765 0.300245]
// [-3.83427 -1.535927 0.372171]
// [ 1.360346 0.128852 3.917699]
// [ 2.053945 -1.307678 3.160474]
// [ 3.055397 0.133647 3.403037]
// [ 1.677262 1.430072 1.750899]
// [ 2.372265 -0.029237 0.985204]
// [-0.245956 2.754188 0.771433]
// [-1.656897 2.472855 -0.287156]
// [-0.664186 4.739148 -0.712606]
// [-0.489413 3.734366 -2.161038]
// [ 0.903055 4.016867 -1.112198]
// [ 1.919521 -0.229395 -2.269681]
// [ 2.474031 -0.680069 -0.629949]
// [ 2.344478 -3.136247 -1.273862]
// [ 1.786854 -2.695974 -2.890647]
// [ 3.41648 -2.242409 -2.365094]
// [-1.884889 -1.858617 1.28054 ]
// [-1.976206 -2.322432 -0.440995]
// [-4.284706 -1.26469 -0.591463]
// [-4.225999 -2.520759 0.656131]
// [-4.193468 -0.809557 1.112677]]
// -14.1664924726
// [ 9.9615 18.102 27.0569 31.8459 39.0096 55.0091
// 66.4992 80.4552 86.4912 123.3551 141.6058 155.5448
// 159.4747 167.0013 178.5676 207.3738 237.3201 255.3487
// 264.5649 292.867 309.4248 344.6503 434.8231 470.2074
// 488.9717 749.1722 834.257 834.6594 837.7292 839.6352
// 887.9767 892.9538 899.5374 992.1851 1020.6164 1020.8671
// 1028.3897 1046.7945 1049.1768 1059.4704 1065.1505 1107.4001
// 1108.1567 1109.0466 1112.6677 1122.7785 1124.4315 1128.4163
// 1153.3438 1167.6705 1170.9627 1174.9613 1232.1826 1331.8459
// 1335.3932 1335.8677 1343.9556 1371.37 1372.8127 1375.5428
// 1396.0344 1402.4082 1402.7554 1403.2463 1403.396 1411.6946
// 1412.2456 1412.3519 1414.5982 1415.3613 1415.5698 1415.7993
// 1418.5409 2870.7446 2905.3132 2907.0361 2914.1662 2949.2646
// 2965.825 2967.7667 2971.5223 3086.3849 3086.3878 3086.6448
// 3086.687 3089.2274 3089.4105 3089.4743 3089.5841 3186.0753
// 3186.1375 3186.3511 3186.365 ]
// [ 0.52729 0.49992 0.42466]
//note: above example has since been updated to print molecular mass; also frequency and atomic number format has been updated
String [] stringArray;
natoms = Integer.parseInt(br.readLine());//read line 1: number of atoms
stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read line 2: the atomic numbers (first removing braces)
// line = br.readLine().replace("[", "").replace("]","");//read line 2: the atomic numbers (first removing braces)
// StringTokenizer st = new StringTokenizer(line); //apprently the stringTokenizer class is deprecated, but I am having trouble getting the regular expressions to work properly
for(int i=0; i < natoms; i++){
// atomicNumber.add(i,Integer.parseInt(stringArray[i]));
atomicNumber.add(i,Integer.parseInt(stringArray[i]));
}
for(int i=0; i < natoms; i++){
stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read line 3+: coordinates for atom i; used /s+ for split; using spaces with default limit of 0 was giving empty string
x_coor.add(i,Double.parseDouble(stringArray[0]));
y_coor.add(i,Double.parseDouble(stringArray[1]));
z_coor.add(i,Double.parseDouble(stringArray[2]));
}
energy = Double.parseDouble(br.readLine());//read next line: energy
molmass = Double.parseDouble(br.readLine());//read next line: molecular mass (in amu)
if (natoms>1){//read additional info for non-monoatomic species
stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read next line: frequencies
for(int i=0; i < stringArray.length; i++){
freqs.add(i,Double.parseDouble(stringArray[i]));
}
stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read next line rotational constants (converting from GHz to Hz in the process)
rotCons_1 = Double.parseDouble(stringArray[0])*1000000000;
rotCons_2 = Double.parseDouble(stringArray[1])*1000000000;
rotCons_3 = Double.parseDouble(stringArray[2])*1000000000;
}
while ( (line = br.readLine()) != null) {
//do nothing (there shouldn't be any more information, but this is included to get all the output)
}
int exitValue = cclibProc.waitFor();
}
catch (Exception e) {
String err = "Error in running ccLib Python process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
///////////end of block taken from the bulk of getPM3MM4ThermoDataUsingCCLib////////////
//2. compute H0; note that we will pass H0 to CanTherm by H0=H298(harmonicMM4)-(H298-H0)harmonicMM4, where harmonicMM4 values come from cclib parsing and since it is enthalpy, it should not be NaN due to zero frequencies
double Hartree_to_kcal = 627.5095; //conversion from Hartree to kcal/mol taken from Gaussian thermo white paper
energy *= Hartree_to_kcal;//convert from Hartree to kcal/mol
//*** to be written
//3. write CanTherm input file
String canInp = "Calculation: Thermo\n";
- canInp += "Trange 300 100 13\n";//temperatures from 300 to 1500 in increments of 100
+ canInp += "Trange: 300 100 13\n";//temperatures from 300 to 1500 in increments of 100
canInp += "Scale: 1.0\n";//scale factor of 1
canInp += "Mol 1\n";
if(p_chemGraph.getAtomNumber()==1) canInp += "ATOM\n";
else if (p_chemGraph.isLinear()) canInp+="LINEAR\n";
else canInp+="NONLINEAR\n";
canInp += "GEOM MM4File " + name+".mm4out\n";//geometry file; ***special MM4 treatment in CanTherm; another option would be to use mm4opt file, but CanTherm code would need to be modified accordingly
canInp += "FORCEC MM4File "+name+".fmat\n";//force constant file; ***special MM4 treatment in CanTherm
canInp += "ENERGY "+ energy +" MM4\n";//***special MM4 treatment in CanTherm
canInp+="EXTSYM 1\n";//use external symmetry of 1; it will be corrected for below
canInp+="NELEC 1\n";//multiplicity = 1; all cases we consider will be non-radicals
if(!useHindRot) canInp += "ROTORS 0\n";//do not consider hindered rotors
else{
//this section still needs to be written
canInp+="";
}
try{
File canFile=new File(directory+"/"+name+".can");
FileWriter fw = new FileWriter(canFile);
fw.write(canInp);
fw.close();
}
catch(Exception e){
String err = "Error in writing CanTherm input \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//4 and 5. call CanTherm and read in output
Double Hf298 = null;
Double S298 = null;
Double Cp300 = null;
Double Cp400 = null;
Double Cp500 = null;
Double Cp600 = null;
Double Cp800 = null;
Double Cp1000 = null;
Double Cp1500 = null;
try{
File runningDirectory = new File(qmfolder);
String canCommand="python " + System.getenv("RMG")+"/source/CanTherm/source/CanTherm.py "+name+".can";
Process canProc = Runtime.getRuntime().exec(canCommand, null, runningDirectory);
InputStream is = canProc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
if(line.startsWith("reading Geometry from the file")){
String[] split = br.readLine().trim().split("\\s+");
Hf298 = Double.parseDouble(split[0]);
S298 = Double.parseDouble(split[1]);
Cp300 = Double.parseDouble(split[2]);
Cp400 = Double.parseDouble(split[3]);
Cp500 = Double.parseDouble(split[4]);
Cp600 = Double.parseDouble(split[5]);
Cp800 = Double.parseDouble(split[7]);
Cp1000 = Double.parseDouble(split[9]);
Cp1500 = Double.parseDouble(split[14]);
}
}
int exitValue = canProc.waitFor();
}
catch(Exception e){
String err = "Error in running CanTherm process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//6. correct the output for symmetry number (everything has been assumed to be one) : useHindRot=true case: use ChemGraph symmetry number; otherwise, we use SYMMETRY
if(!useHindRot){
double R = 1.9872; //ideal gas constant in cal/mol-K (does this appear elsewhere in RMG, so I don't need to reuse it?)
//determine point group using the SYMMETRY Program
String geom = natoms + "\n";
for(int i=0; i < natoms; i++){
geom += atomicNumber.get(i) + " "+ x_coor.get(i) + " " + y_coor.get(i) + " " +z_coor.get(i) + "\n";
}
String pointGroup = determinePointGroupUsingSYMMETRYProgram(geom);
double sigmaCorr = getSigmaCorr(pointGroup);
S298+= R*sigmaCorr;
}
else{
//***to be written
}
ThermoData result = new ThermoData(Hf298,S298,Cp300,Cp400,Cp500,Cp600,Cp800,Cp1000,Cp1500,3,1,1,"MM4 calculation; includes CanTherm analysis of force-constant matrix");//this includes rough estimates of uncertainty
System.out.println("Thermo for " + name + ": "+ result.toString());//print result, at least for debugging purposes
return result;
}
//parse the results using cclib and return a ThermoData object; name and directory indicate the location of the MOPAC .out file
public ThermoData parseMopacPM3(String name, String directory, ChemGraph p_chemGraph){
String command=null;
if (System.getProperty("os.name").toLowerCase().contains("windows")){//special windows case where paths can have spaces and are allowed to be surrounded by quotes
command = "python \""+System.getProperty("RMG.workingDirectory")+"/scripts/MopacPM3ParsingScript.py\" ";
String logfilepath="\""+directory+"/"+name+".out\"";
command=command.concat(logfilepath);
command=command.concat(" \""+ System.getenv("RMG")+"/source\"");//this will pass $RMG/source to the script (in order to get the appropriate path for importing
}
else{//non-Windows case
command = "python "+System.getProperty("RMG.workingDirectory")+"/scripts/MopacPM3ParsingScript.py ";
String logfilepath=directory+"/"+name+".out";
command=command.concat(logfilepath);
command=command.concat(" "+ System.getenv("RMG")+"/source");//this will pass $RMG/source to the script (in order to get the appropriate path for importing
}
ThermoData result = getPM3MM4ThermoDataUsingCCLib(name, directory, p_chemGraph, command);
System.out.println("Thermo for " + name + ": "+ result.toString());//print result, at least for debugging purposes
return result;
}
//separated from parseMopacPM3, since the function was originally based off of parseGaussianPM3 and was very similar (differences being command and logfilepath variables);
public ThermoData getPM3MM4ThermoDataUsingCCLib(String name, String directory, ChemGraph p_chemGraph, String command){
//parse the Mopac file using cclib
int natoms = 0; //number of atoms from Mopac file; in principle, this should agree with number of chemGraph atoms
ArrayList atomicNumber = new ArrayList(); //vector of atomic numbers (integers) (apparently Vector is thread-safe; cf. http://answers.yahoo.com/question/index?qid=20081214065127AArZDT3; ...should I be using this instead?)
ArrayList x_coor = new ArrayList(); //vectors of x-, y-, and z-coordinates (doubles) (Angstroms) (in order corresponding to above atomic numbers)
ArrayList y_coor = new ArrayList();
ArrayList z_coor = new ArrayList();
double energy = 0; //PM3 energy (Hf298) in Hartree (***note: in the case of MOPAC, the MOPAC file will contain in units of kcal/mol, but modified ccLib will return in Hartree)
double molmass = 0; //molecular mass in amu
ArrayList freqs = new ArrayList(); //list of frequencies in units of cm^-1
double rotCons_1 = 0;//rotational constants in (1/s)
double rotCons_2 = 0;
double rotCons_3 = 0;
int gdStateDegen = p_chemGraph.getRadicalNumber()+1;//calculate ground state degeneracy from the number of radicals; this should give the same result as spin multiplicity in Gaussian input file (and output file), but we do not explicitly check this (we could use "mult" which cclib reads in if we wanted to do so); also, note that this is not always correct, as there can apparently be additional spatial degeneracy for non-symmetric linear molecules like OH radical (cf. http://cccbdb.nist.gov/thermo.asp)
try{
Process cclibProc = Runtime.getRuntime().exec(command);
//read the stdout of the process, which should contain the desired information in a particular format
InputStream is = cclibProc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
//example output:
// C:\Python25>python.exe GaussianPM3ParsingScript.py TEOS.out
// 33
// [ 6 6 8 14 8 6 6 8 6 6 8 6 6 1 1 1 1 1 1 1 1 1 1 1 1
// 1 1 1 1 1 1 1 1]
// [[ 2.049061 -0.210375 3.133106]
// [ 1.654646 0.321749 1.762752]
// [ 0.359284 -0.110429 1.471465]
// [-0.201871 -0.013365 -0.12819 ]
// [ 0.086307 1.504918 -0.82893 ]
// [-0.559186 2.619928 -0.284003]
// [-0.180246 3.839463 -1.113029]
// [ 0.523347 -1.188305 -1.112765]
// [ 1.857584 -1.018167 -1.495088]
// [ 2.375559 -2.344392 -2.033403]
// [-1.870397 -0.297297 -0.075427]
// [-2.313824 -1.571765 0.300245]
// [-3.83427 -1.535927 0.372171]
// [ 1.360346 0.128852 3.917699]
// [ 2.053945 -1.307678 3.160474]
// [ 3.055397 0.133647 3.403037]
// [ 1.677262 1.430072 1.750899]
// [ 2.372265 -0.029237 0.985204]
// [-0.245956 2.754188 0.771433]
// [-1.656897 2.472855 -0.287156]
// [-0.664186 4.739148 -0.712606]
// [-0.489413 3.734366 -2.161038]
// [ 0.903055 4.016867 -1.112198]
// [ 1.919521 -0.229395 -2.269681]
// [ 2.474031 -0.680069 -0.629949]
// [ 2.344478 -3.136247 -1.273862]
// [ 1.786854 -2.695974 -2.890647]
// [ 3.41648 -2.242409 -2.365094]
// [-1.884889 -1.858617 1.28054 ]
// [-1.976206 -2.322432 -0.440995]
// [-4.284706 -1.26469 -0.591463]
// [-4.225999 -2.520759 0.656131]
// [-4.193468 -0.809557 1.112677]]
// -14.1664924726
// [ 9.9615 18.102 27.0569 31.8459 39.0096 55.0091
// 66.4992 80.4552 86.4912 123.3551 141.6058 155.5448
// 159.4747 167.0013 178.5676 207.3738 237.3201 255.3487
// 264.5649 292.867 309.4248 344.6503 434.8231 470.2074
// 488.9717 749.1722 834.257 834.6594 837.7292 839.6352
// 887.9767 892.9538 899.5374 992.1851 1020.6164 1020.8671
// 1028.3897 1046.7945 1049.1768 1059.4704 1065.1505 1107.4001
// 1108.1567 1109.0466 1112.6677 1122.7785 1124.4315 1128.4163
// 1153.3438 1167.6705 1170.9627 1174.9613 1232.1826 1331.8459
// 1335.3932 1335.8677 1343.9556 1371.37 1372.8127 1375.5428
// 1396.0344 1402.4082 1402.7554 1403.2463 1403.396 1411.6946
// 1412.2456 1412.3519 1414.5982 1415.3613 1415.5698 1415.7993
// 1418.5409 2870.7446 2905.3132 2907.0361 2914.1662 2949.2646
// 2965.825 2967.7667 2971.5223 3086.3849 3086.3878 3086.6448
// 3086.687 3089.2274 3089.4105 3089.4743 3089.5841 3186.0753
// 3186.1375 3186.3511 3186.365 ]
// [ 0.52729 0.49992 0.42466]
//note: above example has since been updated to print molecular mass; also frequency and atomic number format has been updated
String [] stringArray;
natoms = Integer.parseInt(br.readLine());//read line 1: number of atoms
stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read line 2: the atomic numbers (first removing braces)
// line = br.readLine().replace("[", "").replace("]","");//read line 2: the atomic numbers (first removing braces)
// StringTokenizer st = new StringTokenizer(line); //apprently the stringTokenizer class is deprecated, but I am having trouble getting the regular expressions to work properly
for(int i=0; i < natoms; i++){
// atomicNumber.add(i,Integer.parseInt(stringArray[i]));
atomicNumber.add(i,Integer.parseInt(stringArray[i]));
}
for(int i=0; i < natoms; i++){
stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read line 3+: coordinates for atom i; used /s+ for split; using spaces with default limit of 0 was giving empty string
x_coor.add(i,Double.parseDouble(stringArray[0]));
y_coor.add(i,Double.parseDouble(stringArray[1]));
z_coor.add(i,Double.parseDouble(stringArray[2]));
}
energy = Double.parseDouble(br.readLine());//read next line: energy
molmass = Double.parseDouble(br.readLine());//read next line: molecular mass (in amu)
if (natoms>1){//read additional info for non-monoatomic species
stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read next line: frequencies
for(int i=0; i < stringArray.length; i++){
freqs.add(i,Double.parseDouble(stringArray[i]));
}
stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read next line rotational constants (converting from GHz to Hz in the process)
rotCons_1 = Double.parseDouble(stringArray[0])*1000000000;
rotCons_2 = Double.parseDouble(stringArray[1])*1000000000;
rotCons_3 = Double.parseDouble(stringArray[2])*1000000000;
}
while ( (line = br.readLine()) != null) {
//do nothing (there shouldn't be any more information, but this is included to get all the output)
}
int exitValue = cclibProc.waitFor();
}
catch (Exception e) {
String err = "Error in running ccLib Python process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
ThermoData result = calculateThermoFromPM3MM4Calc(natoms, atomicNumber, x_coor, y_coor, z_coor, energy, molmass, freqs, rotCons_1, rotCons_2, rotCons_3, gdStateDegen);
return result;
}
//returns a thermo result, given results from quantum PM3 calculation or MM4 calculation (originally, this was in parseGaussianPM3 function
public ThermoData calculateThermoFromPM3MM4Calc(int natoms, ArrayList atomicNumber, ArrayList x_coor, ArrayList y_coor, ArrayList z_coor, double energy, double molmass, ArrayList freqs, double rotCons_1, double rotCons_2, double rotCons_3, int gdStateDegen){
//determine point group using the SYMMETRY Program
String geom = natoms + "\n";
for(int i=0; i < natoms; i++){
geom += atomicNumber.get(i) + " "+ x_coor.get(i) + " " + y_coor.get(i) + " " +z_coor.get(i) + "\n";
}
// String pointGroup = determinePointGroupUsingSYMMETRYProgram(geom, 0.01);
String pointGroup = determinePointGroupUsingSYMMETRYProgram(geom);
//calculate thermo quantities using stat. mech. equations
double R = 1.9872; //ideal gas constant in cal/mol-K (does this appear elsewhere in RMG, so I don't need to reuse it?)
double Hartree_to_kcal = 627.5095; //conversion from Hartree to kcal/mol taken from Gaussian thermo white paper
double Na = 6.02214179E23;//Avagadro's number; cf. http://physics.nist.gov/cgi-bin/cuu/Value?na|search_for=physchem_in!
double k = 1.3806504E-23;//Boltzmann's constant in J/K; cf. http://physics.nist.gov/cgi-bin/cuu/Value?na|search_for=physchem_in!
double h = 6.62606896E-34;//Planck's constant in J-s; cf. http://physics.nist.gov/cgi-bin/cuu/Value?h|search_for=universal_in!
double c = 299792458. *100;//speed of light in vacuum in cm/s, cf. http://physics.nist.gov/cgi-bin/cuu/Value?c|search_for=universal_in!
//boolean linearity = p_chemGraph.isLinear();//determine linearity (perhaps it would be more appropriate to determine this from point group?)
boolean linearity = false;
if (pointGroup.equals("Cinfv")||pointGroup.equals("Dinfh")) linearity=true;//determine linearity from 3D-geometry; changed to correctly consider linear ketene radical case
//we will use number of atoms from above (alternatively, we could use the chemGraph); this is needed to test whether the species is monoatomic
double Hf298, S298, Cp300, Cp400, Cp500, Cp600, Cp800, Cp1000, Cp1500;
double sigmaCorr = getSigmaCorr(pointGroup);
Hf298 = energy*Hartree_to_kcal;
S298 = R*Math.log(gdStateDegen)+R*(3./2.*Math.log(2.*Math.PI*molmass/(1000.*Na*Math.pow(h,2.)))+5./2.*Math.log(k*298.15)-Math.log(100000.)+5./2.);//electronic + translation; note use of 10^5 Pa for standard pressure; also note that molecular mass needs to be divided by 1000 for kg units
Cp300 = 5./2.*R;
Cp400 = 5./2.*R;
Cp500 = 5./2.*R;
Cp600 = 5./2.*R;
Cp800 = 5./2.*R;
Cp1000 = 5./2.*R;
Cp1500 = 5./2.*R;
if(natoms>1){//include statistical correction and rotational (without symmetry number, vibrational contributions if species is polyatomic
if(linearity){//linear case
//determine the rotational constant (note that one of the rotcons will be zero)
double rotCons;
if(rotCons_1 > 0.0001) rotCons = rotCons_1;
else rotCons = rotCons_2;
S298 += R*sigmaCorr+R*(Math.log(k*298.15/(h*rotCons))+1)+R*calcVibS(freqs, 298.15, h, k, c);
Cp300 += R + R*calcVibCp(freqs, 300., h, k, c);
Cp400 += R + R*calcVibCp(freqs, 400., h, k, c);
Cp500 += R + R*calcVibCp(freqs, 500., h, k, c);
Cp600 += R + R*calcVibCp(freqs, 600., h, k, c);
Cp800 += R + R*calcVibCp(freqs, 800., h, k, c);
Cp1000 += R + R*calcVibCp(freqs, 1000., h, k, c);
Cp1500 += R + R*calcVibCp(freqs, 1500., h, k, c);
}
else{//nonlinear case
S298 += R*sigmaCorr+R*(3./2.*Math.log(k*298.15/h)-1./2.*Math.log(rotCons_1*rotCons_2*rotCons_3/Math.PI)+3./2.)+R*calcVibS(freqs, 298.15, h, k, c);
Cp300 += 3./2.*R + R*calcVibCp(freqs, 300., h, k, c);
Cp400 += 3./2.*R + R*calcVibCp(freqs, 400., h, k, c);
Cp500 += 3./2.*R + R*calcVibCp(freqs, 500., h, k, c);
Cp600 += 3./2.*R + R*calcVibCp(freqs, 600., h, k, c);
Cp800 += 3./2.*R + R*calcVibCp(freqs, 800., h, k, c);
Cp1000 += 3./2.*R + R*calcVibCp(freqs, 1000., h, k, c);
Cp1500 += 3./2.*R + R*calcVibCp(freqs, 1500., h, k, c);
}
}
ThermoData result = new ThermoData(Hf298,S298,Cp300,Cp400,Cp500,Cp600,Cp800,Cp1000,Cp1500,5,1,1,"PM3 or MM4 calculation");//this includes rough estimates of uncertainty
return result;
}
//gets the statistical correction for S in dimensionless units (divided by R)
public double getSigmaCorr(String pointGroup){
double sigmaCorr=0;
//determine statistical correction factor for 1. external rotational symmetry (affects rotational partition function) and 2. chirality (will add R*ln2 to entropy) based on point group
//ref: http://cccbdb.nist.gov/thermo.asp
//assumptions below for Sn, T, Th, O, I seem to be in line with expectations based on order reported at: http://en.wikipedia.org/w/index.php?title=List_of_character_tables_for_chemically_important_3D_point_groups&oldid=287261611 (assuming order = symmetry number * 2 (/2 if chiral))...this appears to be true for all point groups I "know" to be correct
//minor concern: does SYMMETRY appropriately calculate all Sn groups considering 2007 discovery of previous errors in character tables (cf. Wikipedia article above)
if (pointGroup.equals("C1")) sigmaCorr=+Math.log(2.);//rot. sym. = 1, chiral
else if (pointGroup.equals("Cs")) sigmaCorr=0; //rot. sym. = 1
else if (pointGroup.equals("Ci")) sigmaCorr=0; //rot. sym. = 1
else if (pointGroup.equals("C2")) sigmaCorr=0;//rot. sym. = 2, chiral (corrections cancel)
else if (pointGroup.equals("C3")) sigmaCorr=+Math.log(2.)-Math.log(3.);//rot. sym. = 3, chiral
else if (pointGroup.equals("C4")) sigmaCorr=+Math.log(2.)-Math.log(4.);//rot. sym. = 4, chiral
else if (pointGroup.equals("C5")) sigmaCorr=+Math.log(2.)-Math.log(5.);//rot. sym. = 5, chiral
else if (pointGroup.equals("C6")) sigmaCorr=+Math.log(2.)-Math.log(6.);//rot. sym. = 6, chiral
else if (pointGroup.equals("C7")) sigmaCorr=+Math.log(2.)-Math.log(7.);//rot. sym. = 7, chiral
else if (pointGroup.equals("C8")) sigmaCorr=+Math.log(2.)-Math.log(8.);//rot. sym. = 8, chiral
else if (pointGroup.equals("D2")) sigmaCorr=+Math.log(2.)-Math.log(4.);//rot. sym. = 4, chiral
else if (pointGroup.equals("D3")) sigmaCorr=+Math.log(2.)-Math.log(6.);//rot. sym. = 6, chiral
else if (pointGroup.equals("D4")) sigmaCorr=+Math.log(2.)-Math.log(8.);//rot. sym. = 8, chiral
else if (pointGroup.equals("D5")) sigmaCorr=+Math.log(2.)-Math.log(10.);//rot. sym. = 10, chiral
else if (pointGroup.equals("D6")) sigmaCorr=+Math.log(2.)-Math.log(12.);//rot. sym. = 12, chiral
else if (pointGroup.equals("D7")) sigmaCorr=+Math.log(2.)-Math.log(14.);//rot. sym. = 14, chiral
else if (pointGroup.equals("D8")) sigmaCorr=+Math.log(2.)-Math.log(16.);//rot. sym. = 16, chiral
else if (pointGroup.equals("C2v")) sigmaCorr=-Math.log(2.);//rot. sym. = 2
else if (pointGroup.equals("C3v")) sigmaCorr=-Math.log(3.);//rot. sym. = 3
else if (pointGroup.equals("C4v")) sigmaCorr=-Math.log(4.);//rot. sym. = 4
else if (pointGroup.equals("C5v")) sigmaCorr=-Math.log(5.);//rot. sym. = 5
else if (pointGroup.equals("C6v")) sigmaCorr=-Math.log(6.);//rot. sym. = 6
else if (pointGroup.equals("C7v")) sigmaCorr=-Math.log(7.);//rot. sym. = 7
else if (pointGroup.equals("C8v")) sigmaCorr=-Math.log(8.);//rot. sym. = 8
else if (pointGroup.equals("C2h")) sigmaCorr=-Math.log(2.);//rot. sym. = 2
else if (pointGroup.equals("C3h")) sigmaCorr=-Math.log(3.);//rot. sym. = 3
else if (pointGroup.equals("C4h")) sigmaCorr=-Math.log(4.);//rot. sym. = 4
else if (pointGroup.equals("C5h")) sigmaCorr=-Math.log(5.);//rot. sym. = 5
else if (pointGroup.equals("C6h")) sigmaCorr=-Math.log(6.);//rot. sym. = 6
else if (pointGroup.equals("C7h")) sigmaCorr=-Math.log(7.);//rot. sym. = 7
else if (pointGroup.equals("C8h")) sigmaCorr=-Math.log(8.);//rot. sym. = 8
else if (pointGroup.equals("D2h")) sigmaCorr=-Math.log(4.);//rot. sym. = 4
else if (pointGroup.equals("D3h")) sigmaCorr=-Math.log(6.);//rot. sym. = 6
else if (pointGroup.equals("D4h")) sigmaCorr=-Math.log(8.);//rot. sym. = 8
else if (pointGroup.equals("D5h")) sigmaCorr=-Math.log(10.);//rot. sym. = 10
else if (pointGroup.equals("D6h")) sigmaCorr=-Math.log(12.);//rot. sym. = 12
else if (pointGroup.equals("D7h")) sigmaCorr=-Math.log(14.);//rot. sym. = 14
else if (pointGroup.equals("D8h")) sigmaCorr=-Math.log(16.);//rot. sym. = 16
else if (pointGroup.equals("D2d")) sigmaCorr=-Math.log(4.);//rot. sym. = 4
else if (pointGroup.equals("D3d")) sigmaCorr=-Math.log(6.);//rot. sym. = 6
else if (pointGroup.equals("D4d")) sigmaCorr=-Math.log(8.);//rot. sym. = 8
else if (pointGroup.equals("D5d")) sigmaCorr=-Math.log(10.);//rot. sym. = 10
else if (pointGroup.equals("D6d")) sigmaCorr=-Math.log(12.);//rot. sym. = 12
else if (pointGroup.equals("D7d")) sigmaCorr=-Math.log(14.);//rot. sym. = 14
else if (pointGroup.equals("D8d")) sigmaCorr=-Math.log(16.);//rot. sym. = 16
else if (pointGroup.equals("S4")) sigmaCorr=-Math.log(2.);//rot. sym. = 2 ;*** assumed achiral
else if (pointGroup.equals("S6")) sigmaCorr=-Math.log(3.);//rot. sym. = 3 ;*** assumed achiral
else if (pointGroup.equals("S8")) sigmaCorr=-Math.log(4.);//rot. sym. = 4 ;*** assumed achiral
else if (pointGroup.equals("T")) sigmaCorr=+Math.log(2.)-Math.log(12.);//rot. sym. = 12, *** assumed chiral
else if (pointGroup.equals("Th")) sigmaCorr=-Math.log(12.);//***assumed rot. sym. = 12
else if (pointGroup.equals("Td")) sigmaCorr=-Math.log(12.);//rot. sym. = 12
else if (pointGroup.equals("O")) sigmaCorr=+Math.log(2.)-Math.log(24.);//***assumed rot. sym. = 24, chiral
else if (pointGroup.equals("Oh")) sigmaCorr=-Math.log(24.);//rot. sym. = 24
else if (pointGroup.equals("Cinfv")) sigmaCorr=0;//rot. sym. = 1
else if (pointGroup.equals("Dinfh")) sigmaCorr=-Math.log(2.);//rot. sym. = 2
else if (pointGroup.equals("I")) sigmaCorr=+Math.log(2.)-Math.log(60.);//***assumed rot. sym. = 60, chiral
else if (pointGroup.equals("Ih")) sigmaCorr=-Math.log(60.);//rot. sym. = 60
else if (pointGroup.equals("Kh")) sigmaCorr=0;//arbitrarily set to zero...one could argue that it is infinite; apparently this is the point group of a single atom (cf. http://www.cobalt.chem.ucalgary.ca/ps/symmetry/tests/G_Kh); this should not have a rotational partition function, and we should not use the symmetry correction in this case
else{//this point should not be reached, based on checks performed in determinePointGroupUsingSYMMETRYProgram
System.out.println("Unrecognized point group: "+ pointGroup);
System.exit(0);
}
return sigmaCorr;
}
//determine the point group using the SYMMETRY program (http://www.cobalt.chem.ucalgary.ca/ps/symmetry/)
//required input is a line with number of atoms followed by lines for each atom including atom number and x,y,z coordinates
//finalTol determines how loose the point group criteria are; values are comparable to those specifed in the GaussView point group interface
//public String determinePointGroupUsingSYMMETRYProgram(String geom, double finalTol){
public String determinePointGroupUsingSYMMETRYProgram(String geom){
int attemptNumber = 1;
int maxAttemptNumber = 2;
boolean pointGroupFound=false;
//write the input file
try {
File inputFile=new File(qmfolder+"symminput.txt");//SYMMETRY program directory
FileWriter fw = new FileWriter(inputFile);
fw.write(geom);
fw.close();
} catch (IOException e) {
String err = "Error writing input file for point group calculation";
err += e.toString();
System.out.println(err);
System.exit(0);
}
String result = "";
String command = "";
while (attemptNumber<=maxAttemptNumber && !pointGroupFound){
//call the program and read the result
result = "";
String [] lineArray;
try{
if (System.getProperty("os.name").toLowerCase().contains("windows")){//the Windows case where the precompiled executable seems to need to be called from a batch script
if(attemptNumber==1) command = "\""+System.getProperty("RMG.workingDirectory")+"/scripts/symmetryDefault2.bat\" "+qmfolder+ "symminput.txt";//12/1/09 gmagoon: switched to use slightly looser criteria of 0.02 rather than 0.01 to handle methylperoxyl radical result from MOPAC
else if (attemptNumber==2) command = "\""+System.getProperty("RMG.workingDirectory")+"/scripts/symmetryLoose.bat\" " +qmfolder+ "symminput.txt";//looser criteria (0.1 instead of 0.01) to properly identify C2v group in VBURLMBUVWIEMQ-UHFFFAOYAVmult5 (InChI=1/C3H4O2/c1-3(2,4)5/h1-2H2/mult5) MOPAC result; C2 and sigma were identified with default, but it should be C2 and sigma*2
else{
System.out.println("Invalid attemptNumber: "+ attemptNumber);
System.exit(0);
}
}
else{//in other (non-Windows) cases, where it is compiled from scratch, we should be able to run this directly
if(attemptNumber==1) command = System.getProperty("RMG.workingDirectory")+"/bin/SYMMETRY.EXE -final 0.02 " +qmfolder+ "symminput.txt";//12/1/09 gmagoon: switched to use slightly looser criteria of 0.02 rather than 0.01 to handle methylperoxyl radical result from MOPAC
else if (attemptNumber==2) command = System.getProperty("RMG.workingDirectory")+"/bin/SYMMETRY.EXE -final 0.1 " +qmfolder+ "symminput.txt";//looser criteria (0.1 instead of 0.01) to properly identify C2v group in VBURLMBUVWIEMQ-UHFFFAOYAVmult5 (InChI=1/C3H4O2/c1-3(2,4)5/h1-2H2/mult5) MOPAC result; C2 and sigma were identified with default, but it should be C2 and sigma*2
else{
System.out.println("Invalid attemptNumber: "+ attemptNumber);
System.exit(0);
}
}
Process symmProc = Runtime.getRuntime().exec(command);
//check for errors and display the error if there is one
InputStream is = symmProc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
if(line.startsWith("It seems to be the ")){//last line, ("It seems to be the [x] point group") indicates point group
lineArray = line.split(" ");//split the line around spaces
result = lineArray[5];//point group string should be the 6th word
}
}
int exitValue = symmProc.waitFor();
}
catch(Exception e){
String err = "Error in running point group calculation process using SYMMETRY \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//check for a recognized point group
if (result.equals("C1")||result.equals("Cs")||result.equals("Ci")||result.equals("C2")||result.equals("C3")||result.equals("C4")||result.equals("C5")||result.equals("C6")||result.equals("C7")||result.equals("C8")||result.equals("D2")||result.equals("D3")||result.equals("D4")||result.equals("D5")||result.equals("D6")||result.equals("D7")||result.equals("D8")||result.equals("C2v")||result.equals("C3v")||result.equals("C4v")||result.equals("C5v")||result.equals("C6v")||result.equals("C7v")||result.equals("C8v")||result.equals("C2h")||result.equals("C3h")||result.equals("C4h")||result.equals("C5h")||result.equals("C6h")||result.equals("C7h")||result.equals("C8h")||result.equals("D2h")||result.equals("D3h")||result.equals("D4h")||result.equals("D5h")||result.equals("D6h")||result.equals("D7h")||result.equals("D8h")||result.equals("D2d")||result.equals("D3d")||result.equals("D4d")||result.equals("D5d")||result.equals("D6d")||result.equals("D7d")||result.equals("D8d")||result.equals("S4")||result.equals("S6")||result.equals("S8")||result.equals("T")||result.equals("Th")||result.equals("Td")||result.equals("O")||result.equals("Oh")||result.equals("Cinfv")||result.equals("Dinfh")||result.equals("I")||result.equals("Ih")||result.equals("Kh")) pointGroupFound=true;
else{
if(attemptNumber < maxAttemptNumber) System.out.println("Attempt number "+attemptNumber+" did not identify a recognized point group (" +result+"). Will retry with looser point group criteria.");
else{
System.out.println("Final attempt number "+attemptNumber+" did not identify a recognized point group (" +result+"). Exiting.");
System.exit(0);
}
attemptNumber++;
}
}
System.out.println("Point group: "+ result);//print result, at least for debugging purposes
return result;
}
//gmagoon 6/8/09
//calculate the vibrational contribution (divided by R, dimensionless) at temperature, T, in Kelvin to entropy
//p_freqs in cm^-1; c in cm/s; k in J/K; h in J-s
//ref.: http://cccbdb.nist.gov/thermo.asp
public double calcVibS(ArrayList p_freqs, double p_T, double h, double k, double c){
double Scontrib = 0;
double dr;
for(int i=0; i < p_freqs.size(); i++){
double freq = (Double)p_freqs.get(i);
dr = h*c*freq/(k*p_T); //frequently used dimensionless ratio
Scontrib = Scontrib - Math.log(1.-Math.exp(-dr))+dr*Math.exp(-dr)/(1.-Math.exp(-dr));
}
return Scontrib;
}
//gmagoon 6/8/09
//calculate the vibrational contribution (divided by R, dimensionless) at temperature, T, in Kelvin to heat capacity, Cp
//p_freqs in cm^-1; c in cm/s; k in J/K; h in J-s
//ref.: http://cccbdb.nist.gov/thermo.asp
public double calcVibCp(ArrayList p_freqs, double p_T, double h, double k, double c){
double Cpcontrib = 0;
double dr;
for(int i=0; i < p_freqs.size(); i++){
double freq = (Double)p_freqs.get(i);
dr = h*c*freq/(k*p_T); //frequently used dimensionless ratio
Cpcontrib = Cpcontrib + Math.pow(dr, 2.)*Math.exp(-dr)/Math.pow(1.-Math.exp(-dr),2.);
}
return Cpcontrib;
}
//determine the QM filename (element 0) and augmented InChI (element 1) for a ChemGraph
//QM filename is InChIKey appended with mult3, mult4, mult5, or mult6 for multiplicities of 3 or higher
//augmented InChI is InChI appended with /mult3, /mult4, /mult5, or /mult6 for multiplicities of 3 or higher
public String [] getQMFileName(ChemGraph p_chemGraph){
String [] result = new String[2];
result[0] = p_chemGraph.getModifiedInChIKeyAnew();//need to generate InChI and key anew because ChemGraph may have changed (in particular, adding/removing hydrogens in HBI process)
result[1] = p_chemGraph.getModifiedInChIAnew();
return result;
}
//returns true if a Gaussian file for the given name and directory (.log suffix) exists and indicates successful completion (same criteria as used after calculation runs); terminates if the InChI doesn't match the InChI in the file or if there is no InChI in the file; returns false otherwise
public boolean successfulGaussianResultExistsQ(String name, String directory, String InChIaug){
//part of the code is taken from runGaussian code above
//look in the output file to check for the successful termination of the Gaussian calculation
//failed jobs will contain the a line beginning with " Error termination" near the end of the file
File file = new File(directory+"/"+name+".log");
if(file.exists()){//if the file exists, do further checks; otherwise, we will skip to final statement and return false
int failureFlag=0;//flag (1 or 0) indicating whether the Gaussian job failed
int InChIMatch=0;//flag (1 or 0) indicating whether the InChI in the file matches InChIaug; this can only be 1 if InChIFound is also 1;
int InChIFound=0;//flag (1 or 0) indicating whether an InChI was found in the log file
int InChIPartialMatch=0;//flag (1 or 0) indicating whether the InChI in the log file is a substring of the InChI in RMG's memory
String logFileInChI="";
try{
FileReader in = new FileReader(file);
BufferedReader reader = new BufferedReader(in);
String line=reader.readLine();
while(line!=null){
if (line.startsWith(" Error termination ")) failureFlag=1;
else if (line.startsWith(" ******")){//also look for imaginary frequencies
if (line.contains("imaginary frequencies")) failureFlag=1;
}
else if(line.startsWith(" InChI=")){
logFileInChI = line.trim();
//continue reading lines until a line of dashes is found (in this way, we can read InChIs that span multiple lines)
line=reader.readLine();
while (!line.startsWith(" --------")){
logFileInChI += line.trim();
line=reader.readLine();
}
InChIFound=1;
if(logFileInChI.equals(InChIaug)) InChIMatch=1;
else if(InChIaug.startsWith(logFileInChI)) InChIPartialMatch=1;
}
line=reader.readLine();
}
}
catch(Exception e){
String err = "Error in reading preexisting Gaussian log file \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//if the failure flag is still 0, the process should have been successful
if (failureFlag==0&&InChIMatch==1){
System.out.println("Pre-existing successful quantum result for " + name + " ("+InChIaug+") has been found. This log file will be used.");
return true;
}
else if (InChIFound==1 && InChIMatch == 0){//InChIs do not match (most likely due to limited name length mirrored in log file (79 characters), but possibly due to a collision)
if(InChIPartialMatch == 1){//case where the InChI in memory begins with the InChI in the log file; we will continue and check the input file, printing a warning if there is no match
File inputFile = new File(directory+"/"+name+".gjf");
if(inputFile.exists()){//read the Gaussian inputFile
String inputFileInChI="";
try{
FileReader inI = new FileReader(inputFile);
BufferedReader readerI = new BufferedReader(inI);
String lineI=readerI.readLine();
while(lineI!=null){
if(lineI.startsWith(" InChI=")){
inputFileInChI = lineI.trim();
}
lineI=readerI.readLine();
}
}
catch(Exception e){
String err = "Error in reading preexisting Gaussian gjf file \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
if(inputFileInChI.equals(InChIaug)){
if(failureFlag==0){
System.out.println("Pre-existing successful quantum result for " + name + " ("+InChIaug+") has been found. This log file will be used. *Note that input file was read to confirm lack of InChIKey collision (InChI probably more than 79 characters)");
return true;
}
else{//otherwise, failureFlag==1
System.out.println("Pre-existing quantum result for " + name + " ("+InChIaug+") has been found, but the result was apparently unsuccessful. The file will be overwritten with a new calculation. *Note that input file was read to confirm lack of InChIKey collision (InChI probably more than 79 characters)");
return false;
}
}
else{
if(inputFileInChI.equals("")){//InChI was not found in input file
System.out.println("*****Warning: potential InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " Log file Augmented InChI = "+logFileInChI + " . InChI could not be found in the Gaussian input file. You should manually check that the log file contains the intended species.");
return true;
}
else{//InChI was found but doesn't match
System.out.println("Congratulations! You appear to have discovered the first recorded instance of an InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " Gaussian input file Augmented InChI = "+inputFileInChI);
System.exit(0);
}
}
}
else{
System.out.println("*****Warning: potential InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " Log file Augmented InChI = "+logFileInChI + " . Gaussian input file could not be found to check full InChI. You should manually check that the log file contains the intended species.");
return true;
}
}
else{
System.out.println("Congratulations! You appear to have discovered the first recorded instance of an InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " Log file Augmented InChI = "+logFileInChI);
System.exit(0);
}
}
else if (InChIFound==0){
System.out.println("An InChI was not found in file: " +name+".log");
System.exit(0);
}
else if (failureFlag==1){//note these should cover all possible results for this block, and if the file.exists block is entered, it should return from within the block and should not reach the return statement below
System.out.println("Pre-existing quantum result for " + name + " ("+InChIaug+") has been found, but the result was apparently unsuccessful. The file will be overwritten with a new calculation.");
return false;
}
}
//we could print a line here for cases where the file doesn't exist, but this would probably be too verbose
return false;
}
//returns true if a successful result exists (either Gaussian or MOPAC)
// public boolean [] successfulResultExistsQ(String name, String directory, String InChIaug){
// boolean gaussianResult=successfulGaussianResultExistsQ(name, directory, InChIaug);
// boolean mopacResult=successfulMOPACResultExistsQ(name, directory, InChIaug);
// return (gaussianResult || mopacResult);// returns true if either a successful Gaussian or MOPAC result exists
// }
//returns true if a MOPAC output file for the given name and directory (.out suffix) exists and indicates successful completion (same criteria as used after calculation runs); terminates if the InChI doesn't match the InChI in the file or if there is no InChI in the file; returns false otherwise
public boolean successfulMopacResultExistsQ(String name, String directory, String InChIaug){
//part of the code is taken from analogous code for Gaussian
//look in the output file to check for the successful termination of the calculation (assumed to be successful if "description of vibrations appears)
File file = new File(directory+"/"+name+".out");
if(file.exists()){//if the file exists, do further checks; otherwise, we will skip to final statement and return false
int failureFlag=1;//flag (1 or 0) indicating whether the MOPAC job failed
int failureOverrideFlag=0;//flag (1 or 0) to override success as measured by failureFlag
int InChIMatch=0;//flag (1 or 0) indicating whether the InChI in the file matches InChIaug; this can only be 1 if InChIFound is also 1;
int InChIFound=0;//flag (1 or 0) indicating whether an InChI was found in the log file
int InChIPartialMatch=0;//flag (1 or 0) indicating whether the InChI in the log file is a substring of the InChI in RMG's memory
String logFileInChI="";
try{
FileReader in = new FileReader(file);
BufferedReader reader = new BufferedReader(in);
String line=reader.readLine();
while(line!=null){
String trimLine= line.trim();
if (trimLine.equals("DESCRIPTION OF VIBRATIONS")){
// if(!MopacFileContainsNegativeFreqsQ(name, directory)) failureFlag=0;//check for this line; if it is here, check for negative frequencies
failureFlag = 0;
}
//negative frequencies notice example:
// NOTE: SYSTEM IS NOT A GROUND STATE, THEREFORE ZERO POINT
// ENERGY IS NOT MEANINGFULL. ZERO POINT ENERGY PRINTED
// DOES NOT INCLUDE THE 2 IMAGINARY FREQUENCIES
else if (trimLine.endsWith("IMAGINARY FREQUENCIES")){
// System.out.println("*****Imaginary freqencies found:");
failureOverrideFlag=1;
}
else if (trimLine.equals("EXCESS NUMBER OF OPTIMIZATION CYCLES")){//exceeding max cycles error
failureOverrideFlag=1;
}
else if (trimLine.equals("NOT ENOUGH TIME FOR ANOTHER CYCLE")){//timeout error
failureOverrideFlag=1;
}
else if(line.startsWith(" InChI=")){
logFileInChI = line.trim();//output files should take up to 240 characters of the name in the input file
InChIFound=1;
if(logFileInChI.equals(InChIaug)) InChIMatch=1;
else if(InChIaug.startsWith(logFileInChI)) InChIPartialMatch=1;
}
line=reader.readLine();
}
}
catch(Exception e){
String err = "Error in reading preexisting MOPAC output file \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
if(failureOverrideFlag==1) failureFlag=1; //job will be considered a failure if there are imaginary frequencies or if job terminates to to excess time/cycles
//if the failure flag is still 0, the process should have been successful
if (failureFlag==0&&InChIMatch==1){
System.out.println("Pre-existing successful MOPAC quantum result for " + name + " ("+InChIaug+") has been found. This log file will be used.");
return true;
}
else if (InChIFound==1 && InChIMatch == 0){//InChIs do not match (most likely due to limited name length mirrored in log file (240 characters), but possibly due to a collision)
// if(InChIPartialMatch == 1){//case where the InChI in memory begins with the InChI in the log file; we will continue and check the input file, printing a warning if there is no match
//look in the input file if the InChI doesn't match (apparently, certain characters can be deleted in MOPAC output file for long InChIs)
File inputFile = new File(directory+"/"+name+".mop");
if(inputFile.exists()){//read the MOPAC inputFile
String inputFileInChI="";
try{
FileReader inI = new FileReader(inputFile);
BufferedReader readerI = new BufferedReader(inI);
String lineI=readerI.readLine();
while(lineI!=null){
if(lineI.startsWith("InChI=")){
inputFileInChI = lineI.trim();
}
lineI=readerI.readLine();
}
}
catch(Exception e){
String err = "Error in reading preexisting MOPAC input file \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
if(inputFileInChI.equals(InChIaug)){
if(failureFlag==0){
System.out.println("Pre-existing successful MOPAC quantum result for " + name + " ("+InChIaug+") has been found. This log file will be used. *Note that input file was read to confirm lack of InChIKey collision (InChI probably more than 240 characters or characters probably deleted from InChI in .out file)");
return true;
}
else{//otherwise, failureFlag==1
System.out.println("Pre-existing MOPAC quantum result for " + name + " ("+InChIaug+") has been found, but the result was apparently unsuccessful. The file will be overwritten with a new calculation or Gaussian result (if available) will be used. *Note that input file was read to confirm lack of InChIKey collision (InChI probably more than 240 characters or characters probably deleted from InChI in .out file)");
return false;
}
}
else{
if(inputFileInChI.equals("")){//InChI was not found in input file
System.out.println("*****Warning: potential InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " Log file Augmented InChI = "+logFileInChI + " . InChI could not be found in the MOPAC input file. You should manually check that the output file contains the intended species.");
return true;
}
else{//InChI was found but doesn't match
System.out.println("Congratulations! You appear to have discovered the first recorded instance of an InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " MOPAC input file Augmented InChI = " + inputFileInChI + " Log file Augmented InChI = "+logFileInChI);
System.exit(0);
}
}
}
else{
System.out.println("*****Warning: potential InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " Log file Augmented InChI = "+logFileInChI + " . MOPAC input file could not be found to check full InChI. You should manually check that the log file contains the intended species.");
return true;
}
// }
// else{
// System.out.println("Congratulations! You appear to have discovered the first recorded instance of an InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " MOPAC output file Augmented InChI = "+logFileInChI);
// System.exit(0);
// }
}
else if (InChIFound==0){
System.out.println("An InChI was not found in file: " +name+".out");
System.exit(0);
}
else if (failureFlag==1){//note these should cover all possible results for this block, and if the file.exists block is entered, it should return from within the block and should not reach the return statement below
System.out.println("Pre-existing MOPAC quantum result for " + name + " ("+InChIaug+") has been found, but the result was apparently unsuccessful. The file will be overwritten with a new calculation or Gaussian result (if available) will be used.");
return false;
}
}
//we could print a line here for cases where the file doesn't exist, but this would probably be too verbose
return false;
}
//returns true if an MM4 output file for the given name and directory (.mm4out suffix) exists and indicates successful completion (same criteria as used after calculation runs); terminates if the InChI doesn't match the InChI in the file or if there is no InChI in the file; returns false otherwise
public boolean successfulMM4ResultExistsQ(String name, String directory, String InChIaug){
//part of the code is taken from analogous code for MOPAC (first ~half) and Gaussian (second ~half)
//look in the output file to check for the successful termination of the calculation (assumed to be successful if "description of vibrations appears)
int failureFlag=1;//flag (1 or 0) indicating whether the MM4 job failed
int failureOverrideFlag=0;//flag (1 or 0) to override success as measured by failureFlag
File file = new File(directory+"/"+name+".mm4out");
int InChIMatch=0;//flag (1 or 0) indicating whether the InChI in the file matches InChIaug; this can only be 1 if InChIFound is also 1;
int InChIFound=0;//flag (1 or 0) indicating whether an InChI was found in the log file
int InChIPartialMatch=0;//flag (1 or 0) indicating whether the InChI in the log file is a substring of the InChI in RMG's memory
if(file.exists()){//if the file exists, do further checks; otherwise, we will skip to final statement and return false
String logFileInChI="";
try{
FileReader in = new FileReader(file);
BufferedReader reader = new BufferedReader(in);
String line=reader.readLine();
while(line!=null){
String trimLine= line.trim();
if (trimLine.equals("STATISTICAL THERMODYNAMICS ANALYSIS")){
failureFlag = 0;
}
else if (trimLine.endsWith("imaginary frequencies,")){//read the number of imaginary frequencies and make sure it is zero
String[] split = trimLine.split("\\s+");
if (Integer.parseInt(split[3])>0){
System.out.println("*****Imaginary freqencies found:");
failureOverrideFlag=1;
}
}
else if (trimLine.contains(" 0.0 (fir )")){
if (useCanTherm){//zero frequencies are only acceptable when CanTherm is used
System.out.println("*****Warning: zero freqencies found (values lower than 7.7 cm^-1 are rounded to zero in MM4 output); CanTherm should hopefully correct this:");
}
else{
System.out.println("*****Zero freqencies found:");
failureOverrideFlag=1;
}
}
else if(trimLine.startsWith("InChI=")){
logFileInChI = line.trim();//output files should take up to about 60 (?) characters of the name in the input file
InChIFound=1;
if(logFileInChI.equals(InChIaug)) InChIMatch=1;
else if(InChIaug.startsWith(logFileInChI)) InChIPartialMatch=1;
}
line=reader.readLine();
}
}
catch(Exception e){
String err = "Error in reading preexisting MM4 output file \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
if(failureOverrideFlag==1) failureFlag=1; //job will be considered a failure if there are imaginary frequencies or if job terminates to to excess time/cycles
//if the failure flag is still 0, the process should have been successful
if (failureFlag==0&&InChIMatch==1){
System.out.println("Pre-existing successful MM4 result for " + name + " ("+InChIaug+") has been found. This log file will be used.");
return true;
}
else if (InChIFound==1 && InChIMatch == 0){//InChIs do not match (most likely due to limited name length mirrored in log file (79 characters), but possibly due to a collision)
if(InChIPartialMatch == 1){//case where the InChI in memory begins with the InChI in the log file; we will continue and check the input file, printing a warning if there is no match
File inputFile = new File(directory+"/"+name+".mm4");
if(inputFile.exists()){//read the MM4 inputFile
String inputFileInChI="";
try{
FileReader inI = new FileReader(inputFile);
BufferedReader readerI = new BufferedReader(inI);
String lineI=readerI.readLine();
//InChI should be repeated after in the first line of the input file
inputFileInChI = lineI.trim().substring(80);//extract the string starting with character 81
}
catch(Exception e){
String err = "Error in reading preexisting MM4 .mm4 file \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
if(inputFileInChI.equals(InChIaug)){
if(failureFlag==0){
System.out.println("Pre-existing successful MM4 result for " + name + " ("+InChIaug+") has been found. This log file will be used. *Note that input file was read to confirm lack of InChIKey collision (InChI probably more than ~60 characters)");
return true;
}
else{//otherwise, failureFlag==1
System.out.println("Pre-existing MM4 result for " + name + " ("+InChIaug+") has been found, but the result was apparently unsuccessful. The file will be overwritten with a new calculation. *Note that input file was read to confirm lack of InChIKey collision (InChI probably more than ~60 characters)");
return false;
}
}
else{
if(inputFileInChI.equals("")){//InChI was not found in input file
System.out.println("*****Warning: potential InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " Log file Augmented InChI = "+logFileInChI + " . InChI could not be found in the MM4 input file. You should manually check that the log file contains the intended species.");
return true;
}
else{//InChI was found but doesn't match
System.out.println("Congratulations! You appear to have discovered the first recorded instance of an InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " MM4 input file Augmented InChI = "+inputFileInChI);
System.exit(0);
}
}
}
else{
System.out.println("*****Warning: potential InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " Log file Augmented InChI = "+logFileInChI + " . MM4 input file could not be found to check full InChI. You should manually check that the log file contains the intended species.");
return true;
}
}
else{
System.out.println("Congratulations! You appear to have discovered the first recorded instance of an InChIKey collision: InChIKey(augmented) = " + name + " RMG Augmented InChI = "+ InChIaug + " Log file Augmented InChI = "+logFileInChI);
System.exit(0);
}
}
else if (InChIFound==0){
System.out.println("An InChI was not found in file: " +name+".mm4out");
System.exit(0);
}
else if (failureFlag==1){//note these should cover all possible results for this block, and if the file.exists block is entered, it should return from within the block and should not reach the return statement below
System.out.println("Pre-existing MM4 result for " + name + " ("+InChIaug+") has been found, but the result was apparently unsuccessful. The file will be overwritten with a new calculation.");
return false;
}
}
//we could print a line here for cases where the file doesn't exist, but this would probably be too verbose
return false;
}
// //checks the MOPAC file for negative frequencies
// public boolean MopacFileContainsNegativeFreqsQ(String name, String directory){
// boolean negativeFreq=false;
//
// //code below copied from parseMopacPM3()
// String command = "c:/Python25/python.exe c:/Python25/MopacPM3ParsingScript.py ";//this should eventually be modified for added generality
// String logfilepath=directory+"/"+name+".out";
// command=command.concat(logfilepath);
//
// //much of code below is copied from calculateThermoFromPM3Calc()
// //parse the Mopac file using cclib
// int natoms = 0; //number of atoms from Mopac file; in principle, this should agree with number of chemGraph atoms
// ArrayList atomicNumber = new ArrayList(); //vector of atomic numbers (integers) (apparently Vector is thread-safe; cf. http://answers.yahoo.com/question/index?qid=20081214065127AArZDT3; ...should I be using this instead?)
// ArrayList x_coor = new ArrayList(); //vectors of x-, y-, and z-coordinates (doubles) (Angstroms) (in order corresponding to above atomic numbers)
// ArrayList y_coor = new ArrayList();
// ArrayList z_coor = new ArrayList();
// double energy = 0; //PM3 energy (Hf298) in Hartree (***note: in the case of MOPAC, the MOPAC file will contain in units of kcal/mol, but modified ccLib will return in Hartree)
// double molmass = 0; //molecular mass in amu
// ArrayList freqs = new ArrayList(); //list of frequencies in units of cm^-1
// double rotCons_1 = 0;//rotational constants in (1/s)
// double rotCons_2 = 0;
// double rotCons_3 = 0;
// //int gdStateDegen = p_chemGraph.getRadicalNumber()+1;//calculate ground state degeneracy from the number of radicals; this should give the same result as spin multiplicity in Gaussian input file (and output file), but we do not explicitly check this (we could use "mult" which cclib reads in if we wanted to do so); also, note that this is not always correct, as there can apparently be additional spatial degeneracy for non-symmetric linear molecules like OH radical (cf. http://cccbdb.nist.gov/thermo.asp)
// try{
// File runningdir=new File(directory);
// Process cclibProc = Runtime.getRuntime().exec(command, null, runningdir);
// //read the stdout of the process, which should contain the desired information in a particular format
// InputStream is = cclibProc.getInputStream();
// InputStreamReader isr = new InputStreamReader(is);
// BufferedReader br = new BufferedReader(isr);
// String line=null;
// //example output:
//// C:\Python25>python.exe GaussianPM3ParsingScript.py TEOS.out
//// 33
//// [ 6 6 8 14 8 6 6 8 6 6 8 6 6 1 1 1 1 1 1 1 1 1 1 1 1
//// 1 1 1 1 1 1 1 1]
//// [[ 2.049061 -0.210375 3.133106]
//// [ 1.654646 0.321749 1.762752]
//// [ 0.359284 -0.110429 1.471465]
//// [-0.201871 -0.013365 -0.12819 ]
//// [ 0.086307 1.504918 -0.82893 ]
//// [-0.559186 2.619928 -0.284003]
//// [-0.180246 3.839463 -1.113029]
//// [ 0.523347 -1.188305 -1.112765]
//// [ 1.857584 -1.018167 -1.495088]
//// [ 2.375559 -2.344392 -2.033403]
//// [-1.870397 -0.297297 -0.075427]
//// [-2.313824 -1.571765 0.300245]
//// [-3.83427 -1.535927 0.372171]
//// [ 1.360346 0.128852 3.917699]
//// [ 2.053945 -1.307678 3.160474]
//// [ 3.055397 0.133647 3.403037]
//// [ 1.677262 1.430072 1.750899]
//// [ 2.372265 -0.029237 0.985204]
//// [-0.245956 2.754188 0.771433]
//// [-1.656897 2.472855 -0.287156]
//// [-0.664186 4.739148 -0.712606]
//// [-0.489413 3.734366 -2.161038]
//// [ 0.903055 4.016867 -1.112198]
//// [ 1.919521 -0.229395 -2.269681]
//// [ 2.474031 -0.680069 -0.629949]
//// [ 2.344478 -3.136247 -1.273862]
//// [ 1.786854 -2.695974 -2.890647]
//// [ 3.41648 -2.242409 -2.365094]
//// [-1.884889 -1.858617 1.28054 ]
//// [-1.976206 -2.322432 -0.440995]
//// [-4.284706 -1.26469 -0.591463]
//// [-4.225999 -2.520759 0.656131]
//// [-4.193468 -0.809557 1.112677]]
//// -14.1664924726
//// [ 9.9615 18.102 27.0569 31.8459 39.0096 55.0091
//// 66.4992 80.4552 86.4912 123.3551 141.6058 155.5448
//// 159.4747 167.0013 178.5676 207.3738 237.3201 255.3487
//// 264.5649 292.867 309.4248 344.6503 434.8231 470.2074
//// 488.9717 749.1722 834.257 834.6594 837.7292 839.6352
//// 887.9767 892.9538 899.5374 992.1851 1020.6164 1020.8671
//// 1028.3897 1046.7945 1049.1768 1059.4704 1065.1505 1107.4001
//// 1108.1567 1109.0466 1112.6677 1122.7785 1124.4315 1128.4163
//// 1153.3438 1167.6705 1170.9627 1174.9613 1232.1826 1331.8459
//// 1335.3932 1335.8677 1343.9556 1371.37 1372.8127 1375.5428
//// 1396.0344 1402.4082 1402.7554 1403.2463 1403.396 1411.6946
//// 1412.2456 1412.3519 1414.5982 1415.3613 1415.5698 1415.7993
//// 1418.5409 2870.7446 2905.3132 2907.0361 2914.1662 2949.2646
//// 2965.825 2967.7667 2971.5223 3086.3849 3086.3878 3086.6448
//// 3086.687 3089.2274 3089.4105 3089.4743 3089.5841 3186.0753
//// 3186.1375 3186.3511 3186.365 ]
//// [ 0.52729 0.49992 0.42466]
////note: above example has since been updated to print molecular mass; also frequency and atomic number format has been updated
// String [] stringArray;
// natoms = Integer.parseInt(br.readLine());//read line 1: number of atoms
// stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read line 2: the atomic numbers (first removing braces)
// // line = br.readLine().replace("[", "").replace("]","");//read line 2: the atomic numbers (first removing braces)
// // StringTokenizer st = new StringTokenizer(line); //apprently the stringTokenizer class is deprecated, but I am having trouble getting the regular expressions to work properly
// for(int i=0; i < natoms; i++){
// // atomicNumber.add(i,Integer.parseInt(stringArray[i]));
// atomicNumber.add(i,Integer.parseInt(stringArray[i]));
// }
// for(int i=0; i < natoms; i++){
// stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read line 3+: coordinates for atom i; used /s+ for split; using spaces with default limit of 0 was giving empty string
// x_coor.add(i,Double.parseDouble(stringArray[0]));
// y_coor.add(i,Double.parseDouble(stringArray[1]));
// z_coor.add(i,Double.parseDouble(stringArray[2]));
// }
// energy = Double.parseDouble(br.readLine());//read next line: energy
// molmass = Double.parseDouble(br.readLine());//read next line: molecular mass (in amu)
// if (natoms>1){//read additional info for non-monoatomic species
// stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read next line: frequencies
// for(int i=0; i < stringArray.length; i++){
// freqs.add(i,Double.parseDouble(stringArray[i]));
// }
// stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read next line rotational constants (converting from GHz to Hz in the process)
// rotCons_1 = Double.parseDouble(stringArray[0])*1000000000;
// rotCons_2 = Double.parseDouble(stringArray[1])*1000000000;
// rotCons_3 = Double.parseDouble(stringArray[2])*1000000000;
// }
// while ( (line = br.readLine()) != null) {
// //do nothing (there shouldn't be any more information, but this is included to get all the output)
// }
// int exitValue = cclibProc.waitFor();
// }
// catch (Exception e) {
// String err = "Error in running ccLib Python process \n";
// err += e.toString();
// e.printStackTrace();
// System.exit(0);
// }
//
// //start of code "new" to this function (aside from initialization of negativeFreq)
// if(natoms > 0){
// for (int i=0; i<freqs.size(); i++){
// if((Double)freqs.get(i) < 0) negativeFreq = true;
// }
// }
// return negativeFreq;
// }
//## operation initGAGroupLibrary()
protected void initGAGroupLibrary() {
//#[ operation initGAGroupLibrary()
thermoLibrary = ThermoGAGroupLibrary.getINSTANCE();
//#]
}
}
/*********************************************************************
File Path : RMG\RMG\jing\chem\QMTP.java
*********************************************************************/
| true | true | public ThermoData parseMM4withForceMat(String name, String directory, ChemGraph p_chemGraph){
//1. parse the MM4 file with cclib to get atomic number vector and geometry
String command = "python "+System.getProperty("RMG.workingDirectory")+"/scripts/MM4ParsingScript.py ";
String logfilepath=directory+"/"+name+".mm4out";
command=command.concat(logfilepath);
command=command.concat(" "+ System.getenv("RMG")+"/source");//this will pass $RMG/source to the script (in order to get the appropriate path for importing
///////////beginning of block taken from the bulk of getPM3MM4ThermoDataUsingCCLib////////////
//parse the file using cclib
int natoms = 0; //number of atoms from Mopac file; in principle, this should agree with number of chemGraph atoms
ArrayList atomicNumber = new ArrayList(); //vector of atomic numbers (integers) (apparently Vector is thread-safe; cf. http://answers.yahoo.com/question/index?qid=20081214065127AArZDT3; ...should I be using this instead?)
ArrayList x_coor = new ArrayList(); //vectors of x-, y-, and z-coordinates (doubles) (Angstroms) (in order corresponding to above atomic numbers)
ArrayList y_coor = new ArrayList();
ArrayList z_coor = new ArrayList();
double energy = 0; // energy (Hf298) in Hartree
double molmass = 0; //molecular mass in amu
ArrayList freqs = new ArrayList(); //list of frequencies in units of cm^-1
double rotCons_1 = 0;//rotational constants in (1/s)
double rotCons_2 = 0;
double rotCons_3 = 0;
int gdStateDegen = p_chemGraph.getRadicalNumber()+1;//calculate ground state degeneracy from the number of radicals; this should give the same result as spin multiplicity in Gaussian input file (and output file), but we do not explicitly check this (we could use "mult" which cclib reads in if we wanted to do so); also, note that this is not always correct, as there can apparently be additional spatial degeneracy for non-symmetric linear molecules like OH radical (cf. http://cccbdb.nist.gov/thermo.asp)
try{
Process cclibProc = Runtime.getRuntime().exec(command);
//read the stdout of the process, which should contain the desired information in a particular format
InputStream is = cclibProc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
//example output:
// C:\Python25>python.exe GaussianPM3ParsingScript.py TEOS.out
// 33
// [ 6 6 8 14 8 6 6 8 6 6 8 6 6 1 1 1 1 1 1 1 1 1 1 1 1
// 1 1 1 1 1 1 1 1]
// [[ 2.049061 -0.210375 3.133106]
// [ 1.654646 0.321749 1.762752]
// [ 0.359284 -0.110429 1.471465]
// [-0.201871 -0.013365 -0.12819 ]
// [ 0.086307 1.504918 -0.82893 ]
// [-0.559186 2.619928 -0.284003]
// [-0.180246 3.839463 -1.113029]
// [ 0.523347 -1.188305 -1.112765]
// [ 1.857584 -1.018167 -1.495088]
// [ 2.375559 -2.344392 -2.033403]
// [-1.870397 -0.297297 -0.075427]
// [-2.313824 -1.571765 0.300245]
// [-3.83427 -1.535927 0.372171]
// [ 1.360346 0.128852 3.917699]
// [ 2.053945 -1.307678 3.160474]
// [ 3.055397 0.133647 3.403037]
// [ 1.677262 1.430072 1.750899]
// [ 2.372265 -0.029237 0.985204]
// [-0.245956 2.754188 0.771433]
// [-1.656897 2.472855 -0.287156]
// [-0.664186 4.739148 -0.712606]
// [-0.489413 3.734366 -2.161038]
// [ 0.903055 4.016867 -1.112198]
// [ 1.919521 -0.229395 -2.269681]
// [ 2.474031 -0.680069 -0.629949]
// [ 2.344478 -3.136247 -1.273862]
// [ 1.786854 -2.695974 -2.890647]
// [ 3.41648 -2.242409 -2.365094]
// [-1.884889 -1.858617 1.28054 ]
// [-1.976206 -2.322432 -0.440995]
// [-4.284706 -1.26469 -0.591463]
// [-4.225999 -2.520759 0.656131]
// [-4.193468 -0.809557 1.112677]]
// -14.1664924726
// [ 9.9615 18.102 27.0569 31.8459 39.0096 55.0091
// 66.4992 80.4552 86.4912 123.3551 141.6058 155.5448
// 159.4747 167.0013 178.5676 207.3738 237.3201 255.3487
// 264.5649 292.867 309.4248 344.6503 434.8231 470.2074
// 488.9717 749.1722 834.257 834.6594 837.7292 839.6352
// 887.9767 892.9538 899.5374 992.1851 1020.6164 1020.8671
// 1028.3897 1046.7945 1049.1768 1059.4704 1065.1505 1107.4001
// 1108.1567 1109.0466 1112.6677 1122.7785 1124.4315 1128.4163
// 1153.3438 1167.6705 1170.9627 1174.9613 1232.1826 1331.8459
// 1335.3932 1335.8677 1343.9556 1371.37 1372.8127 1375.5428
// 1396.0344 1402.4082 1402.7554 1403.2463 1403.396 1411.6946
// 1412.2456 1412.3519 1414.5982 1415.3613 1415.5698 1415.7993
// 1418.5409 2870.7446 2905.3132 2907.0361 2914.1662 2949.2646
// 2965.825 2967.7667 2971.5223 3086.3849 3086.3878 3086.6448
// 3086.687 3089.2274 3089.4105 3089.4743 3089.5841 3186.0753
// 3186.1375 3186.3511 3186.365 ]
// [ 0.52729 0.49992 0.42466]
//note: above example has since been updated to print molecular mass; also frequency and atomic number format has been updated
String [] stringArray;
natoms = Integer.parseInt(br.readLine());//read line 1: number of atoms
stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read line 2: the atomic numbers (first removing braces)
// line = br.readLine().replace("[", "").replace("]","");//read line 2: the atomic numbers (first removing braces)
// StringTokenizer st = new StringTokenizer(line); //apprently the stringTokenizer class is deprecated, but I am having trouble getting the regular expressions to work properly
for(int i=0; i < natoms; i++){
// atomicNumber.add(i,Integer.parseInt(stringArray[i]));
atomicNumber.add(i,Integer.parseInt(stringArray[i]));
}
for(int i=0; i < natoms; i++){
stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read line 3+: coordinates for atom i; used /s+ for split; using spaces with default limit of 0 was giving empty string
x_coor.add(i,Double.parseDouble(stringArray[0]));
y_coor.add(i,Double.parseDouble(stringArray[1]));
z_coor.add(i,Double.parseDouble(stringArray[2]));
}
energy = Double.parseDouble(br.readLine());//read next line: energy
molmass = Double.parseDouble(br.readLine());//read next line: molecular mass (in amu)
if (natoms>1){//read additional info for non-monoatomic species
stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read next line: frequencies
for(int i=0; i < stringArray.length; i++){
freqs.add(i,Double.parseDouble(stringArray[i]));
}
stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read next line rotational constants (converting from GHz to Hz in the process)
rotCons_1 = Double.parseDouble(stringArray[0])*1000000000;
rotCons_2 = Double.parseDouble(stringArray[1])*1000000000;
rotCons_3 = Double.parseDouble(stringArray[2])*1000000000;
}
while ( (line = br.readLine()) != null) {
//do nothing (there shouldn't be any more information, but this is included to get all the output)
}
int exitValue = cclibProc.waitFor();
}
catch (Exception e) {
String err = "Error in running ccLib Python process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
///////////end of block taken from the bulk of getPM3MM4ThermoDataUsingCCLib////////////
//2. compute H0; note that we will pass H0 to CanTherm by H0=H298(harmonicMM4)-(H298-H0)harmonicMM4, where harmonicMM4 values come from cclib parsing and since it is enthalpy, it should not be NaN due to zero frequencies
double Hartree_to_kcal = 627.5095; //conversion from Hartree to kcal/mol taken from Gaussian thermo white paper
energy *= Hartree_to_kcal;//convert from Hartree to kcal/mol
//*** to be written
//3. write CanTherm input file
String canInp = "Calculation: Thermo\n";
canInp += "Trange 300 100 13\n";//temperatures from 300 to 1500 in increments of 100
canInp += "Scale: 1.0\n";//scale factor of 1
canInp += "Mol 1\n";
if(p_chemGraph.getAtomNumber()==1) canInp += "ATOM\n";
else if (p_chemGraph.isLinear()) canInp+="LINEAR\n";
else canInp+="NONLINEAR\n";
canInp += "GEOM MM4File " + name+".mm4out\n";//geometry file; ***special MM4 treatment in CanTherm; another option would be to use mm4opt file, but CanTherm code would need to be modified accordingly
canInp += "FORCEC MM4File "+name+".fmat\n";//force constant file; ***special MM4 treatment in CanTherm
canInp += "ENERGY "+ energy +" MM4\n";//***special MM4 treatment in CanTherm
canInp+="EXTSYM 1\n";//use external symmetry of 1; it will be corrected for below
canInp+="NELEC 1\n";//multiplicity = 1; all cases we consider will be non-radicals
if(!useHindRot) canInp += "ROTORS 0\n";//do not consider hindered rotors
else{
//this section still needs to be written
canInp+="";
}
try{
File canFile=new File(directory+"/"+name+".can");
FileWriter fw = new FileWriter(canFile);
fw.write(canInp);
fw.close();
}
catch(Exception e){
String err = "Error in writing CanTherm input \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//4 and 5. call CanTherm and read in output
Double Hf298 = null;
Double S298 = null;
Double Cp300 = null;
Double Cp400 = null;
Double Cp500 = null;
Double Cp600 = null;
Double Cp800 = null;
Double Cp1000 = null;
Double Cp1500 = null;
try{
File runningDirectory = new File(qmfolder);
String canCommand="python " + System.getenv("RMG")+"/source/CanTherm/source/CanTherm.py "+name+".can";
Process canProc = Runtime.getRuntime().exec(canCommand, null, runningDirectory);
InputStream is = canProc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
if(line.startsWith("reading Geometry from the file")){
String[] split = br.readLine().trim().split("\\s+");
Hf298 = Double.parseDouble(split[0]);
S298 = Double.parseDouble(split[1]);
Cp300 = Double.parseDouble(split[2]);
Cp400 = Double.parseDouble(split[3]);
Cp500 = Double.parseDouble(split[4]);
Cp600 = Double.parseDouble(split[5]);
Cp800 = Double.parseDouble(split[7]);
Cp1000 = Double.parseDouble(split[9]);
Cp1500 = Double.parseDouble(split[14]);
}
}
int exitValue = canProc.waitFor();
}
catch(Exception e){
String err = "Error in running CanTherm process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//6. correct the output for symmetry number (everything has been assumed to be one) : useHindRot=true case: use ChemGraph symmetry number; otherwise, we use SYMMETRY
if(!useHindRot){
double R = 1.9872; //ideal gas constant in cal/mol-K (does this appear elsewhere in RMG, so I don't need to reuse it?)
//determine point group using the SYMMETRY Program
String geom = natoms + "\n";
for(int i=0; i < natoms; i++){
geom += atomicNumber.get(i) + " "+ x_coor.get(i) + " " + y_coor.get(i) + " " +z_coor.get(i) + "\n";
}
String pointGroup = determinePointGroupUsingSYMMETRYProgram(geom);
double sigmaCorr = getSigmaCorr(pointGroup);
S298+= R*sigmaCorr;
}
else{
//***to be written
}
ThermoData result = new ThermoData(Hf298,S298,Cp300,Cp400,Cp500,Cp600,Cp800,Cp1000,Cp1500,3,1,1,"MM4 calculation; includes CanTherm analysis of force-constant matrix");//this includes rough estimates of uncertainty
System.out.println("Thermo for " + name + ": "+ result.toString());//print result, at least for debugging purposes
return result;
}
| public ThermoData parseMM4withForceMat(String name, String directory, ChemGraph p_chemGraph){
//1. parse the MM4 file with cclib to get atomic number vector and geometry
String command = "python "+System.getProperty("RMG.workingDirectory")+"/scripts/MM4ParsingScript.py ";
String logfilepath=directory+"/"+name+".mm4out";
command=command.concat(logfilepath);
command=command.concat(" "+ System.getenv("RMG")+"/source");//this will pass $RMG/source to the script (in order to get the appropriate path for importing
///////////beginning of block taken from the bulk of getPM3MM4ThermoDataUsingCCLib////////////
//parse the file using cclib
int natoms = 0; //number of atoms from Mopac file; in principle, this should agree with number of chemGraph atoms
ArrayList atomicNumber = new ArrayList(); //vector of atomic numbers (integers) (apparently Vector is thread-safe; cf. http://answers.yahoo.com/question/index?qid=20081214065127AArZDT3; ...should I be using this instead?)
ArrayList x_coor = new ArrayList(); //vectors of x-, y-, and z-coordinates (doubles) (Angstroms) (in order corresponding to above atomic numbers)
ArrayList y_coor = new ArrayList();
ArrayList z_coor = new ArrayList();
double energy = 0; // energy (Hf298) in Hartree
double molmass = 0; //molecular mass in amu
ArrayList freqs = new ArrayList(); //list of frequencies in units of cm^-1
double rotCons_1 = 0;//rotational constants in (1/s)
double rotCons_2 = 0;
double rotCons_3 = 0;
int gdStateDegen = p_chemGraph.getRadicalNumber()+1;//calculate ground state degeneracy from the number of radicals; this should give the same result as spin multiplicity in Gaussian input file (and output file), but we do not explicitly check this (we could use "mult" which cclib reads in if we wanted to do so); also, note that this is not always correct, as there can apparently be additional spatial degeneracy for non-symmetric linear molecules like OH radical (cf. http://cccbdb.nist.gov/thermo.asp)
try{
Process cclibProc = Runtime.getRuntime().exec(command);
//read the stdout of the process, which should contain the desired information in a particular format
InputStream is = cclibProc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
//example output:
// C:\Python25>python.exe GaussianPM3ParsingScript.py TEOS.out
// 33
// [ 6 6 8 14 8 6 6 8 6 6 8 6 6 1 1 1 1 1 1 1 1 1 1 1 1
// 1 1 1 1 1 1 1 1]
// [[ 2.049061 -0.210375 3.133106]
// [ 1.654646 0.321749 1.762752]
// [ 0.359284 -0.110429 1.471465]
// [-0.201871 -0.013365 -0.12819 ]
// [ 0.086307 1.504918 -0.82893 ]
// [-0.559186 2.619928 -0.284003]
// [-0.180246 3.839463 -1.113029]
// [ 0.523347 -1.188305 -1.112765]
// [ 1.857584 -1.018167 -1.495088]
// [ 2.375559 -2.344392 -2.033403]
// [-1.870397 -0.297297 -0.075427]
// [-2.313824 -1.571765 0.300245]
// [-3.83427 -1.535927 0.372171]
// [ 1.360346 0.128852 3.917699]
// [ 2.053945 -1.307678 3.160474]
// [ 3.055397 0.133647 3.403037]
// [ 1.677262 1.430072 1.750899]
// [ 2.372265 -0.029237 0.985204]
// [-0.245956 2.754188 0.771433]
// [-1.656897 2.472855 -0.287156]
// [-0.664186 4.739148 -0.712606]
// [-0.489413 3.734366 -2.161038]
// [ 0.903055 4.016867 -1.112198]
// [ 1.919521 -0.229395 -2.269681]
// [ 2.474031 -0.680069 -0.629949]
// [ 2.344478 -3.136247 -1.273862]
// [ 1.786854 -2.695974 -2.890647]
// [ 3.41648 -2.242409 -2.365094]
// [-1.884889 -1.858617 1.28054 ]
// [-1.976206 -2.322432 -0.440995]
// [-4.284706 -1.26469 -0.591463]
// [-4.225999 -2.520759 0.656131]
// [-4.193468 -0.809557 1.112677]]
// -14.1664924726
// [ 9.9615 18.102 27.0569 31.8459 39.0096 55.0091
// 66.4992 80.4552 86.4912 123.3551 141.6058 155.5448
// 159.4747 167.0013 178.5676 207.3738 237.3201 255.3487
// 264.5649 292.867 309.4248 344.6503 434.8231 470.2074
// 488.9717 749.1722 834.257 834.6594 837.7292 839.6352
// 887.9767 892.9538 899.5374 992.1851 1020.6164 1020.8671
// 1028.3897 1046.7945 1049.1768 1059.4704 1065.1505 1107.4001
// 1108.1567 1109.0466 1112.6677 1122.7785 1124.4315 1128.4163
// 1153.3438 1167.6705 1170.9627 1174.9613 1232.1826 1331.8459
// 1335.3932 1335.8677 1343.9556 1371.37 1372.8127 1375.5428
// 1396.0344 1402.4082 1402.7554 1403.2463 1403.396 1411.6946
// 1412.2456 1412.3519 1414.5982 1415.3613 1415.5698 1415.7993
// 1418.5409 2870.7446 2905.3132 2907.0361 2914.1662 2949.2646
// 2965.825 2967.7667 2971.5223 3086.3849 3086.3878 3086.6448
// 3086.687 3089.2274 3089.4105 3089.4743 3089.5841 3186.0753
// 3186.1375 3186.3511 3186.365 ]
// [ 0.52729 0.49992 0.42466]
//note: above example has since been updated to print molecular mass; also frequency and atomic number format has been updated
String [] stringArray;
natoms = Integer.parseInt(br.readLine());//read line 1: number of atoms
stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read line 2: the atomic numbers (first removing braces)
// line = br.readLine().replace("[", "").replace("]","");//read line 2: the atomic numbers (first removing braces)
// StringTokenizer st = new StringTokenizer(line); //apprently the stringTokenizer class is deprecated, but I am having trouble getting the regular expressions to work properly
for(int i=0; i < natoms; i++){
// atomicNumber.add(i,Integer.parseInt(stringArray[i]));
atomicNumber.add(i,Integer.parseInt(stringArray[i]));
}
for(int i=0; i < natoms; i++){
stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read line 3+: coordinates for atom i; used /s+ for split; using spaces with default limit of 0 was giving empty string
x_coor.add(i,Double.parseDouble(stringArray[0]));
y_coor.add(i,Double.parseDouble(stringArray[1]));
z_coor.add(i,Double.parseDouble(stringArray[2]));
}
energy = Double.parseDouble(br.readLine());//read next line: energy
molmass = Double.parseDouble(br.readLine());//read next line: molecular mass (in amu)
if (natoms>1){//read additional info for non-monoatomic species
stringArray = br.readLine().replace("[", "").replace("]","").trim().split(",\\s+");//read next line: frequencies
for(int i=0; i < stringArray.length; i++){
freqs.add(i,Double.parseDouble(stringArray[i]));
}
stringArray = br.readLine().replace("[", "").replace("]","").trim().split("\\s+");//read next line rotational constants (converting from GHz to Hz in the process)
rotCons_1 = Double.parseDouble(stringArray[0])*1000000000;
rotCons_2 = Double.parseDouble(stringArray[1])*1000000000;
rotCons_3 = Double.parseDouble(stringArray[2])*1000000000;
}
while ( (line = br.readLine()) != null) {
//do nothing (there shouldn't be any more information, but this is included to get all the output)
}
int exitValue = cclibProc.waitFor();
}
catch (Exception e) {
String err = "Error in running ccLib Python process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
///////////end of block taken from the bulk of getPM3MM4ThermoDataUsingCCLib////////////
//2. compute H0; note that we will pass H0 to CanTherm by H0=H298(harmonicMM4)-(H298-H0)harmonicMM4, where harmonicMM4 values come from cclib parsing and since it is enthalpy, it should not be NaN due to zero frequencies
double Hartree_to_kcal = 627.5095; //conversion from Hartree to kcal/mol taken from Gaussian thermo white paper
energy *= Hartree_to_kcal;//convert from Hartree to kcal/mol
//*** to be written
//3. write CanTherm input file
String canInp = "Calculation: Thermo\n";
canInp += "Trange: 300 100 13\n";//temperatures from 300 to 1500 in increments of 100
canInp += "Scale: 1.0\n";//scale factor of 1
canInp += "Mol 1\n";
if(p_chemGraph.getAtomNumber()==1) canInp += "ATOM\n";
else if (p_chemGraph.isLinear()) canInp+="LINEAR\n";
else canInp+="NONLINEAR\n";
canInp += "GEOM MM4File " + name+".mm4out\n";//geometry file; ***special MM4 treatment in CanTherm; another option would be to use mm4opt file, but CanTherm code would need to be modified accordingly
canInp += "FORCEC MM4File "+name+".fmat\n";//force constant file; ***special MM4 treatment in CanTherm
canInp += "ENERGY "+ energy +" MM4\n";//***special MM4 treatment in CanTherm
canInp+="EXTSYM 1\n";//use external symmetry of 1; it will be corrected for below
canInp+="NELEC 1\n";//multiplicity = 1; all cases we consider will be non-radicals
if(!useHindRot) canInp += "ROTORS 0\n";//do not consider hindered rotors
else{
//this section still needs to be written
canInp+="";
}
try{
File canFile=new File(directory+"/"+name+".can");
FileWriter fw = new FileWriter(canFile);
fw.write(canInp);
fw.close();
}
catch(Exception e){
String err = "Error in writing CanTherm input \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//4 and 5. call CanTherm and read in output
Double Hf298 = null;
Double S298 = null;
Double Cp300 = null;
Double Cp400 = null;
Double Cp500 = null;
Double Cp600 = null;
Double Cp800 = null;
Double Cp1000 = null;
Double Cp1500 = null;
try{
File runningDirectory = new File(qmfolder);
String canCommand="python " + System.getenv("RMG")+"/source/CanTherm/source/CanTherm.py "+name+".can";
Process canProc = Runtime.getRuntime().exec(canCommand, null, runningDirectory);
InputStream is = canProc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
if(line.startsWith("reading Geometry from the file")){
String[] split = br.readLine().trim().split("\\s+");
Hf298 = Double.parseDouble(split[0]);
S298 = Double.parseDouble(split[1]);
Cp300 = Double.parseDouble(split[2]);
Cp400 = Double.parseDouble(split[3]);
Cp500 = Double.parseDouble(split[4]);
Cp600 = Double.parseDouble(split[5]);
Cp800 = Double.parseDouble(split[7]);
Cp1000 = Double.parseDouble(split[9]);
Cp1500 = Double.parseDouble(split[14]);
}
}
int exitValue = canProc.waitFor();
}
catch(Exception e){
String err = "Error in running CanTherm process \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//6. correct the output for symmetry number (everything has been assumed to be one) : useHindRot=true case: use ChemGraph symmetry number; otherwise, we use SYMMETRY
if(!useHindRot){
double R = 1.9872; //ideal gas constant in cal/mol-K (does this appear elsewhere in RMG, so I don't need to reuse it?)
//determine point group using the SYMMETRY Program
String geom = natoms + "\n";
for(int i=0; i < natoms; i++){
geom += atomicNumber.get(i) + " "+ x_coor.get(i) + " " + y_coor.get(i) + " " +z_coor.get(i) + "\n";
}
String pointGroup = determinePointGroupUsingSYMMETRYProgram(geom);
double sigmaCorr = getSigmaCorr(pointGroup);
S298+= R*sigmaCorr;
}
else{
//***to be written
}
ThermoData result = new ThermoData(Hf298,S298,Cp300,Cp400,Cp500,Cp600,Cp800,Cp1000,Cp1500,3,1,1,"MM4 calculation; includes CanTherm analysis of force-constant matrix");//this includes rough estimates of uncertainty
System.out.println("Thermo for " + name + ": "+ result.toString());//print result, at least for debugging purposes
return result;
}
|
diff --git a/cmds/monkey/src/com/android/commands/monkey/Monkey.java b/cmds/monkey/src/com/android/commands/monkey/Monkey.java
index 43103236..bb0663fd 100644
--- a/cmds/monkey/src/com/android/commands/monkey/Monkey.java
+++ b/cmds/monkey/src/com/android/commands/monkey/Monkey.java
@@ -1,992 +1,992 @@
/*
* Copyright 2007, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.commands.monkey;
import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.IActivityController;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.IPackageManager;
import android.content.pm.ResolveInfo;
import android.os.Debug;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.server.data.CrashData;
import android.view.IWindowManager;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
/**
* Application that injects random key events and other actions into the system.
*/
public class Monkey {
/**
* Monkey Debugging/Dev Support
* <p>
* All values should be zero when checking in.
*/
private final static int DEBUG_ALLOW_ANY_STARTS = 0;
private final static int DEBUG_ALLOW_ANY_RESTARTS = 0;
private IActivityManager mAm;
private IWindowManager mWm;
private IPackageManager mPm;
/** Command line arguments */
private String[] mArgs;
/** Current argument being parsed */
private int mNextArg;
/** Data of current argument */
private String mCurArgData;
/** Running in verbose output mode? 1= verbose, 2=very verbose */
private int mVerbose;
/** Ignore any application crashes while running? */
private boolean mIgnoreCrashes;
/** Ignore any not responding timeouts while running? */
private boolean mIgnoreTimeouts;
/** Ignore security exceptions when launching activities */
/** (The activity launch still fails, but we keep pluggin' away) */
private boolean mIgnoreSecurityExceptions;
/** Monitor /data/tombstones and stop the monkey if new files appear. */
private boolean mMonitorNativeCrashes;
/** Send no events. Use with long throttle-time to watch user operations */
private boolean mSendNoEvents;
/** This is set when we would like to abort the running of the monkey. */
private boolean mAbort;
/**
* Count each event as a cycle. Set to false for scripts so that each time
* through the script increments the count.
*/
private boolean mCountEvents = true;
/**
* This is set by the ActivityController thread to request collection of ANR
* trace files
*/
private boolean mRequestAnrTraces = false;
/**
* This is set by the ActivityController thread to request a
* "dumpsys meminfo"
*/
private boolean mRequestDumpsysMemInfo = false;
/** Kill the process after a timeout or crash. */
private boolean mKillProcessAfterError;
/** Generate hprof reports before/after monkey runs */
private boolean mGenerateHprof;
/** Packages we are allowed to run, or empty if no restriction. */
private HashSet<String> mValidPackages = new HashSet<String>();
/** Categories we are allowed to launch **/
private ArrayList<String> mMainCategories = new ArrayList<String>();
/** Applications we can switch to. */
private ArrayList<ComponentName> mMainApps = new ArrayList<ComponentName>();
/** The delay between event inputs **/
long mThrottle = 0;
/** The number of iterations **/
int mCount = 1000;
/** The random number seed **/
long mSeed = 0;
/** Dropped-event statistics **/
long mDroppedKeyEvents = 0;
long mDroppedPointerEvents = 0;
long mDroppedTrackballEvents = 0;
long mDroppedFlipEvents = 0;
/** a filename to the setup script (if any) */
private String mSetupFileName = null;
/** filenames of the script (if any) */
private ArrayList<String> mScriptFileNames = new ArrayList<String>();
/** a TCP port to listen on for remote commands. */
private int mServerPort = -1;
private static final File TOMBSTONES_PATH = new File("/data/tombstones");
private HashSet<String> mTombstones = null;
float[] mFactors = new float[MonkeySourceRandom.FACTORZ_COUNT];
MonkeyEventSource mEventSource;
private MonkeyNetworkMonitor mNetworkMonitor = new MonkeyNetworkMonitor();
// information on the current activity.
public static Intent currentIntent;
public static String currentPackage;
/**
* Monitor operations happening in the system.
*/
private class ActivityController extends IActivityController.Stub {
public boolean activityStarting(Intent intent, String pkg) {
boolean allow = checkEnteringPackage(pkg) || (DEBUG_ALLOW_ANY_STARTS != 0);
if (mVerbose > 0) {
System.out.println(" // " + (allow ? "Allowing" : "Rejecting") + " start of "
+ intent + " in package " + pkg);
}
currentPackage = pkg;
currentIntent = intent;
return allow;
}
public boolean activityResuming(String pkg) {
System.out.println(" // activityResuming(" + pkg + ")");
boolean allow = checkEnteringPackage(pkg) || (DEBUG_ALLOW_ANY_RESTARTS != 0);
if (!allow) {
if (mVerbose > 0) {
System.out.println(" // " + (allow ? "Allowing" : "Rejecting")
+ " resume of package " + pkg);
}
}
currentPackage = pkg;
return allow;
}
private boolean checkEnteringPackage(String pkg) {
if (pkg == null) {
return true;
}
// preflight the hash lookup to avoid the cost of hash key
// generation
if (mValidPackages.size() == 0) {
return true;
} else {
return mValidPackages.contains(pkg);
}
}
public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg,
byte[] crashData) {
System.err.println("// CRASH: " + processName + " (pid " + pid + ")");
System.err.println("// Short Msg: " + shortMsg);
System.err.println("// Long Msg: " + longMsg);
if (crashData != null) {
try {
CrashData cd = new CrashData(new DataInputStream(new ByteArrayInputStream(
crashData)));
System.err.println("// Build Label: " + cd.getBuildData().getFingerprint());
System.err.println("// Build Changelist: "
+ cd.getBuildData().getIncrementalVersion());
System.err.println("// Build Time: " + cd.getBuildData().getTime());
System.err.println("// ID: " + cd.getId());
System.err.println("// Tag: " + cd.getActivity());
System.err.println(cd.getThrowableData().toString("// "));
} catch (IOException e) {
System.err.println("// BAD STACK CRAWL");
}
}
if (!mIgnoreCrashes) {
synchronized (Monkey.this) {
mAbort = true;
}
return !mKillProcessAfterError;
}
return false;
}
public int appNotResponding(String processName, int pid, String processStats) {
System.err.println("// NOT RESPONDING: " + processName + " (pid " + pid + ")");
System.err.println(processStats);
reportProcRank();
synchronized (Monkey.this) {
mRequestAnrTraces = true;
mRequestDumpsysMemInfo = true;
}
if (!mIgnoreTimeouts) {
synchronized (Monkey.this) {
mAbort = true;
}
return (mKillProcessAfterError) ? -1 : 1;
}
return 1;
}
}
/**
* Run the procrank tool to insert system status information into the debug
* report.
*/
private void reportProcRank() {
commandLineReport("procrank", "procrank");
}
/**
* Run "cat /data/anr/traces.txt". Wait about 5 seconds first, to let the
* asynchronous report writing complete.
*/
private void reportAnrTraces() {
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
}
commandLineReport("anr traces", "cat /data/anr/traces.txt");
}
/**
* Run "dumpsys meminfo"
* <p>
* NOTE: You cannot perform a dumpsys call from the ActivityController
* callback, as it will deadlock. This should only be called from the main
* loop of the monkey.
*/
private void reportDumpsysMemInfo() {
commandLineReport("meminfo", "dumpsys meminfo");
}
/**
* Print report from a single command line.
* <p>
* TODO: Use ProcessBuilder & redirectErrorStream(true) to capture both
* streams (might be important for some command lines)
*
* @param reportName Simple tag that will print before the report and in
* various annotations.
* @param command Command line to execute.
*/
private void commandLineReport(String reportName, String command) {
System.err.println(reportName + ":");
Runtime rt = Runtime.getRuntime();
try {
// Process must be fully qualified here because android.os.Process
// is used elsewhere
java.lang.Process p = Runtime.getRuntime().exec(command);
// pipe everything from process stdout -> System.err
InputStream inStream = p.getInputStream();
InputStreamReader inReader = new InputStreamReader(inStream);
BufferedReader inBuffer = new BufferedReader(inReader);
String s;
while ((s = inBuffer.readLine()) != null) {
System.err.println(s);
}
int status = p.waitFor();
System.err.println("// " + reportName + " status was " + status);
} catch (Exception e) {
System.err.println("// Exception from " + reportName + ":");
System.err.println(e.toString());
}
}
/**
* Command-line entry point.
*
* @param args The command-line arguments
*/
public static void main(String[] args) {
int resultCode = (new Monkey()).run(args);
System.exit(resultCode);
}
/**
* Run the command!
*
* @param args The command-line arguments
* @return Returns a posix-style result code. 0 for no error.
*/
private int run(String[] args) {
// Super-early debugger wait
for (String s : args) {
if ("--wait-dbg".equals(s)) {
Debug.waitForDebugger();
}
}
// Default values for some command-line options
mVerbose = 0;
mCount = 1000;
mSeed = 0;
mThrottle = 0;
// prepare for command-line processing
mArgs = args;
mNextArg = 0;
// set a positive value, indicating none of the factors is provided yet
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
mFactors[i] = 1.0f;
}
if (!processOptions()) {
return -1;
}
// now set up additional data in preparation for launch
if (mMainCategories.size() == 0) {
mMainCategories.add(Intent.CATEGORY_LAUNCHER);
mMainCategories.add(Intent.CATEGORY_MONKEY);
}
if (mVerbose > 0) {
System.out.println(":Monkey: seed=" + mSeed + " count=" + mCount);
if (mValidPackages.size() > 0) {
Iterator<String> it = mValidPackages.iterator();
while (it.hasNext()) {
System.out.println(":AllowPackage: " + it.next());
}
}
if (mMainCategories.size() != 0) {
Iterator<String> it = mMainCategories.iterator();
while (it.hasNext()) {
System.out.println(":IncludeCategory: " + it.next());
}
}
}
if (!checkInternalConfiguration()) {
return -2;
}
if (!getSystemInterfaces()) {
return -3;
}
if (!getMainApps()) {
return -4;
}
if (mScriptFileNames != null && mScriptFileNames.size() == 1) {
// script mode, ignore other options
mEventSource = new MonkeySourceScript(mScriptFileNames.get(0), mThrottle);
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
- } else if (mScriptFileNames != null) {
+ } else if (mScriptFileNames != null && mScriptFileNames.size() > 1) {
if (mSetupFileName != null) {
mEventSource = new MonkeySourceRandomScript(mSetupFileName, mScriptFileNames,
mThrottle, mSeed);
mCount++;
} else {
mEventSource = new MonkeySourceRandomScript(mScriptFileNames, mThrottle, mSeed);
}
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mServerPort != -1) {
try {
mEventSource = new MonkeySourceNetwork(mServerPort);
} catch (IOException e) {
System.out.println("Error binding to network socket.");
return -5;
}
mCount = Integer.MAX_VALUE;
} else {
// random source by default
if (mVerbose >= 2) { // check seeding performance
System.out.println("// Seeded: " + mSeed);
}
mEventSource = new MonkeySourceRandom(mSeed, mMainApps, mThrottle);
mEventSource.setVerbose(mVerbose);
// set any of the factors that has been set
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
if (mFactors[i] <= 0.0f) {
((MonkeySourceRandom) mEventSource).setFactors(i, mFactors[i]);
}
}
// in random mode, we start with a random activity
((MonkeySourceRandom) mEventSource).generateActivity();
}
// validate source generator
if (!mEventSource.validate()) {
return -5;
}
// If we're profiling, do it immediately before/after the main monkey
// loop
if (mGenerateHprof) {
signalPersistentProcesses();
}
mNetworkMonitor.start();
int crashedAtCycle = runMonkeyCycles();
mNetworkMonitor.stop();
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
}
if (mGenerateHprof) {
signalPersistentProcesses();
if (mVerbose > 0) {
System.out.println("// Generated profiling reports in /data/misc");
}
}
try {
mAm.setActivityController(null);
mNetworkMonitor.unregister(mAm);
} catch (RemoteException e) {
// just in case this was latent (after mCount cycles), make sure
// we report it
if (crashedAtCycle >= mCount) {
crashedAtCycle = mCount - 1;
}
}
// report dropped event stats
if (mVerbose > 0) {
System.out.print(":Dropped: keys=");
System.out.print(mDroppedKeyEvents);
System.out.print(" pointers=");
System.out.print(mDroppedPointerEvents);
System.out.print(" trackballs=");
System.out.print(mDroppedTrackballEvents);
System.out.print(" flips=");
System.out.println(mDroppedFlipEvents);
}
// report network stats
mNetworkMonitor.dump();
if (crashedAtCycle < mCount - 1) {
System.err.println("** System appears to have crashed at event " + crashedAtCycle
+ " of " + mCount + " using seed " + mSeed);
return crashedAtCycle;
} else {
if (mVerbose > 0) {
System.out.println("// Monkey finished");
}
return 0;
}
}
/**
* Process the command-line options
*
* @return Returns true if options were parsed with no apparent errors.
*/
private boolean processOptions() {
// quick (throwaway) check for unadorned command
if (mArgs.length < 1) {
showUsage();
return false;
}
try {
String opt;
while ((opt = nextOption()) != null) {
if (opt.equals("-s")) {
mSeed = nextOptionLong("Seed");
} else if (opt.equals("-p")) {
mValidPackages.add(nextOptionData());
} else if (opt.equals("-c")) {
mMainCategories.add(nextOptionData());
} else if (opt.equals("-v")) {
mVerbose += 1;
} else if (opt.equals("--ignore-crashes")) {
mIgnoreCrashes = true;
} else if (opt.equals("--ignore-timeouts")) {
mIgnoreTimeouts = true;
} else if (opt.equals("--ignore-security-exceptions")) {
mIgnoreSecurityExceptions = true;
} else if (opt.equals("--monitor-native-crashes")) {
mMonitorNativeCrashes = true;
} else if (opt.equals("--kill-process-after-error")) {
mKillProcessAfterError = true;
} else if (opt.equals("--hprof")) {
mGenerateHprof = true;
} else if (opt.equals("--pct-touch")) {
int i = MonkeySourceRandom.FACTOR_TOUCH;
mFactors[i] = -nextOptionLong("touch events percentage");
} else if (opt.equals("--pct-motion")) {
int i = MonkeySourceRandom.FACTOR_MOTION;
mFactors[i] = -nextOptionLong("motion events percentage");
} else if (opt.equals("--pct-trackball")) {
int i = MonkeySourceRandom.FACTOR_TRACKBALL;
mFactors[i] = -nextOptionLong("trackball events percentage");
} else if (opt.equals("--pct-nav")) {
int i = MonkeySourceRandom.FACTOR_NAV;
mFactors[i] = -nextOptionLong("nav events percentage");
} else if (opt.equals("--pct-majornav")) {
int i = MonkeySourceRandom.FACTOR_MAJORNAV;
mFactors[i] = -nextOptionLong("major nav events percentage");
} else if (opt.equals("--pct-appswitch")) {
int i = MonkeySourceRandom.FACTOR_APPSWITCH;
mFactors[i] = -nextOptionLong("app switch events percentage");
} else if (opt.equals("--pct-flip")) {
int i = MonkeySourceRandom.FACTOR_FLIP;
mFactors[i] = -nextOptionLong("keyboard flip percentage");
} else if (opt.equals("--pct-anyevent")) {
int i = MonkeySourceRandom.FACTOR_ANYTHING;
mFactors[i] = -nextOptionLong("any events percentage");
} else if (opt.equals("--throttle")) {
mThrottle = nextOptionLong("delay (in milliseconds) to wait between events");
} else if (opt.equals("--wait-dbg")) {
// do nothing - it's caught at the very start of run()
} else if (opt.equals("--dbg-no-events")) {
mSendNoEvents = true;
} else if (opt.equals("--port")) {
mServerPort = (int) nextOptionLong("Server port to listen on for commands");
} else if (opt.equals("--setup")) {
mSetupFileName = nextOptionData();
} else if (opt.equals("-f")) {
mScriptFileNames.add(nextOptionData());
} else if (opt.equals("-h")) {
showUsage();
return false;
} else {
System.err.println("** Error: Unknown option: " + opt);
showUsage();
return false;
}
}
} catch (RuntimeException ex) {
System.err.println("** Error: " + ex.toString());
showUsage();
return false;
}
// If a server port hasn't been specified, we need to specify
// a count
if (mServerPort == -1) {
String countStr = nextArg();
if (countStr == null) {
System.err.println("** Error: Count not specified");
showUsage();
return false;
}
try {
mCount = Integer.parseInt(countStr);
} catch (NumberFormatException e) {
System.err.println("** Error: Count is not a number");
showUsage();
return false;
}
}
return true;
}
/**
* Check for any internal configuration (primarily build-time) errors.
*
* @return Returns true if ready to rock.
*/
private boolean checkInternalConfiguration() {
// Check KEYCODE name array, make sure it's up to date.
String lastKeyName = null;
try {
lastKeyName = MonkeySourceRandom.getLastKeyName();
} catch (RuntimeException e) {
}
if (!"TAG_LAST_KEYCODE".equals(lastKeyName)) {
System.err.println("** Error: Key names array malformed (internal error).");
return false;
}
return true;
}
/**
* Attach to the required system interfaces.
*
* @return Returns true if all system interfaces were available.
*/
private boolean getSystemInterfaces() {
mAm = ActivityManagerNative.getDefault();
if (mAm == null) {
System.err.println("** Error: Unable to connect to activity manager; is the system "
+ "running?");
return false;
}
mWm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
if (mWm == null) {
System.err.println("** Error: Unable to connect to window manager; is the system "
+ "running?");
return false;
}
mPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
if (mPm == null) {
System.err.println("** Error: Unable to connect to package manager; is the system "
+ "running?");
return false;
}
try {
mAm.setActivityController(new ActivityController());
mNetworkMonitor.register(mAm);
} catch (RemoteException e) {
System.err.println("** Failed talking with activity manager!");
return false;
}
return true;
}
/**
* Using the restrictions provided (categories & packages), generate a list
* of activities that we can actually switch to.
*
* @return Returns true if it could successfully build a list of target
* activities
*/
private boolean getMainApps() {
try {
final int N = mMainCategories.size();
for (int i = 0; i < N; i++) {
Intent intent = new Intent(Intent.ACTION_MAIN);
String category = mMainCategories.get(i);
if (category.length() > 0) {
intent.addCategory(category);
}
List<ResolveInfo> mainApps = mPm.queryIntentActivities(intent, null, 0);
if (mainApps == null || mainApps.size() == 0) {
System.err.println("// Warning: no activities found for category " + category);
continue;
}
if (mVerbose >= 2) { // very verbose
System.out.println("// Selecting main activities from category " + category);
}
final int NA = mainApps.size();
for (int a = 0; a < NA; a++) {
ResolveInfo r = mainApps.get(a);
if (mValidPackages.size() == 0
|| mValidPackages.contains(r.activityInfo.applicationInfo.packageName)) {
if (mVerbose >= 2) { // very verbose
System.out.println("// + Using main activity " + r.activityInfo.name
+ " (from package "
+ r.activityInfo.applicationInfo.packageName + ")");
}
mMainApps.add(new ComponentName(r.activityInfo.applicationInfo.packageName,
r.activityInfo.name));
} else {
if (mVerbose >= 3) { // very very verbose
System.out.println("// - NOT USING main activity "
+ r.activityInfo.name + " (from package "
+ r.activityInfo.applicationInfo.packageName + ")");
}
}
}
}
} catch (RemoteException e) {
System.err.println("** Failed talking with package manager!");
return false;
}
if (mMainApps.size() == 0) {
System.out.println("** No activities found to run, monkey aborted.");
return false;
}
return true;
}
/**
* Run mCount cycles and see if we hit any crashers.
* <p>
* TODO: Meta state on keys
*
* @return Returns the last cycle which executed. If the value == mCount, no
* errors detected.
*/
private int runMonkeyCycles() {
int eventCounter = 0;
int cycleCounter = 0;
boolean systemCrashed = false;
while (!systemCrashed && cycleCounter < mCount) {
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
if (mMonitorNativeCrashes) {
// first time through, when eventCounter == 0, just set up
// the watcher (ignore the error)
if (checkNativeCrashes() && (eventCounter > 0)) {
System.out.println("** New native crash detected.");
mAbort = mAbort || mKillProcessAfterError;
}
}
if (mAbort) {
System.out.println("** Monkey aborted due to error.");
System.out.println("Events injected: " + eventCounter);
return eventCounter;
}
}
// In this debugging mode, we never send any events. This is
// primarily here so you can manually test the package or category
// limits, while manually exercising the system.
if (mSendNoEvents) {
eventCounter++;
cycleCounter++;
continue;
}
if ((mVerbose > 0) && (eventCounter % 100) == 0 && eventCounter != 0) {
System.out.println(" // Sending event #" + eventCounter);
}
MonkeyEvent ev = mEventSource.getNextEvent();
if (ev != null) {
int injectCode = ev.injectEvent(mWm, mAm, mVerbose);
if (injectCode == MonkeyEvent.INJECT_FAIL) {
if (ev instanceof MonkeyKeyEvent) {
mDroppedKeyEvents++;
} else if (ev instanceof MonkeyMotionEvent) {
mDroppedPointerEvents++;
} else if (ev instanceof MonkeyFlipEvent) {
mDroppedFlipEvents++;
}
} else if (injectCode == MonkeyEvent.INJECT_ERROR_REMOTE_EXCEPTION) {
systemCrashed = true;
} else if (injectCode == MonkeyEvent.INJECT_ERROR_SECURITY_EXCEPTION) {
systemCrashed = !mIgnoreSecurityExceptions;
}
// Don't count throttling as an event.
if (!(ev instanceof MonkeyThrottleEvent)) {
eventCounter++;
if (mCountEvents) {
cycleCounter++;
}
}
} else {
if (!mCountEvents) {
cycleCounter++;
} else {
break;
}
}
}
// If we got this far, we succeeded!
return eventCounter;
}
/**
* Send SIGNAL_USR1 to all processes. This will generate large (5mb)
* profiling reports in data/misc, so use with care.
*/
private void signalPersistentProcesses() {
try {
mAm.signalPersistentProcesses(Process.SIGNAL_USR1);
synchronized (this) {
wait(2000);
}
} catch (RemoteException e) {
System.err.println("** Failed talking with activity manager!");
} catch (InterruptedException e) {
}
}
/**
* Watch for appearance of new tombstone files, which indicate native
* crashes.
*
* @return Returns true if new files have appeared in the list
*/
private boolean checkNativeCrashes() {
String[] tombstones = TOMBSTONES_PATH.list();
// shortcut path for usually empty directory, so we don't waste even
// more objects
if ((tombstones == null) || (tombstones.length == 0)) {
mTombstones = null;
return false;
}
// use set logic to look for new files
HashSet<String> newStones = new HashSet<String>();
for (String x : tombstones) {
newStones.add(x);
}
boolean result = (mTombstones == null) || !mTombstones.containsAll(newStones);
// keep the new list for the next time
mTombstones = newStones;
return result;
}
/**
* Return the next command line option. This has a number of special cases
* which closely, but not exactly, follow the POSIX command line options
* patterns:
*
* <pre>
* -- means to stop processing additional options
* -z means option z
* -z ARGS means option z with (non-optional) arguments ARGS
* -zARGS means option z with (optional) arguments ARGS
* --zz means option zz
* --zz ARGS means option zz with (non-optional) arguments ARGS
* </pre>
*
* Note that you cannot combine single letter options; -abc != -a -b -c
*
* @return Returns the option string, or null if there are no more options.
*/
private String nextOption() {
if (mNextArg >= mArgs.length) {
return null;
}
String arg = mArgs[mNextArg];
if (!arg.startsWith("-")) {
return null;
}
mNextArg++;
if (arg.equals("--")) {
return null;
}
if (arg.length() > 1 && arg.charAt(1) != '-') {
if (arg.length() > 2) {
mCurArgData = arg.substring(2);
return arg.substring(0, 2);
} else {
mCurArgData = null;
return arg;
}
}
mCurArgData = null;
return arg;
}
/**
* Return the next data associated with the current option.
*
* @return Returns the data string, or null of there are no more arguments.
*/
private String nextOptionData() {
if (mCurArgData != null) {
return mCurArgData;
}
if (mNextArg >= mArgs.length) {
return null;
}
String data = mArgs[mNextArg];
mNextArg++;
return data;
}
/**
* Returns a long converted from the next data argument, with error handling
* if not available.
*
* @param opt The name of the option.
* @return Returns a long converted from the argument.
*/
private long nextOptionLong(final String opt) {
long result;
try {
result = Long.parseLong(nextOptionData());
} catch (NumberFormatException e) {
System.err.println("** Error: " + opt + " is not a number");
throw e;
}
return result;
}
/**
* Return the next argument on the command line.
*
* @return Returns the argument string, or null if we have reached the end.
*/
private String nextArg() {
if (mNextArg >= mArgs.length) {
return null;
}
String arg = mArgs[mNextArg];
mNextArg++;
return arg;
}
/**
* Print how to use this command.
*/
private void showUsage() {
StringBuffer usage = new StringBuffer();
usage.append("usage: monkey [-p ALLOWED_PACKAGE [-p ALLOWED_PACKAGE] ...]\n");
usage.append(" [-c MAIN_CATEGORY [-c MAIN_CATEGORY] ...]\n");
usage.append(" [--ignore-crashes] [--ignore-timeouts]\n");
usage.append(" [--ignore-security-exceptions] [--monitor-native-crashes]\n");
usage.append(" [--kill-process-after-error] [--hprof]\n");
usage.append(" [--pct-touch PERCENT] [--pct-motion PERCENT]\n");
usage.append(" [--pct-trackball PERCENT] [--pct-syskeys PERCENT]\n");
usage.append(" [--pct-nav PERCENT] [--pct-majornav PERCENT]\n");
usage.append(" [--pct-appswitch PERCENT] [--pct-flip PERCENT]\n");
usage.append(" [--pct-anyevent PERCENT]\n");
usage.append(" [--wait-dbg] [--dbg-no-events]\n");
usage.append(" [--setup scriptfile] [-f scriptfile [-f scriptfile] ...]\n");
usage.append(" [--port port]\n");
usage.append(" [-s SEED] [-v [-v] ...] [--throttle MILLISEC]\n");
usage.append(" COUNT");
System.err.println(usage.toString());
}
}
| true | true | private int run(String[] args) {
// Super-early debugger wait
for (String s : args) {
if ("--wait-dbg".equals(s)) {
Debug.waitForDebugger();
}
}
// Default values for some command-line options
mVerbose = 0;
mCount = 1000;
mSeed = 0;
mThrottle = 0;
// prepare for command-line processing
mArgs = args;
mNextArg = 0;
// set a positive value, indicating none of the factors is provided yet
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
mFactors[i] = 1.0f;
}
if (!processOptions()) {
return -1;
}
// now set up additional data in preparation for launch
if (mMainCategories.size() == 0) {
mMainCategories.add(Intent.CATEGORY_LAUNCHER);
mMainCategories.add(Intent.CATEGORY_MONKEY);
}
if (mVerbose > 0) {
System.out.println(":Monkey: seed=" + mSeed + " count=" + mCount);
if (mValidPackages.size() > 0) {
Iterator<String> it = mValidPackages.iterator();
while (it.hasNext()) {
System.out.println(":AllowPackage: " + it.next());
}
}
if (mMainCategories.size() != 0) {
Iterator<String> it = mMainCategories.iterator();
while (it.hasNext()) {
System.out.println(":IncludeCategory: " + it.next());
}
}
}
if (!checkInternalConfiguration()) {
return -2;
}
if (!getSystemInterfaces()) {
return -3;
}
if (!getMainApps()) {
return -4;
}
if (mScriptFileNames != null && mScriptFileNames.size() == 1) {
// script mode, ignore other options
mEventSource = new MonkeySourceScript(mScriptFileNames.get(0), mThrottle);
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mScriptFileNames != null) {
if (mSetupFileName != null) {
mEventSource = new MonkeySourceRandomScript(mSetupFileName, mScriptFileNames,
mThrottle, mSeed);
mCount++;
} else {
mEventSource = new MonkeySourceRandomScript(mScriptFileNames, mThrottle, mSeed);
}
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mServerPort != -1) {
try {
mEventSource = new MonkeySourceNetwork(mServerPort);
} catch (IOException e) {
System.out.println("Error binding to network socket.");
return -5;
}
mCount = Integer.MAX_VALUE;
} else {
// random source by default
if (mVerbose >= 2) { // check seeding performance
System.out.println("// Seeded: " + mSeed);
}
mEventSource = new MonkeySourceRandom(mSeed, mMainApps, mThrottle);
mEventSource.setVerbose(mVerbose);
// set any of the factors that has been set
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
if (mFactors[i] <= 0.0f) {
((MonkeySourceRandom) mEventSource).setFactors(i, mFactors[i]);
}
}
// in random mode, we start with a random activity
((MonkeySourceRandom) mEventSource).generateActivity();
}
// validate source generator
if (!mEventSource.validate()) {
return -5;
}
// If we're profiling, do it immediately before/after the main monkey
// loop
if (mGenerateHprof) {
signalPersistentProcesses();
}
mNetworkMonitor.start();
int crashedAtCycle = runMonkeyCycles();
mNetworkMonitor.stop();
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
}
if (mGenerateHprof) {
signalPersistentProcesses();
if (mVerbose > 0) {
System.out.println("// Generated profiling reports in /data/misc");
}
}
try {
mAm.setActivityController(null);
mNetworkMonitor.unregister(mAm);
} catch (RemoteException e) {
// just in case this was latent (after mCount cycles), make sure
// we report it
if (crashedAtCycle >= mCount) {
crashedAtCycle = mCount - 1;
}
}
// report dropped event stats
if (mVerbose > 0) {
System.out.print(":Dropped: keys=");
System.out.print(mDroppedKeyEvents);
System.out.print(" pointers=");
System.out.print(mDroppedPointerEvents);
System.out.print(" trackballs=");
System.out.print(mDroppedTrackballEvents);
System.out.print(" flips=");
System.out.println(mDroppedFlipEvents);
}
// report network stats
mNetworkMonitor.dump();
if (crashedAtCycle < mCount - 1) {
System.err.println("** System appears to have crashed at event " + crashedAtCycle
+ " of " + mCount + " using seed " + mSeed);
return crashedAtCycle;
} else {
if (mVerbose > 0) {
System.out.println("// Monkey finished");
}
return 0;
}
}
| private int run(String[] args) {
// Super-early debugger wait
for (String s : args) {
if ("--wait-dbg".equals(s)) {
Debug.waitForDebugger();
}
}
// Default values for some command-line options
mVerbose = 0;
mCount = 1000;
mSeed = 0;
mThrottle = 0;
// prepare for command-line processing
mArgs = args;
mNextArg = 0;
// set a positive value, indicating none of the factors is provided yet
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
mFactors[i] = 1.0f;
}
if (!processOptions()) {
return -1;
}
// now set up additional data in preparation for launch
if (mMainCategories.size() == 0) {
mMainCategories.add(Intent.CATEGORY_LAUNCHER);
mMainCategories.add(Intent.CATEGORY_MONKEY);
}
if (mVerbose > 0) {
System.out.println(":Monkey: seed=" + mSeed + " count=" + mCount);
if (mValidPackages.size() > 0) {
Iterator<String> it = mValidPackages.iterator();
while (it.hasNext()) {
System.out.println(":AllowPackage: " + it.next());
}
}
if (mMainCategories.size() != 0) {
Iterator<String> it = mMainCategories.iterator();
while (it.hasNext()) {
System.out.println(":IncludeCategory: " + it.next());
}
}
}
if (!checkInternalConfiguration()) {
return -2;
}
if (!getSystemInterfaces()) {
return -3;
}
if (!getMainApps()) {
return -4;
}
if (mScriptFileNames != null && mScriptFileNames.size() == 1) {
// script mode, ignore other options
mEventSource = new MonkeySourceScript(mScriptFileNames.get(0), mThrottle);
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mScriptFileNames != null && mScriptFileNames.size() > 1) {
if (mSetupFileName != null) {
mEventSource = new MonkeySourceRandomScript(mSetupFileName, mScriptFileNames,
mThrottle, mSeed);
mCount++;
} else {
mEventSource = new MonkeySourceRandomScript(mScriptFileNames, mThrottle, mSeed);
}
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mServerPort != -1) {
try {
mEventSource = new MonkeySourceNetwork(mServerPort);
} catch (IOException e) {
System.out.println("Error binding to network socket.");
return -5;
}
mCount = Integer.MAX_VALUE;
} else {
// random source by default
if (mVerbose >= 2) { // check seeding performance
System.out.println("// Seeded: " + mSeed);
}
mEventSource = new MonkeySourceRandom(mSeed, mMainApps, mThrottle);
mEventSource.setVerbose(mVerbose);
// set any of the factors that has been set
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
if (mFactors[i] <= 0.0f) {
((MonkeySourceRandom) mEventSource).setFactors(i, mFactors[i]);
}
}
// in random mode, we start with a random activity
((MonkeySourceRandom) mEventSource).generateActivity();
}
// validate source generator
if (!mEventSource.validate()) {
return -5;
}
// If we're profiling, do it immediately before/after the main monkey
// loop
if (mGenerateHprof) {
signalPersistentProcesses();
}
mNetworkMonitor.start();
int crashedAtCycle = runMonkeyCycles();
mNetworkMonitor.stop();
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
}
if (mGenerateHprof) {
signalPersistentProcesses();
if (mVerbose > 0) {
System.out.println("// Generated profiling reports in /data/misc");
}
}
try {
mAm.setActivityController(null);
mNetworkMonitor.unregister(mAm);
} catch (RemoteException e) {
// just in case this was latent (after mCount cycles), make sure
// we report it
if (crashedAtCycle >= mCount) {
crashedAtCycle = mCount - 1;
}
}
// report dropped event stats
if (mVerbose > 0) {
System.out.print(":Dropped: keys=");
System.out.print(mDroppedKeyEvents);
System.out.print(" pointers=");
System.out.print(mDroppedPointerEvents);
System.out.print(" trackballs=");
System.out.print(mDroppedTrackballEvents);
System.out.print(" flips=");
System.out.println(mDroppedFlipEvents);
}
// report network stats
mNetworkMonitor.dump();
if (crashedAtCycle < mCount - 1) {
System.err.println("** System appears to have crashed at event " + crashedAtCycle
+ " of " + mCount + " using seed " + mSeed);
return crashedAtCycle;
} else {
if (mVerbose > 0) {
System.out.println("// Monkey finished");
}
return 0;
}
}
|
diff --git a/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/listeners/flag/UseFlagListener.java b/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/listeners/flag/UseFlagListener.java
index 5271392b..ffb292ca 100644
--- a/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/listeners/flag/UseFlagListener.java
+++ b/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/listeners/flag/UseFlagListener.java
@@ -1,101 +1,105 @@
/***************************************************************************
* Project file: NPlugins - NCuboid - UseFlagListener.java *
* Full Class name: fr.ribesg.bukkit.ncuboid.listeners.flag.UseFlagListener*
* *
* Copyright (c) 2013 Ribesg - www.ribesg.fr *
* This file is under GPLv3 -> http://www.gnu.org/licenses/gpl-3.0.txt *
* Please contact me at ribesg[at]yahoo.fr if you improve this file! *
***************************************************************************/
package fr.ribesg.bukkit.ncuboid.listeners.flag;
import fr.ribesg.bukkit.ncuboid.NCuboid;
import fr.ribesg.bukkit.ncuboid.beans.Flag;
import fr.ribesg.bukkit.ncuboid.events.extensions.ExtendedPlayerInteractEntityEvent;
import fr.ribesg.bukkit.ncuboid.events.extensions.ExtendedPlayerInteractEvent;
import fr.ribesg.bukkit.ncuboid.listeners.AbstractListener;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import java.util.HashSet;
import java.util.Set;
public class UseFlagListener extends AbstractListener {
private static Set<EntityType> denyUseEntities;
private static Set<Material> denyUseMaterials;
private static Set<EntityType> getDenyUseEntity() {
if (denyUseEntities == null) {
denyUseEntities = new HashSet<>();
denyUseEntities.add(EntityType.BOAT);
denyUseEntities.add(EntityType.ITEM_FRAME);
denyUseEntities.add(EntityType.MINECART);
denyUseEntities.add(EntityType.MINECART_FURNACE);
}
return denyUseEntities;
}
private static Set<Material> getDenyUseMaterials() {
if (denyUseMaterials == null) {
denyUseMaterials = new HashSet<>();
denyUseMaterials.add(Material.ANVIL);
denyUseMaterials.add(Material.BED_BLOCK);
denyUseMaterials.add(Material.CAKE_BLOCK);
denyUseMaterials.add(Material.CAULDRON);
denyUseMaterials.add(Material.DRAGON_EGG);
denyUseMaterials.add(Material.ENCHANTMENT_TABLE);
denyUseMaterials.add(Material.ENDER_CHEST);
denyUseMaterials.add(Material.ENDER_PORTAL_FRAME);
denyUseMaterials.add(Material.FENCE_GATE);
denyUseMaterials.add(Material.FLOWER_POT);
denyUseMaterials.add(Material.GLOWING_REDSTONE_ORE);
+ denyUseMaterials.add(Material.GOLD_PLATE);
+ denyUseMaterials.add(Material.IRON_PLATE);
denyUseMaterials.add(Material.JUKEBOX);
denyUseMaterials.add(Material.LEVER);
denyUseMaterials.add(Material.NOTE_BLOCK);
denyUseMaterials.add(Material.REDSTONE_ORE);
denyUseMaterials.add(Material.SIGN_POST);
denyUseMaterials.add(Material.SOIL);
denyUseMaterials.add(Material.STONE_BUTTON);
+ denyUseMaterials.add(Material.STONE_PLATE);
denyUseMaterials.add(Material.TRAP_DOOR);
denyUseMaterials.add(Material.WALL_SIGN);
denyUseMaterials.add(Material.WOOD_BUTTON);
denyUseMaterials.add(Material.WOOD_DOOR);
+ denyUseMaterials.add(Material.WOOD_PLATE);
denyUseMaterials.add(Material.WOODEN_DOOR);
denyUseMaterials.add(Material.WORKBENCH);
}
return denyUseMaterials;
}
public UseFlagListener(final NCuboid instance) {
super(instance);
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerInteract(final ExtendedPlayerInteractEvent ext) {
final PlayerInteractEvent event = (PlayerInteractEvent) ext.getBaseEvent();
if (event.hasBlock()) {
if (ext.getRegion() != null &&
ext.getRegion().getFlag(Flag.USE) &&
!ext.getRegion().isUser(event.getPlayer()) &&
getDenyUseMaterials().contains(event.getClickedBlock().getType())) {
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerInteractEntity(final ExtendedPlayerInteractEntityEvent ext) {
final PlayerInteractEntityEvent event = (PlayerInteractEntityEvent) ext.getBaseEvent();
if (ext.getRegion() != null &&
ext.getRegion().getFlag(Flag.USE) &&
!ext.getRegion().isUser(event.getPlayer()) &&
getDenyUseEntity().contains(event.getRightClicked().getType())) {
event.setCancelled(true);
}
}
}
| false | true | private static Set<Material> getDenyUseMaterials() {
if (denyUseMaterials == null) {
denyUseMaterials = new HashSet<>();
denyUseMaterials.add(Material.ANVIL);
denyUseMaterials.add(Material.BED_BLOCK);
denyUseMaterials.add(Material.CAKE_BLOCK);
denyUseMaterials.add(Material.CAULDRON);
denyUseMaterials.add(Material.DRAGON_EGG);
denyUseMaterials.add(Material.ENCHANTMENT_TABLE);
denyUseMaterials.add(Material.ENDER_CHEST);
denyUseMaterials.add(Material.ENDER_PORTAL_FRAME);
denyUseMaterials.add(Material.FENCE_GATE);
denyUseMaterials.add(Material.FLOWER_POT);
denyUseMaterials.add(Material.GLOWING_REDSTONE_ORE);
denyUseMaterials.add(Material.JUKEBOX);
denyUseMaterials.add(Material.LEVER);
denyUseMaterials.add(Material.NOTE_BLOCK);
denyUseMaterials.add(Material.REDSTONE_ORE);
denyUseMaterials.add(Material.SIGN_POST);
denyUseMaterials.add(Material.SOIL);
denyUseMaterials.add(Material.STONE_BUTTON);
denyUseMaterials.add(Material.TRAP_DOOR);
denyUseMaterials.add(Material.WALL_SIGN);
denyUseMaterials.add(Material.WOOD_BUTTON);
denyUseMaterials.add(Material.WOOD_DOOR);
denyUseMaterials.add(Material.WOODEN_DOOR);
denyUseMaterials.add(Material.WORKBENCH);
}
return denyUseMaterials;
}
| private static Set<Material> getDenyUseMaterials() {
if (denyUseMaterials == null) {
denyUseMaterials = new HashSet<>();
denyUseMaterials.add(Material.ANVIL);
denyUseMaterials.add(Material.BED_BLOCK);
denyUseMaterials.add(Material.CAKE_BLOCK);
denyUseMaterials.add(Material.CAULDRON);
denyUseMaterials.add(Material.DRAGON_EGG);
denyUseMaterials.add(Material.ENCHANTMENT_TABLE);
denyUseMaterials.add(Material.ENDER_CHEST);
denyUseMaterials.add(Material.ENDER_PORTAL_FRAME);
denyUseMaterials.add(Material.FENCE_GATE);
denyUseMaterials.add(Material.FLOWER_POT);
denyUseMaterials.add(Material.GLOWING_REDSTONE_ORE);
denyUseMaterials.add(Material.GOLD_PLATE);
denyUseMaterials.add(Material.IRON_PLATE);
denyUseMaterials.add(Material.JUKEBOX);
denyUseMaterials.add(Material.LEVER);
denyUseMaterials.add(Material.NOTE_BLOCK);
denyUseMaterials.add(Material.REDSTONE_ORE);
denyUseMaterials.add(Material.SIGN_POST);
denyUseMaterials.add(Material.SOIL);
denyUseMaterials.add(Material.STONE_BUTTON);
denyUseMaterials.add(Material.STONE_PLATE);
denyUseMaterials.add(Material.TRAP_DOOR);
denyUseMaterials.add(Material.WALL_SIGN);
denyUseMaterials.add(Material.WOOD_BUTTON);
denyUseMaterials.add(Material.WOOD_DOOR);
denyUseMaterials.add(Material.WOOD_PLATE);
denyUseMaterials.add(Material.WOODEN_DOOR);
denyUseMaterials.add(Material.WORKBENCH);
}
return denyUseMaterials;
}
|
diff --git a/src/org/joval/net/Ip4Address.java b/src/org/joval/net/Ip4Address.java
index f1f0a7e4..eeb91b53 100755
--- a/src/org/joval/net/Ip4Address.java
+++ b/src/org/joval/net/Ip4Address.java
@@ -1,84 +1,88 @@
// Copyright (C) 2012 jOVAL.org. All rights reserved.
// This software is licensed under the AGPL 3.0 license available at http://www.joval.org/agpl_v3.txt
package org.joval.net;
import java.util.StringTokenizer;
import org.joval.intf.net.ICIDR;
/**
* A utility class for dealing with individual addresses or CIDR ranges for IPv4.
*
* @author David A. Solin
* @version %I% %G%
*/
public class Ip4Address implements ICIDR<Ip4Address> {
private short[] addr = new short[4];
private short[] mask = new short[4];
private int maskVal;
public Ip4Address(String str) throws IllegalArgumentException {
int ptr = str.indexOf("/");
maskVal = 32;
String ipStr = null;
if (ptr == -1) {
ipStr = str;
} else {
maskVal = Integer.parseInt(str.substring(ptr+1));
ipStr = str.substring(0, ptr);
}
//
// Create the netmask
//
short[] maskBits = new short[32];
for (int i=0; i < 32; i++) {
if (i < maskVal) {
maskBits[i] = 1;
} else {
maskBits[i] = 0;
}
}
for (int i=0; i < 4; i++) {
- mask[i] = (short)(maskBits[8*i + 1] * 8 +
- maskBits[8*i + 2] * 4 +
- maskBits[8*i + 3] * 2 +
- maskBits[8*i + 4]);
+ mask[i] = (short)(maskBits[8*i + 0] * 128 +
+ maskBits[8*i + 1] * 64 +
+ maskBits[8*i + 2] * 32 +
+ maskBits[8*i + 3] * 16 +
+ maskBits[8*i + 4] * 8 +
+ maskBits[8*i + 5] * 4 +
+ maskBits[8*i + 6] * 2 +
+ maskBits[8*i + 7]);
}
StringTokenizer tok = new StringTokenizer(ipStr, ".");
int numTokens = tok.countTokens();
if (numTokens > 4) {
throw new IllegalArgumentException(str);
}
for (int i=0; i < 4 - numTokens; i++) {
addr[i] = 0;
}
for (int i = 4 - tok.countTokens(); tok.hasMoreTokens(); i++) {
addr[i] = (short)(Short.parseShort(tok.nextToken()) & mask[i]);
}
}
public String toString() {
StringBuffer sb = new StringBuffer();
for (int i=0; i < 4; i++) {
if (i > 0) {
sb.append(".");
}
sb.append(Short.toString(addr[i]));
}
return sb.append("/").append(Integer.toString(maskVal)).toString();
}
// Implement ICIDR
public boolean contains(Ip4Address other) {
for (int i=0; i < 4; i++) {
if (addr[i] != (other.addr[i] & mask[i])) {
return false;
}
}
return true;
}
}
| true | true | public Ip4Address(String str) throws IllegalArgumentException {
int ptr = str.indexOf("/");
maskVal = 32;
String ipStr = null;
if (ptr == -1) {
ipStr = str;
} else {
maskVal = Integer.parseInt(str.substring(ptr+1));
ipStr = str.substring(0, ptr);
}
//
// Create the netmask
//
short[] maskBits = new short[32];
for (int i=0; i < 32; i++) {
if (i < maskVal) {
maskBits[i] = 1;
} else {
maskBits[i] = 0;
}
}
for (int i=0; i < 4; i++) {
mask[i] = (short)(maskBits[8*i + 1] * 8 +
maskBits[8*i + 2] * 4 +
maskBits[8*i + 3] * 2 +
maskBits[8*i + 4]);
}
StringTokenizer tok = new StringTokenizer(ipStr, ".");
int numTokens = tok.countTokens();
if (numTokens > 4) {
throw new IllegalArgumentException(str);
}
for (int i=0; i < 4 - numTokens; i++) {
addr[i] = 0;
}
for (int i = 4 - tok.countTokens(); tok.hasMoreTokens(); i++) {
addr[i] = (short)(Short.parseShort(tok.nextToken()) & mask[i]);
}
}
| public Ip4Address(String str) throws IllegalArgumentException {
int ptr = str.indexOf("/");
maskVal = 32;
String ipStr = null;
if (ptr == -1) {
ipStr = str;
} else {
maskVal = Integer.parseInt(str.substring(ptr+1));
ipStr = str.substring(0, ptr);
}
//
// Create the netmask
//
short[] maskBits = new short[32];
for (int i=0; i < 32; i++) {
if (i < maskVal) {
maskBits[i] = 1;
} else {
maskBits[i] = 0;
}
}
for (int i=0; i < 4; i++) {
mask[i] = (short)(maskBits[8*i + 0] * 128 +
maskBits[8*i + 1] * 64 +
maskBits[8*i + 2] * 32 +
maskBits[8*i + 3] * 16 +
maskBits[8*i + 4] * 8 +
maskBits[8*i + 5] * 4 +
maskBits[8*i + 6] * 2 +
maskBits[8*i + 7]);
}
StringTokenizer tok = new StringTokenizer(ipStr, ".");
int numTokens = tok.countTokens();
if (numTokens > 4) {
throw new IllegalArgumentException(str);
}
for (int i=0; i < 4 - numTokens; i++) {
addr[i] = 0;
}
for (int i = 4 - tok.countTokens(); tok.hasMoreTokens(); i++) {
addr[i] = (short)(Short.parseShort(tok.nextToken()) & mask[i]);
}
}
|
diff --git a/web-admin/src/main/java/com/webadmin/client/admin.java b/web-admin/src/main/java/com/webadmin/client/admin.java
index f82de88..bc9ba65 100644
--- a/web-admin/src/main/java/com/webadmin/client/admin.java
+++ b/web-admin/src/main/java/com/webadmin/client/admin.java
@@ -1,76 +1,76 @@
package com.webadmin.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.widget.core.client.TabItemConfig;
import com.sencha.gxt.widget.core.client.TabPanel;
import com.sencha.gxt.widget.core.client.container.HorizontalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.info.Info;
import com.webadmin.client.mainForm.ArmyPage;
import com.webadmin.client.mainForm.views.*;
import com.webadmin.client.services.CommonService;
import com.webadmin.client.services.CommonServiceAsync;
/**
* Entry point classes define
* <code>onModuleLoad()</code>.
*/
public class admin implements EntryPoint {
interface MyUiBinder extends UiBinder<Widget, admin> {
}
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
private final CommonServiceAsync commonService = GWT.create(CommonService.class);
@UiField
HorizontalLayoutContainer attackTyteGridContainer;
@UiField
HorizontalLayoutContainer specialRuleGridContainer;
@UiField
HorizontalLayoutContainer unitTypeGridContainer;
@UiField
HorizontalLayoutContainer weaponTypeGridContainer;
@UiField
HorizontalLayoutContainer unitBaseGridContainer;
@UiField
HorizontalLayoutContainer armyContainer;
@UiField
HorizontalLayoutContainer codexAndFractionsGridContainer;
public Widget asWidget() {
Widget d=uiBinder.createAndBindUi(this);
attackTyteGridContainer.add(new AttackTypeContainer());
specialRuleGridContainer.add(new SpecialRuleContainer());
unitTypeGridContainer.add(new UnitTypeContainer());
weaponTypeGridContainer.add(new WeaponTypeContainer());
unitBaseGridContainer.add(new UnitBaseContainer());
armyContainer.add(new ArmyPage());
VerticalLayoutContainer vc = new VerticalLayoutContainer();
vc.add(new CodexContainer());
- vc.add(new FractionContainer());
+ // vc.add(new FractionContainer());
codexAndFractionsGridContainer.add(vc);
return d;
}
/**
* This is the entry point method.
*/
public void onModuleLoad() {
RootPanel.get().add(asWidget());
}
@UiHandler(value = {"folder"})
void onSelection(SelectionEvent<Widget> event) {
TabPanel panel = (TabPanel) event.getSource();
Widget w = event.getSelectedItem();
TabItemConfig config = panel.getConfig(w);
Info.display("Message", "'" + config.getText() + "' Selected");
}
}
| true | true | public Widget asWidget() {
Widget d=uiBinder.createAndBindUi(this);
attackTyteGridContainer.add(new AttackTypeContainer());
specialRuleGridContainer.add(new SpecialRuleContainer());
unitTypeGridContainer.add(new UnitTypeContainer());
weaponTypeGridContainer.add(new WeaponTypeContainer());
unitBaseGridContainer.add(new UnitBaseContainer());
armyContainer.add(new ArmyPage());
VerticalLayoutContainer vc = new VerticalLayoutContainer();
vc.add(new CodexContainer());
vc.add(new FractionContainer());
codexAndFractionsGridContainer.add(vc);
return d;
}
| public Widget asWidget() {
Widget d=uiBinder.createAndBindUi(this);
attackTyteGridContainer.add(new AttackTypeContainer());
specialRuleGridContainer.add(new SpecialRuleContainer());
unitTypeGridContainer.add(new UnitTypeContainer());
weaponTypeGridContainer.add(new WeaponTypeContainer());
unitBaseGridContainer.add(new UnitBaseContainer());
armyContainer.add(new ArmyPage());
VerticalLayoutContainer vc = new VerticalLayoutContainer();
vc.add(new CodexContainer());
// vc.add(new FractionContainer());
codexAndFractionsGridContainer.add(vc);
return d;
}
|
diff --git a/gnu/testlet/java/lang/Double/DoubleSetterTest.java b/gnu/testlet/java/lang/Double/DoubleSetterTest.java
index dd80102c..acac2949 100644
--- a/gnu/testlet/java/lang/Double/DoubleSetterTest.java
+++ b/gnu/testlet/java/lang/Double/DoubleSetterTest.java
@@ -1,94 +1,94 @@
/* Copyright (C) 1999, 2002 Hewlett-Packard Company
This file is part of Mauve.
Mauve is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
Mauve 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with Mauve; see the file COPYING. If not, write to
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
// Tags: JDK1.1
package gnu.testlet.java.lang.Double;
import gnu.testlet.TestHarness;
import gnu.testlet.Testlet;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class DoubleSetterTest implements Testlet
{
protected static TestHarness harness;
/**
* Tests the conversion of behaviour of max values when converting from double into Double
*/
public void test_max()
{
// Check directly the MAX_VALUE against NaN
- harness.check(!Double.isNaN(Double.MAX_VALUE), "Error: test_max return wrong results");
+ harness.check(!Double.isNaN(Double.MAX_VALUE));
harness.check(!Double.isNaN(new Double(Double.MAX_VALUE).doubleValue()));
// Check the MAX_VALUE against NaN via a direct method setter
DoubleHolder doubleHolder = new DoubleHolder();
doubleHolder.setValue(Double.MAX_VALUE);
harness.check(Double.MAX_VALUE, doubleHolder.getValue());
// Check the MAX_VALUE against NaN via a setter called by reflection
DoubleHolder doubleHolder2 = new DoubleHolder();
try
{
Method setMethod = DoubleHolder.class.getDeclaredMethod("setValue", new Class[] {double.class});
setMethod.invoke(doubleHolder2, new Object[] {new Double(Double.MAX_VALUE)});
} catch (NoSuchMethodException e) {
harness.fail("no method setValue");
} catch (IllegalAccessException e) {
harness.fail("illegal access");
} catch (InvocationTargetException e) {
harness.fail("invocation failed");
}
harness.check(!Double.isNaN(doubleHolder2.getValue()));
}
/**
* Simple holder used to test various way of setting and getting primitive double
*/
private static class DoubleHolder
{
private double value;
public double getValue()
{
return value;
}
public void setValue(double value)
{
this.value = value;
}
}
public void test (TestHarness the_harness)
{
harness = the_harness;
test_max();
}
}
| true | true | public void test_max()
{
// Check directly the MAX_VALUE against NaN
harness.check(!Double.isNaN(Double.MAX_VALUE), "Error: test_max return wrong results");
harness.check(!Double.isNaN(new Double(Double.MAX_VALUE).doubleValue()));
// Check the MAX_VALUE against NaN via a direct method setter
DoubleHolder doubleHolder = new DoubleHolder();
doubleHolder.setValue(Double.MAX_VALUE);
harness.check(Double.MAX_VALUE, doubleHolder.getValue());
// Check the MAX_VALUE against NaN via a setter called by reflection
DoubleHolder doubleHolder2 = new DoubleHolder();
try
{
Method setMethod = DoubleHolder.class.getDeclaredMethod("setValue", new Class[] {double.class});
setMethod.invoke(doubleHolder2, new Object[] {new Double(Double.MAX_VALUE)});
} catch (NoSuchMethodException e) {
harness.fail("no method setValue");
} catch (IllegalAccessException e) {
harness.fail("illegal access");
} catch (InvocationTargetException e) {
harness.fail("invocation failed");
}
harness.check(!Double.isNaN(doubleHolder2.getValue()));
}
| public void test_max()
{
// Check directly the MAX_VALUE against NaN
harness.check(!Double.isNaN(Double.MAX_VALUE));
harness.check(!Double.isNaN(new Double(Double.MAX_VALUE).doubleValue()));
// Check the MAX_VALUE against NaN via a direct method setter
DoubleHolder doubleHolder = new DoubleHolder();
doubleHolder.setValue(Double.MAX_VALUE);
harness.check(Double.MAX_VALUE, doubleHolder.getValue());
// Check the MAX_VALUE against NaN via a setter called by reflection
DoubleHolder doubleHolder2 = new DoubleHolder();
try
{
Method setMethod = DoubleHolder.class.getDeclaredMethod("setValue", new Class[] {double.class});
setMethod.invoke(doubleHolder2, new Object[] {new Double(Double.MAX_VALUE)});
} catch (NoSuchMethodException e) {
harness.fail("no method setValue");
} catch (IllegalAccessException e) {
harness.fail("illegal access");
} catch (InvocationTargetException e) {
harness.fail("invocation failed");
}
harness.check(!Double.isNaN(doubleHolder2.getValue()));
}
|
diff --git a/orbisgis-core/src/test/java/org/orbisgis/core/plugin/PluginHostTest.java b/orbisgis-core/src/test/java/org/orbisgis/core/plugin/PluginHostTest.java
index d1ab63d7f..471f91585 100644
--- a/orbisgis-core/src/test/java/org/orbisgis/core/plugin/PluginHostTest.java
+++ b/orbisgis-core/src/test/java/org/orbisgis/core/plugin/PluginHostTest.java
@@ -1,121 +1,121 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information.
*
* OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-2012 IRSTV (FR CNRS 2488)
*
* This file is part of OrbisGIS.
*
* OrbisGIS is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* OrbisGIS 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.core.plugin;
import java.io.File;
import org.gdms.sql.function.Function;
import org.gdms.sql.function.FunctionManager;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.orbisgis.core.AbstractTest;
import org.orbisgis.core.DataManager;
import org.orbisgis.core.plugin.gdms.DummyScalarFunction;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceRegistration;
/**
* Unit test of plugin-system
* @author Nicolas Fortin
*/
public class PluginHostTest extends AbstractTest {
@Override
public void setUp() throws Exception {
super.setUp();
registerDataManager();
}
private PluginHost startHost() {
PluginHost host = new PluginHost(new File("target"+File.separator+"plugins"));
host.start();
return host;
}
/**
* Unit test of gdms function tracker
* @throws Exception
*/
@Test
public void installGDMSFunctionService() throws Exception {
PluginHost host = startHost();
// Register dummy sql function service
ServiceRegistration<Function> serv = host.getHostBundleContext()
.registerService(Function.class, new DummyScalarFunction(),null);
// check if the function is registered
DataManager dataManager = getDataManager();
assertNotNull(dataManager);
FunctionManager manager = dataManager.getDataSourceFactory().getFunctionManager();
assertTrue(manager.contains("dummy"));
//The bundle normally unregister the service, but there is no bundle in this unit test
serv.unregister();
//end plugin host
host.stop();
//test if the function has been successfully removed
assertFalse(manager.contains("dummy"));
}
/**
* Unit test of the entire plugin system
* @throws Exception
*/
@Test
public void installGDMSFunctionBundle() throws Exception {
DataManager dataManager = getDataManager();
assertNotNull(dataManager);
FunctionManager manager = dataManager.getDataSourceFactory().getFunctionManager();
PluginHost host = startHost();
- File bundlePath = new File("target/bundle/plugin-4.0-SNAPSHOT.jar");
+ File bundlePath = new File("target/bundle/plugin-1.0.jar");
System.out.println("Install plugin :"+bundlePath.getAbsolutePath());
assertTrue(bundlePath.exists());
// Install the external package
Bundle plugin = host.getHostBundleContext().installBundle("file:"+bundlePath.getAbsolutePath());
// start it
plugin.start();
// test if function exists
assertTrue(manager.contains("dummy"));
host.getHostBundleContext().getBundle().stop();
//end plugin host
host.stop();
//test if the function has been successfully removed
assertFalse(manager.contains("dummy"));
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
}
| true | true | public void installGDMSFunctionBundle() throws Exception {
DataManager dataManager = getDataManager();
assertNotNull(dataManager);
FunctionManager manager = dataManager.getDataSourceFactory().getFunctionManager();
PluginHost host = startHost();
File bundlePath = new File("target/bundle/plugin-4.0-SNAPSHOT.jar");
System.out.println("Install plugin :"+bundlePath.getAbsolutePath());
assertTrue(bundlePath.exists());
// Install the external package
Bundle plugin = host.getHostBundleContext().installBundle("file:"+bundlePath.getAbsolutePath());
// start it
plugin.start();
// test if function exists
assertTrue(manager.contains("dummy"));
host.getHostBundleContext().getBundle().stop();
//end plugin host
host.stop();
//test if the function has been successfully removed
assertFalse(manager.contains("dummy"));
}
| public void installGDMSFunctionBundle() throws Exception {
DataManager dataManager = getDataManager();
assertNotNull(dataManager);
FunctionManager manager = dataManager.getDataSourceFactory().getFunctionManager();
PluginHost host = startHost();
File bundlePath = new File("target/bundle/plugin-1.0.jar");
System.out.println("Install plugin :"+bundlePath.getAbsolutePath());
assertTrue(bundlePath.exists());
// Install the external package
Bundle plugin = host.getHostBundleContext().installBundle("file:"+bundlePath.getAbsolutePath());
// start it
plugin.start();
// test if function exists
assertTrue(manager.contains("dummy"));
host.getHostBundleContext().getBundle().stop();
//end plugin host
host.stop();
//test if the function has been successfully removed
assertFalse(manager.contains("dummy"));
}
|
diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/user/ProcessingConfig.java b/chassis/core/src/main/java/com/griddynamics/jagger/user/ProcessingConfig.java
index 5859df9..72164cc 100644
--- a/chassis/core/src/main/java/com/griddynamics/jagger/user/ProcessingConfig.java
+++ b/chassis/core/src/main/java/com/griddynamics/jagger/user/ProcessingConfig.java
@@ -1,421 +1,421 @@
/*
* Copyright (c) 2010-2012 Grid Dynamics Consulting Services, Inc, All Rights Reserved
* http://www.griddynamics.com
*
* 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 any later version.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.griddynamics.jagger.user;
import com.google.common.base.Preconditions;
import com.griddynamics.jagger.reporting.ReportingService;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* User: dkotlyarov
*/
@Root(name = "processing")
public class ProcessingConfig implements Serializable {
@ElementList(name = "tests", entry = "test", inline = true)
public List<Test> tests;
public ProcessingConfig(@ElementList(name = "tests", entry = "test", inline = true) List<Test> tests) {
this.tests = Collections.unmodifiableList(tests);
}
public ProcessingConfig() {
}
public List<Test> getTests() {
return tests;
}
public void setTests(List<Test> tests) {
this.tests = tests;
}
public static class Test implements Serializable {
@Attribute(name = "name")
public String name;
@Attribute(name = "duration", required = false)
public String duration;
@ElementList(name = "tasks", entry = "task", inline = true, required = false)
public List<Task> tasks;
public Test(@Attribute(name = "name") String name,
@Attribute(name = "duration", required = false) String duration,
@ElementList(name = "tasks", entry = "task", inline = true, required = false) List<Task> tasks) {
this.name = name;
this.duration = duration;
this.tasks = Collections.unmodifiableList((tasks != null) ? tasks : new ArrayList<Task>(0));
}
public Test() {
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
public static class Task implements Serializable {
@Attribute(name = "name")
public String name;
@Attribute(name = "duration", required = false)
public String duration;
@Attribute(name = "sample", required = false)
public Integer sample;
@Attribute(name = "delay", required = false)
public Integer delay;
@Attribute(name = "bean")
public String bean;
@ElementList(name = "users", entry = "user", inline = true, required = false)
public List<User> users;
@Element(name = "invocation", required = false)
public Invocation invocation;
@Element(name="tps", required =false)
public Tps tps;
@Element(name="virtualUser", required = false)
public VirtualUser virtualUser;
@Attribute(name = "attendant", required = false)
public boolean attendant;
public Task(@Attribute(name = "name") String name,
@Attribute(name = "duration", required = false) String duration,
@Attribute(name = "sample", required = false) Integer sample,
@Attribute(name = "iterations", required = false) Integer iterations,
@Attribute(name = "delay", required = false) Integer delay,
- @Attribute(name = "attendant", required = false) Boolean attendant,
+ @Attribute(name = "attendant", required = false) boolean attendant,
@Attribute(name = "bean") String bean,
@ElementList(name = "users", entry = "user", inline = true, required = false) List<User> users,
@Element(name = "invocation", required = false) Invocation invocation,
@Element(name = "tps", required = false) Tps tps,
@Element(name = "virtualUser", required = false) VirtualUser virtualUser) {
Preconditions.checkArgument((invocation == null ||
users == null ||
virtualUser == null ||
tps == null), "Malformed configuration! <invocation> and <user> elements are mutually exclusive.");
this.name = name;
this.duration = duration;
this.sample = (sample != null) ? sample : -1;
this.sample = (iterations != null) ? iterations : -1;
this.delay = (delay != null) ? delay : 0;
this.bean = bean;
this.users = Collections.unmodifiableList((users != null) ? users : new ArrayList<User>(0));
this.tps = tps;
this.invocation = invocation;
- this.attendant = (attendant != null) ? attendant : false;
+ this.attendant = attendant;
this.setVirtualUser(virtualUser);
}
public Task() {
}
public void setIterations(Integer iterations){
this.sample = iterations;
}
public Integer getIterations(){
return sample;
}
public boolean isAttendant() {
return attendant;
}
public void setAttendant(boolean attendant) {
this.attendant = attendant;
}
public String getTestDescription() {
return bean;
}
public void setTestDescription(String description) {
this.bean = description;
}
public void setBean(String bean){
this.bean = bean;
}
public String getBean(){
return this.bean;
}
public Integer getDelay() {
return delay;
}
public void setDelay(Integer delay) {
this.delay = delay;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public Invocation getInvocation() {
return invocation;
}
public void setInvocation(Invocation invocation) {
this.invocation = invocation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSample() {
return sample;
}
public void setSample(Integer sample) {
this.sample = sample;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public void setTps(Tps tps){
this.tps = tps;
}
public Tps getTps(){
return this.tps;
}
public VirtualUser getVirtualUser() {
return virtualUser;
}
public void setVirtualUser(VirtualUser virtualUser) {
this.virtualUser = virtualUser;
}
public static class Invocation implements Serializable {
@Attribute(name = "exactcount")
public Integer exactcount;
@Attribute(name = "threads", required = false)
public Integer threads;
public Invocation(@Attribute(name = "exactcount") Integer exactcount,
@Attribute(name = "threads", required = false) Integer threads) {
this.exactcount = exactcount;
this.threads = threads != null ? threads : 1;
}
public Invocation() {
}
public void setExactcount(Integer exactcount) {
this.exactcount = exactcount;
}
public void setThreads(Integer threads) {
this.threads = threads;
}
public Integer getExactcount() {
return exactcount;
}
public Integer getThreads() {
return threads;
}
}
public static class User implements Serializable {
@Attribute(name = "count")
public String count;
@Attribute(name = "startCount")
public String startCount;
@Attribute(name = "startIn")
public String startIn;
@Attribute(name = "startBy")
public String startBy;
@Attribute(name = "life")
public String life;
public User(@Attribute(name = "count") String count,
@Attribute(name = "startCount") String startCount,
@Attribute(name = "startIn") String startIn,
@Attribute(name = "startBy") String startBy,
@Attribute(name = "life") String life) {
this.count = count;
this.startCount = startCount;
this.startIn = startIn;
this.startBy = startBy;
this.life = life;
}
public User() {
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getLife() {
return life;
}
public void setLife(String life) {
this.life = life;
}
public String getStartBy() {
return startBy;
}
public void setStartBy(String startBy) {
this.startBy = startBy;
}
public String getStartCount() {
return startCount;
}
public void setStartCount(String startCount) {
this.startCount = startCount;
}
public String getStartIn() {
return startIn;
}
public void setStartIn(String startIn) {
this.startIn = startIn;
}
}
public static class Tps implements Serializable{
@Attribute(name = "value")
public Integer value;
public Tps(){
}
public Tps(@Attribute(name = "value") Integer value){
this.value = value;
}
public Integer getValue(){
return value;
}
public void setValue(Integer value){
this.value = value;
}
}
public static class VirtualUser implements Serializable{
@Attribute(name="count")
public Integer count;
@Attribute(name="tickInterval")
public Integer tickInterval;
public VirtualUser(){
}
public VirtualUser(@Attribute(name="count") Integer count,
@Attribute(name="tickInterval") Integer tickInterval){
this.setCount(count);
this.setTickInterval(tickInterval);
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Integer getTickInterval() {
return tickInterval;
}
public void setTickInterval(Integer tickInterval) {
this.tickInterval = tickInterval;
}
}
}
}
}
| false | true | public Task(@Attribute(name = "name") String name,
@Attribute(name = "duration", required = false) String duration,
@Attribute(name = "sample", required = false) Integer sample,
@Attribute(name = "iterations", required = false) Integer iterations,
@Attribute(name = "delay", required = false) Integer delay,
@Attribute(name = "attendant", required = false) Boolean attendant,
@Attribute(name = "bean") String bean,
@ElementList(name = "users", entry = "user", inline = true, required = false) List<User> users,
@Element(name = "invocation", required = false) Invocation invocation,
@Element(name = "tps", required = false) Tps tps,
@Element(name = "virtualUser", required = false) VirtualUser virtualUser) {
Preconditions.checkArgument((invocation == null ||
users == null ||
virtualUser == null ||
tps == null), "Malformed configuration! <invocation> and <user> elements are mutually exclusive.");
this.name = name;
this.duration = duration;
this.sample = (sample != null) ? sample : -1;
this.sample = (iterations != null) ? iterations : -1;
this.delay = (delay != null) ? delay : 0;
this.bean = bean;
this.users = Collections.unmodifiableList((users != null) ? users : new ArrayList<User>(0));
this.tps = tps;
this.invocation = invocation;
this.attendant = (attendant != null) ? attendant : false;
this.setVirtualUser(virtualUser);
}
| public Task(@Attribute(name = "name") String name,
@Attribute(name = "duration", required = false) String duration,
@Attribute(name = "sample", required = false) Integer sample,
@Attribute(name = "iterations", required = false) Integer iterations,
@Attribute(name = "delay", required = false) Integer delay,
@Attribute(name = "attendant", required = false) boolean attendant,
@Attribute(name = "bean") String bean,
@ElementList(name = "users", entry = "user", inline = true, required = false) List<User> users,
@Element(name = "invocation", required = false) Invocation invocation,
@Element(name = "tps", required = false) Tps tps,
@Element(name = "virtualUser", required = false) VirtualUser virtualUser) {
Preconditions.checkArgument((invocation == null ||
users == null ||
virtualUser == null ||
tps == null), "Malformed configuration! <invocation> and <user> elements are mutually exclusive.");
this.name = name;
this.duration = duration;
this.sample = (sample != null) ? sample : -1;
this.sample = (iterations != null) ? iterations : -1;
this.delay = (delay != null) ? delay : 0;
this.bean = bean;
this.users = Collections.unmodifiableList((users != null) ? users : new ArrayList<User>(0));
this.tps = tps;
this.invocation = invocation;
this.attendant = attendant;
this.setVirtualUser(virtualUser);
}
|
diff --git a/src/main/java/nl/mindef/c2sc/nbs/olsr/pud/uplink/server/handlers/impl/debug/Faker.java b/src/main/java/nl/mindef/c2sc/nbs/olsr/pud/uplink/server/handlers/impl/debug/Faker.java
index 8e8eae8..f781495 100644
--- a/src/main/java/nl/mindef/c2sc/nbs/olsr/pud/uplink/server/handlers/impl/debug/Faker.java
+++ b/src/main/java/nl/mindef/c2sc/nbs/olsr/pud/uplink/server/handlers/impl/debug/Faker.java
@@ -1,179 +1,183 @@
package nl.mindef.c2sc.nbs.olsr.pud.uplink.server.handlers.impl.debug;
import java.util.Random;
import nl.mindef.c2sc.nbs.olsr.pud.uplink.server.dao.domainmodel.Gateway;
import nl.mindef.c2sc.nbs.olsr.pud.uplink.server.handlers.ClusterLeaderHandler;
import nl.mindef.c2sc.nbs.olsr.pud.uplink.server.handlers.PositionUpdateHandler;
import org.olsr.plugin.pud.ClusterLeader;
import org.olsr.plugin.pud.PositionUpdate;
import org.springframework.beans.factory.annotation.Required;
public class Faker {
private ClusterLeaderHandler clusterLeaderHandler;
/**
* @param clusterLeaderHandler
* the clusterLeaderHandler to set
*/
@Required
public final void setClusterLeaderHandler(ClusterLeaderHandler clusterLeaderHandler) {
this.clusterLeaderHandler = clusterLeaderHandler;
}
private PositionUpdateHandler positionUpdateHandler;
/**
* @param positionUpdateHandler
* the positionUpdateHandler to set
*/
@Required
public final void setPositionUpdateHandler(PositionUpdateHandler positionUpdateHandler) {
this.positionUpdateHandler = positionUpdateHandler;
}
public enum MSGTYPE {
PU, CL
}
private boolean firstFake = true;
/**
* @return the firstFake
*/
public final boolean isFirstFake() {
return this.firstFake;
}
/**
* @param firstFake
* the firstFake to set
*/
public final void setFirstFake(boolean firstFake) {
this.firstFake = firstFake;
}
/* locations in byte array */
static private final int UplinkMessage_v4_olsrMessage_v4_originator_network = 10;
static private final int UplinkMessage_v4_olsrMessage_v4_originator_node = 11;
static private final int UplinkMessage_v4_clusterLeader_originator_network = 8;
static private final int UplinkMessage_v4_clusterLeader_originator_node = 9;
static private final int UplinkMessage_v4_clusterLeader_clusterLeader_network = 12;
static private final int UplinkMessage_v4_clusterLeader_clusterLeader_node = 13;
public void fakeit(Gateway gateway, long utcTimestamp, MSGTYPE type, Object msg) {
if (!this.firstFake) {
return;
}
Random random = new Random();
int randomRange = 100;
byte[] clmsg = null;
byte[] pumsg = null;
int initialNetwork = 0;
byte initialNode = 1;
if (type == MSGTYPE.PU) {
pumsg = ((PositionUpdate) msg).getData();
initialNetwork = pumsg[UplinkMessage_v4_olsrMessage_v4_originator_network];
initialNode = pumsg[UplinkMessage_v4_olsrMessage_v4_originator_node];
} else /* if (type == MSGTYPE.CL) */{
clmsg = ((ClusterLeader) msg).getData();
initialNetwork = clmsg[UplinkMessage_v4_clusterLeader_originator_network];
initialNode = clmsg[UplinkMessage_v4_clusterLeader_originator_node];
}
boolean firstNode = true;
int network = initialNetwork;
int networkMax = network + 2;
byte node = initialNode;
int nodeCount = 0;
int nodeCountMax = 6;
byte clusterLeaderNode = node;
while (network <= networkMax) {
node = initialNode;
clusterLeaderNode = node;
nodeCount = 0;
while (nodeCount < nodeCountMax) {
if (!firstNode) {
boolean skipNode = ((network == (initialNetwork + 1)) && (node == initialNode));
if (!skipNode) {
/*
* Position Update Message
*/
if (type == MSGTYPE.PU) {
+ assert (pumsg != null);
byte[] pumsgClone = pumsg.clone();
/* olsr originator */
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_network] = (byte) network;
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_node] = node;
PositionUpdate pu = new PositionUpdate(pumsgClone, pumsgClone.length);
this.positionUpdateHandler.handlePositionMessage(gateway, utcTimestamp + random.nextInt(randomRange), pu);
}
/*
* Cluster Leader Message
*/
else /* if (type == MSGTYPE.CL) */{
+ assert (clmsg != null);
byte[] clmsgClone = clmsg.clone();
/* originator */
clmsgClone[UplinkMessage_v4_clusterLeader_originator_network] = (byte) network;
clmsgClone[UplinkMessage_v4_clusterLeader_originator_node] = node;
/* clusterLeader */
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_network] = (byte) network;
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_node] = clusterLeaderNode;
ClusterLeader cl = new ClusterLeader(clmsgClone, clmsgClone.length);
this.clusterLeaderHandler.handleClusterLeaderMessage(gateway, utcTimestamp + random.nextInt(randomRange),
cl);
}
}
} else {
firstNode = false;
}
node++;
if (node == 0) {
node++;
}
nodeCount++;
}
network++;
}
/* add an extra standalone node */
node = initialNode;
/*
* Position Update Message
*/
if (type == MSGTYPE.PU) {
+ assert (pumsg != null);
byte[] pumsgClone = pumsg.clone();
// olsr originator
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_network] = (byte) network;
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_node] = node;
PositionUpdate pu = new PositionUpdate(pumsgClone, pumsgClone.length);
this.positionUpdateHandler.handlePositionMessage(gateway, utcTimestamp + random.nextInt(randomRange), pu);
}
/*
* Cluster Leader Message
*/
else /* if (type == MSGTYPE.CL) */{
+ assert (clmsg != null);
byte[] clmsgClone = clmsg.clone();
// originator
clmsgClone[UplinkMessage_v4_clusterLeader_originator_network] = (byte) network;
clmsgClone[UplinkMessage_v4_clusterLeader_originator_node] = node;
// clusterLeader
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_network] = (byte) (network - 1);
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_node] = (byte) (clusterLeaderNode + nodeCountMax - 1);
ClusterLeader cl = new ClusterLeader(clmsgClone, clmsgClone.length);
this.clusterLeaderHandler.handleClusterLeaderMessage(gateway, utcTimestamp + random.nextInt(randomRange), cl);
}
}
}
| false | true | public void fakeit(Gateway gateway, long utcTimestamp, MSGTYPE type, Object msg) {
if (!this.firstFake) {
return;
}
Random random = new Random();
int randomRange = 100;
byte[] clmsg = null;
byte[] pumsg = null;
int initialNetwork = 0;
byte initialNode = 1;
if (type == MSGTYPE.PU) {
pumsg = ((PositionUpdate) msg).getData();
initialNetwork = pumsg[UplinkMessage_v4_olsrMessage_v4_originator_network];
initialNode = pumsg[UplinkMessage_v4_olsrMessage_v4_originator_node];
} else /* if (type == MSGTYPE.CL) */{
clmsg = ((ClusterLeader) msg).getData();
initialNetwork = clmsg[UplinkMessage_v4_clusterLeader_originator_network];
initialNode = clmsg[UplinkMessage_v4_clusterLeader_originator_node];
}
boolean firstNode = true;
int network = initialNetwork;
int networkMax = network + 2;
byte node = initialNode;
int nodeCount = 0;
int nodeCountMax = 6;
byte clusterLeaderNode = node;
while (network <= networkMax) {
node = initialNode;
clusterLeaderNode = node;
nodeCount = 0;
while (nodeCount < nodeCountMax) {
if (!firstNode) {
boolean skipNode = ((network == (initialNetwork + 1)) && (node == initialNode));
if (!skipNode) {
/*
* Position Update Message
*/
if (type == MSGTYPE.PU) {
byte[] pumsgClone = pumsg.clone();
/* olsr originator */
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_network] = (byte) network;
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_node] = node;
PositionUpdate pu = new PositionUpdate(pumsgClone, pumsgClone.length);
this.positionUpdateHandler.handlePositionMessage(gateway, utcTimestamp + random.nextInt(randomRange), pu);
}
/*
* Cluster Leader Message
*/
else /* if (type == MSGTYPE.CL) */{
byte[] clmsgClone = clmsg.clone();
/* originator */
clmsgClone[UplinkMessage_v4_clusterLeader_originator_network] = (byte) network;
clmsgClone[UplinkMessage_v4_clusterLeader_originator_node] = node;
/* clusterLeader */
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_network] = (byte) network;
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_node] = clusterLeaderNode;
ClusterLeader cl = new ClusterLeader(clmsgClone, clmsgClone.length);
this.clusterLeaderHandler.handleClusterLeaderMessage(gateway, utcTimestamp + random.nextInt(randomRange),
cl);
}
}
} else {
firstNode = false;
}
node++;
if (node == 0) {
node++;
}
nodeCount++;
}
network++;
}
/* add an extra standalone node */
node = initialNode;
/*
* Position Update Message
*/
if (type == MSGTYPE.PU) {
byte[] pumsgClone = pumsg.clone();
// olsr originator
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_network] = (byte) network;
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_node] = node;
PositionUpdate pu = new PositionUpdate(pumsgClone, pumsgClone.length);
this.positionUpdateHandler.handlePositionMessage(gateway, utcTimestamp + random.nextInt(randomRange), pu);
}
/*
* Cluster Leader Message
*/
else /* if (type == MSGTYPE.CL) */{
byte[] clmsgClone = clmsg.clone();
// originator
clmsgClone[UplinkMessage_v4_clusterLeader_originator_network] = (byte) network;
clmsgClone[UplinkMessage_v4_clusterLeader_originator_node] = node;
// clusterLeader
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_network] = (byte) (network - 1);
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_node] = (byte) (clusterLeaderNode + nodeCountMax - 1);
ClusterLeader cl = new ClusterLeader(clmsgClone, clmsgClone.length);
this.clusterLeaderHandler.handleClusterLeaderMessage(gateway, utcTimestamp + random.nextInt(randomRange), cl);
}
}
| public void fakeit(Gateway gateway, long utcTimestamp, MSGTYPE type, Object msg) {
if (!this.firstFake) {
return;
}
Random random = new Random();
int randomRange = 100;
byte[] clmsg = null;
byte[] pumsg = null;
int initialNetwork = 0;
byte initialNode = 1;
if (type == MSGTYPE.PU) {
pumsg = ((PositionUpdate) msg).getData();
initialNetwork = pumsg[UplinkMessage_v4_olsrMessage_v4_originator_network];
initialNode = pumsg[UplinkMessage_v4_olsrMessage_v4_originator_node];
} else /* if (type == MSGTYPE.CL) */{
clmsg = ((ClusterLeader) msg).getData();
initialNetwork = clmsg[UplinkMessage_v4_clusterLeader_originator_network];
initialNode = clmsg[UplinkMessage_v4_clusterLeader_originator_node];
}
boolean firstNode = true;
int network = initialNetwork;
int networkMax = network + 2;
byte node = initialNode;
int nodeCount = 0;
int nodeCountMax = 6;
byte clusterLeaderNode = node;
while (network <= networkMax) {
node = initialNode;
clusterLeaderNode = node;
nodeCount = 0;
while (nodeCount < nodeCountMax) {
if (!firstNode) {
boolean skipNode = ((network == (initialNetwork + 1)) && (node == initialNode));
if (!skipNode) {
/*
* Position Update Message
*/
if (type == MSGTYPE.PU) {
assert (pumsg != null);
byte[] pumsgClone = pumsg.clone();
/* olsr originator */
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_network] = (byte) network;
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_node] = node;
PositionUpdate pu = new PositionUpdate(pumsgClone, pumsgClone.length);
this.positionUpdateHandler.handlePositionMessage(gateway, utcTimestamp + random.nextInt(randomRange), pu);
}
/*
* Cluster Leader Message
*/
else /* if (type == MSGTYPE.CL) */{
assert (clmsg != null);
byte[] clmsgClone = clmsg.clone();
/* originator */
clmsgClone[UplinkMessage_v4_clusterLeader_originator_network] = (byte) network;
clmsgClone[UplinkMessage_v4_clusterLeader_originator_node] = node;
/* clusterLeader */
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_network] = (byte) network;
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_node] = clusterLeaderNode;
ClusterLeader cl = new ClusterLeader(clmsgClone, clmsgClone.length);
this.clusterLeaderHandler.handleClusterLeaderMessage(gateway, utcTimestamp + random.nextInt(randomRange),
cl);
}
}
} else {
firstNode = false;
}
node++;
if (node == 0) {
node++;
}
nodeCount++;
}
network++;
}
/* add an extra standalone node */
node = initialNode;
/*
* Position Update Message
*/
if (type == MSGTYPE.PU) {
assert (pumsg != null);
byte[] pumsgClone = pumsg.clone();
// olsr originator
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_network] = (byte) network;
pumsgClone[UplinkMessage_v4_olsrMessage_v4_originator_node] = node;
PositionUpdate pu = new PositionUpdate(pumsgClone, pumsgClone.length);
this.positionUpdateHandler.handlePositionMessage(gateway, utcTimestamp + random.nextInt(randomRange), pu);
}
/*
* Cluster Leader Message
*/
else /* if (type == MSGTYPE.CL) */{
assert (clmsg != null);
byte[] clmsgClone = clmsg.clone();
// originator
clmsgClone[UplinkMessage_v4_clusterLeader_originator_network] = (byte) network;
clmsgClone[UplinkMessage_v4_clusterLeader_originator_node] = node;
// clusterLeader
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_network] = (byte) (network - 1);
clmsgClone[UplinkMessage_v4_clusterLeader_clusterLeader_node] = (byte) (clusterLeaderNode + nodeCountMax - 1);
ClusterLeader cl = new ClusterLeader(clmsgClone, clmsgClone.length);
this.clusterLeaderHandler.handleClusterLeaderMessage(gateway, utcTimestamp + random.nextInt(randomRange), cl);
}
}
|
diff --git a/src/main/java/edu/uib/info310/search/builder/OntologyBuilder.java b/src/main/java/edu/uib/info310/search/builder/OntologyBuilder.java
index dc496ff..f679b80 100644
--- a/src/main/java/edu/uib/info310/search/builder/OntologyBuilder.java
+++ b/src/main/java/edu/uib/info310/search/builder/OntologyBuilder.java
@@ -1,72 +1,76 @@
package edu.uib.info310.search.builder;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.uib.info310.model.Artist;
import edu.uib.info310.model.imp.ArtistImp;
import edu.uib.info310.search.DiscogSearch;
import edu.uib.info310.search.LastFMSearch;
import edu.uib.info310.transformation.XslTransformer;
import edu.uib.info310.util.GetArtistInfo;
@Component
public class OntologyBuilder {
private LastFMSearch search = new LastFMSearch();
private XslTransformer transformer = new XslTransformer();
private static final String SIMILAR_XSL = "src/main/resources/XSL/SimilarArtistLastFM.xsl";
private static final String ARTIST_EVENTS_XSL = "src/main/resources/XSL/Events.xsl";
private static final Logger LOGGER = LoggerFactory.getLogger(OntologyBuilder.class);
private DiscogSearch disc = new DiscogSearch();
public Model createArtistOntology(String search_string) {
Model model = ModelFactory.createDefaultModel();
Model discs = disc.getDiscography(search_string);
LOGGER.debug("Number of items in discography: " + discs.size());
model.add(discs);
LOGGER.debug("Model size after getting artist discography: " + model.size());
+ Model tracks = disc.getTracks(search_string);
+ LOGGER.debug("Number of tracks to discography: " + tracks.size());
+ model.add(tracks);
+ LOGGER.debug("Model size after getting artist tracksy: " + model.size());
try{
transformer.setXml(search.getSimilarArtist(search_string));
transformer.setXsl(new File(SIMILAR_XSL));
InputStream in = new ByteArrayInputStream(transformer.transform().toByteArray());
model.read(in, null);
LOGGER.debug("Model size after getting similar artists: " + model.size());
transformer.setXml(search.getArtistEvents(search_string));
transformer.setXsl(new File(ARTIST_EVENTS_XSL));
in = new ByteArrayInputStream(transformer.transform().toByteArray());
model.read(in, null);
LOGGER.debug("Model size after getting artist events: " + model.size());
}
catch (Exception e) {
e.printStackTrace();
}
// get BBC_MUSIC model and add to model
model.add(GetArtistInfo.ArtistInfo(search_string));
return model;
}
}
| true | true | public Model createArtistOntology(String search_string) {
Model model = ModelFactory.createDefaultModel();
Model discs = disc.getDiscography(search_string);
LOGGER.debug("Number of items in discography: " + discs.size());
model.add(discs);
LOGGER.debug("Model size after getting artist discography: " + model.size());
try{
transformer.setXml(search.getSimilarArtist(search_string));
transformer.setXsl(new File(SIMILAR_XSL));
InputStream in = new ByteArrayInputStream(transformer.transform().toByteArray());
model.read(in, null);
LOGGER.debug("Model size after getting similar artists: " + model.size());
transformer.setXml(search.getArtistEvents(search_string));
transformer.setXsl(new File(ARTIST_EVENTS_XSL));
in = new ByteArrayInputStream(transformer.transform().toByteArray());
model.read(in, null);
LOGGER.debug("Model size after getting artist events: " + model.size());
}
catch (Exception e) {
e.printStackTrace();
}
// get BBC_MUSIC model and add to model
model.add(GetArtistInfo.ArtistInfo(search_string));
return model;
}
| public Model createArtistOntology(String search_string) {
Model model = ModelFactory.createDefaultModel();
Model discs = disc.getDiscography(search_string);
LOGGER.debug("Number of items in discography: " + discs.size());
model.add(discs);
LOGGER.debug("Model size after getting artist discography: " + model.size());
Model tracks = disc.getTracks(search_string);
LOGGER.debug("Number of tracks to discography: " + tracks.size());
model.add(tracks);
LOGGER.debug("Model size after getting artist tracksy: " + model.size());
try{
transformer.setXml(search.getSimilarArtist(search_string));
transformer.setXsl(new File(SIMILAR_XSL));
InputStream in = new ByteArrayInputStream(transformer.transform().toByteArray());
model.read(in, null);
LOGGER.debug("Model size after getting similar artists: " + model.size());
transformer.setXml(search.getArtistEvents(search_string));
transformer.setXsl(new File(ARTIST_EVENTS_XSL));
in = new ByteArrayInputStream(transformer.transform().toByteArray());
model.read(in, null);
LOGGER.debug("Model size after getting artist events: " + model.size());
}
catch (Exception e) {
e.printStackTrace();
}
// get BBC_MUSIC model and add to model
model.add(GetArtistInfo.ArtistInfo(search_string));
return model;
}
|
diff --git a/src/sphinx4/edu/cmu/sphinx/frontend/feature/LiveCMN.java b/src/sphinx4/edu/cmu/sphinx/frontend/feature/LiveCMN.java
index a423675d..ebc3dec1 100644
--- a/src/sphinx4/edu/cmu/sphinx/frontend/feature/LiveCMN.java
+++ b/src/sphinx4/edu/cmu/sphinx/frontend/feature/LiveCMN.java
@@ -1,209 +1,211 @@
/*
* Copyright 1999-2002 Carnegie Mellon University.
* Portions Copyright 2002 Sun Microsystems, Inc.
* Portions Copyright 2002 Mitsubishi Electric Research Laboratories.
* All Rights Reserved. Use is subject to license terms.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
package edu.cmu.sphinx.frontend.feature;
import edu.cmu.sphinx.frontend.*;
import edu.cmu.sphinx.util.props.PropertyException;
import edu.cmu.sphinx.util.props.PropertySheet;
import edu.cmu.sphinx.util.props.S4Double;
import edu.cmu.sphinx.util.props.S4Integer;
/**
* Subtracts the mean of all the input so far from the Data objects. Unlike the {@link BatchCMN}, it does not read in
* the entire stream of Data objects before it calculates the mean. It estimates the mean from already seen data and
* subtracts the mean from the Data objects on the fly. Therefore, there is no delay introduced by LiveCMN.
* <p/>
* The Sphinx properties that affect this processor are defined by the fields {@link #PROP_INITIAL_MEAN}, {@link
* #PROP_CMN_WINDOW}, and {@link #PROP_CMN_SHIFT_WINDOW}. Please follow the link "Constant Field Values" below to see
* the actual name of the Sphinx properties.
* <p/>
* <p>The mean of all the input cepstrum so far is not reestimated for each cepstrum. This mean is recalculated after
* every {@link #PROP_CMN_SHIFT_WINDOW} cepstra. This mean is estimated by dividing the sum of all input cepstrum so
* far. After obtaining the mean, the sum is exponentially decayed by multiplying it by the ratio:
* <pre>
* cmnWindow/(cmnWindow + number of frames since the last recalculation)
* </pre>
* <p/>
* <p>This is a 1-to-1 processor.
*
* @see BatchCMN
*/
public class LiveCMN extends BaseDataProcessor {
/** The property for the initial cepstral mean. This is a front-end dependent magic number. */
@S4Double(defaultValue = 12.0)
public static final String PROP_INITIAL_MEAN = "initialMean";
private double initialMean; // initial mean, magic number
/** The property for the live CMN window size. */
@S4Integer(defaultValue = 100)
public static final String PROP_CMN_WINDOW = "cmnWindow";
private int cmnWindow;
/**
* The property for the CMN shifting window. The shifting window specifies how many cepstrum after
* which we re-calculate the cepstral mean.
*/
@S4Integer(defaultValue = 160)
public static final String PROP_CMN_SHIFT_WINDOW = "shiftWindow";
private int cmnShiftWindow; // # of Cepstrum to recalculate mean
private double[] currentMean; // array of current means
private double[] sum; // array of current sums
private int numberFrame; // total number of input Cepstrum
public LiveCMN(double initialMean, int cmnWindow, int cmnShiftWindow) {
initLogger();
this.initialMean = initialMean;
this.cmnWindow = cmnWindow;
this.cmnShiftWindow = cmnShiftWindow;
}
public LiveCMN() {
}
@Override
public void newProperties(PropertySheet ps) throws PropertyException {
super.newProperties(ps);
initialMean = ps.getDouble(PROP_INITIAL_MEAN);
cmnWindow = ps.getInt(PROP_CMN_WINDOW);
cmnShiftWindow = ps.getInt(PROP_CMN_SHIFT_WINDOW);
}
/** Initializes this LiveCMN. */
@Override
public void initialize() {
super.initialize();
}
/**
* Initializes the currentMean and sum arrays with the given cepstrum length.
*
* @param cepstrumLength the length of the cepstrum
*/
private void initMeansSums(int cepstrumLength) {
currentMean = new double[cepstrumLength];
currentMean[0] = initialMean;
// hack until we've fixed the NonSpeechDataFilter
if (sum == null)
sum = new double[cepstrumLength];
}
/**
* Returns the next Data object, which is a normalized Data produced by this class. Signals are returned
* unmodified.
*
* @return the next available Data object, returns null if no Data object is available
* @throws DataProcessingException if there is a data processing error
*/
@Override
public Data getData() throws DataProcessingException {
Data input = getPredecessor().getData();
- if (input instanceof DataStartSignal)
+ if (input instanceof DataStartSignal) {
sum = null;
+ numberFrame = 0;
+ }
getTimer().start();
if (input != null) {
if (input instanceof DoubleData) {
DoubleData data = (DoubleData) input;
if (sum == null) {
initMeansSums(data.getValues().length);
}
normalize(data);
} else if (input instanceof DataEndSignal) {
updateMeanSumBuffers();
}
}
getTimer().stop();
return input;
}
/**
* Normalizes the given Data with using the currentMean array. Updates the sum array with the given Data.
*
* @param cepstrumObject the Data object to normalize
*/
private void normalize(DoubleData cepstrumObject) {
double[] cepstrum = cepstrumObject.getValues();
if (cepstrum.length != sum.length) {
throw new Error("Data length (" + cepstrum.length +
") not equal sum array length (" +
sum.length + ')');
}
for (int j = 0; j < cepstrum.length; j++) {
sum[j] += cepstrum[j];
cepstrum[j] -= currentMean[j];
}
numberFrame++;
if (numberFrame > cmnShiftWindow) {
updateMeanSumBuffers();
}
}
/**
* Updates the currentMean buffer with the values in the sum buffer. Then decay the sum buffer exponentially, i.e.,
* divide the sum with numberFrames.
*/
private void updateMeanSumBuffers() {
if (numberFrame > 0) {
// update the currentMean buffer with the sum buffer
double sf = 1.0 / numberFrame;
System.arraycopy(sum, 0, currentMean, 0, sum.length);
multiplyArray(currentMean, sf);
// decay the sum buffer exponentially
if (numberFrame >= cmnShiftWindow) {
multiplyArray(sum, (sf * cmnWindow));
numberFrame = cmnWindow;
}
}
}
/**
* Multiplies each element of the given array by the multiplier.
*
* @param array the array to multiply
* @param multiplier the amount to multiply by
*/
private static void multiplyArray(double[] array, double multiplier) {
for (int i = 0; i < array.length; i++) {
array[i] *= multiplier;
}
}
}
| false | true | public Data getData() throws DataProcessingException {
Data input = getPredecessor().getData();
if (input instanceof DataStartSignal)
sum = null;
getTimer().start();
if (input != null) {
if (input instanceof DoubleData) {
DoubleData data = (DoubleData) input;
if (sum == null) {
initMeansSums(data.getValues().length);
}
normalize(data);
} else if (input instanceof DataEndSignal) {
updateMeanSumBuffers();
}
}
getTimer().stop();
return input;
}
| public Data getData() throws DataProcessingException {
Data input = getPredecessor().getData();
if (input instanceof DataStartSignal) {
sum = null;
numberFrame = 0;
}
getTimer().start();
if (input != null) {
if (input instanceof DoubleData) {
DoubleData data = (DoubleData) input;
if (sum == null) {
initMeansSums(data.getValues().length);
}
normalize(data);
} else if (input instanceof DataEndSignal) {
updateMeanSumBuffers();
}
}
getTimer().stop();
return input;
}
|
diff --git a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java
index 24bf983..7ca9a21 100644
--- a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java
+++ b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java
@@ -1,142 +1,144 @@
package org.jboss.tools.esb.ui.bot.tests.examples;
import org.jboss.tools.ui.bot.ext.SWTEclipseExt;
import org.jboss.tools.ui.bot.ext.SWTOpenExt;
import org.jboss.tools.ui.bot.ext.SWTTestExt;
import org.jboss.tools.ui.bot.ext.Timing;
import org.jboss.tools.ui.bot.ext.config.Annotations.Require;
import org.jboss.tools.ui.bot.ext.config.Annotations.Server;
import org.jboss.tools.ui.bot.ext.config.Annotations.ServerState;
import org.jboss.tools.ui.bot.ext.config.Annotations.ServerType;
import org.jboss.tools.ui.bot.ext.gen.ActionItem;
import org.jboss.tools.ui.bot.ext.gen.ActionItem.NewObject.ESBESBFile;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTableItem;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.jboss.tools.ui.bot.ext.gen.ActionItem.NewObject.GeneralFolder;
@Require(server=@Server(type=ServerType.SOA,state=ServerState.Running))
public class HelloWorldFileAction extends ESBExampleTest {
public static String inputDir = "inputDir";
public static String outputDir = "outputDir";
public static String errorDir = "errorDir";
public static String projectName = "helloworld_file_action";
public static String clientProjectName = "helloworld_file_action_client";
public static String baseDir = null;
@Override
public String getExampleName() {
return "JBoss ESB HelloWorld File Action Example - ESB";
}
@Override
public String[] getProjectNames() {
return new String[] {"helloworld_file_action","helloworld_file_action_client"};
}
@Override
protected void executeExample() {
/* Create the data directories needed by the quickstart */
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(inputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(outputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(errorDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
/* We need to get the project base dir for the directory definitions in jboss-esb.xml */
SWTBotView theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theProject = bot.tree(0).getTreeItem(projectName).select();
bot.menu("File").menu("Properties").click();
if (System.getProperty("file.separator").equals("/")) {
baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
}
else {
/* Needed to avoid a syntax error with Windows \ dir path characters */
//baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), System.getProperty("file.separator") + System.getProperty("file.separator")) + System.getProperty("file.separator");
+ baseDir = bot.textWithLabel("Location:").getText();
+ System.out.println("DEBUG baseDir = " + bot.textWithLabel("Location:").getText()) ;
baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), "zzz");
}
// if (System.getProperty("file.separator").equals("/")) {
// baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
// }
// else {
// baseDir = bot.textWithLabel("Location:").getText().replaceAll("\\", "\\\\") + System.getProperty("file.separator");
// }
bot.button("OK").click();
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotEditor editor = projectExplorer.openFile(projectName, "esbcontent","META-INF","jboss-esb.xml");
SWTBot theEditor = editor.bot();
theEditor.tree(0).expandNode("jboss-esb.xml", true);
SWTBotTreeItem jbossesbxml = theEditor.tree(0).getTreeItem("jboss-esb.xml");
SWTBotTreeItem providers = jbossesbxml.getNode("Providers");
SWTBotTreeItem FSProvider1 = providers.getNode("FSprovider1");
SWTBotTreeItem helloFileChannel = FSProvider1.getNode("helloFileChannel");
SWTBotTreeItem filter = helloFileChannel.getNode("Filter");
filter.select();
theEditor.text("@INPUTDIR@").setText(baseDir + inputDir);
theEditor.text("@OUTPUTDIR@").setText(baseDir + outputDir);
theEditor.text("@ERRORDIR@").setText(baseDir + errorDir);
editor.save();
bot.sleep(Timing.time30S());
//bot.sleep(30000l);
/* Deploy the quickstart */
super.executeExample();
/* Now, edit the client code */
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theClientProject = bot.tree(0).getTreeItem(clientProjectName).select();
theClientProject.expand();
//bot.sleep(30000l);
editor = projectExplorer.openFile(clientProjectName, "src","org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java");
theEditor = editor.bot();
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
theEditor.styledText().insertText(10, 0, "//");
theEditor.styledText().insertText(11, 0, "\t\tString inputDirectory = \"" + baseDir + "\" + System.getProperty(\"file.separator\") + \"inputDir\";\n");
theEditor.styledText().insertText(12, 0, "//");
theEditor.styledText().insertText(13, 0, "\t\tString fileName = \"MyInput.dat" + "\";\n");
theEditor.styledText().insertText(14, 0, "//");
theEditor.styledText().insertText(15, 0, "\t\tString fileContents = \"Hello World In A File\";\n");
theEditor.styledText().insertText(16, 0, "//");
theEditor.styledText().insertText(17, 0, "\t\tFile x = new File(inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
theEditor.styledText().insertText(23, 0, "//");
theEditor.styledText().insertText(24, 0, "\t\tSystem.out.println(\"Error while writing the file: \" + inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
//bot.sleep(30000l);
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
editor.save();
//bot.sleep(30000l);
String text = executeClientGetServerOutput(getExampleClientProjectName(),"src",
"org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test",
"CreateTestFile.java");
assertFalse ("Test fails due to ESB deployment error: NNNN", text.contains("ERROR [org.apache.juddi.v3.client.transport.wrapper.RequestHandler]"));
assertNotNull("Calling JMS Send message failed, nothing appened to server log",text);
assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Body: Hello World"));
SWTTestExt.servers.removeAllProjectsFromServer();
}
}
| true | true | protected void executeExample() {
/* Create the data directories needed by the quickstart */
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(inputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(outputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(errorDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
/* We need to get the project base dir for the directory definitions in jboss-esb.xml */
SWTBotView theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theProject = bot.tree(0).getTreeItem(projectName).select();
bot.menu("File").menu("Properties").click();
if (System.getProperty("file.separator").equals("/")) {
baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
}
else {
/* Needed to avoid a syntax error with Windows \ dir path characters */
//baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), System.getProperty("file.separator") + System.getProperty("file.separator")) + System.getProperty("file.separator");
baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), "zzz");
}
// if (System.getProperty("file.separator").equals("/")) {
// baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
// }
// else {
// baseDir = bot.textWithLabel("Location:").getText().replaceAll("\\", "\\\\") + System.getProperty("file.separator");
// }
bot.button("OK").click();
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotEditor editor = projectExplorer.openFile(projectName, "esbcontent","META-INF","jboss-esb.xml");
SWTBot theEditor = editor.bot();
theEditor.tree(0).expandNode("jboss-esb.xml", true);
SWTBotTreeItem jbossesbxml = theEditor.tree(0).getTreeItem("jboss-esb.xml");
SWTBotTreeItem providers = jbossesbxml.getNode("Providers");
SWTBotTreeItem FSProvider1 = providers.getNode("FSprovider1");
SWTBotTreeItem helloFileChannel = FSProvider1.getNode("helloFileChannel");
SWTBotTreeItem filter = helloFileChannel.getNode("Filter");
filter.select();
theEditor.text("@INPUTDIR@").setText(baseDir + inputDir);
theEditor.text("@OUTPUTDIR@").setText(baseDir + outputDir);
theEditor.text("@ERRORDIR@").setText(baseDir + errorDir);
editor.save();
bot.sleep(Timing.time30S());
//bot.sleep(30000l);
/* Deploy the quickstart */
super.executeExample();
/* Now, edit the client code */
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theClientProject = bot.tree(0).getTreeItem(clientProjectName).select();
theClientProject.expand();
//bot.sleep(30000l);
editor = projectExplorer.openFile(clientProjectName, "src","org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java");
theEditor = editor.bot();
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
theEditor.styledText().insertText(10, 0, "//");
theEditor.styledText().insertText(11, 0, "\t\tString inputDirectory = \"" + baseDir + "\" + System.getProperty(\"file.separator\") + \"inputDir\";\n");
theEditor.styledText().insertText(12, 0, "//");
theEditor.styledText().insertText(13, 0, "\t\tString fileName = \"MyInput.dat" + "\";\n");
theEditor.styledText().insertText(14, 0, "//");
theEditor.styledText().insertText(15, 0, "\t\tString fileContents = \"Hello World In A File\";\n");
theEditor.styledText().insertText(16, 0, "//");
theEditor.styledText().insertText(17, 0, "\t\tFile x = new File(inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
theEditor.styledText().insertText(23, 0, "//");
theEditor.styledText().insertText(24, 0, "\t\tSystem.out.println(\"Error while writing the file: \" + inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
//bot.sleep(30000l);
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
editor.save();
//bot.sleep(30000l);
String text = executeClientGetServerOutput(getExampleClientProjectName(),"src",
"org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test",
"CreateTestFile.java");
assertFalse ("Test fails due to ESB deployment error: NNNN", text.contains("ERROR [org.apache.juddi.v3.client.transport.wrapper.RequestHandler]"));
assertNotNull("Calling JMS Send message failed, nothing appened to server log",text);
assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Body: Hello World"));
SWTTestExt.servers.removeAllProjectsFromServer();
}
| protected void executeExample() {
/* Create the data directories needed by the quickstart */
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(inputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(outputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(errorDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
/* We need to get the project base dir for the directory definitions in jboss-esb.xml */
SWTBotView theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theProject = bot.tree(0).getTreeItem(projectName).select();
bot.menu("File").menu("Properties").click();
if (System.getProperty("file.separator").equals("/")) {
baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
}
else {
/* Needed to avoid a syntax error with Windows \ dir path characters */
//baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), System.getProperty("file.separator") + System.getProperty("file.separator")) + System.getProperty("file.separator");
baseDir = bot.textWithLabel("Location:").getText();
System.out.println("DEBUG baseDir = " + bot.textWithLabel("Location:").getText()) ;
baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), "zzz");
}
// if (System.getProperty("file.separator").equals("/")) {
// baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
// }
// else {
// baseDir = bot.textWithLabel("Location:").getText().replaceAll("\\", "\\\\") + System.getProperty("file.separator");
// }
bot.button("OK").click();
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotEditor editor = projectExplorer.openFile(projectName, "esbcontent","META-INF","jboss-esb.xml");
SWTBot theEditor = editor.bot();
theEditor.tree(0).expandNode("jboss-esb.xml", true);
SWTBotTreeItem jbossesbxml = theEditor.tree(0).getTreeItem("jboss-esb.xml");
SWTBotTreeItem providers = jbossesbxml.getNode("Providers");
SWTBotTreeItem FSProvider1 = providers.getNode("FSprovider1");
SWTBotTreeItem helloFileChannel = FSProvider1.getNode("helloFileChannel");
SWTBotTreeItem filter = helloFileChannel.getNode("Filter");
filter.select();
theEditor.text("@INPUTDIR@").setText(baseDir + inputDir);
theEditor.text("@OUTPUTDIR@").setText(baseDir + outputDir);
theEditor.text("@ERRORDIR@").setText(baseDir + errorDir);
editor.save();
bot.sleep(Timing.time30S());
//bot.sleep(30000l);
/* Deploy the quickstart */
super.executeExample();
/* Now, edit the client code */
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theClientProject = bot.tree(0).getTreeItem(clientProjectName).select();
theClientProject.expand();
//bot.sleep(30000l);
editor = projectExplorer.openFile(clientProjectName, "src","org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java");
theEditor = editor.bot();
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
theEditor.styledText().insertText(10, 0, "//");
theEditor.styledText().insertText(11, 0, "\t\tString inputDirectory = \"" + baseDir + "\" + System.getProperty(\"file.separator\") + \"inputDir\";\n");
theEditor.styledText().insertText(12, 0, "//");
theEditor.styledText().insertText(13, 0, "\t\tString fileName = \"MyInput.dat" + "\";\n");
theEditor.styledText().insertText(14, 0, "//");
theEditor.styledText().insertText(15, 0, "\t\tString fileContents = \"Hello World In A File\";\n");
theEditor.styledText().insertText(16, 0, "//");
theEditor.styledText().insertText(17, 0, "\t\tFile x = new File(inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
theEditor.styledText().insertText(23, 0, "//");
theEditor.styledText().insertText(24, 0, "\t\tSystem.out.println(\"Error while writing the file: \" + inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
//bot.sleep(30000l);
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
editor.save();
//bot.sleep(30000l);
String text = executeClientGetServerOutput(getExampleClientProjectName(),"src",
"org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test",
"CreateTestFile.java");
assertFalse ("Test fails due to ESB deployment error: NNNN", text.contains("ERROR [org.apache.juddi.v3.client.transport.wrapper.RequestHandler]"));
assertNotNull("Calling JMS Send message failed, nothing appened to server log",text);
assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Body: Hello World"));
SWTTestExt.servers.removeAllProjectsFromServer();
}
|
diff --git a/src/main/java/com/google/gson/TypeInfoFactory.java b/src/main/java/com/google/gson/TypeInfoFactory.java
index e02b647..deb88a2 100644
--- a/src/main/java/com/google/gson/TypeInfoFactory.java
+++ b/src/main/java/com/google/gson/TypeInfoFactory.java
@@ -1,124 +1,130 @@
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
/**
* A static factory class used to construct the "TypeInfo" objects.
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
final class TypeInfoFactory {
private TypeInfoFactory() {
// Not instantiable since it provides factory methods only.
}
public static TypeInfoArray getTypeInfoForArray(Type type) {
Preconditions.checkArgument(TypeUtils.isArray(type));
return new TypeInfoArray(type);
}
/**
* Evaluates the "actual" type for the field. If the field is a "TypeVariable" or has a
* "TypeVariable" in a parameterized type then it evaluates the real type.
*
* @param f the actual field object to retrieve the type from
* @param typeDefiningF the type that contains the field {@code f}
* @return the type information for the field
*/
public static TypeInfo getTypeInfoForField(Field f, Type typeDefiningF) {
Class<?> classDefiningF = TypeUtils.toRawClass(typeDefiningF);
Type type = f.getGenericType();
Type actualType = getActualType(type, typeDefiningF, classDefiningF);
return new TypeInfo(actualType);
}
private static Type getActualType(
Type typeToEvaluate, Type parentType, Class<?> rawParentClass) {
if (typeToEvaluate instanceof Class) {
return typeToEvaluate;
} else if (typeToEvaluate instanceof ParameterizedType) {
ParameterizedType castedType = (ParameterizedType) typeToEvaluate;
Type owner = castedType.getOwnerType();
Type[] actualTypeParameters =
extractRealTypes(castedType.getActualTypeArguments(), parentType, rawParentClass);
Type rawType = castedType.getRawType();
return new ParameterizedTypeImpl(rawType, actualTypeParameters, owner);
} else if (typeToEvaluate instanceof GenericArrayType) {
GenericArrayType castedType = (GenericArrayType) typeToEvaluate;
Type componentType = castedType.getGenericComponentType();
Type actualType = getActualType(componentType, parentType, rawParentClass);
if (componentType.equals(actualType)) {
return castedType;
} else {
if (actualType instanceof Class) {
return TypeUtils.wrapWithArray(TypeUtils.toRawClass(actualType));
} else {
return new GenericArrayTypeImpl(actualType);
}
}
} else if (typeToEvaluate instanceof TypeVariable) {
- // The class definition has the actual types used for the type variables.
- // Find the matching actual type for the Type Variable used for the field.
- // For example, class Foo<A> { A a; }
- // new Foo<Integer>(); defines the actual type of A to be Integer.
- // So, to find the type of the field a, we will have to look at the class'
- // actual type arguments.
- TypeVariable<?> fieldTypeVariable = (TypeVariable<?>) typeToEvaluate;
- TypeVariable<?>[] classTypeVariables = rawParentClass.getTypeParameters();
- ParameterizedType objParameterizedType = (ParameterizedType) parentType;
- int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable);
- Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments();
- return actualTypeArguments[indexOfActualTypeArgument];
+ if (parentType instanceof ParameterizedType) {
+ // The class definition has the actual types used for the type variables.
+ // Find the matching actual type for the Type Variable used for the field.
+ // For example, class Foo<A> { A a; }
+ // new Foo<Integer>(); defines the actual type of A to be Integer.
+ // So, to find the type of the field a, we will have to look at the class'
+ // actual type arguments.
+ TypeVariable<?> fieldTypeVariable = (TypeVariable<?>) typeToEvaluate;
+ TypeVariable<?>[] classTypeVariables = rawParentClass.getTypeParameters();
+ ParameterizedType objParameterizedType = (ParameterizedType) parentType;
+ int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable);
+ Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments();
+ return actualTypeArguments[indexOfActualTypeArgument];
+ } else {
+ throw new UnsupportedOperationException("Expecting parameterized type, got " + parentType
+ + ".\n Are you missing the use of TypeToken idiom?\n See "
+ + "http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener");
+ }
} else if (typeToEvaluate instanceof WildcardType) {
WildcardType castedType = (WildcardType) typeToEvaluate;
return getActualType(castedType.getUpperBounds()[0], parentType, rawParentClass);
} else {
throw new IllegalArgumentException("Type \'" + typeToEvaluate + "\' is not a Class, "
+ "ParameterizedType, GenericArrayType or TypeVariable. Can't extract type.");
}
}
private static Type[] extractRealTypes(
Type[] actualTypeArguments, Type parentType, Class<?> rawParentClass) {
Preconditions.checkNotNull(actualTypeArguments);
Type[] retTypes = new Type[actualTypeArguments.length];
for (int i = 0; i < actualTypeArguments.length; ++i) {
retTypes[i] = getActualType(actualTypeArguments[i], parentType, rawParentClass);
}
return retTypes;
}
private static int getIndex(TypeVariable<?>[] types, TypeVariable<?> type) {
for (int i = 0; i < types.length; ++i) {
if (type.equals(types[i])) {
return i;
}
}
throw new IllegalStateException(
"How can the type variable not be present in the class declaration!");
}
}
| true | true | private static Type getActualType(
Type typeToEvaluate, Type parentType, Class<?> rawParentClass) {
if (typeToEvaluate instanceof Class) {
return typeToEvaluate;
} else if (typeToEvaluate instanceof ParameterizedType) {
ParameterizedType castedType = (ParameterizedType) typeToEvaluate;
Type owner = castedType.getOwnerType();
Type[] actualTypeParameters =
extractRealTypes(castedType.getActualTypeArguments(), parentType, rawParentClass);
Type rawType = castedType.getRawType();
return new ParameterizedTypeImpl(rawType, actualTypeParameters, owner);
} else if (typeToEvaluate instanceof GenericArrayType) {
GenericArrayType castedType = (GenericArrayType) typeToEvaluate;
Type componentType = castedType.getGenericComponentType();
Type actualType = getActualType(componentType, parentType, rawParentClass);
if (componentType.equals(actualType)) {
return castedType;
} else {
if (actualType instanceof Class) {
return TypeUtils.wrapWithArray(TypeUtils.toRawClass(actualType));
} else {
return new GenericArrayTypeImpl(actualType);
}
}
} else if (typeToEvaluate instanceof TypeVariable) {
// The class definition has the actual types used for the type variables.
// Find the matching actual type for the Type Variable used for the field.
// For example, class Foo<A> { A a; }
// new Foo<Integer>(); defines the actual type of A to be Integer.
// So, to find the type of the field a, we will have to look at the class'
// actual type arguments.
TypeVariable<?> fieldTypeVariable = (TypeVariable<?>) typeToEvaluate;
TypeVariable<?>[] classTypeVariables = rawParentClass.getTypeParameters();
ParameterizedType objParameterizedType = (ParameterizedType) parentType;
int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable);
Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments();
return actualTypeArguments[indexOfActualTypeArgument];
} else if (typeToEvaluate instanceof WildcardType) {
WildcardType castedType = (WildcardType) typeToEvaluate;
return getActualType(castedType.getUpperBounds()[0], parentType, rawParentClass);
} else {
throw new IllegalArgumentException("Type \'" + typeToEvaluate + "\' is not a Class, "
+ "ParameterizedType, GenericArrayType or TypeVariable. Can't extract type.");
}
}
| private static Type getActualType(
Type typeToEvaluate, Type parentType, Class<?> rawParentClass) {
if (typeToEvaluate instanceof Class) {
return typeToEvaluate;
} else if (typeToEvaluate instanceof ParameterizedType) {
ParameterizedType castedType = (ParameterizedType) typeToEvaluate;
Type owner = castedType.getOwnerType();
Type[] actualTypeParameters =
extractRealTypes(castedType.getActualTypeArguments(), parentType, rawParentClass);
Type rawType = castedType.getRawType();
return new ParameterizedTypeImpl(rawType, actualTypeParameters, owner);
} else if (typeToEvaluate instanceof GenericArrayType) {
GenericArrayType castedType = (GenericArrayType) typeToEvaluate;
Type componentType = castedType.getGenericComponentType();
Type actualType = getActualType(componentType, parentType, rawParentClass);
if (componentType.equals(actualType)) {
return castedType;
} else {
if (actualType instanceof Class) {
return TypeUtils.wrapWithArray(TypeUtils.toRawClass(actualType));
} else {
return new GenericArrayTypeImpl(actualType);
}
}
} else if (typeToEvaluate instanceof TypeVariable) {
if (parentType instanceof ParameterizedType) {
// The class definition has the actual types used for the type variables.
// Find the matching actual type for the Type Variable used for the field.
// For example, class Foo<A> { A a; }
// new Foo<Integer>(); defines the actual type of A to be Integer.
// So, to find the type of the field a, we will have to look at the class'
// actual type arguments.
TypeVariable<?> fieldTypeVariable = (TypeVariable<?>) typeToEvaluate;
TypeVariable<?>[] classTypeVariables = rawParentClass.getTypeParameters();
ParameterizedType objParameterizedType = (ParameterizedType) parentType;
int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable);
Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments();
return actualTypeArguments[indexOfActualTypeArgument];
} else {
throw new UnsupportedOperationException("Expecting parameterized type, got " + parentType
+ ".\n Are you missing the use of TypeToken idiom?\n See "
+ "http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener");
}
} else if (typeToEvaluate instanceof WildcardType) {
WildcardType castedType = (WildcardType) typeToEvaluate;
return getActualType(castedType.getUpperBounds()[0], parentType, rawParentClass);
} else {
throw new IllegalArgumentException("Type \'" + typeToEvaluate + "\' is not a Class, "
+ "ParameterizedType, GenericArrayType or TypeVariable. Can't extract type.");
}
}
|
diff --git a/src/org/broad/igv/track/TrackLoader.java b/src/org/broad/igv/track/TrackLoader.java
index 64ab3df3..ed010868 100644
--- a/src/org/broad/igv/track/TrackLoader.java
+++ b/src/org/broad/igv/track/TrackLoader.java
@@ -1,1111 +1,1111 @@
/*
* Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*
* THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR
* WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER
* OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE
* TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES
* OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
* ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER
* THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT
* SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*/
package org.broad.igv.track;
import org.apache.log4j.Logger;
import org.broad.igv.PreferenceManager;
import org.broad.igv.bbfile.BBFileReader;
import org.broad.igv.bigwig.BigWigDataSource;
import org.broad.igv.das.DASFeatureSource;
import org.broad.igv.data.*;
import org.broad.igv.data.expression.GCTDataset;
import org.broad.igv.data.expression.GCTDatasetParser;
import org.broad.igv.data.rnai.RNAIDataSource;
import org.broad.igv.data.rnai.RNAIGCTDatasetParser;
import org.broad.igv.data.rnai.RNAIGeneScoreParser;
import org.broad.igv.data.rnai.RNAIHairpinParser;
import org.broad.igv.data.seg.FreqData;
import org.broad.igv.data.seg.SegmentedAsciiDataSet;
import org.broad.igv.data.seg.SegmentedBinaryDataSet;
import org.broad.igv.data.seg.SegmentedDataSource;
import org.broad.igv.exceptions.DataLoadException;
import org.broad.igv.feature.*;
import org.broad.igv.feature.dranger.DRangerParser;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.tribble.FeatureFileHeader;
import org.broad.igv.goby.GobyAlignmentQueryReader;
import org.broad.igv.goby.GobyCountArchiveDataSource;
import org.broad.igv.gs.GSUtils;
import org.broad.igv.gwas.GWASData;
import org.broad.igv.gwas.GWASParser;
import org.broad.igv.gwas.GWASTrack;
import org.broad.igv.lists.GeneList;
import org.broad.igv.lists.GeneListManager;
import org.broad.igv.lists.VariantListManager;
import org.broad.igv.maf.MAFTrack;
import org.broad.igv.maf.conservation.OmegaDataSource;
import org.broad.igv.maf.conservation.OmegaTrack;
import org.broad.igv.peaks.PeakTrack;
import org.broad.igv.renderer.*;
import org.broad.igv.sam.*;
import org.broad.igv.sam.reader.IndexNotFoundException;
import org.broad.igv.synteny.BlastMapping;
import org.broad.igv.synteny.BlastParser;
import org.broad.igv.tdf.TDFDataSource;
import org.broad.igv.tdf.TDFReader;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.util.ConfirmDialog;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.HttpUtils;
import org.broad.igv.util.ParsingUtils;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.variant.VariantTrack;
import org.broad.igv.variant.util.PedigreeUtils;
import org.broad.tribble.util.SeekableStream;
import org.broad.tribble.util.SeekableStreamFactory;
import org.broadinstitute.sting.utils.codecs.vcf.VCFHeader;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* User: jrobinso
* Date: Feb 14, 2010
*/
public class TrackLoader {
private static Logger log = Logger.getLogger(TrackLoader.class);
private IGV igv;
/**
* Switches on various attributes of locator (mainly locator path extension and whether the locator is indexed)
* to call the appropriate loading method.
*
* @param locator
* @return
*/
public List<Track> load(ResourceLocator locator, IGV igv) {
this.igv = igv;
- Genome genome = igv.getGenomeManager().getCurrentGenome();
+ Genome genome = igv == null ? null : igv.getGenomeManager().getCurrentGenome();
final String path = locator.getPath();
try {
String typeString = locator.getType();
if (typeString == null) {
// Genome space hack -- check for explicit type converter
//https://dmtest.genomespace.org:8444/datamanager/files/users/SAGDemo/Step1/TF.data.tab
// ?dataformat=http://www.genomespace.org/datamanager/dataformat/gct/0.0.0
- if (GSUtils.isGenomeSpace(new URL(path)) && path.contains("?dataformat")) {
+ if((path.startsWith("http://") || path.startsWith("https://")) && GSUtils.isGenomeSpace(new URL(path)) && path.contains("?dataformat")) {
if (path.contains("dataformat/gct")) {
typeString = ".gct";
} else if (path.contains("dataformat/bed")) {
typeString = ".bed";
} else if (path.contains("dataformat/cn")) {
typeString = ".cn";
}
} else {
typeString = path.toLowerCase();
if (!typeString.endsWith("_sorted.txt") &&
(typeString.endsWith(".txt") || typeString.endsWith(
".xls") || typeString.endsWith(".gz"))) {
typeString = typeString.substring(0, typeString.lastIndexOf("."));
}
}
}
typeString = typeString.toLowerCase();
if (typeString.endsWith(".tbi")) {
MessageUtils.showMessage("<html><b>Error:</b>File type '.tbi' is not recognized. If this is a 'tabix' index <br>" +
" load the associated gzipped file, which should have an extension of '.gz'");
}
//TODO Why is this not inside of isIndexed?
//dhmay seconding this question -- this appears to be taken care of already in isIndexed()
// Check for index
boolean hasIndex = false;
if (locator.isLocal()) {
File indexFile = new File(path + ".sai");
hasIndex = indexFile.exists();
}
//This list will hold all new tracks created for this locator
List<Track> newTracks = new ArrayList<Track>();
if (typeString.endsWith(".gmt")) {
loadGMT(locator);
} else if (typeString.equals("das")) {
loadDASResource(locator, newTracks);
} else if (isIndexed(path)) {
loadIndexed(locator, newTracks, genome);
} else if (typeString.endsWith(".vcf") || typeString.endsWith(".vcf4")) {
// TODO This is a hack, vcf files must be indexed. Fix in next release.
throw new IndexNotFoundException(path);
} else if (typeString.endsWith(".trio")) {
loadTrioData(locator);
} else if (typeString.endsWith("varlist")) {
VariantListManager.loadVariants(locator);
} else if (typeString.endsWith("samplepathmap")) {
VariantListManager.loadSamplePathMap(locator);
} else if (typeString.endsWith("h5") || typeString.endsWith("hbin")) {
throw new DataLoadException("HDF5 files are no longer supported", locator.getPath());
} else if (typeString.endsWith(".rnai.gct")) {
loadRnaiGctFile(locator, newTracks, genome);
} else if (typeString.endsWith(".gct") || typeString.endsWith("res") || typeString.endsWith("tab")) {
loadGctFile(locator, newTracks, genome);
} else if (typeString.endsWith(".cn") || typeString.endsWith(".xcn") || typeString.endsWith(".snp") ||
typeString.endsWith(".igv") || typeString.endsWith(".loh")) {
loadIGVFile(locator, newTracks, genome);
} else if (typeString.endsWith(".mut")) {
loadMutFile(locator, newTracks, genome);
} else if (typeString.endsWith(".cbs") || typeString.endsWith(".seg") ||
typeString.endsWith("glad") || typeString.endsWith("birdseye_canary_calls")) {
loadSegFile(locator, newTracks, genome);
} else if (typeString.endsWith(".seg.zip")) {
loadBinarySegFile(locator, newTracks, genome);
} else if (typeString.endsWith(".gistic")) {
loadGisticFile(locator, newTracks);
} else if (typeString.endsWith(".gs")) {
loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.GENE_SCORE, genome);
} else if (typeString.endsWith(".riger")) {
loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.POOLED, genome);
} else if (typeString.endsWith(".hp")) {
loadRNAiHPScoreFile(locator);
} else if (typeString.endsWith("gene")) {
loadGeneFile(locator, newTracks, genome);
} else if (typeString.contains(".tabblastn") || typeString.endsWith(".orthologs")) {
loadSyntentyMapping(locator, newTracks);
} else if (typeString.endsWith(".sam") || typeString.endsWith(".bam") ||
typeString.endsWith(".sam.list") || typeString.endsWith(".bam.list") ||
typeString.endsWith("_sorted.txt") ||
typeString.endsWith(".aligned") || typeString.endsWith(".sai") ||
typeString.endsWith(".bai")) {
loadAlignmentsTrack(locator, newTracks, genome);
} else if (typeString.endsWith(".bedz") || (typeString.endsWith(".bed") && hasIndex)) {
loadIndexdBedFile(locator, newTracks, genome);
} else if (typeString.endsWith(".omega")) {
loadOmegaTrack(locator, newTracks, genome);
} else if (typeString.endsWith(".wig") || (typeString.endsWith(".bedgraph")) ||
typeString.endsWith("cpg.txt") || typeString.endsWith(".expr")) {
loadWigFile(locator, newTracks, genome);
} else if (typeString.endsWith(".list")) {
loadListFile(locator, newTracks, genome);
} else if (typeString.contains(".dranger")) {
loadDRangerFile(locator, newTracks, genome);
} else if (typeString.endsWith(".ewig.tdf") || (typeString.endsWith(".ewig.ibf"))) {
loadEwigIBFFile(locator, newTracks, genome);
} else if (typeString.endsWith(".bw") || typeString.endsWith(".bb") || typeString.endsWith(".bigwig") ||
typeString.endsWith(".bigbed")) {
loadBWFile(locator, newTracks, genome);
} else if (typeString.endsWith(".ibf") || typeString.endsWith(".tdf")) {
loadTDFFile(locator, newTracks, genome);
} else if (typeString.endsWith(".counts")) {
loadGobyCountsArchive(locator, newTracks, genome);
} else if (typeString.endsWith(".psl") || typeString.endsWith(".psl.gz") ||
typeString.endsWith(".pslx") || typeString.endsWith(".pslx.gz")) {
loadPslFile(locator, newTracks, genome);
//TODO AbstractFeatureParser.getInstanceFor() is called twice. Wasteful
} else if (AbstractFeatureParser.getInstanceFor(locator, genome) != null) {
loadFeatureFile(locator, newTracks, genome);
} else if (MutationParser.isMutationAnnotationFile(locator)) {
this.loadMutFile(locator, newTracks, genome);
} else if (WiggleParser.isWiggle(locator)) {
loadWigFile(locator, newTracks, genome);
} else if (path.toLowerCase().contains(".maf")) {
loadMAFTrack(locator, newTracks);
} else if (path.toLowerCase().contains(".peak.cfg")) {
loadPeakTrack(locator, newTracks, genome);
} else if ("mage-tab".equals(locator.getType()) || GCTDatasetParser.parsableMAGE_TAB(locator)) {
locator.setDescription("MAGE_TAB");
loadGctFile(locator, newTracks, genome);
} else if (typeString.endsWith(".logistic") || typeString.endsWith(".linear") || typeString.endsWith(".assoc") ||
typeString.endsWith(".qassoc") || typeString.endsWith(".gwas")) {
loadGWASFile(locator, newTracks);
} else if (GobyAlignmentQueryReader.supportsFileType(path)) {
loadAlignmentsTrack(locator, newTracks, genome);
} else if (AttributeManager.isSampleInfoFile(locator)) {
// This might be a sample information file.
AttributeManager.getInstance().loadSampleInfo(locator);
} else {
MessageUtils.showMessage("<html>Unknown file type: " + path + "<br>Check file extenstion");
}
// Track line
TrackProperties tp = null;
String trackLine = locator.getTrackLine();
if (trackLine != null) {
tp = new TrackProperties();
ParsingUtils.parseTrackLine(trackLine, tp);
}
for (Track track : newTracks) {
if (locator.getUrl() != null) {
track.setUrl(locator.getUrl());
}
if (tp != null) {
track.setProperties(tp);
}
if (locator.getColor() != null) {
track.setColor(locator.getColor());
}
if (locator.getSampleId() != null) {
track.setSampleId(locator.getSampleId());
}
}
return newTracks;
} catch (DataLoadException dle) {
throw dle;
} catch (Exception e) {
log.error(e);
throw new DataLoadException(e.getMessage(), path);
}
}
private void loadGMT(ResourceLocator locator) throws IOException {
List<GeneList> lists = GeneListManager.getInstance().importGMTFile(locator.getPath());
if (lists.size() == 1) {
GeneList gl = lists.get(0);
IGV.getInstance().setGeneList(gl.getName(), true);
} else {
MessageUtils.showMessage("Loaded " + lists.size() + " gene lists.");
}
}
private void loadIndexed(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException {
TribbleFeatureSource src = new TribbleFeatureSource(locator.getPath(), genome);
String typeString = locator.getPath();
//Track t;
if (typeString.endsWith("vcf") || typeString.endsWith("vcf.gz")) {
VCFHeader header = (VCFHeader) src.getHeader();
// Test if the input VCF file contains methylation rate data:
// This is determined by testing for the presence of two sample format fields: MR and GB, used in the
// rendering of methylation rate.
// MR is the methylation rate on a scale of 0 to 100% and GB is the number of bases that pass
// filter for the position. GB is needed to avoid displaying positions for which limited coverage
// prevents reliable estimation of methylation rate.
boolean enableMethylationRateSupport = (header.getFormatHeaderLine("MR") != null &&
header.getFormatHeaderLine("GB") != null);
List<String> allSamples = new ArrayList(header.getGenotypeSamples());
VariantTrack t = new VariantTrack(locator, src, allSamples, enableMethylationRateSupport);
// VCF tracks handle their own margin
t.setMargin(0);
newTracks.add(t);
} else {
// Create feature source and track
FeatureTrack t = new FeatureTrack(locator, src);
t.setName(locator.getTrackName());
//t.setRendererClass(BasicTribbleRenderer.class);
// Set track properties from header
Object header = src.getHeader();
if (header != null && header instanceof FeatureFileHeader) {
FeatureFileHeader ffh = (FeatureFileHeader) header;
if (ffh.getTrackType() != null) {
t.setTrackType(ffh.getTrackType());
}
if (ffh.getTrackProperties() != null) {
t.setProperties(ffh.getTrackProperties());
}
if (ffh.getTrackType() == TrackType.REPMASK) {
t.setHeight(15);
t.setPreferredHeight(15);
}
}
newTracks.add(t);
}
}
/**
* Load the input file as a BED or Attribute (Sample Info) file. First assume
* it is a BED file, if no features are found load as an attribute file.
*
* @param locator
* @param newTracks
*/
private void loadGeneFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
FeatureParser featureParser = AbstractFeatureParser.getInstanceFor(locator, genome);
if (featureParser != null) {
List<FeatureTrack> tracks = featureParser.loadTracks(locator, genome);
newTracks.addAll(tracks);
}
}
private void loadSyntentyMapping(ResourceLocator locator, List<Track> newTracks) {
List<BlastMapping> mappings = (new BlastParser()).parse(locator.getPath());
List<org.broad.tribble.Feature> features = new ArrayList<org.broad.tribble.Feature>(mappings.size());
features.addAll(mappings);
Genome genome = igv.getGenomeManager().getCurrentGenome();
FeatureTrack track = new FeatureTrack(locator, new FeatureCollectionSource(features, genome));
track.setName(locator.getTrackName());
// track.setRendererClass(AlignmentBlockRenderer.class);
newTracks.add(track);
}
private void loadDRangerFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
DRangerParser parser = new DRangerParser();
newTracks.addAll(parser.loadTracks(locator, genome));
}
/**
* Load the input file as a feature, mutation, or maf (multiple alignment) file.
*
* @param locator
* @param newTracks
*/
private void loadPslFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException {
PSLParser featureParser = new PSLParser(genome);
List<FeatureTrack> tracks = featureParser.loadTracks(locator, genome);
newTracks.addAll(tracks);
for (FeatureTrack t : tracks) {
t.setMinimumHeight(10);
t.setHeight(30);
t.setPreferredHeight(30);
t.setDisplayMode(Track.DisplayMode.EXPANDED);
}
}
/**
* Load the input file as a feature, muation, or maf (multiple alignment) file.
*
* @param locator
* @param newTracks
*/
private void loadFeatureFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException {
if (locator.isLocal() && (locator.getPath().endsWith(".bed") ||
locator.getPath().endsWith(".bed.txt") ||
locator.getPath().endsWith(".bed.gz"))) {
//checkSize takes care of warning the user
if (!checkSize(locator.getPath())) {
return;
}
}
FeatureParser featureParser = AbstractFeatureParser.getInstanceFor(locator, genome);
if (featureParser != null) {
List<FeatureTrack> tracks = featureParser.loadTracks(locator, genome);
newTracks.addAll(tracks);
} else if (MutationParser.isMutationAnnotationFile(locator)) {
this.loadMutFile(locator, newTracks, genome);
} else if (WiggleParser.isWiggle(locator)) {
loadWigFile(locator, newTracks, genome);
} else if (locator.getPath().toLowerCase().contains(".maf")) {
loadMAFTrack(locator, newTracks);
}
}
/**
* Load the input file as a feature, muation, or maf (multiple alignment) file.
*
* @param locator
* @param newTracks
*/
private void loadIndexdBedFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException {
File featureFile = new File(locator.getPath());
File indexFile = new File(locator.getPath() + ".sai");
FeatureSource src = new IndexedBEDFeatureSource(featureFile, indexFile, genome);
Track t = new FeatureTrack(locator, src);
newTracks.add(t);
}
/**
* Load GWAS PLINK result file
*
* @param locator
* @param newTracks
* @throws IOException
*/
private void loadGWASFile(ResourceLocator locator, List<Track> newTracks) throws IOException {
GWASParser gwasParser = new GWASParser(locator);
GWASData gwasData = gwasParser.parse();
GWASTrack gwasTrack = new GWASTrack(locator, locator.getPath(), locator.getFileName(), gwasData, gwasParser);
newTracks.add(gwasTrack);
}
private void loadRnaiGctFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
RNAIGCTDatasetParser parser = new RNAIGCTDatasetParser(locator, genome);
Collection<RNAIDataSource> dataSources = parser.parse();
if (dataSources != null) {
String path = locator.getPath();
for (RNAIDataSource ds : dataSources) {
String trackId = path + "_" + ds.getName();
DataSourceTrack track = new DataSourceTrack(locator, trackId, ds.getName(), ds, genome);
// Set attributes.
track.setAttributeValue("SCREEN", ds.getScreen());
track.setHeight(80);
track.setPreferredHeight(80);
newTracks.add(track);
}
}
}
private void loadGctFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
if (locator.isLocal()) {
if (!checkSize(locator.getPath())) {
return;
}
}
GCTDatasetParser parser = null;
GCTDataset ds = null;
String fName = locator.getTrackName();
// TODO -- handle remote resource
try {
parser = new GCTDatasetParser(locator, null, igv.getGenomeManager().getCurrentGenome());
} catch (IOException e) {
log.error("Error creating GCT parser.", e);
throw new DataLoadException("Error creating GCT parser: " + e, locator.getPath());
}
ds = parser.createDataset();
ds.setName(fName);
ds.setNormalized(true);
ds.setLogValues(true);
/*
* File outputFile = new File(IGV.DEFAULT_USER_DIRECTORY, file.getName() + ".h5");
* OverlappingProcessor proc = new OverlappingProcessor(ds);
* proc.setZoomMax(0);
* proc.process(outputFile.getAbsolutePath());
* loadH5File(outputFile, messages, attributeList, group);
*/
// Counter for generating ID
TrackProperties trackProperties = ds.getTrackProperties();
String path = locator.getPath();
for (String trackName : ds.getTrackNames()) {
Genome currentGenome = igv.getGenomeManager().getCurrentGenome();
DatasetDataSource dataSource = new DatasetDataSource(trackName, ds, currentGenome);
String trackId = path + "_" + trackName;
Track track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome);
track.setRendererClass(HeatmapRenderer.class);
track.setProperties(trackProperties);
newTracks.add(track);
}
}
private void loadIGVFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
if (locator.isLocal()) {
if (!checkSize(locator.getPath())) {
return;
}
}
String dsName = locator.getTrackName();
IGVDataset ds = new IGVDataset(locator, genome, igv);
ds.setName(dsName);
TrackProperties trackProperties = ds.getTrackProperties();
String path = locator.getPath();
TrackType type = ds.getType();
for (String trackName : ds.getTrackNames()) {
DatasetDataSource dataSource = new DatasetDataSource(trackName, ds, genome);
String trackId = path + "_" + trackName;
DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome);
// track.setRendererClass(HeatmapRenderer.class);
track.setTrackType(ds.getType());
track.setProperties(trackProperties);
if (type == TrackType.ALLELE_FREQUENCY) {
track.setRendererClass(ScatterplotRenderer.class);
track.setHeight(40);
track.setPreferredHeight(40);
}
newTracks.add(track);
}
}
private boolean checkSize(String file) {
if (!PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SHOW_SIZE_WARNING)) {
return true;
}
File f = new File(file);
String tmp = file;
if (f.exists()) {
long size = f.length();
if (file.endsWith(".gz")) {
size *= 3;
tmp = file.substring(0, file.length() - 3);
}
if (size > 50000000) {
String message = "";
if (tmp.endsWith(".bed") || tmp.endsWith(".bed.txt")) {
message = "The file " + file + " is large (" + (size / 1000000) + " mb). It is recommended " +
"that large files be indexed using IGVTools or Tabix. Loading un-indexed " +
"ascii fies of this size can lead to poor performance or unresponsiveness (freezing). " +
"<br><br>IGVTools can be launched from the <b>Tools</b> menu or separately as a command line program. " +
"See the user guide for more details.<br><br>Click <b>Continue</b> to continue loading, or <b>Cancel</b>" +
" to skip this file.";
} else {
message = "The file " + file + " is large (" + (size / 1000000) + " mb). It is recommended " +
"that large files be converted to the binary <i>.tdf</i> format using the IGVTools " +
"<b>tile</b> command. Loading unconverted ascii fies of this size can lead to poor " +
"performance or unresponsiveness (freezing). " +
"<br><br>IGVTools can be launched from the <b>Tools</b> menu or separately as a " +
"command line program. See the user guide for more details.<br><br>Click <b>Continue</b> " +
"to continue loading, or <b>Cancel</b> to skip this file.";
}
return ConfirmDialog.optionallyShowConfirmDialog(message, PreferenceManager.SHOW_SIZE_WARNING, true);
}
}
return true;
}
private void loadDOTFile(ResourceLocator locator, List<Track> newTracks) {
//GraphTrack gt = new GraphTrack(locator);
//gt.setHeight(80);
//newTracks.add(gt);
}
private void loadWigFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
if (locator.isLocal()) {
if (!checkSize(locator.getPath())) {
return;
}
}
WiggleDataset ds = (new WiggleParser(locator, genome)).parse();
TrackProperties props = ds.getTrackProperties();
// In case of conflict between the resource locator display name and the track properties name,
// use the resource locator
String name = props == null ? null : props.getName();
String label = locator.getName();
if (name == null) {
name = locator.getFileName();
} else if (label != null) {
props.setName(label); // erase name rom track properties
}
String path = locator.getPath();
boolean multiTrack = ds.getTrackNames().length > 1;
for (String heading : ds.getTrackNames()) {
String trackId = multiTrack ? path + "_" + heading : path;
String trackName = multiTrack ? heading : name;
Genome currentGenome = IGV.getInstance().getGenomeManager().getCurrentGenome();
DatasetDataSource dataSource = new DatasetDataSource(trackId, ds, genome);
DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome);
String displayName = (label == null || multiTrack) ? heading : label;
track.setName(displayName);
track.setProperties(props);
track.setTrackType(ds.getType());
if (ds.getType() == TrackType.EXPR) {
track.setWindowFunction(WindowFunction.none);
}
newTracks.add(track);
}
}
private void loadTDFFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
if (log.isDebugEnabled()) {
log.debug("Loading TDFFile: " + locator.toString());
}
TDFReader reader = TDFReader.getReader(locator.getPath());
TrackType type = reader.getTrackType();
if (log.isDebugEnabled()) {
log.debug("Parsing track line ");
}
TrackProperties props = null;
String trackLine = reader.getTrackLine();
if (trackLine != null && trackLine.length() > 0) {
props = new TrackProperties();
ParsingUtils.parseTrackLine(trackLine, props);
}
// In case of conflict between the resource locator display name and the track properties name,
// use the resource locator
String name = locator.getName();
if (name != null && props != null) {
props.setName(name);
}
if (name == null) {
name = props == null ? locator.getTrackName() : props.getName();
}
int trackNumber = 0;
String path = locator.getPath();
boolean multiTrack = reader.getTrackNames().length > 1;
for (String heading : reader.getTrackNames()) {
String trackId = multiTrack ? path + "_" + heading : path;
String trackName = multiTrack ? heading : name;
final DataSource dataSource = locator.getPath().endsWith(".counts") ?
new GobyCountArchiveDataSource(locator) :
new TDFDataSource(reader, trackNumber, heading, genome);
DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName,
dataSource, genome);
String displayName = (name == null || multiTrack) ? heading : name;
track.setName(displayName);
track.setTrackType(type);
if (props != null) {
track.setProperties(props);
}
newTracks.add(track);
trackNumber++;
}
}
private void loadBWFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException {
String trackName = locator.getTrackName();
String trackId = locator.getPath();
String path = locator.getPath();
SeekableStream ss = SeekableStreamFactory.getStreamFor(path);
BBFileReader reader = new BBFileReader(path, ss);
BigWigDataSource bigwigSource = new BigWigDataSource(reader, genome);
if (reader.isBigWigFile()) {
DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, bigwigSource, genome);
newTracks.add(track);
} else if (reader.isBigBedFile()) {
FeatureTrack track = new FeatureTrack(trackId, trackName, bigwigSource);
newTracks.add(track);
} else {
throw new RuntimeException("Unknown BIGWIG type: " + locator.getPath());
}
}
private void loadGobyCountsArchive(ResourceLocator locator, List<Track> newTracks, Genome genome) {
if (log.isDebugEnabled()) {
log.debug("Loading Goby counts archive: " + locator.toString());
}
String trackId = locator.getSampleId() + " coverage";
String trackName = locator.getFileName();
final DataSource dataSource = new GobyCountArchiveDataSource(locator);
DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName,
dataSource, genome);
newTracks.add(track);
}
private void loadEwigIBFFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
TDFReader reader = TDFReader.getReader(locator.getPath());
TrackProperties props = null;
String trackLine = reader.getTrackLine();
if (trackLine != null && trackLine.length() > 0) {
props = new TrackProperties();
ParsingUtils.parseTrackLine(trackLine, props);
}
EWigTrack track = new EWigTrack(locator, genome);
if (props != null) {
track.setProperties(props);
}
track.setName(locator.getTrackName());
newTracks.add(track);
}
private void loadListFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
try {
FeatureSource source = new FeatureDirSource(locator, genome);
FeatureTrack track = new FeatureTrack(locator, source);
track.setName(locator.getTrackName());
track.setVisibilityWindow(0);
newTracks.add(track);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private void loadGisticFile(ResourceLocator locator, List<Track> newTracks) {
GisticTrack track = GisticFileParser.loadData(locator);
track.setName(locator.getTrackName());
newTracks.add(track);
}
/**
* Load a rnai gene score file and create a datasource and track.
* <p/>
* // TODO -- change parser to use resource locator rather than path.
*
* @param locator
* @param newTracks
*/
private void loadRNAiGeneScoreFile(ResourceLocator locator,
List<Track> newTracks, RNAIGeneScoreParser.Type type,
Genome genome) {
RNAIGeneScoreParser parser = new RNAIGeneScoreParser(locator.getPath(), type, genome);
Collection<RNAIDataSource> dataSources = parser.parse();
String path = locator.getPath();
for (RNAIDataSource ds : dataSources) {
String name = ds.getName();
String trackId = path + "_" + name;
DataSourceTrack track = new DataSourceTrack(locator, trackId, name, ds, genome);
// Set attributes. This "hack" is neccessary to register these attributes with the
// attribute manager to get displayed.
track.setAttributeValue("SCREEN", ds.getScreen());
if ((ds.getCondition() != null) && (ds.getCondition().length() > 0)) {
track.setAttributeValue("CONDITION", ds.getCondition());
}
track.setHeight(80);
track.setPreferredHeight(80);
//track.setDataRange(new DataRange(-3, 0, 3));
newTracks.add(track);
}
}
/**
* Load a RNAi haripin score file. The results of this action are hairpin scores
* added to the RNAIDataManager. Currently no tracks are created for hairpin
* scores, although this could change.
*
* @param locator
*/
private void loadRNAiHPScoreFile(ResourceLocator locator) {
(new RNAIHairpinParser(locator.getPath())).parse();
}
private void loadMAFTrack(ResourceLocator locator, List<Track> newTracks) {
MAFTrack t = new MAFTrack(locator);
t.setName("Multiple Alignments");
newTracks.add(t);
}
private void loadPeakTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException {
PeakTrack t = new PeakTrack(locator, genome);
newTracks.add(t);
}
private void loadOmegaTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) {
OmegaDataSource ds = new OmegaDataSource(genome);
OmegaTrack track = new OmegaTrack(locator, ds, genome);
track.setName("Conservation (Omega)");
track.setHeight(40);
track.setPreferredHeight(40);
newTracks.add(track);
}
/**
* Load a rnai gene score file and create a datasource and track.
*
* @param locator
* @param newTracks
*/
private void loadAlignmentsTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException {
try {
String dsName = locator.getTrackName();
String fn = locator.getPath().toLowerCase();
boolean isBed = fn.endsWith(".bedz") || fn.endsWith(".bed") || fn.endsWith(".bed.gz");
// If the user tried to load the index, look for the file (this is a common mistake)
if (locator.getPath().endsWith(".sai") || locator.getPath().endsWith(".bai")) {
MessageUtils.showMessage("<html><b>ERROR:</b> Loading SAM/BAM index files are not supported: " + locator.getPath() +
"<br>Load the SAM or BAM file directly. ");
return;
}
AlignmentDataManager dataManager = new AlignmentDataManager(locator);
if (locator.getPath().toLowerCase().endsWith(".bam")) {
if (!dataManager.hasIndex()) {
MessageUtils.showMessage("<html>Could not load index file for: " +
locator.getPath() + "<br> An index file is required for SAM & BAM files.");
return;
}
}
AlignmentTrack alignmentTrack = new AlignmentTrack(locator, dataManager, genome); // parser.loadTrack(locator, dsName);
alignmentTrack.setName(dsName);
if (isBed) {
alignmentTrack.setRenderer(new BedRenderer());
alignmentTrack.setPreferredHeight(40);
alignmentTrack.setHeight(40);
}
// Create coverage track
CoverageTrack covTrack = new CoverageTrack(locator, alignmentTrack.getName() + " Coverage", genome);
covTrack.setVisible(PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_COV_TRACK));
newTracks.add(covTrack);
alignmentTrack.setCoverageTrack(covTrack);
if (!isBed) {
covTrack.setDataManager(dataManager);
dataManager.setCoverageTrack(covTrack);
}
// Search for precalculated coverage data
String covPath = locator.getCoverage();
if (covPath == null) {
String path = locator.getPath();
covPath = path + ".tdf";
}
if (covPath != null) {
try {
if ((new File(covPath)).exists() || (HttpUtils.getInstance().isURL(covPath) &&
HttpUtils.getInstance().resourceAvailable(new URL(covPath)))) {
TDFReader reader = TDFReader.getReader(covPath);
TDFDataSource ds = new TDFDataSource(reader, 0, alignmentTrack.getName() + " coverage", genome);
covTrack.setDataSource(ds);
}
} catch (MalformedURLException e) {
// This is expected if
// log.info("Could not loading coverage data: MalformedURL: " + covPath);
}
}
boolean showSpliceJunctionTrack = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_JUNCTION_TRACK);
if (showSpliceJunctionTrack) {
SpliceJunctionFinderTrack spliceJunctionTrack = new SpliceJunctionFinderTrack(locator.getPath() + "_junctions",
alignmentTrack.getName() + " Junctions", dataManager, genome);
// spliceJunctionTrack.setDataManager(dataManager);
spliceJunctionTrack.setHeight(60);
spliceJunctionTrack.setPreferredHeight(60);
spliceJunctionTrack.setVisible(showSpliceJunctionTrack);
newTracks.add(spliceJunctionTrack);
alignmentTrack.setSpliceJunctionTrack(spliceJunctionTrack);
}
newTracks.add(alignmentTrack);
} catch (IndexNotFoundException e) {
MessageUtils.showMessage("<html>Could not find the index file for <br><br> " + e.getSamFile() +
"<br><br>Note: The index file can be created using igvtools and must be in the same directory as the .sam file.");
}
}
/**
* Load a ".mut" file (muation file) and create tracks.
*
* @param locator
* @param newTracks
*/
private void loadMutFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
MutationParser parser = new MutationParser();
List<FeatureTrack> mutationTracks = parser.loadMutationTracks(locator, genome);
for (FeatureTrack track : mutationTracks) {
track.setTrackType(TrackType.MUTATION);
track.setRendererClass(MutationRenderer.class);
newTracks.add(track);
}
}
private void loadSegFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
// TODO - -handle remote resource
SegmentedAsciiDataSet ds = new SegmentedAsciiDataSet(locator, genome);
String path = locator.getPath();
TrackProperties props = ds.getTrackProperties();
// The "freq" track. TODO - make this optional
if (ds.getSampleNames().size() > 1) {
FreqData fd = new FreqData(ds, genome);
String freqTrackId = path;
String freqTrackName = (new File(path)).getName();
CNFreqTrack freqTrack = new CNFreqTrack(locator, freqTrackId, freqTrackName, fd);
newTracks.add(freqTrack);
}
for (String trackName : ds.getDataHeadings()) {
String trackId = path + "_" + trackName;
SegmentedDataSource dataSource = new SegmentedDataSource(trackName, ds);
DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome);
track.setRendererClass(HeatmapRenderer.class);
track.setTrackType(ds.getType());
if (props != null) {
track.setProperties(props);
}
newTracks.add(track);
}
}
private void loadBinarySegFile(ResourceLocator locator, List<Track> newTracks, Genome genome) {
SegmentedBinaryDataSet ds = new SegmentedBinaryDataSet(locator);
String path = locator.getPath();
// The "freq" track. Make this optional?
FreqData fd = new FreqData(ds, genome);
String freqTrackId = path;
String freqTrackName = (new File(path)).getName();
CNFreqTrack freqTrack = new CNFreqTrack(locator, freqTrackId, freqTrackName, fd);
newTracks.add(freqTrack);
for (String trackName : ds.getSampleNames()) {
String trackId = path + "_" + trackName;
SegmentedDataSource dataSource = new SegmentedDataSource(trackName, ds);
DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome);
track.setRendererClass(HeatmapRenderer.class);
track.setTrackType(ds.getType());
newTracks.add(track);
}
}
private void loadDASResource(ResourceLocator locator, List<Track> currentTracks) {
//TODO Connect and get all the attributes of the DAS server, and run the appropriate load statements
//TODO Currently we are only going to be doing features
// TODO -- move the source creation to a factory
DASFeatureSource featureSource = null;
try {
featureSource = new DASFeatureSource(locator);
} catch (MalformedURLException e) {
log.error("Malformed URL", e);
throw new DataLoadException("Error: Malformed URL ", locator.getPath());
}
FeatureTrack track = new FeatureTrack(locator, featureSource);
// Try to create a sensible name from the path
String name = locator.getPath();
if (locator.getPath().contains("genome.ucsc.edu")) {
name = featureSource.getType();
} else {
name = featureSource.getPath().replace("/das/", "").replace("/features", "");
}
track.setName(name);
// A hack until we can notate this some other way
if (locator.getPath().contains("cosmic")) {
track.setRendererClass(CosmicFeatureRenderer.class);
track.setMinimumHeight(2);
track.setHeight(20);
track.setPreferredHeight(20);
track.setDisplayMode(Track.DisplayMode.EXPANDED);
} else {
track.setRendererClass(IGVFeatureRenderer.class);
track.setMinimumHeight(35);
track.setHeight(45);
track.setPreferredHeight(45);
}
currentTracks.add(track);
}
private void loadTrioData(ResourceLocator locator) throws IOException {
PedigreeUtils.parseTrioFile(locator.getPath());
}
public static boolean isIndexed(String path) {
// genome space hack -- genome space files are never indexed (at least not yet)
if (path.contains("genomespace.org")) {
return false;
}
String indexExtension = path.endsWith("gz") ? ".tbi" : ".idx";
String indexPath = path + indexExtension;
try {
if (HttpUtils.getInstance().isURL(path)) {
boolean exists = HttpUtils.getInstance().resourceAvailable(new URL(indexPath));
if (!exists) {
// Check for gzipped index
exists = HttpUtils.getInstance().resourceAvailable(new URL(indexPath + ".gz"));
}
return exists;
} else {
File f = new File(path + indexExtension);
return f.exists();
}
} catch (IOException e) {
return false;
}
}
}
| false | true | public List<Track> load(ResourceLocator locator, IGV igv) {
this.igv = igv;
Genome genome = igv.getGenomeManager().getCurrentGenome();
final String path = locator.getPath();
try {
String typeString = locator.getType();
if (typeString == null) {
// Genome space hack -- check for explicit type converter
//https://dmtest.genomespace.org:8444/datamanager/files/users/SAGDemo/Step1/TF.data.tab
// ?dataformat=http://www.genomespace.org/datamanager/dataformat/gct/0.0.0
if (GSUtils.isGenomeSpace(new URL(path)) && path.contains("?dataformat")) {
if (path.contains("dataformat/gct")) {
typeString = ".gct";
} else if (path.contains("dataformat/bed")) {
typeString = ".bed";
} else if (path.contains("dataformat/cn")) {
typeString = ".cn";
}
} else {
typeString = path.toLowerCase();
if (!typeString.endsWith("_sorted.txt") &&
(typeString.endsWith(".txt") || typeString.endsWith(
".xls") || typeString.endsWith(".gz"))) {
typeString = typeString.substring(0, typeString.lastIndexOf("."));
}
}
}
typeString = typeString.toLowerCase();
if (typeString.endsWith(".tbi")) {
MessageUtils.showMessage("<html><b>Error:</b>File type '.tbi' is not recognized. If this is a 'tabix' index <br>" +
" load the associated gzipped file, which should have an extension of '.gz'");
}
//TODO Why is this not inside of isIndexed?
//dhmay seconding this question -- this appears to be taken care of already in isIndexed()
// Check for index
boolean hasIndex = false;
if (locator.isLocal()) {
File indexFile = new File(path + ".sai");
hasIndex = indexFile.exists();
}
//This list will hold all new tracks created for this locator
List<Track> newTracks = new ArrayList<Track>();
if (typeString.endsWith(".gmt")) {
loadGMT(locator);
} else if (typeString.equals("das")) {
loadDASResource(locator, newTracks);
} else if (isIndexed(path)) {
loadIndexed(locator, newTracks, genome);
} else if (typeString.endsWith(".vcf") || typeString.endsWith(".vcf4")) {
// TODO This is a hack, vcf files must be indexed. Fix in next release.
throw new IndexNotFoundException(path);
} else if (typeString.endsWith(".trio")) {
loadTrioData(locator);
} else if (typeString.endsWith("varlist")) {
VariantListManager.loadVariants(locator);
} else if (typeString.endsWith("samplepathmap")) {
VariantListManager.loadSamplePathMap(locator);
} else if (typeString.endsWith("h5") || typeString.endsWith("hbin")) {
throw new DataLoadException("HDF5 files are no longer supported", locator.getPath());
} else if (typeString.endsWith(".rnai.gct")) {
loadRnaiGctFile(locator, newTracks, genome);
} else if (typeString.endsWith(".gct") || typeString.endsWith("res") || typeString.endsWith("tab")) {
loadGctFile(locator, newTracks, genome);
} else if (typeString.endsWith(".cn") || typeString.endsWith(".xcn") || typeString.endsWith(".snp") ||
typeString.endsWith(".igv") || typeString.endsWith(".loh")) {
loadIGVFile(locator, newTracks, genome);
} else if (typeString.endsWith(".mut")) {
loadMutFile(locator, newTracks, genome);
} else if (typeString.endsWith(".cbs") || typeString.endsWith(".seg") ||
typeString.endsWith("glad") || typeString.endsWith("birdseye_canary_calls")) {
loadSegFile(locator, newTracks, genome);
} else if (typeString.endsWith(".seg.zip")) {
loadBinarySegFile(locator, newTracks, genome);
} else if (typeString.endsWith(".gistic")) {
loadGisticFile(locator, newTracks);
} else if (typeString.endsWith(".gs")) {
loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.GENE_SCORE, genome);
} else if (typeString.endsWith(".riger")) {
loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.POOLED, genome);
} else if (typeString.endsWith(".hp")) {
loadRNAiHPScoreFile(locator);
} else if (typeString.endsWith("gene")) {
loadGeneFile(locator, newTracks, genome);
} else if (typeString.contains(".tabblastn") || typeString.endsWith(".orthologs")) {
loadSyntentyMapping(locator, newTracks);
} else if (typeString.endsWith(".sam") || typeString.endsWith(".bam") ||
typeString.endsWith(".sam.list") || typeString.endsWith(".bam.list") ||
typeString.endsWith("_sorted.txt") ||
typeString.endsWith(".aligned") || typeString.endsWith(".sai") ||
typeString.endsWith(".bai")) {
loadAlignmentsTrack(locator, newTracks, genome);
} else if (typeString.endsWith(".bedz") || (typeString.endsWith(".bed") && hasIndex)) {
loadIndexdBedFile(locator, newTracks, genome);
} else if (typeString.endsWith(".omega")) {
loadOmegaTrack(locator, newTracks, genome);
} else if (typeString.endsWith(".wig") || (typeString.endsWith(".bedgraph")) ||
typeString.endsWith("cpg.txt") || typeString.endsWith(".expr")) {
loadWigFile(locator, newTracks, genome);
} else if (typeString.endsWith(".list")) {
loadListFile(locator, newTracks, genome);
} else if (typeString.contains(".dranger")) {
loadDRangerFile(locator, newTracks, genome);
} else if (typeString.endsWith(".ewig.tdf") || (typeString.endsWith(".ewig.ibf"))) {
loadEwigIBFFile(locator, newTracks, genome);
} else if (typeString.endsWith(".bw") || typeString.endsWith(".bb") || typeString.endsWith(".bigwig") ||
typeString.endsWith(".bigbed")) {
loadBWFile(locator, newTracks, genome);
} else if (typeString.endsWith(".ibf") || typeString.endsWith(".tdf")) {
loadTDFFile(locator, newTracks, genome);
} else if (typeString.endsWith(".counts")) {
loadGobyCountsArchive(locator, newTracks, genome);
} else if (typeString.endsWith(".psl") || typeString.endsWith(".psl.gz") ||
typeString.endsWith(".pslx") || typeString.endsWith(".pslx.gz")) {
loadPslFile(locator, newTracks, genome);
//TODO AbstractFeatureParser.getInstanceFor() is called twice. Wasteful
} else if (AbstractFeatureParser.getInstanceFor(locator, genome) != null) {
loadFeatureFile(locator, newTracks, genome);
} else if (MutationParser.isMutationAnnotationFile(locator)) {
this.loadMutFile(locator, newTracks, genome);
} else if (WiggleParser.isWiggle(locator)) {
loadWigFile(locator, newTracks, genome);
} else if (path.toLowerCase().contains(".maf")) {
loadMAFTrack(locator, newTracks);
} else if (path.toLowerCase().contains(".peak.cfg")) {
loadPeakTrack(locator, newTracks, genome);
} else if ("mage-tab".equals(locator.getType()) || GCTDatasetParser.parsableMAGE_TAB(locator)) {
locator.setDescription("MAGE_TAB");
loadGctFile(locator, newTracks, genome);
} else if (typeString.endsWith(".logistic") || typeString.endsWith(".linear") || typeString.endsWith(".assoc") ||
typeString.endsWith(".qassoc") || typeString.endsWith(".gwas")) {
loadGWASFile(locator, newTracks);
} else if (GobyAlignmentQueryReader.supportsFileType(path)) {
loadAlignmentsTrack(locator, newTracks, genome);
} else if (AttributeManager.isSampleInfoFile(locator)) {
// This might be a sample information file.
AttributeManager.getInstance().loadSampleInfo(locator);
} else {
MessageUtils.showMessage("<html>Unknown file type: " + path + "<br>Check file extenstion");
}
// Track line
TrackProperties tp = null;
String trackLine = locator.getTrackLine();
if (trackLine != null) {
tp = new TrackProperties();
ParsingUtils.parseTrackLine(trackLine, tp);
}
for (Track track : newTracks) {
if (locator.getUrl() != null) {
track.setUrl(locator.getUrl());
}
if (tp != null) {
track.setProperties(tp);
}
if (locator.getColor() != null) {
track.setColor(locator.getColor());
}
if (locator.getSampleId() != null) {
track.setSampleId(locator.getSampleId());
}
}
return newTracks;
} catch (DataLoadException dle) {
throw dle;
} catch (Exception e) {
log.error(e);
throw new DataLoadException(e.getMessage(), path);
}
}
| public List<Track> load(ResourceLocator locator, IGV igv) {
this.igv = igv;
Genome genome = igv == null ? null : igv.getGenomeManager().getCurrentGenome();
final String path = locator.getPath();
try {
String typeString = locator.getType();
if (typeString == null) {
// Genome space hack -- check for explicit type converter
//https://dmtest.genomespace.org:8444/datamanager/files/users/SAGDemo/Step1/TF.data.tab
// ?dataformat=http://www.genomespace.org/datamanager/dataformat/gct/0.0.0
if((path.startsWith("http://") || path.startsWith("https://")) && GSUtils.isGenomeSpace(new URL(path)) && path.contains("?dataformat")) {
if (path.contains("dataformat/gct")) {
typeString = ".gct";
} else if (path.contains("dataformat/bed")) {
typeString = ".bed";
} else if (path.contains("dataformat/cn")) {
typeString = ".cn";
}
} else {
typeString = path.toLowerCase();
if (!typeString.endsWith("_sorted.txt") &&
(typeString.endsWith(".txt") || typeString.endsWith(
".xls") || typeString.endsWith(".gz"))) {
typeString = typeString.substring(0, typeString.lastIndexOf("."));
}
}
}
typeString = typeString.toLowerCase();
if (typeString.endsWith(".tbi")) {
MessageUtils.showMessage("<html><b>Error:</b>File type '.tbi' is not recognized. If this is a 'tabix' index <br>" +
" load the associated gzipped file, which should have an extension of '.gz'");
}
//TODO Why is this not inside of isIndexed?
//dhmay seconding this question -- this appears to be taken care of already in isIndexed()
// Check for index
boolean hasIndex = false;
if (locator.isLocal()) {
File indexFile = new File(path + ".sai");
hasIndex = indexFile.exists();
}
//This list will hold all new tracks created for this locator
List<Track> newTracks = new ArrayList<Track>();
if (typeString.endsWith(".gmt")) {
loadGMT(locator);
} else if (typeString.equals("das")) {
loadDASResource(locator, newTracks);
} else if (isIndexed(path)) {
loadIndexed(locator, newTracks, genome);
} else if (typeString.endsWith(".vcf") || typeString.endsWith(".vcf4")) {
// TODO This is a hack, vcf files must be indexed. Fix in next release.
throw new IndexNotFoundException(path);
} else if (typeString.endsWith(".trio")) {
loadTrioData(locator);
} else if (typeString.endsWith("varlist")) {
VariantListManager.loadVariants(locator);
} else if (typeString.endsWith("samplepathmap")) {
VariantListManager.loadSamplePathMap(locator);
} else if (typeString.endsWith("h5") || typeString.endsWith("hbin")) {
throw new DataLoadException("HDF5 files are no longer supported", locator.getPath());
} else if (typeString.endsWith(".rnai.gct")) {
loadRnaiGctFile(locator, newTracks, genome);
} else if (typeString.endsWith(".gct") || typeString.endsWith("res") || typeString.endsWith("tab")) {
loadGctFile(locator, newTracks, genome);
} else if (typeString.endsWith(".cn") || typeString.endsWith(".xcn") || typeString.endsWith(".snp") ||
typeString.endsWith(".igv") || typeString.endsWith(".loh")) {
loadIGVFile(locator, newTracks, genome);
} else if (typeString.endsWith(".mut")) {
loadMutFile(locator, newTracks, genome);
} else if (typeString.endsWith(".cbs") || typeString.endsWith(".seg") ||
typeString.endsWith("glad") || typeString.endsWith("birdseye_canary_calls")) {
loadSegFile(locator, newTracks, genome);
} else if (typeString.endsWith(".seg.zip")) {
loadBinarySegFile(locator, newTracks, genome);
} else if (typeString.endsWith(".gistic")) {
loadGisticFile(locator, newTracks);
} else if (typeString.endsWith(".gs")) {
loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.GENE_SCORE, genome);
} else if (typeString.endsWith(".riger")) {
loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.POOLED, genome);
} else if (typeString.endsWith(".hp")) {
loadRNAiHPScoreFile(locator);
} else if (typeString.endsWith("gene")) {
loadGeneFile(locator, newTracks, genome);
} else if (typeString.contains(".tabblastn") || typeString.endsWith(".orthologs")) {
loadSyntentyMapping(locator, newTracks);
} else if (typeString.endsWith(".sam") || typeString.endsWith(".bam") ||
typeString.endsWith(".sam.list") || typeString.endsWith(".bam.list") ||
typeString.endsWith("_sorted.txt") ||
typeString.endsWith(".aligned") || typeString.endsWith(".sai") ||
typeString.endsWith(".bai")) {
loadAlignmentsTrack(locator, newTracks, genome);
} else if (typeString.endsWith(".bedz") || (typeString.endsWith(".bed") && hasIndex)) {
loadIndexdBedFile(locator, newTracks, genome);
} else if (typeString.endsWith(".omega")) {
loadOmegaTrack(locator, newTracks, genome);
} else if (typeString.endsWith(".wig") || (typeString.endsWith(".bedgraph")) ||
typeString.endsWith("cpg.txt") || typeString.endsWith(".expr")) {
loadWigFile(locator, newTracks, genome);
} else if (typeString.endsWith(".list")) {
loadListFile(locator, newTracks, genome);
} else if (typeString.contains(".dranger")) {
loadDRangerFile(locator, newTracks, genome);
} else if (typeString.endsWith(".ewig.tdf") || (typeString.endsWith(".ewig.ibf"))) {
loadEwigIBFFile(locator, newTracks, genome);
} else if (typeString.endsWith(".bw") || typeString.endsWith(".bb") || typeString.endsWith(".bigwig") ||
typeString.endsWith(".bigbed")) {
loadBWFile(locator, newTracks, genome);
} else if (typeString.endsWith(".ibf") || typeString.endsWith(".tdf")) {
loadTDFFile(locator, newTracks, genome);
} else if (typeString.endsWith(".counts")) {
loadGobyCountsArchive(locator, newTracks, genome);
} else if (typeString.endsWith(".psl") || typeString.endsWith(".psl.gz") ||
typeString.endsWith(".pslx") || typeString.endsWith(".pslx.gz")) {
loadPslFile(locator, newTracks, genome);
//TODO AbstractFeatureParser.getInstanceFor() is called twice. Wasteful
} else if (AbstractFeatureParser.getInstanceFor(locator, genome) != null) {
loadFeatureFile(locator, newTracks, genome);
} else if (MutationParser.isMutationAnnotationFile(locator)) {
this.loadMutFile(locator, newTracks, genome);
} else if (WiggleParser.isWiggle(locator)) {
loadWigFile(locator, newTracks, genome);
} else if (path.toLowerCase().contains(".maf")) {
loadMAFTrack(locator, newTracks);
} else if (path.toLowerCase().contains(".peak.cfg")) {
loadPeakTrack(locator, newTracks, genome);
} else if ("mage-tab".equals(locator.getType()) || GCTDatasetParser.parsableMAGE_TAB(locator)) {
locator.setDescription("MAGE_TAB");
loadGctFile(locator, newTracks, genome);
} else if (typeString.endsWith(".logistic") || typeString.endsWith(".linear") || typeString.endsWith(".assoc") ||
typeString.endsWith(".qassoc") || typeString.endsWith(".gwas")) {
loadGWASFile(locator, newTracks);
} else if (GobyAlignmentQueryReader.supportsFileType(path)) {
loadAlignmentsTrack(locator, newTracks, genome);
} else if (AttributeManager.isSampleInfoFile(locator)) {
// This might be a sample information file.
AttributeManager.getInstance().loadSampleInfo(locator);
} else {
MessageUtils.showMessage("<html>Unknown file type: " + path + "<br>Check file extenstion");
}
// Track line
TrackProperties tp = null;
String trackLine = locator.getTrackLine();
if (trackLine != null) {
tp = new TrackProperties();
ParsingUtils.parseTrackLine(trackLine, tp);
}
for (Track track : newTracks) {
if (locator.getUrl() != null) {
track.setUrl(locator.getUrl());
}
if (tp != null) {
track.setProperties(tp);
}
if (locator.getColor() != null) {
track.setColor(locator.getColor());
}
if (locator.getSampleId() != null) {
track.setSampleId(locator.getSampleId());
}
}
return newTracks;
} catch (DataLoadException dle) {
throw dle;
} catch (Exception e) {
log.error(e);
throw new DataLoadException(e.getMessage(), path);
}
}
|
diff --git a/Strat-Andro/src/org/globalgamejam/strat/GameRenderer.java b/Strat-Andro/src/org/globalgamejam/strat/GameRenderer.java
index 4aa73d0..e2946b0 100644
--- a/Strat-Andro/src/org/globalgamejam/strat/GameRenderer.java
+++ b/Strat-Andro/src/org/globalgamejam/strat/GameRenderer.java
@@ -1,272 +1,272 @@
package org.globalgamejam.strat;
import java.io.IOException;
import android.util.Log;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class GameRenderer implements ApplicationListener {
private static final int NB_JOUEURS = 6, NB_BONUS = 5, NB_SPRITE_LIFEBAR = 2, NB_SPRITE_BLOCKBAR = 7;
private static final int NB_BLOCK_MAX = 10;
private static int[] posiX, //= { -84, +128, +64, -80, -228, -292 },
posiY ;//= {-184, -248, -372, -460, -372, -248 };
public static String PATH_IMG = "img/";
Texture texAvatar, texBonus, texLifeBar, texBlockBar;
private Sprite[] bonus, avatars, lifeBar, blockBar;
private Sprite bg, bgWait, cursor;
private SpriteBatch batch, batch2;
public static int w, h;
private Communication com;
//Interface
private int selected = -1;
public GameRenderer(String host, int port) throws IOException {
com = new Communication(host, port);
com.start();
}
public void create() {
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight(); // helps the placement of the avatars
batch = new SpriteBatch();
batch2 = new SpriteBatch();
bg = new Sprite(new Texture(PATH_IMG + "bgPhone.png"));
cursor = new Sprite(new Texture(PATH_IMG + "cursor1.png"));
bgWait = new Sprite(new Texture(PATH_IMG + "bgWait.png"));
allocTextures();
loadTextures();
setPositions();
}
public void render() {
int nbPa = com.getActions();
int nbBlock = com.getStones();
int monId = com.getId();
int i, select = -1;
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
if (!com.isConnected()) {
batch.begin();
bgWait.draw(batch);
batch.end();
return;
}
if(com.getStatus()!=0) // beark caca !
return;
if(Gdx.input.isTouched())
{
int x = Gdx.input.getX(), y = Gdx.input.getY();
//select = -1;
//Log.i("colision", "collision au " + "x " + x + " y : " + y);
for(i=0; i< NB_JOUEURS;i++)
{
if(collision(x, h-y, avatars[i].getX(), avatars[i].getY(),avatars[i].getWidth(), avatars[i].getHeight()))
{
select = i;
//Log.i("colision", "collision avec " + select);
//Log.i("coordonnees", "x : " + avatars[select].getX() + "y : " + avatars[select].getY() +
// "w : "+ avatars[select].getWidth() + "h : " + avatars[select].getHeight());
}
}
if(select != -1 && select != selected)
{
if(selected == -1)
{
selected=select;
Log.i("setSelected", " new selection : " + selected);
}
else
{
Log.i("setSelect", " new selection : " + selected);
if(selected == monId)
{
Log.i("action", "transfert de pierre du joueur vers " + select);
com.giveStone(select);
}
else if(select == monId)
{
Log.i("action", "transfert de pierre vers le joueur de la part de " + select);
- com.stealStone(select);
+ com.stealStone(selected);
}
else
{
Log.i("action", "action spéciale de " + selected + "vers " + select);
}
selected=-1;
}
}
}
batch.begin();
bg.draw(batch);
/* LIFEBAR */
for (i = 0; i < nbPa - 1; i++) {
lifeBar[0].setPosition(i * (lifeBar[0].getWidth()),
Gdx.graphics.getHeight() - lifeBar[0].getHeight());
lifeBar[0].draw(batch);
}
lifeBar[1].setPosition((nbPa - 1) * (lifeBar[1].getWidth()),
Gdx.graphics.getHeight() - lifeBar[1].getHeight());
lifeBar[1].draw(batch);
/* LIFEBAR */
/* BLOCKS */
for (i = 0; i < nbBlock; i++) {
blockBar[monId]
.setPosition(10, 5 + i * (blockBar[monId].getHeight() + 5));
blockBar[monId].draw(batch);
}
for (; i < NB_BLOCK_MAX; i++) {
blockBar[NB_SPRITE_BLOCKBAR-1].setPosition(10, 5 + i * (blockBar[0].getHeight() + 5));
blockBar[NB_SPRITE_BLOCKBAR-1].draw(batch);
}
/* FIN BLOCK */
batch.end();
batch2.begin();
avatars[monId].setPosition(posiX[0], posiY[0]);
avatars[monId].draw(batch2);
for (i = 1; i < NB_JOUEURS; i++) {
avatars[posiToId(i, monId)].setPosition(posiX[i], posiY[i]);
avatars[posiToId(i, monId)].setScale(0.8f);
avatars[posiToId(i, monId)].draw(batch2);
}
if(selected != -1)
{
cursor.setPosition(posiX[idToPosi(selected, monId)], posiY[idToPosi(selected, monId)]);
cursor.draw(batch2);
//Log.d("lulz", "selected : " + selected + " select : " + select);
}
batch2.end();
}
private void setPositions() {
int padding = 20;
posiX = new int[6];
posiY = new int[6];
posiX[0] = (int) ((w - bonus[0].getWidth() - blockBar[0].getWidth()) / 2) ;//- avatars[0].getWidth()/2);
posiX[1] = (int) (w - bonus[1].getWidth() - avatars[1].getWidth() - padding);
posiX[2] = (int) (posiX[1] - avatars[1].getWidth()/2 - padding);
posiX[3] = posiX[0];
posiX[4] = (int) (posiX[5] + avatars[0].getWidth() + 2*padding);
posiX[5] = (int) (blockBar[1].getWidth() + padding);
posiY[0] = (int) (h - lifeBar[0].getHeight() - avatars[0].getHeight() - padding);
posiY[1] = posiY[0] - padding;
posiY[2] = (int) (h/2 - avatars[0].getHeight()/2 - 2*padding);
posiY[3] = padding;
posiY[4] = posiY[2];
posiY[5] = posiY[1];
}
private void allocTextures() {
texAvatar = new Texture(PATH_IMG + "avatar.png");
texBonus = new Texture(PATH_IMG + "bonus.png");
texLifeBar = new Texture(PATH_IMG + "lifebar.png");
texBlockBar = new Texture(PATH_IMG + "blockbar.png");
}
private void desallocTextures() {
texAvatar.dispose();
texBonus.dispose();
texLifeBar.dispose();
texBlockBar.dispose();
}
private void loadTextures() {
bonus = new Sprite[NB_BONUS];
avatars = new Sprite[NB_JOUEURS];
lifeBar = new Sprite[NB_SPRITE_LIFEBAR];
blockBar = new Sprite[NB_SPRITE_BLOCKBAR];
for (int i = 0; i < NB_JOUEURS; i++)
avatars[i] = new Sprite(new TextureRegion(texAvatar, (i % 3) * 128,
(i / 3) * 128, 128, 128));
for (int i = 0; i < NB_BONUS; i++)
bonus[i] = new Sprite(new TextureRegion(texBonus, (i % 2) * 64,
(i / 2) * 64, 64, 64));
for (int i = 0; i < NB_SPRITE_LIFEBAR; i++)
lifeBar[i] = new Sprite(new TextureRegion(texLifeBar, i * 64, 0,
64, 32));
for (int i = 0; i < NB_SPRITE_BLOCKBAR; i++)
blockBar[i] = new Sprite(new TextureRegion(texBlockBar,
(i % 4) * 64, (i / 4) * 32, 64, 32));
}
private boolean collision(int pX, int pY, float cX, float cY, float cW, float cH) {
if(pX<cX)
return false;
if(pX > cX+cW)
return false;
if(pY<cY)
return false;
if(pY > cY+cH)
return false;
return true;
}
private int idToPosi(int id, int monId) {
return (id-monId+NB_JOUEURS)%NB_JOUEURS;
}
private int posiToId(int posi, int monId) {
return (posi + monId)%NB_JOUEURS;
}
public void dispose() {
desallocTextures();
}
public void pause() {
desallocTextures();
}
public void resize(int arg0, int arg1) {
allocTextures();
loadTextures();
render();
}
public void resume() {
allocTextures();
loadTextures();
render();
}
}
| true | true | public void render() {
int nbPa = com.getActions();
int nbBlock = com.getStones();
int monId = com.getId();
int i, select = -1;
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
if (!com.isConnected()) {
batch.begin();
bgWait.draw(batch);
batch.end();
return;
}
if(com.getStatus()!=0) // beark caca !
return;
if(Gdx.input.isTouched())
{
int x = Gdx.input.getX(), y = Gdx.input.getY();
//select = -1;
//Log.i("colision", "collision au " + "x " + x + " y : " + y);
for(i=0; i< NB_JOUEURS;i++)
{
if(collision(x, h-y, avatars[i].getX(), avatars[i].getY(),avatars[i].getWidth(), avatars[i].getHeight()))
{
select = i;
//Log.i("colision", "collision avec " + select);
//Log.i("coordonnees", "x : " + avatars[select].getX() + "y : " + avatars[select].getY() +
// "w : "+ avatars[select].getWidth() + "h : " + avatars[select].getHeight());
}
}
if(select != -1 && select != selected)
{
if(selected == -1)
{
selected=select;
Log.i("setSelected", " new selection : " + selected);
}
else
{
Log.i("setSelect", " new selection : " + selected);
if(selected == monId)
{
Log.i("action", "transfert de pierre du joueur vers " + select);
com.giveStone(select);
}
else if(select == monId)
{
Log.i("action", "transfert de pierre vers le joueur de la part de " + select);
com.stealStone(select);
}
else
{
Log.i("action", "action spéciale de " + selected + "vers " + select);
}
selected=-1;
}
}
}
batch.begin();
bg.draw(batch);
/* LIFEBAR */
for (i = 0; i < nbPa - 1; i++) {
lifeBar[0].setPosition(i * (lifeBar[0].getWidth()),
Gdx.graphics.getHeight() - lifeBar[0].getHeight());
lifeBar[0].draw(batch);
}
lifeBar[1].setPosition((nbPa - 1) * (lifeBar[1].getWidth()),
Gdx.graphics.getHeight() - lifeBar[1].getHeight());
lifeBar[1].draw(batch);
/* LIFEBAR */
/* BLOCKS */
for (i = 0; i < nbBlock; i++) {
blockBar[monId]
.setPosition(10, 5 + i * (blockBar[monId].getHeight() + 5));
blockBar[monId].draw(batch);
}
for (; i < NB_BLOCK_MAX; i++) {
blockBar[NB_SPRITE_BLOCKBAR-1].setPosition(10, 5 + i * (blockBar[0].getHeight() + 5));
blockBar[NB_SPRITE_BLOCKBAR-1].draw(batch);
}
/* FIN BLOCK */
batch.end();
batch2.begin();
avatars[monId].setPosition(posiX[0], posiY[0]);
avatars[monId].draw(batch2);
for (i = 1; i < NB_JOUEURS; i++) {
avatars[posiToId(i, monId)].setPosition(posiX[i], posiY[i]);
avatars[posiToId(i, monId)].setScale(0.8f);
avatars[posiToId(i, monId)].draw(batch2);
}
if(selected != -1)
{
cursor.setPosition(posiX[idToPosi(selected, monId)], posiY[idToPosi(selected, monId)]);
cursor.draw(batch2);
//Log.d("lulz", "selected : " + selected + " select : " + select);
}
batch2.end();
}
| public void render() {
int nbPa = com.getActions();
int nbBlock = com.getStones();
int monId = com.getId();
int i, select = -1;
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
if (!com.isConnected()) {
batch.begin();
bgWait.draw(batch);
batch.end();
return;
}
if(com.getStatus()!=0) // beark caca !
return;
if(Gdx.input.isTouched())
{
int x = Gdx.input.getX(), y = Gdx.input.getY();
//select = -1;
//Log.i("colision", "collision au " + "x " + x + " y : " + y);
for(i=0; i< NB_JOUEURS;i++)
{
if(collision(x, h-y, avatars[i].getX(), avatars[i].getY(),avatars[i].getWidth(), avatars[i].getHeight()))
{
select = i;
//Log.i("colision", "collision avec " + select);
//Log.i("coordonnees", "x : " + avatars[select].getX() + "y : " + avatars[select].getY() +
// "w : "+ avatars[select].getWidth() + "h : " + avatars[select].getHeight());
}
}
if(select != -1 && select != selected)
{
if(selected == -1)
{
selected=select;
Log.i("setSelected", " new selection : " + selected);
}
else
{
Log.i("setSelect", " new selection : " + selected);
if(selected == monId)
{
Log.i("action", "transfert de pierre du joueur vers " + select);
com.giveStone(select);
}
else if(select == monId)
{
Log.i("action", "transfert de pierre vers le joueur de la part de " + select);
com.stealStone(selected);
}
else
{
Log.i("action", "action spéciale de " + selected + "vers " + select);
}
selected=-1;
}
}
}
batch.begin();
bg.draw(batch);
/* LIFEBAR */
for (i = 0; i < nbPa - 1; i++) {
lifeBar[0].setPosition(i * (lifeBar[0].getWidth()),
Gdx.graphics.getHeight() - lifeBar[0].getHeight());
lifeBar[0].draw(batch);
}
lifeBar[1].setPosition((nbPa - 1) * (lifeBar[1].getWidth()),
Gdx.graphics.getHeight() - lifeBar[1].getHeight());
lifeBar[1].draw(batch);
/* LIFEBAR */
/* BLOCKS */
for (i = 0; i < nbBlock; i++) {
blockBar[monId]
.setPosition(10, 5 + i * (blockBar[monId].getHeight() + 5));
blockBar[monId].draw(batch);
}
for (; i < NB_BLOCK_MAX; i++) {
blockBar[NB_SPRITE_BLOCKBAR-1].setPosition(10, 5 + i * (blockBar[0].getHeight() + 5));
blockBar[NB_SPRITE_BLOCKBAR-1].draw(batch);
}
/* FIN BLOCK */
batch.end();
batch2.begin();
avatars[monId].setPosition(posiX[0], posiY[0]);
avatars[monId].draw(batch2);
for (i = 1; i < NB_JOUEURS; i++) {
avatars[posiToId(i, monId)].setPosition(posiX[i], posiY[i]);
avatars[posiToId(i, monId)].setScale(0.8f);
avatars[posiToId(i, monId)].draw(batch2);
}
if(selected != -1)
{
cursor.setPosition(posiX[idToPosi(selected, monId)], posiY[idToPosi(selected, monId)]);
cursor.draw(batch2);
//Log.d("lulz", "selected : " + selected + " select : " + select);
}
batch2.end();
}
|
diff --git a/src/demos/es1/RedSquare.java b/src/demos/es1/RedSquare.java
index 2926746..81713ea 100755
--- a/src/demos/es1/RedSquare.java
+++ b/src/demos/es1/RedSquare.java
@@ -1,151 +1,151 @@
package demos.es1;
import java.nio.*;
import javax.media.opengl.*;
import javax.media.opengl.util.*;
import javax.media.opengl.glu.*;
import com.sun.javafx.newt.*;
public class RedSquare implements MouseListener {
public boolean quit = false;
public boolean toggleFS = false;
public void mouseClicked(MouseEvent e) {
switch(e.getClickCount()) {
case 1:
toggleFS=true;
break;
default:
quit=true;
break;
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public static void main(String[] args) {
System.out.println("RedSquare.main()");
- GLProfile.setProfile(GLProfile.GLES1);
+ GLProfile.setProfileGL2ES1();
try {
Display display = NewtFactory.createDisplay(null); // local display
Screen screen = NewtFactory.createScreen(display, 0); // screen 0
Window window = NewtFactory.createWindow(screen, 0); // dummy VisualID
RedSquare ml = new RedSquare();
window.addMouseListener(ml);
// Size OpenGL to Video Surface
int width = 800;
int height = 480;
window.setSize(width, height);
window.setFullscreen(true);
// Hook this into EGL
GLDrawableFactory factory = GLDrawableFactory.getFactory(window);
GLCapabilities caps = new GLCapabilities();
// For emulation library, use 16 bpp
caps.setRedBits(5);
caps.setGreenBits(6);
caps.setBlueBits(5);
caps.setDepthBits(16);
GLDrawable drawable = factory.createGLDrawable(window, caps, null);
window.setVisible(true);
drawable.setRealized(true);
GLContext context = drawable.createContext(null);
context.makeCurrent();
GL2ES1 gl = context.getGL().getGL2ES1();
- GLU glu = new javax.media.opengl.glu.es1.GLUes1();
+ GLU glu = GLU.createGLU(gl);
//----------------------------------------------------------------------
// Code for GLEventListener.init()
//
System.out.println("Entering initialization");
System.out.println("GL_VERSION=" + gl.glGetString(GL2ES1.GL_VERSION));
System.out.println("GL_EXTENSIONS:");
System.out.println(" " + gl.glGetString(GL2ES1.GL_EXTENSIONS));
// Allocate vertex arrays
FloatBuffer colors = BufferUtil.newFloatBuffer(16);
FloatBuffer vertices = BufferUtil.newFloatBuffer(12);
// Fill them up
colors.put( 0, 1); colors.put( 1, 0); colors.put( 2, 0); colors.put( 3, 1);
colors.put( 4, 1); colors.put( 5, 0); colors.put( 6, 0); colors.put( 7, 1);
colors.put( 8, 1); colors.put( 9, 0); colors.put(10, 0); colors.put(11, 1);
colors.put(12, 1); colors.put(13, 0); colors.put(14, 0); colors.put(15, 1);
vertices.put(0, -2); vertices.put( 1, 2); vertices.put( 2, 0);
vertices.put(3, 2); vertices.put( 4, 2); vertices.put( 5, 0);
vertices.put(6, -2); vertices.put( 7, -2); vertices.put( 8, 0);
vertices.put(9, 2); vertices.put(10, -2); vertices.put(11, 0);
gl.glEnableClientState(GL2ES1.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL2ES1.GL_FLOAT, 0, vertices);
gl.glEnableClientState(GL2ES1.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL2ES1.GL_FLOAT, 0, colors);
// OpenGL Render Settings
gl.glClearColor(0, 0, 0, 1);
gl.glEnable(GL2ES1.GL_DEPTH_TEST);
//----------------------------------------------------------------------
// Code for GLEventListener.display()
//
long startTime = System.currentTimeMillis();
long curTime;
while (!ml.quit && ((curTime = System.currentTimeMillis()) - startTime) < 20000) {
gl.glClear(GL2ES1.GL_COLOR_BUFFER_BIT | GL2ES1.GL_DEPTH_BUFFER_BIT);
// Set location in front of camera
width = window.getWidth();
height = window.getHeight();
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL2ES1.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluPerspective(45.0f, (float)width / (float)height, 1.0f, 100.0f);
gl.glMatrixMode(GL2ES1.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0, 0, -10);
// One rotation every four seconds
float ang = (((float) (curTime - startTime)) * 360.0f) / 4000.0f;
gl.glRotatef(ang, 0, 0, 1);
// Draw a square
gl.glDrawArrays(GL2ES1.GL_TRIANGLE_STRIP, 0, 4);
drawable.swapBuffers();
if(ml.toggleFS) {
window.setFullscreen(!window.isFullscreen());
ml.toggleFS=false;
}
window.pumpMessages();
}
// Shut things down cooperatively
context.release();
context.destroy();
drawable.destroy();
factory.shutdown();
System.out.println("RedSquare shut down cleanly.");
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(0);
}
}
| false | true | public static void main(String[] args) {
System.out.println("RedSquare.main()");
GLProfile.setProfile(GLProfile.GLES1);
try {
Display display = NewtFactory.createDisplay(null); // local display
Screen screen = NewtFactory.createScreen(display, 0); // screen 0
Window window = NewtFactory.createWindow(screen, 0); // dummy VisualID
RedSquare ml = new RedSquare();
window.addMouseListener(ml);
// Size OpenGL to Video Surface
int width = 800;
int height = 480;
window.setSize(width, height);
window.setFullscreen(true);
// Hook this into EGL
GLDrawableFactory factory = GLDrawableFactory.getFactory(window);
GLCapabilities caps = new GLCapabilities();
// For emulation library, use 16 bpp
caps.setRedBits(5);
caps.setGreenBits(6);
caps.setBlueBits(5);
caps.setDepthBits(16);
GLDrawable drawable = factory.createGLDrawable(window, caps, null);
window.setVisible(true);
drawable.setRealized(true);
GLContext context = drawable.createContext(null);
context.makeCurrent();
GL2ES1 gl = context.getGL().getGL2ES1();
GLU glu = new javax.media.opengl.glu.es1.GLUes1();
//----------------------------------------------------------------------
// Code for GLEventListener.init()
//
System.out.println("Entering initialization");
System.out.println("GL_VERSION=" + gl.glGetString(GL2ES1.GL_VERSION));
System.out.println("GL_EXTENSIONS:");
System.out.println(" " + gl.glGetString(GL2ES1.GL_EXTENSIONS));
// Allocate vertex arrays
FloatBuffer colors = BufferUtil.newFloatBuffer(16);
FloatBuffer vertices = BufferUtil.newFloatBuffer(12);
// Fill them up
colors.put( 0, 1); colors.put( 1, 0); colors.put( 2, 0); colors.put( 3, 1);
colors.put( 4, 1); colors.put( 5, 0); colors.put( 6, 0); colors.put( 7, 1);
colors.put( 8, 1); colors.put( 9, 0); colors.put(10, 0); colors.put(11, 1);
colors.put(12, 1); colors.put(13, 0); colors.put(14, 0); colors.put(15, 1);
vertices.put(0, -2); vertices.put( 1, 2); vertices.put( 2, 0);
vertices.put(3, 2); vertices.put( 4, 2); vertices.put( 5, 0);
vertices.put(6, -2); vertices.put( 7, -2); vertices.put( 8, 0);
vertices.put(9, 2); vertices.put(10, -2); vertices.put(11, 0);
gl.glEnableClientState(GL2ES1.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL2ES1.GL_FLOAT, 0, vertices);
gl.glEnableClientState(GL2ES1.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL2ES1.GL_FLOAT, 0, colors);
// OpenGL Render Settings
gl.glClearColor(0, 0, 0, 1);
gl.glEnable(GL2ES1.GL_DEPTH_TEST);
//----------------------------------------------------------------------
// Code for GLEventListener.display()
//
long startTime = System.currentTimeMillis();
long curTime;
while (!ml.quit && ((curTime = System.currentTimeMillis()) - startTime) < 20000) {
gl.glClear(GL2ES1.GL_COLOR_BUFFER_BIT | GL2ES1.GL_DEPTH_BUFFER_BIT);
// Set location in front of camera
width = window.getWidth();
height = window.getHeight();
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL2ES1.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluPerspective(45.0f, (float)width / (float)height, 1.0f, 100.0f);
gl.glMatrixMode(GL2ES1.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0, 0, -10);
// One rotation every four seconds
float ang = (((float) (curTime - startTime)) * 360.0f) / 4000.0f;
gl.glRotatef(ang, 0, 0, 1);
// Draw a square
gl.glDrawArrays(GL2ES1.GL_TRIANGLE_STRIP, 0, 4);
drawable.swapBuffers();
if(ml.toggleFS) {
window.setFullscreen(!window.isFullscreen());
ml.toggleFS=false;
}
window.pumpMessages();
}
// Shut things down cooperatively
context.release();
context.destroy();
drawable.destroy();
factory.shutdown();
System.out.println("RedSquare shut down cleanly.");
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(0);
}
| public static void main(String[] args) {
System.out.println("RedSquare.main()");
GLProfile.setProfileGL2ES1();
try {
Display display = NewtFactory.createDisplay(null); // local display
Screen screen = NewtFactory.createScreen(display, 0); // screen 0
Window window = NewtFactory.createWindow(screen, 0); // dummy VisualID
RedSquare ml = new RedSquare();
window.addMouseListener(ml);
// Size OpenGL to Video Surface
int width = 800;
int height = 480;
window.setSize(width, height);
window.setFullscreen(true);
// Hook this into EGL
GLDrawableFactory factory = GLDrawableFactory.getFactory(window);
GLCapabilities caps = new GLCapabilities();
// For emulation library, use 16 bpp
caps.setRedBits(5);
caps.setGreenBits(6);
caps.setBlueBits(5);
caps.setDepthBits(16);
GLDrawable drawable = factory.createGLDrawable(window, caps, null);
window.setVisible(true);
drawable.setRealized(true);
GLContext context = drawable.createContext(null);
context.makeCurrent();
GL2ES1 gl = context.getGL().getGL2ES1();
GLU glu = GLU.createGLU(gl);
//----------------------------------------------------------------------
// Code for GLEventListener.init()
//
System.out.println("Entering initialization");
System.out.println("GL_VERSION=" + gl.glGetString(GL2ES1.GL_VERSION));
System.out.println("GL_EXTENSIONS:");
System.out.println(" " + gl.glGetString(GL2ES1.GL_EXTENSIONS));
// Allocate vertex arrays
FloatBuffer colors = BufferUtil.newFloatBuffer(16);
FloatBuffer vertices = BufferUtil.newFloatBuffer(12);
// Fill them up
colors.put( 0, 1); colors.put( 1, 0); colors.put( 2, 0); colors.put( 3, 1);
colors.put( 4, 1); colors.put( 5, 0); colors.put( 6, 0); colors.put( 7, 1);
colors.put( 8, 1); colors.put( 9, 0); colors.put(10, 0); colors.put(11, 1);
colors.put(12, 1); colors.put(13, 0); colors.put(14, 0); colors.put(15, 1);
vertices.put(0, -2); vertices.put( 1, 2); vertices.put( 2, 0);
vertices.put(3, 2); vertices.put( 4, 2); vertices.put( 5, 0);
vertices.put(6, -2); vertices.put( 7, -2); vertices.put( 8, 0);
vertices.put(9, 2); vertices.put(10, -2); vertices.put(11, 0);
gl.glEnableClientState(GL2ES1.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL2ES1.GL_FLOAT, 0, vertices);
gl.glEnableClientState(GL2ES1.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL2ES1.GL_FLOAT, 0, colors);
// OpenGL Render Settings
gl.glClearColor(0, 0, 0, 1);
gl.glEnable(GL2ES1.GL_DEPTH_TEST);
//----------------------------------------------------------------------
// Code for GLEventListener.display()
//
long startTime = System.currentTimeMillis();
long curTime;
while (!ml.quit && ((curTime = System.currentTimeMillis()) - startTime) < 20000) {
gl.glClear(GL2ES1.GL_COLOR_BUFFER_BIT | GL2ES1.GL_DEPTH_BUFFER_BIT);
// Set location in front of camera
width = window.getWidth();
height = window.getHeight();
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL2ES1.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluPerspective(45.0f, (float)width / (float)height, 1.0f, 100.0f);
gl.glMatrixMode(GL2ES1.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0, 0, -10);
// One rotation every four seconds
float ang = (((float) (curTime - startTime)) * 360.0f) / 4000.0f;
gl.glRotatef(ang, 0, 0, 1);
// Draw a square
gl.glDrawArrays(GL2ES1.GL_TRIANGLE_STRIP, 0, 4);
drawable.swapBuffers();
if(ml.toggleFS) {
window.setFullscreen(!window.isFullscreen());
ml.toggleFS=false;
}
window.pumpMessages();
}
// Shut things down cooperatively
context.release();
context.destroy();
drawable.destroy();
factory.shutdown();
System.out.println("RedSquare shut down cleanly.");
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(0);
}
|
diff --git a/freeplane/src/org/freeplane/features/common/icon/IconStore.java b/freeplane/src/org/freeplane/features/common/icon/IconStore.java
index 3da2f625e..a12491ecc 100644
--- a/freeplane/src/org/freeplane/features/common/icon/IconStore.java
+++ b/freeplane/src/org/freeplane/features/common/icon/IconStore.java
@@ -1,147 +1,146 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2009 Tamas Eppel
*
* This file author is Tamas Eppel
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.common.icon;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.freeplane.core.resources.ResourceController;
import org.freeplane.features.common.icon.factory.MindIconFactory;
/**
*
* Stores all kinds of icons used in Freeplane.
*
* @author Tamas Eppel
*
*/
public class IconStore {
private final Map<String, IconGroup> groups;
private final Map<String, MindIcon> mindIcons;
private final Map<String, UIIcon> uiIcons;
public IconStore() {
groups = new LinkedHashMap<String, IconGroup>();
mindIcons = new HashMap<String, MindIcon>();
uiIcons = new HashMap<String, UIIcon>();
}
/**
* Adds a new MindIcon group to the store.
*
* @param group
*/
public void addGroup(final IconGroup group) {
groups.put(group.getName(), group);
for (final MindIcon icon : group.getIcons()) {
mindIcons.put(icon.getName(), icon);
}
}
/**
* Adds a new MindIcon to the group with the given name.
*
* @param groupName where to add the icon
* @param icon to add
*/
public void addMindIcon(final String groupName, final MindIcon icon) {
if (!groups.containsKey(groupName)) {
final IconGroup group = new IconGroup(groupName, icon);
groups.put(groupName, group);
}
groups.get(groupName).addIcon(icon);
mindIcons.put(icon.getName(), icon);
}
public void addUIIcon(final UIIcon uiIcon) {
uiIcons.put(uiIcon.getFileName(), uiIcon);
}
/**
* @return all groups in the store
*/
public Collection<IconGroup> getGroups() {
return groups.values();
}
/**
* @return all MindIcons from all groups in the store, including user icons
*/
public Collection<MindIcon> getMindIcons() {
final List<MindIcon> icons = new ArrayList<MindIcon>();
for (final IconGroup group : groups.values()) {
icons.addAll(group.getIcons());
}
return icons;
}
/**
* @return all user icons in the store
*/
public Collection<MindIcon> getUserIcons() {
return groups.get("user").getIcons();
}
/**
* @param name of MindIcon to return
* @return MindIcon with given name
*/
public MindIcon getMindIcon(final String name) {
- MindIcon result;
+ if(name == null){
+ return IconNotFound.instance();
+ }
if (mindIcons.containsKey(name)) {
- result = mindIcons.get(name);
+ return mindIcons.get(name);
}
- else {
- // icons in directory /image are not registered
- final MindIcon mindIcon = MindIconFactory.create(name);
- if (ResourceController.getResourceController().getResource(mindIcon.getPath()) != null) {
- return mindIcon;
- }
- result = IconNotFound.instance();
+ // icons in directory /image are not registered
+ final MindIcon mindIcon = MindIconFactory.create(name);
+ if (ResourceController.getResourceController().getResource(mindIcon.getPath()) != null) {
+ return mindIcon;
}
- return result;
+ return IconNotFound.instance();
}
/**
* Returns a UIIcon with a given name. If one is not found in the store,
* it will be created and stored.
*
* @param name of UIIcon to return
* @return UIIcon with given name
*/
public UIIcon getUIIcon(final String name) {
UIIcon result;
if (mindIcons.containsKey(name)) {
result = mindIcons.get(name);
}
else if (uiIcons.containsKey(name)) {
result = uiIcons.get(name);
}
else {
result = new UIIcon(name, name);
uiIcons.put(name, result);
}
return result;
}
}
| false | true | public MindIcon getMindIcon(final String name) {
MindIcon result;
if (mindIcons.containsKey(name)) {
result = mindIcons.get(name);
}
else {
// icons in directory /image are not registered
final MindIcon mindIcon = MindIconFactory.create(name);
if (ResourceController.getResourceController().getResource(mindIcon.getPath()) != null) {
return mindIcon;
}
result = IconNotFound.instance();
}
return result;
}
| public MindIcon getMindIcon(final String name) {
if(name == null){
return IconNotFound.instance();
}
if (mindIcons.containsKey(name)) {
return mindIcons.get(name);
}
// icons in directory /image are not registered
final MindIcon mindIcon = MindIconFactory.create(name);
if (ResourceController.getResourceController().getResource(mindIcon.getPath()) != null) {
return mindIcon;
}
return IconNotFound.instance();
}
|
diff --git a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyScalarisWikiModel.java b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyScalarisWikiModel.java
index 05d39c86..d80aa20b 100644
--- a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyScalarisWikiModel.java
+++ b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyScalarisWikiModel.java
@@ -1,136 +1,136 @@
/**
* Copyright 2011 Zuse Institute Berlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.zib.scalaris.examples.wikipedia.bliki;
import java.util.HashMap;
import java.util.Map;
import de.zib.scalaris.Connection;
import de.zib.scalaris.examples.wikipedia.RevisionResult;
import de.zib.scalaris.examples.wikipedia.ScalarisDataHandler;
/**
* Wiki model using Scalaris to fetch (new) data, e.g. templates.
*
* @author Nico Kruber, [email protected]
*/
public class MyScalarisWikiModel extends MyWikiModel {
protected Connection connection;
protected Map<String, String> magicWordCache = new HashMap<String, String>();
/**
* Creates a new wiki model to render wiki text using the given connection
* to Scalaris.
*
* @param imageBaseURL
* base url pointing to images - can contain ${image} for
* replacement
* @param linkBaseURL
* base url pointing to links - can contain ${title} for
* replacement
* @param connection
* connection to Scalaris
* @param namespace
* namespace of the wiki
*/
public MyScalarisWikiModel(String imageBaseURL, String linkBaseURL, Connection connection, MyNamespace namespace) {
super(imageBaseURL, linkBaseURL, namespace);
this.connection = connection;
}
/* (non-Javadoc)
* @see info.bliki.wiki.model.AbstractWikiModel#getRawWikiContent(java.lang.String, java.lang.String, java.util.Map)
*/
@Override
public String getRawWikiContent(String namespace, String articleName,
Map<String, String> templateParameters) {
if (isTemplateNamespace(namespace)) {
String magicWord = articleName;
String parameter = "";
int index = magicWord.indexOf(':');
if (index > 0) {
parameter = magicWord.substring(index + 1).trim();
magicWord = magicWord.substring(0, index);
}
if (MyScalarisMagicWord.isMagicWord(magicWord)) {
// cache values for magic words:
if (magicWordCache.containsKey(articleName)) {
return magicWordCache.get(articleName);
} else {
String value = MyScalarisMagicWord.processMagicWord(magicWord, parameter, this);
magicWordCache.put(articleName, value);
return value;
}
} else {
// retrieve template from Scalaris:
// note: templates are already cached, no need to cache them here
if (connection != null) {
// (ugly) fix for template parameter replacement if no parameters given,
// e.g. "{{noun}}" in the simple English Wiktionary
- if (templateParameters.isEmpty()) {
+ if (templateParameters != null && templateParameters.isEmpty()) {
templateParameters.put("", null);
}
String pageName = getTemplateNamespace() + ":" + articleName;
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
String text = getRevResult.revision.getText();
text = removeNoIncludeContents(text);
return text;
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: template " + pageName + " not available: " + getRevResult.message + "</b>";
/*
* the template was not found and will never be - assume
* an empty content instead of letting the model try
* again (which is what it does if null is returned)
*/
return "";
}
}
}
}
if (getRedirectLink() != null) {
// requesting a page from a redirect?
return getRedirectContent(getRedirectLink());
}
// System.out.println("getRawWikiContent(" + namespace + ", " + articleName + ", " +
// templateParameters + ")");
return null;
}
/**
* Gets the contents of the newest revision of the page redirected to.
*
* @param pageName
* the name of the page redirected to
*
* @return the contents of the newest revision of that page or a placeholder
* string
*/
public String getRedirectContent(String pageName) {
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
// make PAGENAME in the redirected content work as expected
setPageName(pageName);
return getRevResult.revision.getText();
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: redirect to " + getRedirectLink() + " failed: " + getRevResult.message + "</b>";
return "#redirect [[" + pageName + "]]";
}
}
}
| true | true | public String getRawWikiContent(String namespace, String articleName,
Map<String, String> templateParameters) {
if (isTemplateNamespace(namespace)) {
String magicWord = articleName;
String parameter = "";
int index = magicWord.indexOf(':');
if (index > 0) {
parameter = magicWord.substring(index + 1).trim();
magicWord = magicWord.substring(0, index);
}
if (MyScalarisMagicWord.isMagicWord(magicWord)) {
// cache values for magic words:
if (magicWordCache.containsKey(articleName)) {
return magicWordCache.get(articleName);
} else {
String value = MyScalarisMagicWord.processMagicWord(magicWord, parameter, this);
magicWordCache.put(articleName, value);
return value;
}
} else {
// retrieve template from Scalaris:
// note: templates are already cached, no need to cache them here
if (connection != null) {
// (ugly) fix for template parameter replacement if no parameters given,
// e.g. "{{noun}}" in the simple English Wiktionary
if (templateParameters.isEmpty()) {
templateParameters.put("", null);
}
String pageName = getTemplateNamespace() + ":" + articleName;
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
String text = getRevResult.revision.getText();
text = removeNoIncludeContents(text);
return text;
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: template " + pageName + " not available: " + getRevResult.message + "</b>";
/*
* the template was not found and will never be - assume
* an empty content instead of letting the model try
* again (which is what it does if null is returned)
*/
return "";
}
}
}
}
if (getRedirectLink() != null) {
// requesting a page from a redirect?
return getRedirectContent(getRedirectLink());
}
// System.out.println("getRawWikiContent(" + namespace + ", " + articleName + ", " +
// templateParameters + ")");
return null;
}
| public String getRawWikiContent(String namespace, String articleName,
Map<String, String> templateParameters) {
if (isTemplateNamespace(namespace)) {
String magicWord = articleName;
String parameter = "";
int index = magicWord.indexOf(':');
if (index > 0) {
parameter = magicWord.substring(index + 1).trim();
magicWord = magicWord.substring(0, index);
}
if (MyScalarisMagicWord.isMagicWord(magicWord)) {
// cache values for magic words:
if (magicWordCache.containsKey(articleName)) {
return magicWordCache.get(articleName);
} else {
String value = MyScalarisMagicWord.processMagicWord(magicWord, parameter, this);
magicWordCache.put(articleName, value);
return value;
}
} else {
// retrieve template from Scalaris:
// note: templates are already cached, no need to cache them here
if (connection != null) {
// (ugly) fix for template parameter replacement if no parameters given,
// e.g. "{{noun}}" in the simple English Wiktionary
if (templateParameters != null && templateParameters.isEmpty()) {
templateParameters.put("", null);
}
String pageName = getTemplateNamespace() + ":" + articleName;
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
String text = getRevResult.revision.getText();
text = removeNoIncludeContents(text);
return text;
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: template " + pageName + " not available: " + getRevResult.message + "</b>";
/*
* the template was not found and will never be - assume
* an empty content instead of letting the model try
* again (which is what it does if null is returned)
*/
return "";
}
}
}
}
if (getRedirectLink() != null) {
// requesting a page from a redirect?
return getRedirectContent(getRedirectLink());
}
// System.out.println("getRawWikiContent(" + namespace + ", " + articleName + ", " +
// templateParameters + ")");
return null;
}
|
diff --git a/src/test/java/com/roosterpark/rptime/selenium/LoginTest.java b/src/test/java/com/roosterpark/rptime/selenium/LoginTest.java
index 2bc3311..2d0d134 100644
--- a/src/test/java/com/roosterpark/rptime/selenium/LoginTest.java
+++ b/src/test/java/com/roosterpark/rptime/selenium/LoginTest.java
@@ -1,63 +1,63 @@
package com.roosterpark.rptime.selenium;
import com.roosterpark.rptime.selenium.mule.LoginMule;
import com.roosterpark.rptime.selenium.mule.WorkerMule;
import com.roosterpark.rptime.selenium.page.*;
import com.roosterpark.rptime.selenium.user.AdminUser;
import com.roosterpark.rptime.selenium.user.StandardUser;
import com.roosterpark.rptime.selenium.user.User;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* User: John
* Date: 10/22/13
* Time: 3:14 PM
*/
public class LoginTest extends BasicSeleniumTest {
private LandingPage landingPage;
private LoginPage loginPage;
private ConfirmationPage confirmationPage;
private HomePage homePage;
private WorkerMule workerMule;
private LoginMule loginMule;
private User user;
@Before
public void setup() {
landingPage = new LandingPage(getDriver());
workerMule = new WorkerMule(getDriver());
loginMule = new LoginMule(getDriver());
}
@Test
public void standardLoginTest() {
workerMule.setHomePage(loginMule.loginAsAdmin());
- WorkerPage workerPage = workerMule.addSalariedWorker("Test", "User", "[email protected]", "01-01-2014");
+ WorkerPage workerPage = workerMule.addSalariedWorker("Test", "User", "[email protected]", "2014-01-01");
workerPage.clickSignOutButton();
user = new StandardUser();
landingPage.openPage();
loginPage = landingPage.clickSignInLink();
confirmationPage = loginPage.signIn(user.getUsername(), user.getPassword());
homePage = confirmationPage.confirm();
assertFalse("Logged in as admin!", homePage.isAdminWarningVisible());
homePage.close();
}
@Test
public void adminLoginTest() {
user = new AdminUser();
landingPage.openPage();
loginPage = landingPage.clickSignInLink();
confirmationPage = loginPage.signIn(user.getUsername(), user.getPassword());
homePage = confirmationPage.confirm();
assertTrue("Not logged in as admin!", homePage.isAdminWarningVisible());
homePage.close();
}
}
| true | true | public void standardLoginTest() {
workerMule.setHomePage(loginMule.loginAsAdmin());
WorkerPage workerPage = workerMule.addSalariedWorker("Test", "User", "[email protected]", "01-01-2014");
workerPage.clickSignOutButton();
user = new StandardUser();
landingPage.openPage();
loginPage = landingPage.clickSignInLink();
confirmationPage = loginPage.signIn(user.getUsername(), user.getPassword());
homePage = confirmationPage.confirm();
assertFalse("Logged in as admin!", homePage.isAdminWarningVisible());
homePage.close();
}
| public void standardLoginTest() {
workerMule.setHomePage(loginMule.loginAsAdmin());
WorkerPage workerPage = workerMule.addSalariedWorker("Test", "User", "[email protected]", "2014-01-01");
workerPage.clickSignOutButton();
user = new StandardUser();
landingPage.openPage();
loginPage = landingPage.clickSignInLink();
confirmationPage = loginPage.signIn(user.getUsername(), user.getPassword());
homePage = confirmationPage.confirm();
assertFalse("Logged in as admin!", homePage.isAdminWarningVisible());
homePage.close();
}
|
diff --git a/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/dialogs/ResizableDialogBox.java b/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/dialogs/ResizableDialogBox.java
index 955a03ce..362b1f00 100644
--- a/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/dialogs/ResizableDialogBox.java
+++ b/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/dialogs/ResizableDialogBox.java
@@ -1,166 +1,158 @@
package org.pentaho.gwt.widgets.client.dialogs;
import org.pentaho.gwt.widgets.client.buttons.RoundedButton;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
public class ResizableDialogBox {
private AbsolutePanel boundaryPanel;
private WindowPanel windowPanel;
private IDialogValidatorCallback validatorCallback;
private IDialogCallback callback;
private Widget content;
public ResizableDialogBox(final String headerText, String okText, String cancelText, final Widget content, final boolean modal) {
this.content = content;
boundaryPanel = new AbsolutePanel() {
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (!modal && event.getTypeInt() == Event.ONCLICK) {
hide();
}
}
};
- boundaryPanel.setSize("100%", Window.getClientHeight() + Window.getScrollTop() + "px"); //$NON-NLS-1$
+ boundaryPanel.setSize("100%", Window.getClientHeight() + Window.getScrollTop() + "px"); //$NON-NLS-1$ //$NON-NLS-2$
boundaryPanel.setVisible(true);
RootPanel.get().add(boundaryPanel, 0, 0);
boundaryPanel.sinkEvents(Event.ONCLICK);
// initialize window controller which provides drag and resize windows
WindowController windowController = new WindowController(boundaryPanel);
// content wrapper
RoundedButton ok = new RoundedButton(okText);
- ok.getElement().setAttribute("id", "okButton");
+ ok.getElement().setAttribute("id", "okButton"); //$NON-NLS-1$ //$NON-NLS-2$
ok.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
if (validatorCallback == null || (validatorCallback != null && validatorCallback.validate())) {
try {
if (callback != null) {
callback.okPressed();
}
} catch (Throwable dontCare) {
}
hide();
}
}
});
final HorizontalPanel dialogButtonPanel = new HorizontalPanel();
dialogButtonPanel.setSpacing(2);
dialogButtonPanel.add(ok);
if (cancelText != null) {
RoundedButton cancel = new RoundedButton(cancelText);
- cancel.getElement().setAttribute("id", "cancelButton");
+ cancel.getElement().setAttribute("id", "cancelButton"); //$NON-NLS-1$ //$NON-NLS-2$
cancel.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
try {
if (callback != null) {
callback.cancelPressed();
}
} catch (Throwable dontCare) {
}
hide();
}
});
dialogButtonPanel.add(cancel);
}
HorizontalPanel dialogButtonPanelWrapper = new HorizontalPanel();
if (okText != null && cancelText != null) {
dialogButtonPanelWrapper.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
} else {
dialogButtonPanelWrapper.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
}
- dialogButtonPanelWrapper.setStyleName("dialogButtonPanel");
- dialogButtonPanelWrapper.setWidth("100%");
+ dialogButtonPanelWrapper.setStyleName("dialogButtonPanel"); //$NON-NLS-1$
+ dialogButtonPanelWrapper.setWidth("100%"); //$NON-NLS-1$
dialogButtonPanelWrapper.add(dialogButtonPanel);
Grid dialogContent = new Grid(2, 1);
dialogContent.setCellPadding(0);
dialogContent.setCellSpacing(0);
dialogContent.getCellFormatter().setVerticalAlignment(1, 0, HasVerticalAlignment.ALIGN_TOP);
dialogContent.getCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_LEFT);
// add content
dialogContent.setWidget(0, 0, content);
dialogContent.getCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_TOP);
// add button panel
dialogContent.setWidget(1, 0, dialogButtonPanelWrapper);
dialogContent.getCellFormatter().setVerticalAlignment(1, 0, HasVerticalAlignment.ALIGN_BOTTOM);
- dialogContent.setWidth("100%");
- dialogContent.setHeight("100%");
+ dialogContent.setWidth("100%"); //$NON-NLS-1$
+ dialogContent.setHeight("100%"); //$NON-NLS-1$
- windowPanel = new WindowPanel(windowController, headerText, dialogContent, true) {
- public void onBrowserEvent(Event event) {
- if (!modal) {
- event.cancelBubble(true);
- return;
- }
- super.onBrowserEvent(event);
- }
- };
+ windowPanel = new WindowPanel(windowController, headerText, dialogContent, true);
}
public void hide() {
boundaryPanel.clear();
RootPanel.get().remove(boundaryPanel);
}
public void center() {
boundaryPanel.clear();
int left = (Window.getClientWidth() - windowPanel.getOffsetWidth()) >> 1;
int top = (Window.getClientHeight() - windowPanel.getOffsetHeight()) >> 1;
boundaryPanel.add(windowPanel, Window.getScrollLeft() + left, Window.getScrollTop() + top);
left = (Window.getClientWidth() - windowPanel.getOffsetWidth()) >> 1;
top = (Window.getClientHeight() - windowPanel.getOffsetHeight()) >> 1;
boundaryPanel.clear();
boundaryPanel.add(windowPanel, Window.getScrollLeft() + left, Window.getScrollTop() + top);
}
public void show() {
center();
}
public IDialogValidatorCallback getValidatorCallback() {
return validatorCallback;
}
public void setValidatorCallback(IDialogValidatorCallback validatorCallback) {
this.validatorCallback = validatorCallback;
}
public IDialogCallback getCallback() {
return callback;
}
public void setCallback(IDialogCallback callback) {
this.callback = callback;
}
public Widget getContent() {
return content;
}
public void setText(String text) {
windowPanel.setText(text);
}
public void setTitle(String title) {
windowPanel.setTitle(title);
}
public void setPixelSize(int width, int height) {
windowPanel.setPixelSize(width, height);
}
}
| false | true | public ResizableDialogBox(final String headerText, String okText, String cancelText, final Widget content, final boolean modal) {
this.content = content;
boundaryPanel = new AbsolutePanel() {
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (!modal && event.getTypeInt() == Event.ONCLICK) {
hide();
}
}
};
boundaryPanel.setSize("100%", Window.getClientHeight() + Window.getScrollTop() + "px"); //$NON-NLS-1$
boundaryPanel.setVisible(true);
RootPanel.get().add(boundaryPanel, 0, 0);
boundaryPanel.sinkEvents(Event.ONCLICK);
// initialize window controller which provides drag and resize windows
WindowController windowController = new WindowController(boundaryPanel);
// content wrapper
RoundedButton ok = new RoundedButton(okText);
ok.getElement().setAttribute("id", "okButton");
ok.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
if (validatorCallback == null || (validatorCallback != null && validatorCallback.validate())) {
try {
if (callback != null) {
callback.okPressed();
}
} catch (Throwable dontCare) {
}
hide();
}
}
});
final HorizontalPanel dialogButtonPanel = new HorizontalPanel();
dialogButtonPanel.setSpacing(2);
dialogButtonPanel.add(ok);
if (cancelText != null) {
RoundedButton cancel = new RoundedButton(cancelText);
cancel.getElement().setAttribute("id", "cancelButton");
cancel.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
try {
if (callback != null) {
callback.cancelPressed();
}
} catch (Throwable dontCare) {
}
hide();
}
});
dialogButtonPanel.add(cancel);
}
HorizontalPanel dialogButtonPanelWrapper = new HorizontalPanel();
if (okText != null && cancelText != null) {
dialogButtonPanelWrapper.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
} else {
dialogButtonPanelWrapper.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
}
dialogButtonPanelWrapper.setStyleName("dialogButtonPanel");
dialogButtonPanelWrapper.setWidth("100%");
dialogButtonPanelWrapper.add(dialogButtonPanel);
Grid dialogContent = new Grid(2, 1);
dialogContent.setCellPadding(0);
dialogContent.setCellSpacing(0);
dialogContent.getCellFormatter().setVerticalAlignment(1, 0, HasVerticalAlignment.ALIGN_TOP);
dialogContent.getCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_LEFT);
// add content
dialogContent.setWidget(0, 0, content);
dialogContent.getCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_TOP);
// add button panel
dialogContent.setWidget(1, 0, dialogButtonPanelWrapper);
dialogContent.getCellFormatter().setVerticalAlignment(1, 0, HasVerticalAlignment.ALIGN_BOTTOM);
dialogContent.setWidth("100%");
dialogContent.setHeight("100%");
windowPanel = new WindowPanel(windowController, headerText, dialogContent, true) {
public void onBrowserEvent(Event event) {
if (!modal) {
event.cancelBubble(true);
return;
}
super.onBrowserEvent(event);
}
};
}
| public ResizableDialogBox(final String headerText, String okText, String cancelText, final Widget content, final boolean modal) {
this.content = content;
boundaryPanel = new AbsolutePanel() {
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (!modal && event.getTypeInt() == Event.ONCLICK) {
hide();
}
}
};
boundaryPanel.setSize("100%", Window.getClientHeight() + Window.getScrollTop() + "px"); //$NON-NLS-1$ //$NON-NLS-2$
boundaryPanel.setVisible(true);
RootPanel.get().add(boundaryPanel, 0, 0);
boundaryPanel.sinkEvents(Event.ONCLICK);
// initialize window controller which provides drag and resize windows
WindowController windowController = new WindowController(boundaryPanel);
// content wrapper
RoundedButton ok = new RoundedButton(okText);
ok.getElement().setAttribute("id", "okButton"); //$NON-NLS-1$ //$NON-NLS-2$
ok.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
if (validatorCallback == null || (validatorCallback != null && validatorCallback.validate())) {
try {
if (callback != null) {
callback.okPressed();
}
} catch (Throwable dontCare) {
}
hide();
}
}
});
final HorizontalPanel dialogButtonPanel = new HorizontalPanel();
dialogButtonPanel.setSpacing(2);
dialogButtonPanel.add(ok);
if (cancelText != null) {
RoundedButton cancel = new RoundedButton(cancelText);
cancel.getElement().setAttribute("id", "cancelButton"); //$NON-NLS-1$ //$NON-NLS-2$
cancel.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
try {
if (callback != null) {
callback.cancelPressed();
}
} catch (Throwable dontCare) {
}
hide();
}
});
dialogButtonPanel.add(cancel);
}
HorizontalPanel dialogButtonPanelWrapper = new HorizontalPanel();
if (okText != null && cancelText != null) {
dialogButtonPanelWrapper.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
} else {
dialogButtonPanelWrapper.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
}
dialogButtonPanelWrapper.setStyleName("dialogButtonPanel"); //$NON-NLS-1$
dialogButtonPanelWrapper.setWidth("100%"); //$NON-NLS-1$
dialogButtonPanelWrapper.add(dialogButtonPanel);
Grid dialogContent = new Grid(2, 1);
dialogContent.setCellPadding(0);
dialogContent.setCellSpacing(0);
dialogContent.getCellFormatter().setVerticalAlignment(1, 0, HasVerticalAlignment.ALIGN_TOP);
dialogContent.getCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_LEFT);
// add content
dialogContent.setWidget(0, 0, content);
dialogContent.getCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_TOP);
// add button panel
dialogContent.setWidget(1, 0, dialogButtonPanelWrapper);
dialogContent.getCellFormatter().setVerticalAlignment(1, 0, HasVerticalAlignment.ALIGN_BOTTOM);
dialogContent.setWidth("100%"); //$NON-NLS-1$
dialogContent.setHeight("100%"); //$NON-NLS-1$
windowPanel = new WindowPanel(windowController, headerText, dialogContent, true);
}
|
diff --git a/src/nl/giantit/minecraft/GiantShop/API/GSW/PickupQueue.java b/src/nl/giantit/minecraft/GiantShop/API/GSW/PickupQueue.java
index af30c4c..4ed6650 100644
--- a/src/nl/giantit/minecraft/GiantShop/API/GSW/PickupQueue.java
+++ b/src/nl/giantit/minecraft/GiantShop/API/GSW/PickupQueue.java
@@ -1,141 +1,143 @@
package nl.giantit.minecraft.GiantShop.API.GSW;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import nl.giantit.minecraft.GiantShop.API.conf;
import nl.giantit.minecraft.GiantShop.GiantShop;
import nl.giantit.minecraft.GiantShop.Misc.Heraut;
import nl.giantit.minecraft.GiantShop.Misc.Messages;
import nl.giantit.minecraft.GiantShop.core.Database.drivers.iDriver;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
/**
*
* @author Giant
*/
public class PickupQueue {
private GiantShop p;
private Messages mH;
private HashMap<String, ArrayList<Queued>> queue = new HashMap<String, ArrayList<Queued>>();
public PickupQueue(GiantShop p) {
this.p = p;
this.mH = p.getMsgHandler();
}
public void addToQueue(String transactionID, String player, int amount, int id, int type) {
// Add purchase to database and take money
iDriver db = p.getDB().getEngine();
ArrayList<String> fields = new ArrayList<String>() {
{
add("transactionID");
add("player");
add("amount");
add("itemID");
add("itemType");
}
};
HashMap<Integer, HashMap<String, String>> values = new HashMap<Integer, HashMap<String, String>>();
int i = 0;
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equals("transactionID")) {
- temp.put("data", "'" + transactionID + "'");
+ temp.put("data", transactionID);
values.put(i, temp);
}else if(field.equals("player")) {
temp.put("data", player);
values.put(i, temp);
}else if(field.equals("amount")) {
+ temp.put("kind", "INT");
temp.put("data", "" + amount);
values.put(i, temp);
}else if(field.equals("itemID")) {
+ temp.put("kind", "INT");
temp.put("data", "" + id);
values.put(i, temp);
}else if(field.equals("itemType")) {
temp.put("kind", "INT");
temp.put("data", "" + type);
values.put(i, temp);
}
i++;
}
// Insert transaction into database as ready pickup!
db.insert("#__api_gsw_pickups", fields, values).updateQuery();
ArrayList<Queued> q;
if(this.queue.containsKey(player)) {
q = this.queue.remove(player);
}else{
q = new ArrayList<Queued>();
}
Queued Q = new Queued(id, type, amount, transactionID);
q.add(Q);
this.queue.put(player, q);
this.stalkUser(player);
}
public boolean inQueue(String player) {
return false;
}
public void stalkUser(String player) {
Player pl = p.getSrvr().getPlayerExact(player);
if(null != pl) {
// Player is online! Bug him about his new purchase now!
conf c = GSWAPI.getInstance().getConfig();
if(c.getBoolean("GiantShopWeb.Items.PickupsRequireCommand")) {
Heraut.say(pl, mH.getMsg(Messages.msgType.MAIN, "itemWaitingForPickup"));
Heraut.say(pl, mH.getMsg(Messages.msgType.MAIN, "itemPickupHelp"));
}else{
this.deliver(pl);
}
}
}
public void deliver(Player player) {
Inventory inv = player.getInventory();
ArrayList<Queued> qList = this.queue.get(player.getName());
for(Queued q : qList) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("transactionID", q.getTransactionID());
data.put("itemID", String.valueOf(q.getItemID()));
data.put("itemType", String.valueOf(q.getItemType()));
data.put("itemName", q.getItemName());
data.put("amount", String.valueOf(q.getAmount()));
Heraut.say(player, mH.getMsg(Messages.msgType.MAIN, "itemDelivery", data));
ItemStack iStack;
if(q.getItemType() != -1 && q.getItemType() != 0) {
if(q.getItemID() != 373)
iStack = new MaterialData(q.getItemID(), (byte) ((int) q.getItemType())).toItemStack(q.getAmount());
else
iStack = new ItemStack(q.getItemID(), q.getAmount(), (short) ((int) q.getItemType()));
}else{
iStack = new ItemStack(q.getItemID(), q.getAmount());
}
HashMap<Integer, ItemStack> left = inv.addItem(iStack);
if(!left.isEmpty()) {
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "infFull"));
for(Map.Entry<Integer, ItemStack> stack : left.entrySet()) {
player.getWorld().dropItem(player.getLocation(), stack.getValue());
}
}
}
Heraut.say(player, mH.getMsg(Messages.msgType.MAIN, "itemsDelivered"));
}
}
| false | true | public void addToQueue(String transactionID, String player, int amount, int id, int type) {
// Add purchase to database and take money
iDriver db = p.getDB().getEngine();
ArrayList<String> fields = new ArrayList<String>() {
{
add("transactionID");
add("player");
add("amount");
add("itemID");
add("itemType");
}
};
HashMap<Integer, HashMap<String, String>> values = new HashMap<Integer, HashMap<String, String>>();
int i = 0;
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equals("transactionID")) {
temp.put("data", "'" + transactionID + "'");
values.put(i, temp);
}else if(field.equals("player")) {
temp.put("data", player);
values.put(i, temp);
}else if(field.equals("amount")) {
temp.put("data", "" + amount);
values.put(i, temp);
}else if(field.equals("itemID")) {
temp.put("data", "" + id);
values.put(i, temp);
}else if(field.equals("itemType")) {
temp.put("kind", "INT");
temp.put("data", "" + type);
values.put(i, temp);
}
i++;
}
// Insert transaction into database as ready pickup!
db.insert("#__api_gsw_pickups", fields, values).updateQuery();
ArrayList<Queued> q;
if(this.queue.containsKey(player)) {
q = this.queue.remove(player);
}else{
q = new ArrayList<Queued>();
}
Queued Q = new Queued(id, type, amount, transactionID);
q.add(Q);
this.queue.put(player, q);
this.stalkUser(player);
}
| public void addToQueue(String transactionID, String player, int amount, int id, int type) {
// Add purchase to database and take money
iDriver db = p.getDB().getEngine();
ArrayList<String> fields = new ArrayList<String>() {
{
add("transactionID");
add("player");
add("amount");
add("itemID");
add("itemType");
}
};
HashMap<Integer, HashMap<String, String>> values = new HashMap<Integer, HashMap<String, String>>();
int i = 0;
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equals("transactionID")) {
temp.put("data", transactionID);
values.put(i, temp);
}else if(field.equals("player")) {
temp.put("data", player);
values.put(i, temp);
}else if(field.equals("amount")) {
temp.put("kind", "INT");
temp.put("data", "" + amount);
values.put(i, temp);
}else if(field.equals("itemID")) {
temp.put("kind", "INT");
temp.put("data", "" + id);
values.put(i, temp);
}else if(field.equals("itemType")) {
temp.put("kind", "INT");
temp.put("data", "" + type);
values.put(i, temp);
}
i++;
}
// Insert transaction into database as ready pickup!
db.insert("#__api_gsw_pickups", fields, values).updateQuery();
ArrayList<Queued> q;
if(this.queue.containsKey(player)) {
q = this.queue.remove(player);
}else{
q = new ArrayList<Queued>();
}
Queued Q = new Queued(id, type, amount, transactionID);
q.add(Q);
this.queue.put(player, q);
this.stalkUser(player);
}
|
diff --git a/src/com/android/phone/EmergencyDialer.java b/src/com/android/phone/EmergencyDialer.java
index ac7d5885..f3d9a149 100644
--- a/src/com/android/phone/EmergencyDialer.java
+++ b/src/com/android/phone/EmergencyDialer.java
@@ -1,633 +1,637 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.StatusBarManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.PhoneNumberUtils;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DialerKeyListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityManager;
import android.widget.EditText;
/**
* EmergencyDialer is a special dialer that is used ONLY for dialing emergency calls.
*
* It's a simplified version of the regular dialer (i.e. the TwelveKeyDialer
* activity from apps/Contacts) that:
* 1. Allows ONLY emergency calls to be dialed
* 2. Disallows voicemail functionality
* 3. Uses the FLAG_SHOW_WHEN_LOCKED window manager flag to allow this
* activity to stay in front of the keyguard.
*
* TODO: Even though this is an ultra-simplified version of the normal
* dialer, there's still lots of code duplication between this class and
* the TwelveKeyDialer class from apps/Contacts. Could the common code be
* moved into a shared base class that would live in the framework?
* Or could we figure out some way to move *this* class into apps/Contacts
* also?
*/
public class EmergencyDialer extends Activity implements View.OnClickListener,
View.OnLongClickListener, View.OnHoverListener, View.OnKeyListener, TextWatcher {
// Keys used with onSaveInstanceState().
private static final String LAST_NUMBER = "lastNumber";
// Intent action for this activity.
public static final String ACTION_DIAL = "com.android.phone.EmergencyDialer.DIAL";
// List of dialer button IDs.
private static final int[] DIALER_KEYS = new int[] {
R.id.one, R.id.two, R.id.three,
R.id.four, R.id.five, R.id.six,
R.id.seven, R.id.eight, R.id.nine,
R.id.star, R.id.zero, R.id.pound };
// Debug constants.
private static final boolean DBG = false;
private static final String LOG_TAG = "EmergencyDialer";
private PhoneGlobals mApp;
private StatusBarManager mStatusBarManager;
private AccessibilityManager mAccessibilityManager;
/** The length of DTMF tones in milliseconds */
private static final int TONE_LENGTH_MS = 150;
/** The DTMF tone volume relative to other sounds in the stream */
private static final int TONE_RELATIVE_VOLUME = 80;
/** Stream type used to play the DTMF tones off call, and mapped to the volume control keys */
private static final int DIAL_TONE_STREAM_TYPE = AudioManager.STREAM_DTMF;
private static final int BAD_EMERGENCY_NUMBER_DIALOG = 0;
private static final int USER_ACTIVITY_TIMEOUT_WHEN_NO_PROX_SENSOR = 15000; // millis
EditText mDigits;
private View mDialButton;
private View mDelete;
private ToneGenerator mToneGenerator;
private Object mToneGeneratorLock = new Object();
// determines if we want to playback local DTMF tones.
private boolean mDTMFToneEnabled;
// Haptic feedback (vibration) for dialer key presses.
private HapticFeedback mHaptic = new HapticFeedback();
// close activity when screen turns off
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
finish();
}
}
};
private String mLastNumber; // last number we tried to dial. Used to restore error dialog.
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Do nothing
}
@Override
public void onTextChanged(CharSequence input, int start, int before, int changeCount) {
// Do nothing
}
@Override
public void afterTextChanged(Editable input) {
// Check for special sequences, in particular the "**04" or "**05"
// sequences that allow you to enter PIN or PUK-related codes.
//
// But note we *don't* allow most other special sequences here,
// like "secret codes" (*#*#<code>#*#*) or IMEI display ("*#06#"),
// since those shouldn't be available if the device is locked.
//
// So we call SpecialCharSequenceMgr.handleCharsForLockedDevice()
// here, not the regular handleChars() method.
if (SpecialCharSequenceMgr.handleCharsForLockedDevice(this, input.toString(), this)) {
// A special sequence was entered, clear the digits
mDigits.getText().clear();
}
updateDialAndDeleteButtonStateEnabledAttr();
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mApp = PhoneGlobals.getInstance();
mStatusBarManager = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE);
mAccessibilityManager = (AccessibilityManager) getSystemService(ACCESSIBILITY_SERVICE);
// Allow this activity to be displayed in front of the keyguard / lockscreen.
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
if (!mApp.proximitySensorModeEnabled()) {
// When no proximity sensor is available, use a shorter timeout.
lp.userActivityTimeout = USER_ACTIVITY_TIMEOUT_WHEN_NO_PROX_SENSOR;
}
getWindow().setAttributes(lp);
setContentView(R.layout.emergency_dialer);
mDigits = (EditText) findViewById(R.id.digits);
mDigits.setKeyListener(DialerKeyListener.getInstance());
mDigits.setOnClickListener(this);
mDigits.setOnKeyListener(this);
mDigits.setLongClickable(false);
+ if (mAccessibilityManager.isEnabled()) {
+ // The text view must be selected to send accessibility events.
+ mDigits.setSelected(true);
+ }
maybeAddNumberFormatting();
// Check for the presence of the keypad
View view = findViewById(R.id.one);
if (view != null) {
setupKeypad();
}
mDelete = findViewById(R.id.deleteButton);
mDelete.setOnClickListener(this);
mDelete.setOnLongClickListener(this);
mDialButton = findViewById(R.id.dialButton);
// Check whether we should show the onscreen "Dial" button and co.
Resources res = getResources();
if (res.getBoolean(R.bool.config_show_onscreen_dial_button)) {
mDialButton.setOnClickListener(this);
} else {
mDialButton.setVisibility(View.GONE);
}
if (icicle != null) {
super.onRestoreInstanceState(icicle);
}
// Extract phone number from intent
Uri data = getIntent().getData();
if (data != null && (Constants.SCHEME_TEL.equals(data.getScheme()))) {
String number = PhoneNumberUtils.getNumberFromIntent(getIntent(), this);
if (number != null) {
mDigits.setText(number);
}
}
// if the mToneGenerator creation fails, just continue without it. It is
// a local audio signal, and is not as important as the dtmf tone itself.
synchronized (mToneGeneratorLock) {
if (mToneGenerator == null) {
try {
mToneGenerator = new ToneGenerator(DIAL_TONE_STREAM_TYPE, TONE_RELATIVE_VOLUME);
} catch (RuntimeException e) {
Log.w(LOG_TAG, "Exception caught while creating local tone generator: " + e);
mToneGenerator = null;
}
}
}
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mBroadcastReceiver, intentFilter);
try {
mHaptic.init(this, res.getBoolean(R.bool.config_enable_dialer_key_vibration));
} catch (Resources.NotFoundException nfe) {
Log.e(LOG_TAG, "Vibrate control bool missing.", nfe);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
synchronized (mToneGeneratorLock) {
if (mToneGenerator != null) {
mToneGenerator.release();
mToneGenerator = null;
}
}
unregisterReceiver(mBroadcastReceiver);
}
@Override
protected void onRestoreInstanceState(Bundle icicle) {
mLastNumber = icicle.getString(LAST_NUMBER);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(LAST_NUMBER, mLastNumber);
}
/**
* Explicitly turn off number formatting, since it gets in the way of the emergency
* number detector
*/
protected void maybeAddNumberFormatting() {
// Do nothing.
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// This can't be done in onCreate(), since the auto-restoring of the digits
// will play DTMF tones for all the old digits if it is when onRestoreSavedInstanceState()
// is called. This method will be called every time the activity is created, and
// will always happen after onRestoreSavedInstanceState().
mDigits.addTextChangedListener(this);
}
private void setupKeypad() {
// Setup the listeners for the buttons
for (int id : DIALER_KEYS) {
final View key = findViewById(id);
key.setOnClickListener(this);
key.setOnHoverListener(this);
}
View view = findViewById(R.id.zero);
view.setOnLongClickListener(this);
}
/**
* handle key events
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
// Happen when there's a "Call" hard button.
case KeyEvent.KEYCODE_CALL: {
if (TextUtils.isEmpty(mDigits.getText().toString())) {
// if we are adding a call from the InCallScreen and the phone
// number entered is empty, we just close the dialer to expose
// the InCallScreen under it.
finish();
} else {
// otherwise, we place the call.
placeCall();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private void keyPressed(int keyCode) {
mHaptic.vibrate();
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
mDigits.onKeyDown(keyCode, event);
}
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
switch (view.getId()) {
case R.id.digits:
// Happen when "Done" button of the IME is pressed. This can happen when this
// Activity is forced into landscape mode due to a desk dock.
if (keyCode == KeyEvent.KEYCODE_ENTER
&& event.getAction() == KeyEvent.ACTION_UP) {
placeCall();
return true;
}
break;
}
return false;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.one: {
playTone(ToneGenerator.TONE_DTMF_1);
keyPressed(KeyEvent.KEYCODE_1);
return;
}
case R.id.two: {
playTone(ToneGenerator.TONE_DTMF_2);
keyPressed(KeyEvent.KEYCODE_2);
return;
}
case R.id.three: {
playTone(ToneGenerator.TONE_DTMF_3);
keyPressed(KeyEvent.KEYCODE_3);
return;
}
case R.id.four: {
playTone(ToneGenerator.TONE_DTMF_4);
keyPressed(KeyEvent.KEYCODE_4);
return;
}
case R.id.five: {
playTone(ToneGenerator.TONE_DTMF_5);
keyPressed(KeyEvent.KEYCODE_5);
return;
}
case R.id.six: {
playTone(ToneGenerator.TONE_DTMF_6);
keyPressed(KeyEvent.KEYCODE_6);
return;
}
case R.id.seven: {
playTone(ToneGenerator.TONE_DTMF_7);
keyPressed(KeyEvent.KEYCODE_7);
return;
}
case R.id.eight: {
playTone(ToneGenerator.TONE_DTMF_8);
keyPressed(KeyEvent.KEYCODE_8);
return;
}
case R.id.nine: {
playTone(ToneGenerator.TONE_DTMF_9);
keyPressed(KeyEvent.KEYCODE_9);
return;
}
case R.id.zero: {
playTone(ToneGenerator.TONE_DTMF_0);
keyPressed(KeyEvent.KEYCODE_0);
return;
}
case R.id.pound: {
playTone(ToneGenerator.TONE_DTMF_P);
keyPressed(KeyEvent.KEYCODE_POUND);
return;
}
case R.id.star: {
playTone(ToneGenerator.TONE_DTMF_S);
keyPressed(KeyEvent.KEYCODE_STAR);
return;
}
case R.id.deleteButton: {
keyPressed(KeyEvent.KEYCODE_DEL);
return;
}
case R.id.dialButton: {
mHaptic.vibrate(); // Vibrate here too, just like we do for the regular keys
placeCall();
return;
}
case R.id.digits: {
if (mDigits.length() != 0) {
mDigits.setCursorVisible(true);
}
return;
}
}
}
/**
* Implemented for {@link android.view.View.OnHoverListener}. Handles touch
* events for accessibility when touch exploration is enabled.
*/
@Override
public boolean onHover(View v, MotionEvent event) {
// When touch exploration is turned on, lifting a finger while inside
// the button's hover target bounds should perform a click action.
if (mAccessibilityManager.isEnabled()
&& mAccessibilityManager.isTouchExplorationEnabled()) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_HOVER_ENTER:
// Lift-to-type temporarily disables double-tap activation.
v.setClickable(false);
break;
case MotionEvent.ACTION_HOVER_EXIT:
final int left = v.getPaddingLeft();
final int right = (v.getWidth() - v.getPaddingRight());
final int top = v.getPaddingTop();
final int bottom = (v.getHeight() - v.getPaddingBottom());
final int x = (int) event.getX();
final int y = (int) event.getY();
if ((x > left) && (x < right) && (y > top) && (y < bottom)) {
v.performClick();
}
v.setClickable(true);
break;
}
}
return false;
}
/**
* called for long touch events
*/
@Override
public boolean onLongClick(View view) {
int id = view.getId();
switch (id) {
case R.id.deleteButton: {
mDigits.getText().clear();
// TODO: The framework forgets to clear the pressed
// status of disabled button. Until this is fixed,
// clear manually the pressed status. b/2133127
mDelete.setPressed(false);
return true;
}
case R.id.zero: {
keyPressed(KeyEvent.KEYCODE_PLUS);
return true;
}
}
return false;
}
@Override
protected void onResume() {
super.onResume();
// retrieve the DTMF tone play back setting.
mDTMFToneEnabled = Settings.System.getInt(getContentResolver(),
Settings.System.DTMF_TONE_WHEN_DIALING, 1) == 1;
// Retrieve the haptic feedback setting.
mHaptic.checkSystemSetting();
// if the mToneGenerator creation fails, just continue without it. It is
// a local audio signal, and is not as important as the dtmf tone itself.
synchronized (mToneGeneratorLock) {
if (mToneGenerator == null) {
try {
mToneGenerator = new ToneGenerator(AudioManager.STREAM_DTMF,
TONE_RELATIVE_VOLUME);
} catch (RuntimeException e) {
Log.w(LOG_TAG, "Exception caught while creating local tone generator: " + e);
mToneGenerator = null;
}
}
}
// Disable the status bar and set the poke lock timeout to medium.
// There is no need to do anything with the wake lock.
if (DBG) Log.d(LOG_TAG, "disabling status bar, set to long timeout");
mStatusBarManager.disable(StatusBarManager.DISABLE_EXPAND);
updateDialAndDeleteButtonStateEnabledAttr();
}
@Override
public void onPause() {
// Reenable the status bar and set the poke lock timeout to default.
// There is no need to do anything with the wake lock.
if (DBG) Log.d(LOG_TAG, "reenabling status bar and closing the dialer");
mStatusBarManager.disable(StatusBarManager.DISABLE_NONE);
super.onPause();
synchronized (mToneGeneratorLock) {
if (mToneGenerator != null) {
mToneGenerator.release();
mToneGenerator = null;
}
}
}
/**
* place the call, but check to make sure it is a viable number.
*/
private void placeCall() {
mLastNumber = mDigits.getText().toString();
if (PhoneNumberUtils.isLocalEmergencyNumber(mLastNumber, this)) {
if (DBG) Log.d(LOG_TAG, "placing call to " + mLastNumber);
// place the call if it is a valid number
if (mLastNumber == null || !TextUtils.isGraphic(mLastNumber)) {
// There is no number entered.
playTone(ToneGenerator.TONE_PROP_NACK);
return;
}
Intent intent = new Intent(Intent.ACTION_CALL_EMERGENCY);
intent.setData(Uri.fromParts(Constants.SCHEME_TEL, mLastNumber, null));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else {
if (DBG) Log.d(LOG_TAG, "rejecting bad requested number " + mLastNumber);
// erase the number and throw up an alert dialog.
mDigits.getText().delete(0, mDigits.getText().length());
showDialog(BAD_EMERGENCY_NUMBER_DIALOG);
}
}
/**
* Plays the specified tone for TONE_LENGTH_MS milliseconds.
*
* The tone is played locally, using the audio stream for phone calls.
* Tones are played only if the "Audible touch tones" user preference
* is checked, and are NOT played if the device is in silent mode.
*
* @param tone a tone code from {@link ToneGenerator}
*/
void playTone(int tone) {
// if local tone playback is disabled, just return.
if (!mDTMFToneEnabled) {
return;
}
// Also do nothing if the phone is in silent mode.
// We need to re-check the ringer mode for *every* playTone()
// call, rather than keeping a local flag that's updated in
// onResume(), since it's possible to toggle silent mode without
// leaving the current activity (via the ENDCALL-longpress menu.)
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int ringerMode = audioManager.getRingerMode();
if ((ringerMode == AudioManager.RINGER_MODE_SILENT)
|| (ringerMode == AudioManager.RINGER_MODE_VIBRATE)) {
return;
}
synchronized (mToneGeneratorLock) {
if (mToneGenerator == null) {
Log.w(LOG_TAG, "playTone: mToneGenerator == null, tone: " + tone);
return;
}
// Start the new tone (will stop any playing tone)
mToneGenerator.startTone(tone, TONE_LENGTH_MS);
}
}
private CharSequence createErrorMessage(String number) {
if (!TextUtils.isEmpty(number)) {
return getString(R.string.dial_emergency_error, mLastNumber);
} else {
return getText(R.string.dial_emergency_empty_error).toString();
}
}
@Override
protected Dialog onCreateDialog(int id) {
AlertDialog dialog = null;
if (id == BAD_EMERGENCY_NUMBER_DIALOG) {
// construct dialog
dialog = new AlertDialog.Builder(this)
.setTitle(getText(R.string.emergency_enable_radio_dialog_title))
.setMessage(createErrorMessage(mLastNumber))
.setPositiveButton(R.string.ok, null)
.setCancelable(true).create();
// blur stuff behind the dialog
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
}
return dialog;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if (id == BAD_EMERGENCY_NUMBER_DIALOG) {
AlertDialog alert = (AlertDialog) dialog;
alert.setMessage(createErrorMessage(mLastNumber));
}
}
/**
* Update the enabledness of the "Dial" and "Backspace" buttons if applicable.
*/
private void updateDialAndDeleteButtonStateEnabledAttr() {
final boolean notEmpty = mDigits.length() != 0;
mDialButton.setEnabled(notEmpty);
mDelete.setEnabled(notEmpty);
}
}
| true | true | protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mApp = PhoneGlobals.getInstance();
mStatusBarManager = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE);
mAccessibilityManager = (AccessibilityManager) getSystemService(ACCESSIBILITY_SERVICE);
// Allow this activity to be displayed in front of the keyguard / lockscreen.
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
if (!mApp.proximitySensorModeEnabled()) {
// When no proximity sensor is available, use a shorter timeout.
lp.userActivityTimeout = USER_ACTIVITY_TIMEOUT_WHEN_NO_PROX_SENSOR;
}
getWindow().setAttributes(lp);
setContentView(R.layout.emergency_dialer);
mDigits = (EditText) findViewById(R.id.digits);
mDigits.setKeyListener(DialerKeyListener.getInstance());
mDigits.setOnClickListener(this);
mDigits.setOnKeyListener(this);
mDigits.setLongClickable(false);
maybeAddNumberFormatting();
// Check for the presence of the keypad
View view = findViewById(R.id.one);
if (view != null) {
setupKeypad();
}
mDelete = findViewById(R.id.deleteButton);
mDelete.setOnClickListener(this);
mDelete.setOnLongClickListener(this);
mDialButton = findViewById(R.id.dialButton);
// Check whether we should show the onscreen "Dial" button and co.
Resources res = getResources();
if (res.getBoolean(R.bool.config_show_onscreen_dial_button)) {
mDialButton.setOnClickListener(this);
} else {
mDialButton.setVisibility(View.GONE);
}
if (icicle != null) {
super.onRestoreInstanceState(icicle);
}
// Extract phone number from intent
Uri data = getIntent().getData();
if (data != null && (Constants.SCHEME_TEL.equals(data.getScheme()))) {
String number = PhoneNumberUtils.getNumberFromIntent(getIntent(), this);
if (number != null) {
mDigits.setText(number);
}
}
// if the mToneGenerator creation fails, just continue without it. It is
// a local audio signal, and is not as important as the dtmf tone itself.
synchronized (mToneGeneratorLock) {
if (mToneGenerator == null) {
try {
mToneGenerator = new ToneGenerator(DIAL_TONE_STREAM_TYPE, TONE_RELATIVE_VOLUME);
} catch (RuntimeException e) {
Log.w(LOG_TAG, "Exception caught while creating local tone generator: " + e);
mToneGenerator = null;
}
}
}
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mBroadcastReceiver, intentFilter);
try {
mHaptic.init(this, res.getBoolean(R.bool.config_enable_dialer_key_vibration));
} catch (Resources.NotFoundException nfe) {
Log.e(LOG_TAG, "Vibrate control bool missing.", nfe);
}
}
| protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mApp = PhoneGlobals.getInstance();
mStatusBarManager = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE);
mAccessibilityManager = (AccessibilityManager) getSystemService(ACCESSIBILITY_SERVICE);
// Allow this activity to be displayed in front of the keyguard / lockscreen.
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
if (!mApp.proximitySensorModeEnabled()) {
// When no proximity sensor is available, use a shorter timeout.
lp.userActivityTimeout = USER_ACTIVITY_TIMEOUT_WHEN_NO_PROX_SENSOR;
}
getWindow().setAttributes(lp);
setContentView(R.layout.emergency_dialer);
mDigits = (EditText) findViewById(R.id.digits);
mDigits.setKeyListener(DialerKeyListener.getInstance());
mDigits.setOnClickListener(this);
mDigits.setOnKeyListener(this);
mDigits.setLongClickable(false);
if (mAccessibilityManager.isEnabled()) {
// The text view must be selected to send accessibility events.
mDigits.setSelected(true);
}
maybeAddNumberFormatting();
// Check for the presence of the keypad
View view = findViewById(R.id.one);
if (view != null) {
setupKeypad();
}
mDelete = findViewById(R.id.deleteButton);
mDelete.setOnClickListener(this);
mDelete.setOnLongClickListener(this);
mDialButton = findViewById(R.id.dialButton);
// Check whether we should show the onscreen "Dial" button and co.
Resources res = getResources();
if (res.getBoolean(R.bool.config_show_onscreen_dial_button)) {
mDialButton.setOnClickListener(this);
} else {
mDialButton.setVisibility(View.GONE);
}
if (icicle != null) {
super.onRestoreInstanceState(icicle);
}
// Extract phone number from intent
Uri data = getIntent().getData();
if (data != null && (Constants.SCHEME_TEL.equals(data.getScheme()))) {
String number = PhoneNumberUtils.getNumberFromIntent(getIntent(), this);
if (number != null) {
mDigits.setText(number);
}
}
// if the mToneGenerator creation fails, just continue without it. It is
// a local audio signal, and is not as important as the dtmf tone itself.
synchronized (mToneGeneratorLock) {
if (mToneGenerator == null) {
try {
mToneGenerator = new ToneGenerator(DIAL_TONE_STREAM_TYPE, TONE_RELATIVE_VOLUME);
} catch (RuntimeException e) {
Log.w(LOG_TAG, "Exception caught while creating local tone generator: " + e);
mToneGenerator = null;
}
}
}
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mBroadcastReceiver, intentFilter);
try {
mHaptic.init(this, res.getBoolean(R.bool.config_enable_dialer_key_vibration));
} catch (Resources.NotFoundException nfe) {
Log.e(LOG_TAG, "Vibrate control bool missing.", nfe);
}
}
|
diff --git a/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/utilities/ast/DartElementLocatorTest.java b/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/utilities/ast/DartElementLocatorTest.java
index ae7db31b5..d0425d0a6 100644
--- a/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/utilities/ast/DartElementLocatorTest.java
+++ b/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/utilities/ast/DartElementLocatorTest.java
@@ -1,191 +1,191 @@
/*
* Copyright 2011, the Dart project authors.
*
* Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.dart.tools.core.utilities.ast;
import static com.google.dart.tools.core.test.util.MoneyProjectUtilities.getMoneyCompilationUnit;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.dart.compiler.DartCompilationError;
import com.google.dart.compiler.ast.DartUnit;
import com.google.dart.tools.core.model.CompilationUnit;
import com.google.dart.tools.core.model.DartElement;
import com.google.dart.tools.core.model.DartModelException;
import com.google.dart.tools.core.utilities.compiler.DartCompilerUtilities;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.List;
public class DartElementLocatorTest extends TestCase {
public void test_VariableElement_parameter_inClassMethod() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
- "print(x) {}",
+ "process(x) {}",
"class A {",
" foo(a, bb, ccc) {",
- " print(bb);",
+ " process(bb);",
" }",
"}"}, "bb);", "bb, ", 2);
}
public void test_VariableElement_parameter_inTopMethod() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
- "print(x) {}",
+ "process(x) {}",
"foo(a, bb, ccc) {",
- " print(bb);",
+ " process(bb);",
"}"}, "bb);", "bb, ", 2);
}
public void test_VariableElement_localVariable() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
- "print(x) {}",
+ "process(x) {}",
"foo() {",
" var aaa = 1;",
- " print(aaa);",
+ " process(aaa);",
"}"}, "aaa);", "aaa = 1", 3);
}
public void test_FieldElement_topLevel() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
- "print(x) {}",
+ "process(x) {}",
"var aaa = 1;",
"foo() {",
- " print(aaa);",
+ " process(aaa);",
"}"}, "aaa);", "aaa = 1", 3);
}
public void test_FieldElement_classMember() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
- "print(x) {}",
+ "process(x) {}",
"class A {",
" var bbb = 1;",
"}",
"foo() {",
" A a = new A();",
- " print(a.bbb);",
+ " process(a.bbb);",
"}"}, "bbb);", "bbb = 1", 3);
}
public void test_type_typeName() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"class A {}",
"foo() {",
" A a = null;",
"}"}, "A a =", "A {}", 1);
}
public void test_type_newExpression() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"class A {",
" A() {}",
"}",
"foo() {",
" A a = new A();",
"}"}, "A();", "A() {}", 1);
}
public void test_methodInvocation() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"foo() {}",
"bar() {",
" foo();",
"}"}, "foo();", "foo() {}", 3);
}
private void testElementLocator(String[] sourceLines,
String posMarker,
String expectedMarker,
int expectedLen) throws Exception {
TestProject testProject = new TestProject("Test");
try {
CompilationUnit unit =
testProject.setUnitContent("Test.dart", Joiner.on("\n").join(sourceLines));
assertLocation(unit, posMarker, expectedMarker, expectedLen);
} finally {
testProject.dispose();
}
}
private static void assertLocation(CompilationUnit unit,
String posMarker,
String expectedMarker,
int expectedLen) throws Exception {
String source = unit.getSource();
// prepare DartUnit
DartUnit dartUnit;
{
List<DartCompilationError> errors = Lists.newArrayList();
dartUnit = DartCompilerUtilities.resolveUnit(unit, errors);
// we don't want errors
if (!errors.isEmpty()) {
fail("Parse/resolve errors: " + errors);
}
}
// prepare position to search on
int pos = source.indexOf(posMarker);
assertTrue("Unable to find position marker '" + posMarker + "'", pos > 0);
// use Locator
DartElementLocator locator = new DartElementLocator(unit, pos, true);
DartElement result = locator.searchWithin(dartUnit);
// verify
if (expectedMarker != null) {
assertNotNull(result);
int expectedPos = source.indexOf(expectedMarker);
assertTrue("Unable to find expected marker '" + expectedMarker + "'", expectedPos > 0);
assertEquals(expectedPos, locator.getCandidateRegion().getOffset());
assertEquals(expectedLen, locator.getCandidateRegion().getLength());
} else {
assertNull(result);
}
}
public void test_DartElementLocator_searchWithin_declaration_with() throws Exception {
CompilationUnit unit = getMoneyCompilationUnit("simple_money.dart");
assertLocation(true, unit, 418, true);
}
public void test_DartElementLocator_searchWithin_declaration_without() throws Exception {
CompilationUnit unit = getMoneyCompilationUnit("simple_money.dart");
assertLocation(false, unit, 418, false);
}
public void test_DartElementLocator_searchWithin_reference() throws Exception {
CompilationUnit unit = getMoneyCompilationUnit("simple_money.dart");
assertLocation(true, unit, 394, false);
}
private void assertLocation(boolean expectElement,
CompilationUnit unit,
int offset,
boolean includeDeclarations) throws DartModelException {
DartUnit ast = DartCompilerUtilities.resolveUnit(unit, new ArrayList<DartCompilationError>());
DartElementLocator locator = new DartElementLocator(unit, offset, includeDeclarations);
DartElement result = locator.searchWithin(ast);
if (expectElement) {
assertNotNull(result);
} else {
assertNull(result);
}
}
}
| false | true | public void test_VariableElement_parameter_inClassMethod() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"print(x) {}",
"class A {",
" foo(a, bb, ccc) {",
" print(bb);",
" }",
"}"}, "bb);", "bb, ", 2);
}
public void test_VariableElement_parameter_inTopMethod() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"print(x) {}",
"foo(a, bb, ccc) {",
" print(bb);",
"}"}, "bb);", "bb, ", 2);
}
public void test_VariableElement_localVariable() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"print(x) {}",
"foo() {",
" var aaa = 1;",
" print(aaa);",
"}"}, "aaa);", "aaa = 1", 3);
}
public void test_FieldElement_topLevel() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"print(x) {}",
"var aaa = 1;",
"foo() {",
" print(aaa);",
"}"}, "aaa);", "aaa = 1", 3);
}
public void test_FieldElement_classMember() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"print(x) {}",
"class A {",
" var bbb = 1;",
"}",
"foo() {",
" A a = new A();",
" print(a.bbb);",
"}"}, "bbb);", "bbb = 1", 3);
}
public void test_type_typeName() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"class A {}",
"foo() {",
" A a = null;",
"}"}, "A a =", "A {}", 1);
}
public void test_type_newExpression() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"class A {",
" A() {}",
"}",
"foo() {",
" A a = new A();",
"}"}, "A();", "A() {}", 1);
}
public void test_methodInvocation() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"foo() {}",
"bar() {",
" foo();",
"}"}, "foo();", "foo() {}", 3);
}
private void testElementLocator(String[] sourceLines,
String posMarker,
String expectedMarker,
int expectedLen) throws Exception {
TestProject testProject = new TestProject("Test");
try {
CompilationUnit unit =
testProject.setUnitContent("Test.dart", Joiner.on("\n").join(sourceLines));
assertLocation(unit, posMarker, expectedMarker, expectedLen);
} finally {
testProject.dispose();
}
}
private static void assertLocation(CompilationUnit unit,
String posMarker,
String expectedMarker,
int expectedLen) throws Exception {
String source = unit.getSource();
// prepare DartUnit
DartUnit dartUnit;
{
List<DartCompilationError> errors = Lists.newArrayList();
dartUnit = DartCompilerUtilities.resolveUnit(unit, errors);
// we don't want errors
if (!errors.isEmpty()) {
fail("Parse/resolve errors: " + errors);
}
}
// prepare position to search on
int pos = source.indexOf(posMarker);
assertTrue("Unable to find position marker '" + posMarker + "'", pos > 0);
// use Locator
DartElementLocator locator = new DartElementLocator(unit, pos, true);
DartElement result = locator.searchWithin(dartUnit);
// verify
if (expectedMarker != null) {
assertNotNull(result);
int expectedPos = source.indexOf(expectedMarker);
assertTrue("Unable to find expected marker '" + expectedMarker + "'", expectedPos > 0);
assertEquals(expectedPos, locator.getCandidateRegion().getOffset());
assertEquals(expectedLen, locator.getCandidateRegion().getLength());
} else {
assertNull(result);
}
}
public void test_DartElementLocator_searchWithin_declaration_with() throws Exception {
CompilationUnit unit = getMoneyCompilationUnit("simple_money.dart");
assertLocation(true, unit, 418, true);
}
public void test_DartElementLocator_searchWithin_declaration_without() throws Exception {
CompilationUnit unit = getMoneyCompilationUnit("simple_money.dart");
assertLocation(false, unit, 418, false);
}
public void test_DartElementLocator_searchWithin_reference() throws Exception {
CompilationUnit unit = getMoneyCompilationUnit("simple_money.dart");
assertLocation(true, unit, 394, false);
}
private void assertLocation(boolean expectElement,
CompilationUnit unit,
int offset,
boolean includeDeclarations) throws DartModelException {
DartUnit ast = DartCompilerUtilities.resolveUnit(unit, new ArrayList<DartCompilationError>());
DartElementLocator locator = new DartElementLocator(unit, offset, includeDeclarations);
DartElement result = locator.searchWithin(ast);
if (expectElement) {
assertNotNull(result);
} else {
assertNull(result);
}
}
}
| public void test_VariableElement_parameter_inClassMethod() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"process(x) {}",
"class A {",
" foo(a, bb, ccc) {",
" process(bb);",
" }",
"}"}, "bb);", "bb, ", 2);
}
public void test_VariableElement_parameter_inTopMethod() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"process(x) {}",
"foo(a, bb, ccc) {",
" process(bb);",
"}"}, "bb);", "bb, ", 2);
}
public void test_VariableElement_localVariable() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"process(x) {}",
"foo() {",
" var aaa = 1;",
" process(aaa);",
"}"}, "aaa);", "aaa = 1", 3);
}
public void test_FieldElement_topLevel() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"process(x) {}",
"var aaa = 1;",
"foo() {",
" process(aaa);",
"}"}, "aaa);", "aaa = 1", 3);
}
public void test_FieldElement_classMember() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"process(x) {}",
"class A {",
" var bbb = 1;",
"}",
"foo() {",
" A a = new A();",
" process(a.bbb);",
"}"}, "bbb);", "bbb = 1", 3);
}
public void test_type_typeName() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"class A {}",
"foo() {",
" A a = null;",
"}"}, "A a =", "A {}", 1);
}
public void test_type_newExpression() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"class A {",
" A() {}",
"}",
"foo() {",
" A a = new A();",
"}"}, "A();", "A() {}", 1);
}
public void test_methodInvocation() throws Exception {
testElementLocator(new String[]{
"// filler filler filler filler filler filler filler filler filler filler filler",
"foo() {}",
"bar() {",
" foo();",
"}"}, "foo();", "foo() {}", 3);
}
private void testElementLocator(String[] sourceLines,
String posMarker,
String expectedMarker,
int expectedLen) throws Exception {
TestProject testProject = new TestProject("Test");
try {
CompilationUnit unit =
testProject.setUnitContent("Test.dart", Joiner.on("\n").join(sourceLines));
assertLocation(unit, posMarker, expectedMarker, expectedLen);
} finally {
testProject.dispose();
}
}
private static void assertLocation(CompilationUnit unit,
String posMarker,
String expectedMarker,
int expectedLen) throws Exception {
String source = unit.getSource();
// prepare DartUnit
DartUnit dartUnit;
{
List<DartCompilationError> errors = Lists.newArrayList();
dartUnit = DartCompilerUtilities.resolveUnit(unit, errors);
// we don't want errors
if (!errors.isEmpty()) {
fail("Parse/resolve errors: " + errors);
}
}
// prepare position to search on
int pos = source.indexOf(posMarker);
assertTrue("Unable to find position marker '" + posMarker + "'", pos > 0);
// use Locator
DartElementLocator locator = new DartElementLocator(unit, pos, true);
DartElement result = locator.searchWithin(dartUnit);
// verify
if (expectedMarker != null) {
assertNotNull(result);
int expectedPos = source.indexOf(expectedMarker);
assertTrue("Unable to find expected marker '" + expectedMarker + "'", expectedPos > 0);
assertEquals(expectedPos, locator.getCandidateRegion().getOffset());
assertEquals(expectedLen, locator.getCandidateRegion().getLength());
} else {
assertNull(result);
}
}
public void test_DartElementLocator_searchWithin_declaration_with() throws Exception {
CompilationUnit unit = getMoneyCompilationUnit("simple_money.dart");
assertLocation(true, unit, 418, true);
}
public void test_DartElementLocator_searchWithin_declaration_without() throws Exception {
CompilationUnit unit = getMoneyCompilationUnit("simple_money.dart");
assertLocation(false, unit, 418, false);
}
public void test_DartElementLocator_searchWithin_reference() throws Exception {
CompilationUnit unit = getMoneyCompilationUnit("simple_money.dart");
assertLocation(true, unit, 394, false);
}
private void assertLocation(boolean expectElement,
CompilationUnit unit,
int offset,
boolean includeDeclarations) throws DartModelException {
DartUnit ast = DartCompilerUtilities.resolveUnit(unit, new ArrayList<DartCompilationError>());
DartElementLocator locator = new DartElementLocator(unit, offset, includeDeclarations);
DartElement result = locator.searchWithin(ast);
if (expectElement) {
assertNotNull(result);
} else {
assertNull(result);
}
}
}
|
diff --git a/WeCharades/src/com/example/wecharades/presenter/Presenter.java b/WeCharades/src/com/example/wecharades/presenter/Presenter.java
index 56e0361..9e7e4ae 100644
--- a/WeCharades/src/com/example/wecharades/presenter/Presenter.java
+++ b/WeCharades/src/com/example/wecharades/presenter/Presenter.java
@@ -1,83 +1,83 @@
package com.example.wecharades.presenter;
import java.util.Observable;
import java.util.Observer;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;
import com.example.wecharades.model.DCMessage;
import com.example.wecharades.model.DataController;
import com.example.wecharades.views.GenericActivity;
import com.example.wecharades.views.LoginActivity;
public abstract class Presenter implements Observer{
protected DataController dc;
protected GenericActivity activity;
/**
* Needed in order to use parse commands
* @param context - the context (the activity: use 'this' most often)
*/
public Presenter(GenericActivity activity) {
this.activity = activity;
this.dc = DataController.getDataController(activity);
dc.addObserver(this);
}
/**
* A method to show a toast
* @param context
* @param msg
*/
protected void showToast(Context context, String msg) {
Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
toast.show();
}
/**
* Go to the login screen
*/
public void goToLoginActivity() {
Intent i = new Intent(activity.getApplicationContext(), LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(i);
// Close current view, effectively restarting the app
activity.finish();
}
/**
* Called whenever an activity is closed.
*/
public void saveState(){
dc.deleteObserver(this);
dc.saveState(activity);
}
/**
* Called whenever an update is received from a class this presenter subscribes to.
*/
public void update(Observable dataController, Object obj){
if(dataController.getClass().equals(DataController.class)
&& obj != null
&& obj.getClass().equals(DCMessage.class)){
DCMessage dcm = (DCMessage) obj;
if(dcm.getMessage() == DCMessage.ERROR){
- activity.showErrorDialog((String) dcm.getData());
+ //activity.showErrorDialog((String) dcm.getData());
} else if(dcm.getMessage() == DCMessage.MESSAGE){
activity.showToast((String) dcm.getData());
}
}
}
/**
* Check if the user has internet connection
* @return true if the user has internet connection, false otherwise
*/
public boolean isNetworkConnected() {
return ((ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
}
| true | true | public void update(Observable dataController, Object obj){
if(dataController.getClass().equals(DataController.class)
&& obj != null
&& obj.getClass().equals(DCMessage.class)){
DCMessage dcm = (DCMessage) obj;
if(dcm.getMessage() == DCMessage.ERROR){
activity.showErrorDialog((String) dcm.getData());
} else if(dcm.getMessage() == DCMessage.MESSAGE){
activity.showToast((String) dcm.getData());
}
}
}
| public void update(Observable dataController, Object obj){
if(dataController.getClass().equals(DataController.class)
&& obj != null
&& obj.getClass().equals(DCMessage.class)){
DCMessage dcm = (DCMessage) obj;
if(dcm.getMessage() == DCMessage.ERROR){
//activity.showErrorDialog((String) dcm.getData());
} else if(dcm.getMessage() == DCMessage.MESSAGE){
activity.showToast((String) dcm.getData());
}
}
}
|
diff --git a/core/src/java/com/robonobo/core/service/UserService.java b/core/src/java/com/robonobo/core/service/UserService.java
index 311e27d..56efb95 100644
--- a/core/src/java/com/robonobo/core/service/UserService.java
+++ b/core/src/java/com/robonobo/core/service/UserService.java
@@ -1,590 +1,590 @@
package com.robonobo.core.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.robonobo.common.concurrent.CatchingRunnable;
import com.robonobo.common.exceptions.SeekInnerCalmException;
import com.robonobo.common.serialization.SerializationException;
import com.robonobo.common.serialization.SerializationManager;
import com.robonobo.core.api.*;
import com.robonobo.core.api.config.MetadataServerConfig;
import com.robonobo.core.api.model.*;
import com.robonobo.core.api.proto.CoreApi.PlaylistMsg;
import com.robonobo.core.api.proto.CoreApi.UserConfigMsg;
import com.robonobo.core.api.proto.CoreApi.UserMsg;
/**
* Managers users (me and my friends) and associated playlists. We pull everything down via http on startup (and update
* it periodically); nothing is persisted locally
*/
@SuppressWarnings("unchecked")
public class UserService extends AbstractService {
Log log = LogFactory.getLog(getClass());
private User me;
private UserConfig myUserCfg;
MetadataServerConfig msc;
/**
* We keep users and playlists in a hashmap, and look them up on demand. This is because they are being updated
* asynchronously, and so if we kept pointers, they'd go out of date.
*/
private Map<String, User> usersByEmail = Collections.synchronizedMap(new HashMap<String, User>());
private Map<Long, User> usersById = Collections.synchronizedMap(new HashMap<Long, User>());
private Map<Long, Playlist> playlists = Collections.synchronizedMap(new HashMap<Long, Playlist>());
private Map<String, Long> myPlaylistIdsByTitle = Collections.synchronizedMap(new HashMap<String, Long>());
private ScheduledFuture updateScheduler;
private ReentrantLock userUpdateLock = new ReentrantLock();
private ReentrantLock startupLock = new ReentrantLock();
private Condition startupCondition = startupLock.newCondition();
private boolean started = false;
public UserService() {
addHardDependency("core.metadata");
addHardDependency("core.storage");
addHardDependency("core.tasks");
}
@Override
public void startup() throws Exception {
int updateFreq = rbnb.getConfig().getUserUpdateFrequency();
updateScheduler = rbnb.getExecutor().scheduleAtFixedRate(new CatchingRunnable() {
public void doRun() throws Exception {
rbnb.getTaskService().runTask(new UpdateTask());
}
}, updateFreq, updateFreq, TimeUnit.SECONDS);
started = true;
startupLock.lock();
try {
startupCondition.signalAll();
} finally {
startupLock.unlock();
}
}
public String getName() {
return "User service";
}
public String getProvides() {
return "core.users";
}
@Override
public void shutdown() throws Exception {
if (updateScheduler != null)
updateScheduler.cancel(true);
}
public void checkAllUsersUpdate() {
rbnb.getTaskService().runTask(new UpdateTask());
}
public void login(final String email, final String password) throws IOException, SerializationException {
// We get called immediately here, which might be before we've started... wait, if so
if (!started) {
startupLock.lock();
try {
try {
log.debug("Waiting to login until user service is started");
startupCondition.await();
} catch (InterruptedException e) {
return;
}
} finally {
startupLock.unlock();
}
}
MetadataServerConfig msc = new MetadataServerConfig(rbnb.getConfig().getMetadataServerUrl());
log.info("Attempting login as user " + email);
try {
UserMsg.Builder ub = UserMsg.newBuilder();
// If the details are wrong, this will chuck UnauthorizedException
SerializationManager sm = rbnb.getSerializationManager();
sm.setCreds(email, password);
sm.getObjectFromUrl(ub, msc.getUserUrl(email));
User tryUser = new User(ub.build());
tryUser.setPassword(password);
rbnb.getConfig().setMetadataServerUsername(email);
rbnb.getConfig().setMetadataServerPassword(password);
rbnb.saveConfig();
// Reload everything again
usersByEmail.clear();
usersById.clear();
playlists.clear();
myPlaylistIdsByTitle.clear();
usersByEmail.put(email, tryUser);
usersById.put(tryUser.getUserId(), tryUser);
this.msc = msc;
me = tryUser;
log.info("Login as " + email + " successful");
rbnb.getExecutor().execute(new CatchingRunnable() {
public void doRun() throws Exception {
rbnb.getEventService().fireLoggedIn();
synchronized (UserService.this) {
usersByEmail.put(me.getEmail(), me);
usersById.put(me.getUserId(), me);
}
rbnb.getEventService().fireUserChanged(me);
rbnb.getTaskService().runTask(new InitialFetchTask());
}
});
- if (rbnb.getMina() != null & rbnb.getMina().isConnectedToSupernode()) {
+ if (rbnb.getMina() != null && rbnb.getMina().isConnectedToSupernode()) {
rbnb.setStatus(RobonoboStatus.Connected);
rbnb.getEventService().fireStatusChanged();
}
} catch (IOException e) {
log.error("Caught exception logging in", e);
throw e;
} catch (SerializationException e) {
log.error("Caught exception logging in", e);
throw e;
}
}
public void saveUserConfigItem(String itemName, String itemValue) {
if (me == null) {
log.error("Error: tried to save user config, but I am not logged in");
return;
}
UserConfig cfg = new UserConfig();
cfg.setUserId(me.getUserId());
cfg.getItems().put(itemName, itemValue);
try {
rbnb.getSerializationManager().putObjectToUrl(cfg.toMsg(), msc.getUserConfigUrl(me.getUserId()));
} catch (IOException e) {
log.error("Errot saving user config", e);
}
}
public void requestTopUp() throws IOException {
if (me != null) {
try {
rbnb.getSerializationManager().hitUrl(msc.getTopUpUrl());
} catch (IOException e) {
log.error("Error requesting topup", e);
throw e;
}
}
}
public boolean isLoggedIn() {
return me != null;
}
public User getMyUser() {
if (me == null)
return null;
return getUser(me.getEmail());
}
public UserConfig getMyUserConfig() {
return myUserCfg;
}
public UserConfig refreshMyUserConfig() {
UserConfigMsg.Builder b = UserConfigMsg.newBuilder();
try {
rbnb.getSerializationManager().getObjectFromUrl(b, msc.getUserConfigUrl(me.getUserId()));
} catch (Exception e) {
log.error("Caught exception fetching user config", e);
return null;
}
myUserCfg = new UserConfig(b.build());
rbnb.getEventService().fireUserConfigChanged(myUserCfg);
return myUserCfg;
}
public MetadataServerConfig getMsc() {
return msc;
}
public void updateMyUser(User u) throws IOException {
if (u.getEmail() != me.getEmail()) {
throw new SeekInnerCalmException();
}
userUpdateLock.lock();
try {
rbnb.getSerializationManager().putObjectToUrl(u.toMsg(false), msc.getUserUrl(u.getEmail()));
synchronized (this) {
me = u;
usersByEmail.put(u.getEmail(), u);
usersById.put(u.getUserId(), u);
}
} finally {
userUpdateLock.unlock();
}
rbnb.getEventService().fireUserChanged(u);
}
/**
* Returns the playlist with the playlist id set
*/
public Playlist addOrUpdatePlaylist(Playlist newP) throws IOException, RobonoboException {
String playlistUrl = msc.getPlaylistUrl(newP.getPlaylistId());
if (newP.getPlaylistId() <= 0) {
// New playlist - the server will send it back with the playlist id set
PlaylistMsg.Builder bldr = PlaylistMsg.newBuilder();
rbnb.getSerializationManager().putObjectToUrl(newP.toMsg(), playlistUrl, bldr);
Playlist updatedP = new Playlist(bldr.build());
// Grab a new copy of my user, it'll have the new playlist in it
checkUserUpdate(me, false);
// Fire this playlist as being updated
rbnb.getEventService().firePlaylistChanged(updatedP);
return updatedP;
} else {
rbnb.getSerializationManager().putObjectToUrl(newP.toMsg(), playlistUrl);
rbnb.getEventService().firePlaylistChanged(newP);
return newP;
}
}
public void nukePlaylist(Playlist pl) throws IOException, RobonoboException {
rbnb.getSerializationManager().deleteObjectAtUrl(msc.getPlaylistUrl(pl.getPlaylistId()));
myPlaylistIdsByTitle.remove(pl.getTitle());
// Get a new copy of my user without this playlist
checkUserUpdate(me, false);
// If we were sharing this with any of our friends, update it so that we
// are no longer registered as an owner
boolean sharing = false;
synchronized (this) {
for (Long friendId : me.getFriendIds()) {
User friend = getUser(friendId);
if (friend.getPlaylistIds().contains(pl.getPlaylistId())) {
sharing = true;
break;
}
}
}
if (sharing) {
try {
checkPlaylistUpdate(pl.getPlaylistId());
} catch (RobonoboException e) {
log.error("Error checking updated playlist after delete", e);
}
}
}
public void sharePlaylist(Playlist p, Set<Long> friendIds, Set<String> emails) throws IOException,
RobonoboException {
rbnb.getSerializationManager().hitUrl(msc.getSharePlaylistUrl(p.getPlaylistId(), friendIds, emails));
List<User> friends = new ArrayList<User>(friendIds.size());
for (Long friendId : friendIds) {
friends.add(getUser(friendId));
}
checkUserUpdate(friends);
}
public void postFacebookUpdate(long playlistId, String msg) throws IOException {
rbnb.getSerializationManager().hitUrl(msc.getFacebookPlaylistUrl(playlistId, msg));
}
public void postTwitterUpdate(long playlistId, String msg) throws IOException {
rbnb.getSerializationManager().hitUrl(msc.getTwitterPlaylistUrl(playlistId, msg));
}
public synchronized User getUser(String email) {
return usersByEmail.get(email);
}
public synchronized User getUser(long userId) {
return usersById.get(userId);
}
public synchronized Playlist getExistingPlaylist(long playlistId) {
return playlists.get(playlistId);
}
public Playlist getOrFetchPlaylist(long plId) {
Playlist p = getExistingPlaylist(plId);
if (p != null)
return p;
try {
p = getUpdatedPlaylist(plId);
} catch (Exception e) {
log.error("Error fetching playlist with pId " + plId, e);
return null;
}
synchronized (this) {
playlists.put(plId, p);
}
return p;
}
public synchronized Playlist getMyPlaylistByTitle(String title) {
Long plId = myPlaylistIdsByTitle.get(title);
if (plId == null)
return null;
return getExistingPlaylist(plId);
}
private User getUpdatedUser(long userId) throws IOException, SerializationException {
UserMsg.Builder ub = UserMsg.newBuilder();
rbnb.getSerializationManager().getObjectFromUrl(ub, msc.getUserUrl(userId));
return new User(ub.build());
}
private Playlist getUpdatedPlaylist(long playlistId) throws IOException, SerializationException {
String playlistUrl = msc.getPlaylistUrl(playlistId);
PlaylistMsg.Builder pb = PlaylistMsg.newBuilder();
rbnb.getSerializationManager().getObjectFromUrl(pb, playlistUrl);
return new Playlist(pb.build());
}
public void checkPlaylistUpdate(long playlistId) throws IOException, RobonoboException {
Playlist currentP = playlists.get(playlistId);
final Playlist updatedP = getUpdatedPlaylist(playlistId);
PlaylistConfig pc = rbnb.getDbService().getPlaylistConfig(playlistId);
if (currentP == null || currentP.getUpdated() == null || updatedP.getUpdated().after(currentP.getUpdated())) {
// Make sure we have copies of all streams
for (String sid : updatedP.getStreamIds()) {
rbnb.getMetadataService().getStream(sid);
}
playlists.put(playlistId, updatedP);
if (me.getPlaylistIds().contains(updatedP.getPlaylistId())) {
if (currentP != null)
myPlaylistIdsByTitle.remove(currentP.getTitle());
myPlaylistIdsByTitle.put(updatedP.getTitle(), updatedP.getPlaylistId());
}
rbnb.getEventService().firePlaylistChanged(updatedP);
}
if (((pc != null) && "true".equalsIgnoreCase(pc.getItem("autoDownload")))) {
for (String streamId : updatedP.getStreamIds()) {
Track t = rbnb.getTrackService().getTrack(streamId);
if (t instanceof CloudTrack)
rbnb.getDownloadService().addDownload(streamId);
}
}
if (pc != null && "true".equalsIgnoreCase(pc.getItem("iTunesExport"))) {
final List<User> contUsers = new ArrayList<User>();
synchronized (this) {
for (User u : usersById.values()) {
if (u.getPlaylistIds().contains(playlistId))
contUsers.add(u);
}
}
// Update itunes in another thread
getRobonobo().getExecutor().execute(new CatchingRunnable() {
public void doRun() throws Exception {
for (User u : contUsers) {
getRobonobo().getITunesService().syncPlaylist(u, updatedP);
}
}
});
}
}
/**
* Update things that need to be updated on playlists containing this track we're now sharing
*/
public void checkPlaylistsForNewShare(SharedTrack sh) {
// Currently, just sync to itunes if necessary
final Map<User, List<Playlist>> contPls = new HashMap<User, List<Playlist>>();
synchronized (this) {
for (User u : usersById.values()) {
for (Long plId : u.getPlaylistIds()) {
PlaylistConfig pc = getRobonobo().getDbService().getPlaylistConfig(plId);
if ("true".equalsIgnoreCase(pc.getItem("iTunesExport"))) {
if (!contPls.containsKey(u))
contPls.put(u, new ArrayList<Playlist>());
contPls.get(u).add(getExistingPlaylist(plId));
}
}
}
}
// Come out of sync and do this in another thread, it'll take a while
getRobonobo().getExecutor().execute(new CatchingRunnable() {
public void doRun() throws Exception {
for (User u : contPls.keySet()) {
for (Playlist p : contPls.get(u)) {
getRobonobo().getITunesService().syncPlaylist(u, p);
}
}
}
});
}
private void lookupNewUser(long userId) throws RobonoboException, IOException {
User u;
try {
u = getUpdatedUser(userId);
} catch (Exception e) {
throw new RobonoboException(e);
}
if (u == null)
return;
synchronized (this) {
usersByEmail.put(u.getEmail(), u);
usersById.put(u.getUserId(), u);
}
rbnb.getEventService().fireUserChanged(u);
for (Long playlistId : u.getPlaylistIds()) {
// For shared playlists, don't hit the server again if we already have it - but fire the playlist
// changed event so it's added to the friend tree
// for this user
Playlist p = getExistingPlaylist(playlistId);
if (p == null)
checkPlaylistUpdate(playlistId);
else
rbnb.getEventService().firePlaylistChanged(p);
}
for (long friendId : u.getFriendIds()) {
if (!usersById.containsKey(friendId)) {
lookupNewUser(userId);
}
}
}
private void checkUserUpdate(User u, boolean cascade) throws IOException, RobonoboException {
User newU = getUpdatedUser(u.getUserId());
boolean isUpdated = (newU.getUpdated() == null && u.getUpdated() == null)
|| newU.getUpdated().after(u.getUpdated());
if (isUpdated) {
synchronized (this) {
if (newU.equals(me)) {
newU.setPassword(me.getPassword());
me = newU;
}
usersByEmail.put(newU.getEmail(), newU);
usersById.put(newU.getUserId(), newU);
}
rbnb.getEventService().fireUserChanged(newU);
}
if (cascade) {
for (Long playlistId : newU.getPlaylistIds()) {
checkPlaylistUpdate(playlistId);
}
}
if (isUpdated) {
for (long friendId : newU.getFriendIds()) {
if (!usersById.containsKey(friendId))
lookupNewUser(friendId);
}
}
}
/**
* This updates all the users before updating the playlists, so if they share playlists they all catch the changes
*
* @throws RobonoboException
* @throws IOException
*/
private void checkUserUpdate(Collection<User> users) throws IOException, RobonoboException {
Set<Long> playlistsToCheck = new HashSet<Long>();
for (User u : users) {
User newU = getUpdatedUser(u.getUserId());
if ((newU.getUpdated() == null && u.getUpdated() == null) || newU.getUpdated().after(u.getUpdated())) {
for (long friendId : newU.getFriendIds()) {
if (!usersById.containsKey(friendId))
lookupNewUser(friendId);
}
synchronized (UserService.this) {
usersByEmail.put(newU.getEmail(), newU);
usersById.put(newU.getUserId(), newU);
}
rbnb.getEventService().fireUserChanged(newU);
}
for (Long playlistId : newU.getPlaylistIds()) {
playlistsToCheck.add(playlistId);
}
}
for (Long playlistId : playlistsToCheck) {
checkPlaylistUpdate(playlistId);
}
}
class InitialFetchTask extends Task {
public InitialFetchTask() {
title = "Fetching friends and playlists";
}
public void doRun() throws Exception {
log.info("Fetching initial user & playlist info");
Set<Long> playlistIds = me.getPlaylistIds();
Set<Long> friendIds = me.getFriendIds();
// Have to estimate a percentage for completion, so we assume that everyone has as many playlists as we do
int psPerU = playlistIds.size();
if (psPerU == 0)
psPerU = 1;
int totalSteps = ((friendIds.size() + 1) * psPerU) + 1;
int stepsDone = 0;
int playlistsDone = 0;
for (long pId : playlistIds) {
statusText = "Fetching playlist " + (playlistsDone + 1) + " of " + playlistIds.size();
fireUpdated();
checkPlaylistUpdate(pId);
stepsDone++;
playlistsDone++;
completion = (float) stepsDone / totalSteps;
}
int friendsDone = 0;
for (long uId : friendIds) {
statusText = "Fetching friend " + (friendsDone + 1) + " of " + friendIds.size();
fireUpdated();
lookupNewUser(uId);
friendsDone++;
stepsDone += psPerU;
completion = (float) stepsDone / totalSteps;
}
statusText = "Fetching my user config";
fireUpdated();
refreshMyUserConfig();
statusText = "Done.";
completion = 1f;
fireUpdated();
rbnb.getEventService().fireAllUsersAndPlaylistsUpdated();
}
}
class UpdateTask extends Task {
public UpdateTask() {
title = "Updating friends and playlists";
}
public void doRun() throws Exception {
if (me == null) {
return;
}
log.info("Fetching updated info for all users & playlists");
// Copy out users so we can iterate over them safely
User[] uArr = new User[usersByEmail.size()];
usersByEmail.values().toArray(uArr);
for (int i = 0; i < uArr.length; i++) {
if (cancelRequested) {
cancelled = true;
fireUpdated();
return;
}
User u = uArr[i];
completion = (float) i / uArr.length;
statusText = "Fetching user " + u.getEmail();
fireUpdated();
if (me.equals(u)) {
// This is me - check to see if we're currently updating my
// user, and if we are, don't bother to check for updates -
// just leave it until next time
if (userUpdateLock.isLocked())
continue;
}
checkUserUpdate(u, true);
}
statusText = "Done.";
completion = 1f;
fireUpdated();
rbnb.getEventService().fireAllUsersAndPlaylistsUpdated();
}
}
}
| true | true | public void login(final String email, final String password) throws IOException, SerializationException {
// We get called immediately here, which might be before we've started... wait, if so
if (!started) {
startupLock.lock();
try {
try {
log.debug("Waiting to login until user service is started");
startupCondition.await();
} catch (InterruptedException e) {
return;
}
} finally {
startupLock.unlock();
}
}
MetadataServerConfig msc = new MetadataServerConfig(rbnb.getConfig().getMetadataServerUrl());
log.info("Attempting login as user " + email);
try {
UserMsg.Builder ub = UserMsg.newBuilder();
// If the details are wrong, this will chuck UnauthorizedException
SerializationManager sm = rbnb.getSerializationManager();
sm.setCreds(email, password);
sm.getObjectFromUrl(ub, msc.getUserUrl(email));
User tryUser = new User(ub.build());
tryUser.setPassword(password);
rbnb.getConfig().setMetadataServerUsername(email);
rbnb.getConfig().setMetadataServerPassword(password);
rbnb.saveConfig();
// Reload everything again
usersByEmail.clear();
usersById.clear();
playlists.clear();
myPlaylistIdsByTitle.clear();
usersByEmail.put(email, tryUser);
usersById.put(tryUser.getUserId(), tryUser);
this.msc = msc;
me = tryUser;
log.info("Login as " + email + " successful");
rbnb.getExecutor().execute(new CatchingRunnable() {
public void doRun() throws Exception {
rbnb.getEventService().fireLoggedIn();
synchronized (UserService.this) {
usersByEmail.put(me.getEmail(), me);
usersById.put(me.getUserId(), me);
}
rbnb.getEventService().fireUserChanged(me);
rbnb.getTaskService().runTask(new InitialFetchTask());
}
});
if (rbnb.getMina() != null & rbnb.getMina().isConnectedToSupernode()) {
rbnb.setStatus(RobonoboStatus.Connected);
rbnb.getEventService().fireStatusChanged();
}
} catch (IOException e) {
log.error("Caught exception logging in", e);
throw e;
} catch (SerializationException e) {
log.error("Caught exception logging in", e);
throw e;
}
}
| public void login(final String email, final String password) throws IOException, SerializationException {
// We get called immediately here, which might be before we've started... wait, if so
if (!started) {
startupLock.lock();
try {
try {
log.debug("Waiting to login until user service is started");
startupCondition.await();
} catch (InterruptedException e) {
return;
}
} finally {
startupLock.unlock();
}
}
MetadataServerConfig msc = new MetadataServerConfig(rbnb.getConfig().getMetadataServerUrl());
log.info("Attempting login as user " + email);
try {
UserMsg.Builder ub = UserMsg.newBuilder();
// If the details are wrong, this will chuck UnauthorizedException
SerializationManager sm = rbnb.getSerializationManager();
sm.setCreds(email, password);
sm.getObjectFromUrl(ub, msc.getUserUrl(email));
User tryUser = new User(ub.build());
tryUser.setPassword(password);
rbnb.getConfig().setMetadataServerUsername(email);
rbnb.getConfig().setMetadataServerPassword(password);
rbnb.saveConfig();
// Reload everything again
usersByEmail.clear();
usersById.clear();
playlists.clear();
myPlaylistIdsByTitle.clear();
usersByEmail.put(email, tryUser);
usersById.put(tryUser.getUserId(), tryUser);
this.msc = msc;
me = tryUser;
log.info("Login as " + email + " successful");
rbnb.getExecutor().execute(new CatchingRunnable() {
public void doRun() throws Exception {
rbnb.getEventService().fireLoggedIn();
synchronized (UserService.this) {
usersByEmail.put(me.getEmail(), me);
usersById.put(me.getUserId(), me);
}
rbnb.getEventService().fireUserChanged(me);
rbnb.getTaskService().runTask(new InitialFetchTask());
}
});
if (rbnb.getMina() != null && rbnb.getMina().isConnectedToSupernode()) {
rbnb.setStatus(RobonoboStatus.Connected);
rbnb.getEventService().fireStatusChanged();
}
} catch (IOException e) {
log.error("Caught exception logging in", e);
throw e;
} catch (SerializationException e) {
log.error("Caught exception logging in", e);
throw e;
}
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/PatternBoard.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/PatternBoard.java
index b9fac8c91..1b3d382ce 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/PatternBoard.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/PatternBoard.java
@@ -1,189 +1,191 @@
/* This program 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 3 of
the License, or (at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.edgetype;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Route;
import org.onebusaway.gtfs.model.Trip;
import org.opentripplanner.gtfs.GtfsLibrary;
import org.opentripplanner.routing.core.RouteSpec;
import org.opentripplanner.routing.core.ServiceDay;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.StateEditor;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.core.TraverseModeSet;
import org.opentripplanner.routing.core.TraverseOptions;
import org.opentripplanner.routing.core.Vertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vividsolutions.jts.geom.Geometry;
/**
* Models boarding a vehicle - that is to say, traveling from a station off vehicle to a station
* on vehicle. When traversed forward, the the resultant state has the time of the next
* departure, in addition the pattern that was boarded. When traversed backward, the result
* state is unchanged. A boarding penalty can also be applied to discourage transfers.
*/
public class PatternBoard extends PatternEdge implements OnBoardForwardEdge {
private static final long serialVersionUID = 1042740795612978747L;
private static final Logger _log = LoggerFactory.getLogger(PatternBoard.class);
private int stopIndex;
private int modeMask;
public PatternBoard(Vertex startStation, Vertex startJourney, TripPattern pattern, int stopIndex, TraverseMode mode) {
super(startStation, startJourney, pattern);
this.stopIndex = stopIndex;
this.modeMask = new TraverseModeSet(mode).getMask();
}
public String getDirection() {
return null;
}
public double getDistance() {
return 0;
}
public Geometry getGeometry() {
return null;
}
public TraverseMode getMode() {
return TraverseMode.BOARDING;
}
public String getName() {
return "leave street network for transit network";
}
public State traverse(State state0) {
TraverseOptions options = state0.getOptions();
if (options.isArriveBy()) {
/* reverse traversal, not so much to do */
if (!getPattern().canBoard(stopIndex)) {
return null;
}
StateEditor s1 = state0.edit(this);
s1.setTripId(null);
+ s1.setLastAlightedTime(state0.getTime());
+ s1.setPreviousStop(tov);
return s1.makeState();
} else {
/* forward traversal: look for a transit trip on this pattern */
if (!options.getModes().get(modeMask)) {
return null;
}
/* find next boarding time */
/*
* check lists of transit serviceIds running yesterday, today, and tomorrow (relative to initial state)
* if this pattern's serviceId is running look for the next boarding time
* choose the soonest boarding time among trips starting yesterday, today, or tomorrow
*/
long current_time = state0.getTime();
int bestWait = -1;
int bestPatternIndex = -1;
AgencyAndId serviceId = getPattern().getExemplar().getServiceId();
for (ServiceDay sd : options.serviceDays) {
int secondsSinceMidnight = sd.secondsSinceMidnight(current_time);
// only check for service on days that are not in the future
// this avoids unnecessarily examining tomorrow's services
if (secondsSinceMidnight < 0) continue;
if (sd.serviceIdRunning(serviceId)) {
int patternIndex = getPattern().getNextTrip(stopIndex, secondsSinceMidnight, options.wheelchairAccessible,
options.getModes().getBicycle(), true);
if (patternIndex >= 0) {
// a trip was found, index is valid, wait will be non-negative
int wait = (int) ((sd.time(getPattern().getDepartureTime(stopIndex, patternIndex)) - current_time) / 1000);
if (wait < 0) _log.error("negative wait time on board");
if (bestWait < 0 || wait < bestWait) {
// track the soonest departure over all relevant schedules
bestWait = wait;
bestPatternIndex = patternIndex;
}
}
}
}
if (bestWait < 0) {
return null;
}
Trip trip = getPattern().getTrip(bestPatternIndex);
/* check if route banned for this plan */
if (options.bannedRoutes != null) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(), GtfsLibrary.getRouteName(route));
if (options.bannedRoutes.contains(spec)) {
return null;
}
}
/* check if route is preferred for this plan */
long preferences_penalty = 0;
if (options.preferredRoutes != null && options.preferredRoutes.size()>0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(), GtfsLibrary.getRouteName(route));
if (!options.preferredRoutes.contains(spec)) {
preferences_penalty += options.useAnotherThanPreferredRoutesPenalty;
}
}
/* check if route is unpreferred for this plan*/
if (options.unpreferredRoutes != null && options.unpreferredRoutes.size()>0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(), GtfsLibrary.getRouteName(route));
if (options.unpreferredRoutes.contains(spec)) {
preferences_penalty += options.useUnpreferredRoutesPenalty;
}
}
StateEditor s1 = state0.edit(this);
s1.setTrip(bestPatternIndex);
s1.incrementTimeInSeconds(bestWait);
s1.incrementNumBoardings();
s1.setTripId(trip.getId());
s1.setZone(getPattern().getZone(stopIndex));
s1.setRoute(trip.getRoute().getId());
long wait_cost = bestWait;
if (state0.getNumBoardings() == 0) {
wait_cost *= options.waitAtBeginningFactor;
}
else {
wait_cost *= options.waitReluctance;
}
s1.incrementWeight(preferences_penalty);
s1.incrementWeight(wait_cost + options.boardCost);
return s1.makeState();
}
}
public State optimisticTraverse(State state0) {
StateEditor s1 = state0.edit(this);
// no cost (see patternalight)
return s1.makeState();
}
public int getStopIndex() {
return stopIndex;
}
public String toString() {
return "PatternBoard(" + getFromVertex() + ", " + getToVertex() + ")";
}
}
| true | true | public State traverse(State state0) {
TraverseOptions options = state0.getOptions();
if (options.isArriveBy()) {
/* reverse traversal, not so much to do */
if (!getPattern().canBoard(stopIndex)) {
return null;
}
StateEditor s1 = state0.edit(this);
s1.setTripId(null);
return s1.makeState();
} else {
/* forward traversal: look for a transit trip on this pattern */
if (!options.getModes().get(modeMask)) {
return null;
}
/* find next boarding time */
/*
* check lists of transit serviceIds running yesterday, today, and tomorrow (relative to initial state)
* if this pattern's serviceId is running look for the next boarding time
* choose the soonest boarding time among trips starting yesterday, today, or tomorrow
*/
long current_time = state0.getTime();
int bestWait = -1;
int bestPatternIndex = -1;
AgencyAndId serviceId = getPattern().getExemplar().getServiceId();
for (ServiceDay sd : options.serviceDays) {
int secondsSinceMidnight = sd.secondsSinceMidnight(current_time);
// only check for service on days that are not in the future
// this avoids unnecessarily examining tomorrow's services
if (secondsSinceMidnight < 0) continue;
if (sd.serviceIdRunning(serviceId)) {
int patternIndex = getPattern().getNextTrip(stopIndex, secondsSinceMidnight, options.wheelchairAccessible,
options.getModes().getBicycle(), true);
if (patternIndex >= 0) {
// a trip was found, index is valid, wait will be non-negative
int wait = (int) ((sd.time(getPattern().getDepartureTime(stopIndex, patternIndex)) - current_time) / 1000);
if (wait < 0) _log.error("negative wait time on board");
if (bestWait < 0 || wait < bestWait) {
// track the soonest departure over all relevant schedules
bestWait = wait;
bestPatternIndex = patternIndex;
}
}
}
}
if (bestWait < 0) {
return null;
}
Trip trip = getPattern().getTrip(bestPatternIndex);
/* check if route banned for this plan */
if (options.bannedRoutes != null) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(), GtfsLibrary.getRouteName(route));
if (options.bannedRoutes.contains(spec)) {
return null;
}
}
/* check if route is preferred for this plan */
long preferences_penalty = 0;
if (options.preferredRoutes != null && options.preferredRoutes.size()>0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(), GtfsLibrary.getRouteName(route));
if (!options.preferredRoutes.contains(spec)) {
preferences_penalty += options.useAnotherThanPreferredRoutesPenalty;
}
}
/* check if route is unpreferred for this plan*/
if (options.unpreferredRoutes != null && options.unpreferredRoutes.size()>0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(), GtfsLibrary.getRouteName(route));
if (options.unpreferredRoutes.contains(spec)) {
preferences_penalty += options.useUnpreferredRoutesPenalty;
}
}
StateEditor s1 = state0.edit(this);
s1.setTrip(bestPatternIndex);
s1.incrementTimeInSeconds(bestWait);
s1.incrementNumBoardings();
s1.setTripId(trip.getId());
s1.setZone(getPattern().getZone(stopIndex));
s1.setRoute(trip.getRoute().getId());
long wait_cost = bestWait;
if (state0.getNumBoardings() == 0) {
wait_cost *= options.waitAtBeginningFactor;
}
else {
wait_cost *= options.waitReluctance;
}
s1.incrementWeight(preferences_penalty);
s1.incrementWeight(wait_cost + options.boardCost);
return s1.makeState();
}
}
| public State traverse(State state0) {
TraverseOptions options = state0.getOptions();
if (options.isArriveBy()) {
/* reverse traversal, not so much to do */
if (!getPattern().canBoard(stopIndex)) {
return null;
}
StateEditor s1 = state0.edit(this);
s1.setTripId(null);
s1.setLastAlightedTime(state0.getTime());
s1.setPreviousStop(tov);
return s1.makeState();
} else {
/* forward traversal: look for a transit trip on this pattern */
if (!options.getModes().get(modeMask)) {
return null;
}
/* find next boarding time */
/*
* check lists of transit serviceIds running yesterday, today, and tomorrow (relative to initial state)
* if this pattern's serviceId is running look for the next boarding time
* choose the soonest boarding time among trips starting yesterday, today, or tomorrow
*/
long current_time = state0.getTime();
int bestWait = -1;
int bestPatternIndex = -1;
AgencyAndId serviceId = getPattern().getExemplar().getServiceId();
for (ServiceDay sd : options.serviceDays) {
int secondsSinceMidnight = sd.secondsSinceMidnight(current_time);
// only check for service on days that are not in the future
// this avoids unnecessarily examining tomorrow's services
if (secondsSinceMidnight < 0) continue;
if (sd.serviceIdRunning(serviceId)) {
int patternIndex = getPattern().getNextTrip(stopIndex, secondsSinceMidnight, options.wheelchairAccessible,
options.getModes().getBicycle(), true);
if (patternIndex >= 0) {
// a trip was found, index is valid, wait will be non-negative
int wait = (int) ((sd.time(getPattern().getDepartureTime(stopIndex, patternIndex)) - current_time) / 1000);
if (wait < 0) _log.error("negative wait time on board");
if (bestWait < 0 || wait < bestWait) {
// track the soonest departure over all relevant schedules
bestWait = wait;
bestPatternIndex = patternIndex;
}
}
}
}
if (bestWait < 0) {
return null;
}
Trip trip = getPattern().getTrip(bestPatternIndex);
/* check if route banned for this plan */
if (options.bannedRoutes != null) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(), GtfsLibrary.getRouteName(route));
if (options.bannedRoutes.contains(spec)) {
return null;
}
}
/* check if route is preferred for this plan */
long preferences_penalty = 0;
if (options.preferredRoutes != null && options.preferredRoutes.size()>0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(), GtfsLibrary.getRouteName(route));
if (!options.preferredRoutes.contains(spec)) {
preferences_penalty += options.useAnotherThanPreferredRoutesPenalty;
}
}
/* check if route is unpreferred for this plan*/
if (options.unpreferredRoutes != null && options.unpreferredRoutes.size()>0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(), GtfsLibrary.getRouteName(route));
if (options.unpreferredRoutes.contains(spec)) {
preferences_penalty += options.useUnpreferredRoutesPenalty;
}
}
StateEditor s1 = state0.edit(this);
s1.setTrip(bestPatternIndex);
s1.incrementTimeInSeconds(bestWait);
s1.incrementNumBoardings();
s1.setTripId(trip.getId());
s1.setZone(getPattern().getZone(stopIndex));
s1.setRoute(trip.getRoute().getId());
long wait_cost = bestWait;
if (state0.getNumBoardings() == 0) {
wait_cost *= options.waitAtBeginningFactor;
}
else {
wait_cost *= options.waitReluctance;
}
s1.incrementWeight(preferences_penalty);
s1.incrementWeight(wait_cost + options.boardCost);
return s1.makeState();
}
}
|
diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java
index e4dec127..77207781 100644
--- a/media/java/android/media/AudioService.java
+++ b/media/java/android/media/AudioService.java
@@ -1,5471 +1,5474 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.media;
import static android.Manifest.permission.REMOTE_AUDIO_PLAYBACK;
import static android.media.AudioManager.RINGER_MODE_NORMAL;
import static android.media.AudioManager.RINGER_MODE_SILENT;
import static android.media.AudioManager.RINGER_MODE_VIBRATE;
import android.app.Activity;
import android.app.ActivityManagerNative;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.PendingIntent.OnFinished;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.os.Vibrator;
import android.provider.Settings;
import android.provider.Settings.System;
import android.speech.RecognizerIntent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.VolumePanel;
import android.provider.Settings.SettingNotFoundException;
import android.content.res.Resources;
import com.android.internal.app.ThemeUtils;
import com.android.internal.telephony.ITelephony;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Stack;
/**
* The implementation of the volume manager service.
* <p>
* This implementation focuses on delivering a responsive UI. Most methods are
* asynchronous to external calls. For example, the task of setting a volume
* will update our internal state, but in a separate thread will set the system
* volume and later persist to the database. Similarly, setting the ringer mode
* will update the state and broadcast a change and in a separate thread later
* persist the ringer mode.
*
* @hide
*/
public class AudioService extends IAudioService.Stub implements OnFinished {
private static final String TAG = "AudioService";
/** Debug remote control client/display feature */
protected static final boolean DEBUG_RC = false;
/** Debug volumes */
protected static final boolean DEBUG_VOL = false;
/** How long to delay before persisting a change in volume/ringer mode. */
private static final int PERSIST_DELAY = 500;
private Context mContext;
private ContentResolver mContentResolver;
private boolean mVoiceCapable;
/** The UI */
private VolumePanel mVolumePanel;
private Context mUiContext;
private Handler mHandler;
// sendMsg() flags
/** If the msg is already queued, replace it with this one. */
private static final int SENDMSG_REPLACE = 0;
/** If the msg is already queued, ignore this one and leave the old. */
private static final int SENDMSG_NOOP = 1;
/** If the msg is already queued, queue this one and leave the old. */
private static final int SENDMSG_QUEUE = 2;
// AudioHandler messages
private static final int MSG_SET_DEVICE_VOLUME = 0;
private static final int MSG_PERSIST_VOLUME = 1;
private static final int MSG_PERSIST_MASTER_VOLUME = 2;
private static final int MSG_PERSIST_RINGER_MODE = 3;
private static final int MSG_MEDIA_SERVER_DIED = 4;
private static final int MSG_MEDIA_SERVER_STARTED = 5;
private static final int MSG_PLAY_SOUND_EFFECT = 6;
private static final int MSG_BTA2DP_DOCK_TIMEOUT = 7;
private static final int MSG_LOAD_SOUND_EFFECTS = 8;
private static final int MSG_SET_FORCE_USE = 9;
private static final int MSG_PERSIST_MEDIABUTTONRECEIVER = 10;
private static final int MSG_BT_HEADSET_CNCT_FAILED = 11;
private static final int MSG_RCDISPLAY_CLEAR = 12;
private static final int MSG_RCDISPLAY_UPDATE = 13;
private static final int MSG_SET_ALL_VOLUMES = 14;
private static final int MSG_PERSIST_MASTER_VOLUME_MUTE = 15;
private static final int MSG_REPORT_NEW_ROUTES = 16;
private static final int MSG_REEVALUATE_REMOTE = 17;
private static final int MSG_RCC_NEW_PLAYBACK_INFO = 18;
private static final int MSG_RCC_NEW_VOLUME_OBS = 19;
// start of messages handled under wakelock
// these messages can only be queued, i.e. sent with queueMsgUnderWakeLock(),
// and not with sendMsg(..., ..., SENDMSG_QUEUE, ...)
private static final int MSG_SET_WIRED_DEVICE_CONNECTION_STATE = 20;
private static final int MSG_SET_A2DP_CONNECTION_STATE = 21;
// end of messages handled under wakelock
// flags for MSG_PERSIST_VOLUME indicating if current and/or last audible volume should be
// persisted
private static final int PERSIST_CURRENT = 0x1;
private static final int PERSIST_LAST_AUDIBLE = 0x2;
private static final int BTA2DP_DOCK_TIMEOUT_MILLIS = 8000;
// Timeout for connection to bluetooth headset service
private static final int BT_HEADSET_CNCT_TIMEOUT_MS = 3000;
/** @see AudioSystemThread */
private AudioSystemThread mAudioSystemThread;
/** @see AudioHandler */
private AudioHandler mAudioHandler;
/** @see VolumeStreamState */
private VolumeStreamState[] mStreamStates;
private SettingsObserver mSettingsObserver;
//nodelay in a2dp
private boolean noDelayInATwoDP = Resources.getSystem().getBoolean(com.android.internal.R.bool.config_noDelayInATwoDP);
private int mMode;
// protects mRingerMode
private final Object mSettingsLock = new Object();
private boolean mMediaServerOk;
private SoundPool mSoundPool;
private final Object mSoundEffectsLock = new Object();
private static final int NUM_SOUNDPOOL_CHANNELS = 4;
// Internally master volume is a float in the 0.0 - 1.0 range,
// but to support integer based AudioManager API we translate it to 0 - 100
private static final int MAX_MASTER_VOLUME = 100;
// Maximum volume adjust steps allowed in a single batch call.
private static final int MAX_BATCH_VOLUME_ADJUST_STEPS = 4;
/* Sound effect file names */
private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/";
private static final String[] SOUND_EFFECT_FILES = new String[] {
"Effect_Tick.ogg",
"KeypressStandard.ogg",
"KeypressSpacebar.ogg",
"KeypressDelete.ogg",
"KeypressReturn.ogg"
};
/* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to
* file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect
* uses soundpool (second column) */
private final int[][] SOUND_EFFECT_FILES_MAP = new int[][] {
{0, -1}, // FX_KEY_CLICK
{0, -1}, // FX_FOCUS_NAVIGATION_UP
{0, -1}, // FX_FOCUS_NAVIGATION_DOWN
{0, -1}, // FX_FOCUS_NAVIGATION_LEFT
{0, -1}, // FX_FOCUS_NAVIGATION_RIGHT
{1, -1}, // FX_KEYPRESS_STANDARD
{2, -1}, // FX_KEYPRESS_SPACEBAR
{3, -1}, // FX_FOCUS_DELETE
{4, -1} // FX_FOCUS_RETURN
};
/** @hide Maximum volume index values for audio streams */
private final int[] MAX_STREAM_VOLUME = new int[] {
5, // STREAM_VOICE_CALL
7, // STREAM_SYSTEM
7, // STREAM_RING
15, // STREAM_MUSIC
7, // STREAM_ALARM
7, // STREAM_NOTIFICATION
15, // STREAM_BLUETOOTH_SCO
7, // STREAM_SYSTEM_ENFORCED
15, // STREAM_DTMF
15 // STREAM_TTS
};
/* mStreamVolumeAlias[] indicates for each stream if it uses the volume settings
* of another stream: This avoids multiplying the volume settings for hidden
* stream types that follow other stream behavior for volume settings
* NOTE: do not create loops in aliases!
* Some streams alias to different streams according to device category (phone or tablet) or
* use case (in call s off call...).See updateStreamVolumeAlias() for more details
* mStreamVolumeAlias contains the default aliases for a voice capable device (phone) and
* STREAM_VOLUME_ALIAS_NON_VOICE for a non voice capable device (tablet).*/
private final int[] STREAM_VOLUME_ALIAS = new int[] {
AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL
AudioSystem.STREAM_RING, // STREAM_SYSTEM
AudioSystem.STREAM_RING, // STREAM_RING
AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
AudioSystem.STREAM_ALARM, // STREAM_ALARM
AudioSystem.STREAM_RING, // STREAM_NOTIFICATION
AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO
AudioSystem.STREAM_RING, // STREAM_SYSTEM_ENFORCED
AudioSystem.STREAM_RING, // STREAM_DTMF
AudioSystem.STREAM_MUSIC // STREAM_TTS
};
private final int[] STREAM_VOLUME_ALIAS_NON_VOICE = new int[] {
AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL
AudioSystem.STREAM_MUSIC, // STREAM_SYSTEM
AudioSystem.STREAM_RING, // STREAM_RING
AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
AudioSystem.STREAM_ALARM, // STREAM_ALARM
AudioSystem.STREAM_RING, // STREAM_NOTIFICATION
AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO
AudioSystem.STREAM_MUSIC, // STREAM_SYSTEM_ENFORCED
AudioSystem.STREAM_MUSIC, // STREAM_DTMF
AudioSystem.STREAM_MUSIC // STREAM_TTS
};
private int[] mStreamVolumeAlias;
// stream names used by dumpStreamStates()
private final String[] STREAM_NAMES = new String[] {
"STREAM_VOICE_CALL",
"STREAM_SYSTEM",
"STREAM_RING",
"STREAM_MUSIC",
"STREAM_ALARM",
"STREAM_NOTIFICATION",
"STREAM_BLUETOOTH_SCO",
"STREAM_SYSTEM_ENFORCED",
"STREAM_DTMF",
"STREAM_TTS"
};
private boolean mLinkNotificationWithVolume;
// Cap used for safe headset volume restore. The value directly applies
// to AudioSystem.STREAM_MUSIC volume and is rescaled for other streams.
private static final int HEADSET_VOLUME_RESTORE_CAP = 10;
private final AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() {
public void onError(int error) {
switch (error) {
case AudioSystem.AUDIO_STATUS_SERVER_DIED:
if (mMediaServerOk) {
sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SENDMSG_NOOP, 0, 0,
null, 1500);
mMediaServerOk = false;
}
break;
case AudioSystem.AUDIO_STATUS_OK:
if (!mMediaServerOk) {
sendMsg(mAudioHandler, MSG_MEDIA_SERVER_STARTED, SENDMSG_NOOP, 0, 0,
null, 0);
mMediaServerOk = true;
}
break;
default:
break;
}
}
};
/**
* Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL},
* {@link AudioManager#RINGER_MODE_SILENT}, or
* {@link AudioManager#RINGER_MODE_VIBRATE}.
*/
// protected by mSettingsLock
private int mRingerMode;
/** @see System#MODE_RINGER_STREAMS_AFFECTED */
private int mRingerModeAffectedStreams;
// Streams currently muted by ringer mode
private int mRingerModeMutedStreams;
/** @see System#MUTE_STREAMS_AFFECTED */
private int mMuteAffectedStreams;
/**
* NOTE: setVibrateSetting(), getVibrateSetting(), shouldVibrate() are deprecated.
* mVibrateSetting is just maintained during deprecation period but vibration policy is
* now only controlled by mHasVibrator and mRingerMode
*/
private int mVibrateSetting;
// Is there a vibrator
private final boolean mHasVibrator;
// Broadcast receiver for device connections intent broadcasts
private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver();
// Used to alter media button redirection when the phone is ringing.
private boolean mIsRinging = false;
// Devices currently connected
private final HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>();
// Forced device usage for communications
private int mForcedUseForComm;
// True if we have master volume support
private final boolean mUseMasterVolume;
private final int[] mMasterVolumeRamp;
// List of binder death handlers for setMode() client processes.
// The last process to have called setMode() is at the top of the list.
private final ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>();
// List of clients having issued a SCO start request
private final ArrayList <ScoClient> mScoClients = new ArrayList <ScoClient>();
// BluetoothHeadset API to control SCO connection
private BluetoothHeadset mBluetoothHeadset;
// Bluetooth headset device
private BluetoothDevice mBluetoothHeadsetDevice;
// Indicate if SCO audio connection is currently active and if the initiator is
// audio service (internal) or bluetooth headset (external)
private int mScoAudioState;
// SCO audio state is not active
private static final int SCO_STATE_INACTIVE = 0;
// SCO audio activation request waiting for headset service to connect
private static final int SCO_STATE_ACTIVATE_REQ = 1;
// SCO audio state is active or starting due to a local request to start a virtual call
private static final int SCO_STATE_ACTIVE_INTERNAL = 3;
// SCO audio deactivation request waiting for headset service to connect
private static final int SCO_STATE_DEACTIVATE_REQ = 5;
// SCO audio state is active due to an action in BT handsfree (either voice recognition or
// in call audio)
private static final int SCO_STATE_ACTIVE_EXTERNAL = 2;
// Deactivation request for all SCO connections (initiated by audio mode change)
// waiting for headset service to connect
private static final int SCO_STATE_DEACTIVATE_EXT_REQ = 4;
// Current connection state indicated by bluetooth headset
private int mScoConnectionState;
// true if boot sequence has been completed
private boolean mBootCompleted;
// listener for SoundPool sample load completion indication
private SoundPoolCallback mSoundPoolCallBack;
// thread for SoundPool listener
private SoundPoolListenerThread mSoundPoolListenerThread;
// message looper for SoundPool listener
private Looper mSoundPoolLooper = null;
// volume applied to sound played with playSoundEffect()
private static int SOUND_EFFECT_VOLUME_DB;
// getActiveStreamType() will return STREAM_NOTIFICATION during this period after a notification
// stopped
private static final int NOTIFICATION_VOLUME_DELAY_MS = 5000;
// previous volume adjustment direction received by checkForRingerModeChange()
private int mPrevVolDirection = AudioManager.ADJUST_SAME;
// Keyguard manager proxy
private KeyguardManager mKeyguardManager;
// mVolumeControlStream is set by VolumePanel to temporarily force the stream type which volume
// is controlled by Vol keys.
private int mVolumeControlStream = -1;
private final Object mForceControlStreamLock = new Object();
// VolumePanel is currently the only client of forceVolumeControlStream() and runs in system
// server process so in theory it is not necessary to monitor the client death.
// However it is good to be ready for future evolutions.
private ForceControlStreamClient mForceControlStreamClient = null;
// Used to play ringtones outside system_server
private volatile IRingtonePlayer mRingtonePlayer;
private int mDeviceOrientation = Configuration.ORIENTATION_UNDEFINED;
// Request to override default use of A2DP for media
private boolean mBluetoothA2dpEnabled;
private final Object mBluetoothA2dpEnabledLock = new Object();
// Monitoring of audio routes. Protected by mCurAudioRoutes.
final AudioRoutesInfo mCurAudioRoutes = new AudioRoutesInfo();
final RemoteCallbackList<IAudioRoutesObserver> mRoutesObservers
= new RemoteCallbackList<IAudioRoutesObserver>();
/**
* A fake stream type to match the notion of remote media playback
*/
public final static int STREAM_REMOTE_MUSIC = -200;
///////////////////////////////////////////////////////////////////////////
// Construction
///////////////////////////////////////////////////////////////////////////
/** @hide */
public AudioService(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
mHandler = new Handler();
mVoiceCapable = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_voice_capable);
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
mMediaEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleMediaEvent");
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
mHasVibrator = vibrator == null ? false : vibrator.hasVibrator();
// Intialized volume
MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = SystemProperties.getInt(
"ro.config.vc_call_vol_steps",
MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]);
SOUND_EFFECT_VOLUME_DB = context.getResources().getInteger(
com.android.internal.R.integer.config_soundEffectVolumeDb);
mMode = AudioSystem.MODE_NORMAL;
mForcedUseForComm = AudioSystem.FORCE_NONE;
createAudioSystemThread();
readPersistedSettings();
mSettingsObserver = new SettingsObserver();
updateStreamVolumeAlias(false /*updateVolumes*/);
createStreamStates();
mMediaServerOk = true;
// Call setRingerModeInt() to apply correct mute
// state on streams affected by ringer mode.
mRingerModeMutedStreams = 0;
setRingerModeInt(getRingerMode(), false);
AudioSystem.setErrorCallback(mAudioSystemCallback);
// Register for device connection intent broadcasts.
IntentFilter intentFilter =
new IntentFilter(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
if (noDelayInATwoDP)
intentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
intentFilter.addAction(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG);
intentFilter.addAction(Intent.ACTION_USB_AUDIO_DEVICE_PLUG);
intentFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
// Register a configuration change listener only if requested by system properties
// to monitor orientation changes (off by default)
if (SystemProperties.getBoolean("ro.audio.monitorOrientation", false)) {
Log.v(TAG, "monitoring device orientation");
intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
// initialize orientation in AudioSystem
setOrientationForAudioSystem();
}
context.registerReceiver(mReceiver, intentFilter);
// Register for package removal intent broadcasts for media button receiver persistence
IntentFilter pkgFilter = new IntentFilter();
pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
pkgFilter.addDataScheme("package");
context.registerReceiver(mReceiver, pkgFilter);
ThemeUtils.registerThemeChangeReceiver(context, new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mUiContext = null;
}
});
// Register for phone state monitoring
TelephonyManager tmgr = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
tmgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
mUseMasterVolume = context.getResources().getBoolean(
com.android.internal.R.bool.config_useMasterVolume);
restoreMasterVolume();
mMasterVolumeRamp = context.getResources().getIntArray(
com.android.internal.R.array.config_masterVolumeRamp);
mMainRemote = new RemotePlaybackState(-1, MAX_STREAM_VOLUME[AudioManager.STREAM_MUSIC],
MAX_STREAM_VOLUME[AudioManager.STREAM_MUSIC]);
mHasRemotePlayback = false;
mMainRemoteIsActive = false;
postReevaluateRemote();
}
private void createAudioSystemThread() {
mAudioSystemThread = new AudioSystemThread();
mAudioSystemThread.start();
waitForAudioHandlerCreation();
}
/** Waits for the volume handler to be created by the other thread. */
private void waitForAudioHandlerCreation() {
synchronized(this) {
while (mAudioHandler == null) {
try {
// Wait for mAudioHandler to be set by the other thread
wait();
} catch (InterruptedException e) {
Log.e(TAG, "Interrupted while waiting on volume handler.");
}
}
}
}
private void checkAllAliasStreamVolumes() {
int numStreamTypes = AudioSystem.getNumStreamTypes();
for (int streamType = 0; streamType < numStreamTypes; streamType++) {
if (streamType != mStreamVolumeAlias[streamType]) {
mStreamStates[streamType].
setAllIndexes(mStreamStates[mStreamVolumeAlias[streamType]],
false /*lastAudible*/);
mStreamStates[streamType].
setAllIndexes(mStreamStates[mStreamVolumeAlias[streamType]],
true /*lastAudible*/);
}
// apply stream volume
if (mStreamStates[streamType].muteCount() == 0) {
mStreamStates[streamType].applyAllVolumes();
}
}
}
private void createStreamStates() {
int numStreamTypes = AudioSystem.getNumStreamTypes();
VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes];
for (int i = 0; i < numStreamTypes; i++) {
streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[mStreamVolumeAlias[i]], i);
}
checkAllAliasStreamVolumes();
}
private void dumpStreamStates(PrintWriter pw) {
pw.println("\nStream volumes (device: index)");
int numStreamTypes = AudioSystem.getNumStreamTypes();
for (int i = 0; i < numStreamTypes; i++) {
pw.println("- "+STREAM_NAMES[i]+":");
mStreamStates[i].dump(pw);
pw.println("");
}
}
private void updateStreamVolumeAlias(boolean updateVolumes) {
int dtmfStreamAlias;
if (mVoiceCapable) {
mStreamVolumeAlias = STREAM_VOLUME_ALIAS;
dtmfStreamAlias = AudioSystem.STREAM_RING;
} else {
mStreamVolumeAlias = STREAM_VOLUME_ALIAS_NON_VOICE;
dtmfStreamAlias = AudioSystem.STREAM_MUSIC;
}
if (isInCommunication()) {
dtmfStreamAlias = AudioSystem.STREAM_VOICE_CALL;
}
mStreamVolumeAlias[AudioSystem.STREAM_DTMF] = dtmfStreamAlias;
if (updateVolumes) {
mStreamStates[AudioSystem.STREAM_DTMF].setAllIndexes(mStreamStates[dtmfStreamAlias],
false /*lastAudible*/);
mStreamStates[AudioSystem.STREAM_DTMF].setAllIndexes(mStreamStates[dtmfStreamAlias],
true /*lastAudible*/);
sendMsg(mAudioHandler,
MSG_SET_ALL_VOLUMES,
SENDMSG_QUEUE,
0,
0,
mStreamStates[AudioSystem.STREAM_DTMF], 0);
}
}
private void readPersistedSettings() {
final ContentResolver cr = mContentResolver;
int ringerModeFromSettings =
System.getInt(cr, System.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL);
int ringerMode = ringerModeFromSettings;
// sanity check in case the settings are restored from a device with incompatible
// ringer modes
if (!AudioManager.isValidRingerMode(ringerMode)) {
ringerMode = AudioManager.RINGER_MODE_NORMAL;
}
if ((ringerMode == AudioManager.RINGER_MODE_VIBRATE) && !mHasVibrator) {
ringerMode = AudioManager.RINGER_MODE_SILENT;
}
if (ringerMode != ringerModeFromSettings) {
System.putInt(cr, System.MODE_RINGER, ringerMode);
}
synchronized(mSettingsLock) {
mRingerMode = ringerMode;
}
// System.VIBRATE_ON is not used any more but defaults for mVibrateSetting
// are still needed while setVibrateSetting() and getVibrateSetting() are being deprecated.
mVibrateSetting = getValueForVibrateSetting(0,
AudioManager.VIBRATE_TYPE_NOTIFICATION,
mHasVibrator ? AudioManager.VIBRATE_SETTING_ONLY_SILENT
: AudioManager.VIBRATE_SETTING_OFF);
mVibrateSetting = getValueForVibrateSetting(mVibrateSetting,
AudioManager.VIBRATE_TYPE_RINGER,
mHasVibrator ? AudioManager.VIBRATE_SETTING_ONLY_SILENT
: AudioManager.VIBRATE_SETTING_OFF);
// make sure settings for ringer mode are consistent with device type: non voice capable
// devices (tablets) include media stream in silent mode whereas phones don't.
mRingerModeAffectedStreams = Settings.System.getInt(cr,
Settings.System.MODE_RINGER_STREAMS_AFFECTED,
((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
(1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)));
if (mVoiceCapable) {
mRingerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC);
} else {
mRingerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC);
}
boolean linkNotificationWithVolume = Settings.System.getInt(mContentResolver,
Settings.System.VOLUME_LINK_NOTIFICATION, 1) == 1;
if (linkNotificationWithVolume) {
STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
STREAM_VOLUME_ALIAS_NON_VOICE[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
} else {
STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION;
STREAM_VOLUME_ALIAS_NON_VOICE[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION;
}
updateStreamVolumeAlias(false);
Settings.System.putInt(cr,
Settings.System.MODE_RINGER_STREAMS_AFFECTED, mRingerModeAffectedStreams);
mMuteAffectedStreams = System.getInt(cr,
System.MUTE_STREAMS_AFFECTED,
((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM)));
boolean masterMute = System.getInt(cr, System.VOLUME_MASTER_MUTE, 0) == 1;
AudioSystem.setMasterMute(masterMute);
broadcastMasterMuteStatus(masterMute);
// Each stream will read its own persisted settings
// Broadcast the sticky intent
broadcastRingerMode(ringerMode);
// Broadcast vibrate settings
broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION);
// Restore the default media button receiver from the system settings
restoreMediaButtonReceiver();
}
private int rescaleIndex(int index, int srcStream, int dstStream) {
return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex();
}
///////////////////////////////////////////////////////////////////////////
// IPC methods
///////////////////////////////////////////////////////////////////////////
/** @see AudioManager#adjustVolume(int, int) */
public void adjustVolume(int direction, int flags) {
adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags);
}
/** @see AudioManager#adjustLocalOrRemoteStreamVolume(int, int) with current assumption
* on streamType: fixed to STREAM_MUSIC */
public void adjustLocalOrRemoteStreamVolume(int streamType, int direction) {
if (DEBUG_VOL) Log.d(TAG, "adjustLocalOrRemoteStreamVolume(dir="+direction+")");
if (checkUpdateRemoteStateIfActive(AudioSystem.STREAM_MUSIC)) {
adjustRemoteVolume(AudioSystem.STREAM_MUSIC, direction, 0);
} else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)) {
adjustStreamVolume(AudioSystem.STREAM_MUSIC, direction, 0);
}
}
/** @see AudioManager#adjustVolume(int, int, int) */
public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
if (DEBUG_VOL) Log.d(TAG, "adjustSuggestedStreamVolume() stream="+suggestedStreamType);
int streamType;
if (mVolumeControlStream != -1) {
streamType = mVolumeControlStream;
} else {
streamType = getActiveStreamType(suggestedStreamType);
}
// Play sounds on STREAM_RING only and if lock screen is not on.
if ((streamType != STREAM_REMOTE_MUSIC) &&
(flags & AudioManager.FLAG_PLAY_SOUND) != 0 &&
((mStreamVolumeAlias[streamType] != AudioSystem.STREAM_RING)
|| (mKeyguardManager != null && mKeyguardManager.isKeyguardLocked()))) {
flags &= ~AudioManager.FLAG_PLAY_SOUND;
}
if (streamType == STREAM_REMOTE_MUSIC) {
// don't play sounds for remote
flags &= ~AudioManager.FLAG_PLAY_SOUND;
//if (DEBUG_VOL) Log.i(TAG, "Need to adjust remote volume: calling adjustRemoteVolume()");
adjustRemoteVolume(AudioSystem.STREAM_MUSIC, direction, flags);
} else {
adjustStreamVolume(streamType, direction, flags);
}
}
/** @see AudioManager#adjustStreamVolume(int, int, int) */
public void adjustStreamVolume(int streamType, int direction, int flags) {
if (DEBUG_VOL) Log.d(TAG, "adjustStreamVolume() stream="+streamType+", dir="+direction);
ensureValidDirection(direction);
ensureValidStreamType(streamType);
// use stream type alias here so that streams with same alias have the same behavior,
// including with regard to silent mode control (e.g the use of STREAM_RING below and in
// checkForRingerModeChange() in place of STREAM_RING or STREAM_NOTIFICATION)
int streamTypeAlias = mStreamVolumeAlias[streamType];
VolumeStreamState streamState = mStreamStates[streamTypeAlias];
final int device = getDeviceForStream(streamTypeAlias);
// get last audible index if stream is muted, current index otherwise
final int aliasIndex = streamState.getIndex(device,
(streamState.muteCount() != 0) /* lastAudible */);
boolean adjustVolume = true;
// convert one UI step (+/-1) into a number of internal units on the stream alias
int step = rescaleIndex(10, streamType, streamTypeAlias);
// If either the client forces allowing ringer modes for this adjustment,
// or the stream type is one that is affected by ringer modes
if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) ||
(streamTypeAlias == getMasterStreamType())) {
int ringerMode = getRingerMode();
// do not vibrate if already in vibrate mode
if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
flags &= ~AudioManager.FLAG_VIBRATE;
}
// Check if the ringer mode changes with this volume adjustment. If
// it does, it will handle adjusting the volume, so we won't below
adjustVolume = checkForRingerModeChange(aliasIndex, direction, step);
if ((streamTypeAlias == getMasterStreamType()) &&
(mRingerMode == AudioManager.RINGER_MODE_SILENT)) {
streamState.setLastAudibleIndex(0, device);
}
}
// If stream is muted, adjust last audible index only
int index;
final int oldIndex = mStreamStates[streamType].getIndex(device,
(mStreamStates[streamType].muteCount() != 0) /* lastAudible */);
if (streamState.muteCount() != 0) {
if (adjustVolume) {
// Post a persist volume msg
// no need to persist volume on all streams sharing the same alias
streamState.adjustLastAudibleIndex(direction * step, device);
sendMsg(mAudioHandler,
MSG_PERSIST_VOLUME,
SENDMSG_QUEUE,
PERSIST_LAST_AUDIBLE,
device,
streamState,
PERSIST_DELAY);
}
index = mStreamStates[streamType].getIndex(device, true /* lastAudible */);
} else {
if (adjustVolume && streamState.adjustIndex(direction * step, device)) {
// Post message to set system volume (it in turn will post a message
// to persist). Do not change volume if stream is muted.
sendMsg(mAudioHandler,
MSG_SET_DEVICE_VOLUME,
SENDMSG_QUEUE,
device,
0,
streamState,
0);
}
index = mStreamStates[streamType].getIndex(device, false /* lastAudible */);
}
sendVolumeUpdate(streamType, oldIndex, index, flags);
}
/** @see AudioManager#adjustMasterVolume(int) */
public void adjustMasterVolume(int steps, int flags) {
ensureValidSteps(steps);
int volume = Math.round(AudioSystem.getMasterVolume() * MAX_MASTER_VOLUME);
int delta = 0;
int numSteps = Math.abs(steps);
int direction = steps > 0 ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER;
for (int i = 0; i < numSteps; ++i) {
delta = findVolumeDelta(direction, volume);
volume += delta;
}
//Log.d(TAG, "adjustMasterVolume volume: " + volume + " steps: " + steps);
setMasterVolume(volume, flags);
}
/** @see AudioManager#setStreamVolume(int, int, int) */
public void setStreamVolume(int streamType, int index, int flags) {
ensureValidStreamType(streamType);
VolumeStreamState streamState = mStreamStates[mStreamVolumeAlias[streamType]];
final int device = getDeviceForStream(streamType);
// get last audible index if stream is muted, current index otherwise
final int oldIndex = streamState.getIndex(device,
(streamState.muteCount() != 0) /* lastAudible */);
index = rescaleIndex(index * 10, streamType, mStreamVolumeAlias[streamType]);
// setting volume on master stream type also controls silent mode
if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) ||
(mStreamVolumeAlias[streamType] == getMasterStreamType())) {
int newRingerMode;
if (index == 0) {
newRingerMode = mHasVibrator ? AudioManager.RINGER_MODE_VIBRATE
: AudioManager.RINGER_MODE_SILENT;
setStreamVolumeInt(mStreamVolumeAlias[streamType],
index,
device,
false,
true);
} else {
newRingerMode = AudioManager.RINGER_MODE_NORMAL;
}
setRingerMode(newRingerMode);
}
setStreamVolumeInt(mStreamVolumeAlias[streamType], index, device, false, true);
// get last audible index if stream is muted, current index otherwise
index = mStreamStates[streamType].getIndex(device,
(mStreamStates[streamType].muteCount() != 0) /* lastAudible */);
sendVolumeUpdate(streamType, oldIndex, index, flags);
}
/** @see AudioManager#forceVolumeControlStream(int) */
public void forceVolumeControlStream(int streamType, IBinder cb) {
synchronized(mForceControlStreamLock) {
mVolumeControlStream = streamType;
if (mVolumeControlStream == -1) {
if (mForceControlStreamClient != null) {
mForceControlStreamClient.release();
mForceControlStreamClient = null;
}
} else {
mForceControlStreamClient = new ForceControlStreamClient(cb);
}
}
}
private class ForceControlStreamClient implements IBinder.DeathRecipient {
private IBinder mCb; // To be notified of client's death
ForceControlStreamClient(IBinder cb) {
if (cb != null) {
try {
cb.linkToDeath(this, 0);
} catch (RemoteException e) {
// Client has died!
Log.w(TAG, "ForceControlStreamClient() could not link to "+cb+" binder death");
cb = null;
}
}
mCb = cb;
}
public void binderDied() {
synchronized(mForceControlStreamLock) {
Log.w(TAG, "SCO client died");
if (mForceControlStreamClient != this) {
Log.w(TAG, "unregistered control stream client died");
} else {
mForceControlStreamClient = null;
mVolumeControlStream = -1;
}
}
}
public void release() {
if (mCb != null) {
mCb.unlinkToDeath(this, 0);
mCb = null;
}
}
}
private int findVolumeDelta(int direction, int volume) {
int delta = 0;
if (direction == AudioManager.ADJUST_RAISE) {
if (volume == MAX_MASTER_VOLUME) {
return 0;
}
// This is the default value if we make it to the end
delta = mMasterVolumeRamp[1];
// If we're raising the volume move down the ramp array until we
// find the volume we're above and use that groups delta.
for (int i = mMasterVolumeRamp.length - 1; i > 1; i -= 2) {
if (volume >= mMasterVolumeRamp[i - 1]) {
delta = mMasterVolumeRamp[i];
break;
}
}
} else if (direction == AudioManager.ADJUST_LOWER){
if (volume == 0) {
return 0;
}
int length = mMasterVolumeRamp.length;
// This is the default value if we make it to the end
delta = -mMasterVolumeRamp[length - 1];
// If we're lowering the volume move up the ramp array until we
// find the volume we're below and use the group below it's delta
for (int i = 2; i < length; i += 2) {
if (volume <= mMasterVolumeRamp[i]) {
delta = -mMasterVolumeRamp[i - 1];
break;
}
}
}
return delta;
}
// UI update and Broadcast Intent
private void sendVolumeUpdate(int streamType, int oldIndex, int index, int flags) {
if (!mVoiceCapable && (streamType == AudioSystem.STREAM_RING)) {
streamType = AudioSystem.STREAM_NOTIFICATION;
}
showVolumeChangeUi(streamType, flags);
oldIndex = (oldIndex + 5) / 10;
index = (index + 5) / 10;
Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION);
intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType);
intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index);
intent.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex);
mContext.sendBroadcast(intent);
}
// UI update and Broadcast Intent
private void sendMasterVolumeUpdate(int flags, int oldVolume, int newVolume) {
mVolumePanel.postMasterVolumeChanged(flags);
Intent intent = new Intent(AudioManager.MASTER_VOLUME_CHANGED_ACTION);
intent.putExtra(AudioManager.EXTRA_PREV_MASTER_VOLUME_VALUE, oldVolume);
intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_VALUE, newVolume);
mContext.sendBroadcast(intent);
}
// UI update and Broadcast Intent
private void sendMasterMuteUpdate(boolean muted, int flags) {
mVolumePanel.postMasterMuteChanged(flags);
broadcastMasterMuteStatus(muted);
}
private void broadcastMasterMuteStatus(boolean muted) {
Intent intent = new Intent(AudioManager.MASTER_MUTE_CHANGED_ACTION);
intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_MUTED, muted);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
| Intent.FLAG_RECEIVER_REPLACE_PENDING);
long origCallerIdentityToken = Binder.clearCallingIdentity();
mContext.sendStickyBroadcast(intent);
Binder.restoreCallingIdentity(origCallerIdentityToken);
}
/**
* Sets the stream state's index, and posts a message to set system volume.
* This will not call out to the UI. Assumes a valid stream type.
*
* @param streamType Type of the stream
* @param index Desired volume index of the stream
* @param device the device whose volume must be changed
* @param force If true, set the volume even if the desired volume is same
* as the current volume.
* @param lastAudible If true, stores new index as last audible one
*/
private void setStreamVolumeInt(int streamType,
int index,
int device,
boolean force,
boolean lastAudible) {
VolumeStreamState streamState = mStreamStates[streamType];
// If stream is muted, set last audible index only
if (streamState.muteCount() != 0) {
// Do not allow last audible index to be 0
if (index != 0) {
streamState.setLastAudibleIndex(index, device);
// Post a persist volume msg
sendMsg(mAudioHandler,
MSG_PERSIST_VOLUME,
SENDMSG_QUEUE,
PERSIST_LAST_AUDIBLE,
device,
streamState,
PERSIST_DELAY);
}
} else {
if (streamState.setIndex(index, device, lastAudible) || force) {
// Post message to set system volume (it in turn will post a message
// to persist).
sendMsg(mAudioHandler,
MSG_SET_DEVICE_VOLUME,
SENDMSG_QUEUE,
device,
0,
streamState,
0);
}
}
}
/** @see AudioManager#setStreamSolo(int, boolean) */
public void setStreamSolo(int streamType, boolean state, IBinder cb) {
for (int stream = 0; stream < mStreamStates.length; stream++) {
if (!isStreamAffectedByMute(stream) || stream == streamType) continue;
// Bring back last audible volume
mStreamStates[stream].mute(cb, state);
}
}
/** @see AudioManager#setStreamMute(int, boolean) */
public void setStreamMute(int streamType, boolean state, IBinder cb) {
if (isStreamAffectedByMute(streamType)) {
mStreamStates[streamType].mute(cb, state);
}
}
/**
* @see AudioManager#toggleGlobalMute()
* @hide
*/
public void toggleGlobalMute() {
int currentMode = getRingerMode();
if (currentMode == RINGER_MODE_VIBRATE || currentMode == RINGER_MODE_SILENT) {
setRingerMode(RINGER_MODE_NORMAL);
} else {
int ringerMode = mHasVibrator ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT;
setRingerMode(ringerMode);
}
if (mVolumePanel != null) {
int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
if (streamType == STREAM_REMOTE_MUSIC) {
streamType = AudioManager.STREAM_MUSIC;
}
mVolumePanel.postMuteChanged(streamType,
AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_VIBRATE);
}
}
/** get stream mute state. */
public boolean isStreamMute(int streamType) {
return (mStreamStates[streamType].muteCount() != 0);
}
/** @see AudioManager#setMasterMute(boolean, IBinder) */
public void setMasterMute(boolean state, int flags, IBinder cb) {
if (state != AudioSystem.getMasterMute()) {
AudioSystem.setMasterMute(state);
// Post a persist master volume msg
sendMsg(mAudioHandler, MSG_PERSIST_MASTER_VOLUME_MUTE, SENDMSG_REPLACE, state ? 1
: 0, 0, null, PERSIST_DELAY);
sendMasterMuteUpdate(state, flags);
}
}
/** get master mute state. */
public boolean isMasterMute() {
return AudioSystem.getMasterMute();
}
/** @see AudioManager#getStreamVolume(int) */
public int getStreamVolume(int streamType) {
ensureValidStreamType(streamType);
int device = getDeviceForStream(streamType);
return (mStreamStates[streamType].getIndex(device, false /* lastAudible */) + 5) / 10;
}
public int getMasterVolume() {
if (isMasterMute()) return 0;
return getLastAudibleMasterVolume();
}
public void setMasterVolume(int volume, int flags) {
if (volume < 0) {
volume = 0;
} else if (volume > MAX_MASTER_VOLUME) {
volume = MAX_MASTER_VOLUME;
}
doSetMasterVolume((float)volume / MAX_MASTER_VOLUME, flags);
}
private void doSetMasterVolume(float volume, int flags) {
// don't allow changing master volume when muted
if (!AudioSystem.getMasterMute()) {
int oldVolume = getMasterVolume();
AudioSystem.setMasterVolume(volume);
int newVolume = getMasterVolume();
if (newVolume != oldVolume) {
// Post a persist master volume msg
sendMsg(mAudioHandler, MSG_PERSIST_MASTER_VOLUME, SENDMSG_REPLACE,
Math.round(volume * (float)1000.0), 0, null, PERSIST_DELAY);
}
// Send the volume update regardless whether there was a change.
sendMasterVolumeUpdate(flags, oldVolume, newVolume);
}
}
/** @see AudioManager#getStreamMaxVolume(int) */
public int getStreamMaxVolume(int streamType) {
ensureValidStreamType(streamType);
return (mStreamStates[streamType].getMaxIndex() + 5) / 10;
}
public int getMasterMaxVolume() {
return MAX_MASTER_VOLUME;
}
/** Get last audible volume before stream was muted. */
public int getLastAudibleStreamVolume(int streamType) {
ensureValidStreamType(streamType);
int device = getDeviceForStream(streamType);
return (mStreamStates[streamType].getIndex(device, true /* lastAudible */) + 5) / 10;
}
/** Get last audible master volume before it was muted. */
public int getLastAudibleMasterVolume() {
return Math.round(AudioSystem.getMasterVolume() * MAX_MASTER_VOLUME);
}
/** @see AudioManager#getMasterStreamType(int) */
public int getMasterStreamType() {
if (mVoiceCapable) {
return AudioSystem.STREAM_RING;
} else {
return AudioSystem.STREAM_MUSIC;
}
}
/** @see AudioManager#getRingerMode() */
public int getRingerMode() {
synchronized(mSettingsLock) {
return mRingerMode;
}
}
private void ensureValidRingerMode(int ringerMode) {
if (!AudioManager.isValidRingerMode(ringerMode)) {
throw new IllegalArgumentException("Bad ringer mode " + ringerMode);
}
}
/** @see AudioManager#setRingerMode(int) */
public void setRingerMode(int ringerMode) {
if ((ringerMode == AudioManager.RINGER_MODE_VIBRATE) && !mHasVibrator) {
ringerMode = AudioManager.RINGER_MODE_SILENT;
}
if (ringerMode != getRingerMode()) {
setRingerModeInt(ringerMode, true);
// Send sticky broadcast
broadcastRingerMode(ringerMode);
}
}
private void setRingerModeInt(int ringerMode, boolean persist) {
synchronized(mSettingsLock) {
mRingerMode = ringerMode;
}
// Mute stream if not previously muted by ringer mode and ringer mode
// is not RINGER_MODE_NORMAL and stream is affected by ringer mode.
// Unmute stream if previously muted by ringer mode and ringer mode
// is RINGER_MODE_NORMAL or stream is not affected by ringer mode.
int numStreamTypes = AudioSystem.getNumStreamTypes();
for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
if (isStreamMutedByRingerMode(streamType)) {
if (!isStreamAffectedByRingerMode(streamType) ||
ringerMode == AudioManager.RINGER_MODE_NORMAL) {
// ring and notifications volume should never be 0 when not silenced
// on voice capable devices
if (mVoiceCapable &&
mStreamVolumeAlias[streamType] == AudioSystem.STREAM_RING) {
synchronized (mStreamStates[streamType]) {
Set set = mStreamStates[streamType].mLastAudibleIndex.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry)i.next();
if ((Integer)entry.getValue() == 0) {
entry.setValue(10);
}
}
}
}
mStreamStates[streamType].mute(null, false);
mRingerModeMutedStreams &= ~(1 << streamType);
}
} else {
if (isStreamAffectedByRingerMode(streamType) &&
ringerMode != AudioManager.RINGER_MODE_NORMAL) {
mStreamStates[streamType].mute(null, true);
mRingerModeMutedStreams |= (1 << streamType);
}
}
}
// Post a persist ringer mode msg
if (persist) {
sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE,
SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY);
}
}
private void restoreMasterVolume() {
if (mUseMasterVolume) {
float volume = Settings.System.getFloat(mContentResolver,
Settings.System.VOLUME_MASTER, -1.0f);
if (volume >= 0.0f) {
AudioSystem.setMasterVolume(volume);
}
}
}
/** @see AudioManager#shouldVibrate(int) */
public boolean shouldVibrate(int vibrateType) {
if (!mHasVibrator) return false;
switch (getVibrateSetting(vibrateType)) {
case AudioManager.VIBRATE_SETTING_ON:
return getRingerMode() != AudioManager.RINGER_MODE_SILENT;
case AudioManager.VIBRATE_SETTING_ONLY_SILENT:
return getRingerMode() == AudioManager.RINGER_MODE_VIBRATE;
case AudioManager.VIBRATE_SETTING_OFF:
// return false, even for incoming calls
return false;
default:
return false;
}
}
/** @see AudioManager#getVibrateSetting(int) */
public int getVibrateSetting(int vibrateType) {
if (!mHasVibrator) return AudioManager.VIBRATE_SETTING_OFF;
return (mVibrateSetting >> (vibrateType * 2)) & 3;
}
/** @see AudioManager#setVibrateSetting(int, int) */
public void setVibrateSetting(int vibrateType, int vibrateSetting) {
if (!mHasVibrator) return;
mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting);
// Broadcast change
broadcastVibrateSetting(vibrateType);
}
/**
* @see #setVibrateSetting(int, int)
*/
public static int getValueForVibrateSetting(int existingValue, int vibrateType,
int vibrateSetting) {
// First clear the existing setting. Each vibrate type has two bits in
// the value. Note '3' is '11' in binary.
existingValue &= ~(3 << (vibrateType * 2));
// Set into the old value
existingValue |= (vibrateSetting & 3) << (vibrateType * 2);
return existingValue;
}
private class SetModeDeathHandler implements IBinder.DeathRecipient {
private IBinder mCb; // To be notified of client's death
private int mPid;
private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client
SetModeDeathHandler(IBinder cb, int pid) {
mCb = cb;
mPid = pid;
}
public void binderDied() {
int newModeOwnerPid = 0;
synchronized(mSetModeDeathHandlers) {
Log.w(TAG, "setMode() client died");
int index = mSetModeDeathHandlers.indexOf(this);
if (index < 0) {
Log.w(TAG, "unregistered setMode() client died");
} else {
newModeOwnerPid = setModeInt(AudioSystem.MODE_NORMAL, mCb, mPid);
}
}
// when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all
// SCO connections not started by the application changing the mode
if (newModeOwnerPid != 0) {
disconnectBluetoothSco(newModeOwnerPid);
}
}
public int getPid() {
return mPid;
}
public void setMode(int mode) {
mMode = mode;
}
public int getMode() {
return mMode;
}
public IBinder getBinder() {
return mCb;
}
}
/** @see AudioManager#setMode(int) */
public void setMode(int mode, IBinder cb) {
if (!checkAudioSettingsPermission("setMode()")) {
return;
}
if (mode < AudioSystem.MODE_CURRENT || mode >= AudioSystem.NUM_MODES) {
return;
}
int newModeOwnerPid = 0;
synchronized(mSetModeDeathHandlers) {
if (mode == AudioSystem.MODE_CURRENT) {
mode = mMode;
}
newModeOwnerPid = setModeInt(mode, cb, Binder.getCallingPid());
}
// when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all
// SCO connections not started by the application changing the mode
if (newModeOwnerPid != 0) {
disconnectBluetoothSco(newModeOwnerPid);
}
}
// must be called synchronized on mSetModeDeathHandlers
// setModeInt() returns a valid PID if the audio mode was successfully set to
// any mode other than NORMAL.
int setModeInt(int mode, IBinder cb, int pid) {
int newModeOwnerPid = 0;
if (cb == null) {
Log.e(TAG, "setModeInt() called with null binder");
return newModeOwnerPid;
}
SetModeDeathHandler hdlr = null;
Iterator iter = mSetModeDeathHandlers.iterator();
while (iter.hasNext()) {
SetModeDeathHandler h = (SetModeDeathHandler)iter.next();
if (h.getPid() == pid) {
hdlr = h;
// Remove from client list so that it is re-inserted at top of list
iter.remove();
hdlr.getBinder().unlinkToDeath(hdlr, 0);
break;
}
}
int status = AudioSystem.AUDIO_STATUS_OK;
do {
if (mode == AudioSystem.MODE_NORMAL) {
// get new mode from client at top the list if any
if (!mSetModeDeathHandlers.isEmpty()) {
hdlr = mSetModeDeathHandlers.get(0);
cb = hdlr.getBinder();
mode = hdlr.getMode();
}
} else {
if (hdlr == null) {
hdlr = new SetModeDeathHandler(cb, pid);
}
// Register for client death notification
try {
cb.linkToDeath(hdlr, 0);
} catch (RemoteException e) {
// Client has died!
Log.w(TAG, "setMode() could not link to "+cb+" binder death");
}
// Last client to call setMode() is always at top of client list
// as required by SetModeDeathHandler.binderDied()
mSetModeDeathHandlers.add(0, hdlr);
hdlr.setMode(mode);
}
if (mode != mMode) {
status = AudioSystem.setPhoneState(mode);
if (status == AudioSystem.AUDIO_STATUS_OK) {
mMode = mode;
} else {
if (hdlr != null) {
mSetModeDeathHandlers.remove(hdlr);
cb.unlinkToDeath(hdlr, 0);
}
// force reading new top of mSetModeDeathHandlers stack
mode = AudioSystem.MODE_NORMAL;
}
} else {
status = AudioSystem.AUDIO_STATUS_OK;
}
} while (status != AudioSystem.AUDIO_STATUS_OK && !mSetModeDeathHandlers.isEmpty());
if (status == AudioSystem.AUDIO_STATUS_OK) {
if (mode != AudioSystem.MODE_NORMAL) {
if (mSetModeDeathHandlers.isEmpty()) {
Log.e(TAG, "setMode() different from MODE_NORMAL with empty mode client stack");
} else {
newModeOwnerPid = mSetModeDeathHandlers.get(0).getPid();
}
}
int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
if (streamType == STREAM_REMOTE_MUSIC) {
// here handle remote media playback the same way as local playback
streamType = AudioManager.STREAM_MUSIC;
}
int device = getDeviceForStream(streamType);
int index = mStreamStates[mStreamVolumeAlias[streamType]].getIndex(device, false);
setStreamVolumeInt(mStreamVolumeAlias[streamType], index, device, true, false);
updateStreamVolumeAlias(true /*updateVolumes*/);
}
return newModeOwnerPid;
}
/** @see AudioManager#getMode() */
public int getMode() {
return mMode;
}
/** @see AudioManager#playSoundEffect(int) */
public void playSoundEffect(int effectType) {
sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SENDMSG_NOOP,
effectType, -1, null, 0);
}
/** @see AudioManager#playSoundEffect(int, float) */
public void playSoundEffectVolume(int effectType, float volume) {
loadSoundEffects();
sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SENDMSG_NOOP,
effectType, (int) (volume * 1000), null, 0);
}
/**
* Loads samples into the soundpool.
* This method must be called at first when sound effects are enabled
*/
public boolean loadSoundEffects() {
int status;
synchronized (mSoundEffectsLock) {
if (!mBootCompleted) {
Log.w(TAG, "loadSoundEffects() called before boot complete");
return false;
}
if (mSoundPool != null) {
return true;
}
mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0);
try {
mSoundPoolCallBack = null;
mSoundPoolListenerThread = new SoundPoolListenerThread();
mSoundPoolListenerThread.start();
// Wait for mSoundPoolCallBack to be set by the other thread
mSoundEffectsLock.wait();
} catch (InterruptedException e) {
Log.w(TAG, "Interrupted while waiting sound pool listener thread.");
}
if (mSoundPoolCallBack == null) {
Log.w(TAG, "loadSoundEffects() could not create SoundPool listener or thread");
if (mSoundPoolLooper != null) {
mSoundPoolLooper.quit();
mSoundPoolLooper = null;
}
mSoundPoolListenerThread = null;
mSoundPool.release();
mSoundPool = null;
return false;
}
/*
* poolId table: The value -1 in this table indicates that corresponding
* file (same index in SOUND_EFFECT_FILES[] has not been loaded.
* Once loaded, the value in poolId is the sample ID and the same
* sample can be reused for another effect using the same file.
*/
int[] poolId = new int[SOUND_EFFECT_FILES.length];
for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
poolId[fileIdx] = -1;
}
/*
* Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded.
* If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0:
* this indicates we have a valid sample loaded for this effect.
*/
int lastSample = 0;
for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
// Do not load sample if this effect uses the MediaPlayer
if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) {
continue;
}
if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) {
String filePath = Environment.getRootDirectory()
+ SOUND_EFFECTS_PATH
+ SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]];
int sampleId = mSoundPool.load(filePath, 0);
if (sampleId <= 0) {
Log.w(TAG, "Soundpool could not load file: "+filePath);
} else {
SOUND_EFFECT_FILES_MAP[effect][1] = sampleId;
poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId;
lastSample = sampleId;
}
} else {
SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]];
}
}
// wait for all samples to be loaded
if (lastSample != 0) {
mSoundPoolCallBack.setLastSample(lastSample);
try {
mSoundEffectsLock.wait();
status = mSoundPoolCallBack.status();
} catch (java.lang.InterruptedException e) {
Log.w(TAG, "Interrupted while waiting sound pool callback.");
status = -1;
}
} else {
status = -1;
}
if (mSoundPoolLooper != null) {
mSoundPoolLooper.quit();
mSoundPoolLooper = null;
}
mSoundPoolListenerThread = null;
if (status != 0) {
Log.w(TAG,
"loadSoundEffects(), Error "
+ ((lastSample != 0) ? mSoundPoolCallBack.status() : -1)
+ " while loading samples");
for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
if (SOUND_EFFECT_FILES_MAP[effect][1] > 0) {
SOUND_EFFECT_FILES_MAP[effect][1] = -1;
}
}
mSoundPool.release();
mSoundPool = null;
}
}
return (status == 0);
}
/**
* Unloads samples from the sound pool.
* This method can be called to free some memory when
* sound effects are disabled.
*/
public void unloadSoundEffects() {
synchronized (mSoundEffectsLock) {
if (mSoundPool == null) {
return;
}
mAudioHandler.removeMessages(MSG_LOAD_SOUND_EFFECTS);
mAudioHandler.removeMessages(MSG_PLAY_SOUND_EFFECT);
int[] poolId = new int[SOUND_EFFECT_FILES.length];
for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
poolId[fileIdx] = 0;
}
for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) {
continue;
}
if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) {
mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]);
SOUND_EFFECT_FILES_MAP[effect][1] = -1;
poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1;
}
}
mSoundPool.release();
mSoundPool = null;
}
}
class SoundPoolListenerThread extends Thread {
public SoundPoolListenerThread() {
super("SoundPoolListenerThread");
}
@Override
public void run() {
Looper.prepare();
mSoundPoolLooper = Looper.myLooper();
synchronized (mSoundEffectsLock) {
if (mSoundPool != null) {
mSoundPoolCallBack = new SoundPoolCallback();
mSoundPool.setOnLoadCompleteListener(mSoundPoolCallBack);
}
mSoundEffectsLock.notify();
}
Looper.loop();
}
}
private final class SoundPoolCallback implements
android.media.SoundPool.OnLoadCompleteListener {
int mStatus;
int mLastSample;
public int status() {
return mStatus;
}
public void setLastSample(int sample) {
mLastSample = sample;
}
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
synchronized (mSoundEffectsLock) {
if (status != 0) {
mStatus = status;
}
if (sampleId == mLastSample) {
mSoundEffectsLock.notify();
}
}
}
}
/** @see AudioManager#reloadAudioSettings() */
public void reloadAudioSettings() {
// restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings
readPersistedSettings();
// restore volume settings
int numStreamTypes = AudioSystem.getNumStreamTypes();
for (int streamType = 0; streamType < numStreamTypes; streamType++) {
VolumeStreamState streamState = mStreamStates[streamType];
synchronized (streamState) {
streamState.readSettings();
// unmute stream that was muted but is not affect by mute anymore
if (streamState.muteCount() != 0 && !isStreamAffectedByMute(streamType)) {
int size = streamState.mDeathHandlers.size();
for (int i = 0; i < size; i++) {
streamState.mDeathHandlers.get(i).mMuteCount = 1;
streamState.mDeathHandlers.get(i).mute(false);
}
}
}
}
checkAllAliasStreamVolumes();
// apply new ringer mode
setRingerModeInt(getRingerMode(), false);
}
/** @see AudioManager#setSpeakerphoneOn() */
public void setSpeakerphoneOn(boolean on){
if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) {
return;
}
mForcedUseForComm = on ? AudioSystem.FORCE_SPEAKER : AudioSystem.FORCE_NONE;
sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0);
}
/** @see AudioManager#isSpeakerphoneOn() */
public boolean isSpeakerphoneOn() {
return (mForcedUseForComm == AudioSystem.FORCE_SPEAKER);
}
/** @see AudioManager#setBluetoothScoOn() */
public void setBluetoothScoOn(boolean on){
if (!checkAudioSettingsPermission("setBluetoothScoOn()")) {
return;
}
mForcedUseForComm = on ? AudioSystem.FORCE_BT_SCO : AudioSystem.FORCE_NONE;
sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0);
sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
AudioSystem.FOR_RECORD, mForcedUseForComm, null, 0);
}
/** @see AudioManager#isBluetoothScoOn() */
public boolean isBluetoothScoOn() {
return (mForcedUseForComm == AudioSystem.FORCE_BT_SCO);
}
/** @see AudioManager#setBluetoothA2dpOn() */
public void setBluetoothA2dpOn(boolean on) {
if (!checkAudioSettingsPermission("setBluetoothA2dpOn()") && noDelayInATwoDP) {
return;
}
setBluetoothA2dpOnInt(on);
}
/** @see AudioManager#isBluetoothA2dpOn() */
public boolean isBluetoothA2dpOn() {
synchronized (mBluetoothA2dpEnabledLock) {
return mBluetoothA2dpEnabled;
}
}
/** @see AudioManager#startBluetoothSco() */
public void startBluetoothSco(IBinder cb){
if (!checkAudioSettingsPermission("startBluetoothSco()") ||
!mBootCompleted) {
return;
}
ScoClient client = getScoClient(cb, true);
client.incCount();
}
/** @see AudioManager#stopBluetoothSco() */
public void stopBluetoothSco(IBinder cb){
if (!checkAudioSettingsPermission("stopBluetoothSco()") ||
!mBootCompleted) {
return;
}
ScoClient client = getScoClient(cb, false);
if (client != null) {
client.decCount();
}
}
private class ScoClient implements IBinder.DeathRecipient {
private IBinder mCb; // To be notified of client's death
private int mCreatorPid;
private int mStartcount; // number of SCO connections started by this client
ScoClient(IBinder cb) {
mCb = cb;
mCreatorPid = Binder.getCallingPid();
mStartcount = 0;
}
public void binderDied() {
synchronized(mScoClients) {
Log.w(TAG, "SCO client died");
int index = mScoClients.indexOf(this);
if (index < 0) {
Log.w(TAG, "unregistered SCO client died");
} else {
clearCount(true);
mScoClients.remove(this);
}
}
}
public void incCount() {
synchronized(mScoClients) {
requestScoState(BluetoothHeadset.STATE_AUDIO_CONNECTED);
if (mStartcount == 0) {
try {
mCb.linkToDeath(this, 0);
} catch (RemoteException e) {
// client has already died!
Log.w(TAG, "ScoClient incCount() could not link to "+mCb+" binder death");
}
}
mStartcount++;
}
}
public void decCount() {
synchronized(mScoClients) {
if (mStartcount == 0) {
Log.w(TAG, "ScoClient.decCount() already 0");
} else {
mStartcount--;
if (mStartcount == 0) {
try {
mCb.unlinkToDeath(this, 0);
} catch (NoSuchElementException e) {
Log.w(TAG, "decCount() going to 0 but not registered to binder");
}
}
requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
}
}
}
public void clearCount(boolean stopSco) {
synchronized(mScoClients) {
if (mStartcount != 0) {
try {
mCb.unlinkToDeath(this, 0);
} catch (NoSuchElementException e) {
Log.w(TAG, "clearCount() mStartcount: "+mStartcount+" != 0 but not registered to binder");
}
}
mStartcount = 0;
if (stopSco) {
requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
}
}
}
public int getCount() {
return mStartcount;
}
public IBinder getBinder() {
return mCb;
}
public int getPid() {
return mCreatorPid;
}
public int totalCount() {
synchronized(mScoClients) {
int count = 0;
int size = mScoClients.size();
for (int i = 0; i < size; i++) {
count += mScoClients.get(i).getCount();
}
return count;
}
}
private void requestScoState(int state) {
checkScoAudioState();
if (totalCount() == 0) {
if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
// Make sure that the state transitions to CONNECTING even if we cannot initiate
// the connection.
broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTING);
// Accept SCO audio activation only in NORMAL audio mode or if the mode is
// currently controlled by the same client process.
synchronized(mSetModeDeathHandlers) {
if ((mSetModeDeathHandlers.isEmpty() ||
mSetModeDeathHandlers.get(0).getPid() == mCreatorPid) &&
(mScoAudioState == SCO_STATE_INACTIVE ||
mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
if (mScoAudioState == SCO_STATE_INACTIVE) {
if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) {
if (mBluetoothHeadset.startScoUsingVirtualVoiceCall(
mBluetoothHeadsetDevice)) {
mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
} else {
broadcastScoConnectionState(
AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
}
} else if (getBluetoothHeadset()) {
mScoAudioState = SCO_STATE_ACTIVATE_REQ;
}
} else {
mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTED);
}
} else {
broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
}
}
} else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED &&
(mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
mScoAudioState == SCO_STATE_ACTIVATE_REQ)) {
if (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL) {
if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) {
if (!mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
mBluetoothHeadsetDevice)) {
mScoAudioState = SCO_STATE_INACTIVE;
broadcastScoConnectionState(
AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
}
} else if (getBluetoothHeadset()) {
mScoAudioState = SCO_STATE_DEACTIVATE_REQ;
}
} else {
mScoAudioState = SCO_STATE_INACTIVE;
broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
}
}
}
}
}
private void checkScoAudioState() {
if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null &&
mScoAudioState == SCO_STATE_INACTIVE &&
mBluetoothHeadset.getAudioState(mBluetoothHeadsetDevice)
!= BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
}
}
private ScoClient getScoClient(IBinder cb, boolean create) {
synchronized(mScoClients) {
ScoClient client = null;
int size = mScoClients.size();
for (int i = 0; i < size; i++) {
client = mScoClients.get(i);
if (client.getBinder() == cb)
return client;
}
if (create) {
client = new ScoClient(cb);
mScoClients.add(client);
}
return client;
}
}
public void clearAllScoClients(int exceptPid, boolean stopSco) {
synchronized(mScoClients) {
ScoClient savedClient = null;
int size = mScoClients.size();
for (int i = 0; i < size; i++) {
ScoClient cl = mScoClients.get(i);
if (cl.getPid() != exceptPid) {
cl.clearCount(stopSco);
} else {
savedClient = cl;
}
}
mScoClients.clear();
if (savedClient != null) {
mScoClients.add(savedClient);
}
}
}
private boolean getBluetoothHeadset() {
boolean result = false;
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null) {
result = adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
BluetoothProfile.HEADSET);
}
// If we could not get a bluetooth headset proxy, send a failure message
// without delay to reset the SCO audio state and clear SCO clients.
// If we could get a proxy, send a delayed failure message that will reset our state
// in case we don't receive onServiceConnected().
sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
SENDMSG_REPLACE, 0, 0, null, result ? BT_HEADSET_CNCT_TIMEOUT_MS : 0);
return result;
}
private void disconnectBluetoothSco(int exceptPid) {
synchronized(mScoClients) {
checkScoAudioState();
if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL ||
mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) {
if (mBluetoothHeadsetDevice != null) {
if (mBluetoothHeadset != null) {
if (!mBluetoothHeadset.stopVoiceRecognition(
mBluetoothHeadsetDevice)) {
sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
SENDMSG_REPLACE, 0, 0, null, 0);
}
} else if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL &&
getBluetoothHeadset()) {
mScoAudioState = SCO_STATE_DEACTIVATE_EXT_REQ;
}
}
} else {
clearAllScoClients(exceptPid, true);
}
}
}
private void resetBluetoothSco() {
synchronized(mScoClients) {
clearAllScoClients(0, false);
mScoAudioState = SCO_STATE_INACTIVE;
broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
}
}
private void broadcastScoConnectionState(int state) {
if (state != mScoConnectionState) {
Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state);
newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_PREVIOUS_STATE,
mScoConnectionState);
mContext.sendStickyBroadcast(newIntent);
mScoConnectionState = state;
}
}
private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
BluetoothDevice btDevice;
List<BluetoothDevice> deviceList;
switch(profile) {
case BluetoothProfile.A2DP:
BluetoothA2dp a2dp = (BluetoothA2dp) proxy;
deviceList = a2dp.getConnectedDevices();
if (deviceList.size() > 0) {
btDevice = deviceList.get(0);
if (!noDelayInATwoDP){
synchronized (mConnectedDevices) {
int state = a2dp.getConnectionState(btDevice);
int delay = checkSendBecomingNoisyIntent(
AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
(state == BluetoothA2dp.STATE_CONNECTED) ? 1 : 0);
queueMsgUnderWakeLock(mAudioHandler,
MSG_SET_A2DP_CONNECTION_STATE,
state,
0,
btDevice,
delay);
}
} else {
onSetA2dpConnectionState(btDevice, a2dp.getConnectionState(btDevice));
}
}
break;
case BluetoothProfile.HEADSET:
synchronized (mScoClients) {
// Discard timeout message
mAudioHandler.removeMessages(MSG_BT_HEADSET_CNCT_FAILED);
mBluetoothHeadset = (BluetoothHeadset) proxy;
deviceList = mBluetoothHeadset.getConnectedDevices();
if (deviceList.size() > 0) {
mBluetoothHeadsetDevice = deviceList.get(0);
} else {
mBluetoothHeadsetDevice = null;
}
// Refresh SCO audio state
checkScoAudioState();
// Continue pending action if any
if (mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
mScoAudioState == SCO_STATE_DEACTIVATE_REQ ||
mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) {
boolean status = false;
if (mBluetoothHeadsetDevice != null) {
switch (mScoAudioState) {
case SCO_STATE_ACTIVATE_REQ:
mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
status = mBluetoothHeadset.startScoUsingVirtualVoiceCall(
mBluetoothHeadsetDevice);
break;
case SCO_STATE_DEACTIVATE_REQ:
status = mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
mBluetoothHeadsetDevice);
break;
case SCO_STATE_DEACTIVATE_EXT_REQ:
status = mBluetoothHeadset.stopVoiceRecognition(
mBluetoothHeadsetDevice);
}
}
if (!status) {
sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED,
SENDMSG_REPLACE, 0, 0, null, 0);
}
}
}
break;
default:
break;
}
}
public void onServiceDisconnected(int profile) {
switch(profile) {
case BluetoothProfile.A2DP:
synchronized (mConnectedDevices) {
if (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)) {
makeA2dpDeviceUnavailableNow(
mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP));
}
}
break;
case BluetoothProfile.HEADSET:
synchronized (mScoClients) {
mBluetoothHeadset = null;
}
break;
default:
break;
}
}
};
///////////////////////////////////////////////////////////////////////////
// Internal methods
///////////////////////////////////////////////////////////////////////////
/**
* Checks if the adjustment should change ringer mode instead of just
* adjusting volume. If so, this will set the proper ringer mode and volume
* indices on the stream states.
*/
private boolean checkForRingerModeChange(int oldIndex, int direction, int step) {
boolean adjustVolumeIndex = true;
int ringerMode = getRingerMode();
switch (ringerMode) {
case RINGER_MODE_NORMAL:
if (direction == AudioManager.ADJUST_LOWER) {
if (mHasVibrator) {
// "step" is the delta in internal index units corresponding to a
// change of 1 in UI index units.
// Because of rounding when rescaling from one stream index range to its alias
// index range, we cannot simply test oldIndex == step:
// (step <= oldIndex < 2 * step) is equivalent to: (old UI index == 1)
if (step <= oldIndex && oldIndex < 2 * step) {
ringerMode = RINGER_MODE_VIBRATE;
}
} else {
// (oldIndex < step) is equivalent to (old UI index == 0)
if ((oldIndex < step) && mPrevVolDirection != AudioManager.ADJUST_LOWER) {
ringerMode = RINGER_MODE_SILENT;
}
}
}
break;
case RINGER_MODE_VIBRATE:
if (!mHasVibrator) {
Log.e(TAG, "checkForRingerModeChange() current ringer mode is vibrate" +
"but no vibrator is present");
break;
}
if ((direction == AudioManager.ADJUST_LOWER)) {
if (mPrevVolDirection != AudioManager.ADJUST_LOWER) {
ringerMode = RINGER_MODE_SILENT;
}
} else if (direction == AudioManager.ADJUST_RAISE) {
ringerMode = RINGER_MODE_NORMAL;
}
adjustVolumeIndex = false;
break;
case RINGER_MODE_SILENT:
if (direction == AudioManager.ADJUST_RAISE) {
if (mHasVibrator) {
ringerMode = RINGER_MODE_VIBRATE;
} else {
ringerMode = RINGER_MODE_NORMAL;
}
}
adjustVolumeIndex = false;
break;
default:
Log.e(TAG, "checkForRingerModeChange() wrong ringer mode: "+ringerMode);
break;
}
setRingerMode(ringerMode);
mPrevVolDirection = direction;
return adjustVolumeIndex;
}
public boolean isStreamAffectedByRingerMode(int streamType) {
return (mRingerModeAffectedStreams & (1 << streamType)) != 0;
}
private boolean isStreamMutedByRingerMode(int streamType) {
return (mRingerModeMutedStreams & (1 << streamType)) != 0;
}
public boolean isStreamAffectedByMute(int streamType) {
return (mMuteAffectedStreams & (1 << streamType)) != 0;
}
private void ensureValidDirection(int direction) {
if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) {
throw new IllegalArgumentException("Bad direction " + direction);
}
}
private void ensureValidSteps(int steps) {
if (Math.abs(steps) > MAX_BATCH_VOLUME_ADJUST_STEPS) {
throw new IllegalArgumentException("Bad volume adjust steps " + steps);
}
}
private void ensureValidStreamType(int streamType) {
if (streamType < 0 || streamType >= mStreamStates.length) {
throw new IllegalArgumentException("Bad stream type " + streamType);
}
}
private boolean isInCommunication() {
boolean isOffhook = false;
if (mVoiceCapable) {
try {
ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
if (phone != null) isOffhook = phone.isOffhook();
} catch (RemoteException e) {
Log.w(TAG, "Couldn't connect to phone service", e);
}
}
return (isOffhook || getMode() == AudioManager.MODE_IN_COMMUNICATION);
}
private int getActiveStreamType(int suggestedStreamType) {
if (mVoiceCapable) {
if (isInCommunication()) {
if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
== AudioSystem.FORCE_BT_SCO) {
// Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
return AudioSystem.STREAM_BLUETOOTH_SCO;
} else {
// Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
return AudioSystem.STREAM_VOICE_CALL;
}
} else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
// Having the suggested stream be USE_DEFAULT_STREAM_TYPE is how remote control
// volume can have priority over STREAM_MUSIC
if (checkUpdateRemoteStateIfActive(AudioSystem.STREAM_MUSIC)) {
if (DEBUG_VOL)
Log.v(TAG, "getActiveStreamType: Forcing STREAM_REMOTE_MUSIC");
return STREAM_REMOTE_MUSIC;
} else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)) {
if (DEBUG_VOL)
Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC stream active");
return AudioSystem.STREAM_MUSIC;
} else {
if (DEBUG_VOL)
Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING b/c default");
return AudioSystem.STREAM_RING;
}
} else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)) {
if (DEBUG_VOL)
Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC stream active");
return AudioSystem.STREAM_MUSIC;
} else {
if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Returning suggested type "
+ suggestedStreamType);
return suggestedStreamType;
}
} else {
if (isInCommunication()) {
if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
== AudioSystem.FORCE_BT_SCO) {
if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO");
return AudioSystem.STREAM_BLUETOOTH_SCO;
} else {
if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL");
return AudioSystem.STREAM_VOICE_CALL;
}
} else if (AudioSystem.isStreamActive(AudioSystem.STREAM_NOTIFICATION,
NOTIFICATION_VOLUME_DELAY_MS) ||
AudioSystem.isStreamActive(AudioSystem.STREAM_RING,
NOTIFICATION_VOLUME_DELAY_MS)) {
if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_NOTIFICATION");
return AudioSystem.STREAM_NOTIFICATION;
} else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
if (checkUpdateRemoteStateIfActive(AudioSystem.STREAM_MUSIC)) {
// Having the suggested stream be USE_DEFAULT_STREAM_TYPE is how remote control
// volume can have priority over STREAM_MUSIC
if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_REMOTE_MUSIC");
return STREAM_REMOTE_MUSIC;
} else {
if (DEBUG_VOL)
Log.v(TAG, "getActiveStreamType: using STREAM_MUSIC as default");
return AudioSystem.STREAM_MUSIC;
}
} else {
if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Returning suggested type "
+ suggestedStreamType);
return suggestedStreamType;
}
}
}
private void broadcastRingerMode(int ringerMode) {
// Send sticky broadcast
Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION);
broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, ringerMode);
broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
| Intent.FLAG_RECEIVER_REPLACE_PENDING);
long origCallerIdentityToken = Binder.clearCallingIdentity();
mContext.sendStickyBroadcast(broadcast);
Binder.restoreCallingIdentity(origCallerIdentityToken);
}
private void broadcastVibrateSetting(int vibrateType) {
// Send broadcast
if (ActivityManagerNative.isSystemReady()) {
Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION);
broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType);
broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType));
mContext.sendBroadcast(broadcast);
}
}
// Message helper methods
/**
* Queue a message on the given handler's message queue, after acquiring the service wake lock.
* Note that the wake lock needs to be released after the message has been handled.
*/
private void queueMsgUnderWakeLock(Handler handler, int msg,
int arg1, int arg2, Object obj, int delay) {
mMediaEventWakeLock.acquire();
sendMsg(handler, msg, SENDMSG_QUEUE, arg1, arg2, obj, delay);
}
private static void sendMsg(Handler handler, int msg,
int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
if (existingMsgPolicy == SENDMSG_REPLACE) {
handler.removeMessages(msg);
} else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
return;
}
handler.sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay);
}
boolean checkAudioSettingsPermission(String method) {
if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS")
== PackageManager.PERMISSION_GRANTED) {
return true;
}
String msg = "Audio Settings Permission Denial: " + method + " from pid="
+ Binder.getCallingPid()
+ ", uid=" + Binder.getCallingUid();
Log.w(TAG, msg);
return false;
}
private int getDeviceForStream(int stream) {
int device = AudioSystem.getDevicesForStream(stream);
if ((device & (device - 1)) != 0) {
// Multiple device selection is either:
// - speaker + one other device: give priority to the non-speaker device in this case.
// - one A2DP device + another device: happens with duplicated output. In this case
// retain the device on the A2DP output as the other must not correspond to an active
// selection if not the speaker.
if ((device & AudioSystem.DEVICE_OUT_SPEAKER) != 0) {
device ^= AudioSystem.DEVICE_OUT_SPEAKER;
} else {
device &= AudioSystem.DEVICE_OUT_ALL_A2DP;
}
}
return device;
}
public void setWiredDeviceConnectionState(int device, int state, String name) {
synchronized (mConnectedDevices) {
int delay = checkSendBecomingNoisyIntent(device, state);
queueMsgUnderWakeLock(mAudioHandler,
MSG_SET_WIRED_DEVICE_CONNECTION_STATE,
device,
state,
name,
delay);
}
}
public int setBluetoothA2dpDeviceConnectionState(BluetoothDevice device, int state)
{
int delay;
if(!noDelayInATwoDP) {
synchronized (mConnectedDevices) {
delay = checkSendBecomingNoisyIntent(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
(state == BluetoothA2dp.STATE_CONNECTED) ? 1 : 0);
queueMsgUnderWakeLock(mAudioHandler,
MSG_SET_A2DP_CONNECTION_STATE,
state,
0,
device,
delay);
}
} else {
delay = 0;
}
return delay;
}
///////////////////////////////////////////////////////////////////////////
// Inner classes
///////////////////////////////////////////////////////////////////////////
public class VolumeStreamState {
private final int mStreamType;
private String mVolumeIndexSettingName;
private String mLastAudibleVolumeIndexSettingName;
private int mIndexMax;
private final ConcurrentHashMap<Integer, Integer> mIndex =
new ConcurrentHashMap<Integer, Integer>(8, 0.75f, 4);
private final ConcurrentHashMap<Integer, Integer> mLastAudibleIndex =
new ConcurrentHashMap<Integer, Integer>(8, 0.75f, 4);
private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo clients death
private VolumeStreamState(String settingName, int streamType) {
mVolumeIndexSettingName = settingName;
mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
mStreamType = streamType;
mIndexMax = MAX_STREAM_VOLUME[streamType];
AudioSystem.initStreamVolume(streamType, 0, mIndexMax);
mIndexMax *= 10;
readSettings();
mDeathHandlers = new ArrayList<VolumeDeathHandler>();
}
public String getSettingNameForDevice(boolean lastAudible, int device) {
String name = lastAudible ?
mLastAudibleVolumeIndexSettingName :
mVolumeIndexSettingName;
String suffix = AudioSystem.getDeviceName(device);
if (suffix.isEmpty()) {
return name;
}
return name + "_" + suffix;
}
public synchronized void readSettings() {
int remainingDevices = AudioSystem.DEVICE_OUT_ALL;
for (int i = 0; remainingDevices != 0; i++) {
int device = (1 << i);
if ((device & remainingDevices) == 0) {
continue;
}
remainingDevices &= ~device;
// retrieve current volume for device
String name = getSettingNameForDevice(false /* lastAudible */, device);
// if no volume stored for current stream and device, use default volume if default
// device, continue otherwise
int defaultIndex = (device == AudioSystem.DEVICE_OUT_DEFAULT) ?
AudioManager.DEFAULT_STREAM_VOLUME[mStreamType] : -1;
int index = Settings.System.getInt(mContentResolver, name, defaultIndex);
if (index == -1) {
continue;
}
// retrieve last audible volume for device
name = getSettingNameForDevice(true /* lastAudible */, device);
// use stored last audible index if present, otherwise use current index if not 0
// or default index
defaultIndex = (index > 0) ?
index : AudioManager.DEFAULT_STREAM_VOLUME[mStreamType];
int lastAudibleIndex = Settings.System.getInt(mContentResolver, name, defaultIndex);
// a last audible index of 0 should never be stored for ring and notification
// streams on phones (voice capable devices).
// same for system stream on phones and tablets
if ((lastAudibleIndex == 0) &&
((mVoiceCapable &&
(mStreamVolumeAlias[mStreamType] == AudioSystem.STREAM_RING)) ||
(mStreamVolumeAlias[mStreamType] == AudioSystem.STREAM_SYSTEM))) {
lastAudibleIndex = AudioManager.DEFAULT_STREAM_VOLUME[mStreamType];
// Correct the data base
sendMsg(mAudioHandler,
MSG_PERSIST_VOLUME,
SENDMSG_QUEUE,
PERSIST_LAST_AUDIBLE,
device,
this,
PERSIST_DELAY);
}
mLastAudibleIndex.put(device, getValidIndex(10 * lastAudibleIndex));
// the initial index should never be 0 for ring and notification streams on phones
// (voice capable devices) if not in silent or vibrate mode.
// same for system stream on phones and tablets
if ((index == 0) && (mRingerMode == AudioManager.RINGER_MODE_NORMAL) &&
((mVoiceCapable &&
(mStreamVolumeAlias[mStreamType] == AudioSystem.STREAM_RING)) ||
(mStreamVolumeAlias[mStreamType] == AudioSystem.STREAM_SYSTEM))) {
index = lastAudibleIndex;
// Correct the data base
sendMsg(mAudioHandler,
MSG_PERSIST_VOLUME,
SENDMSG_QUEUE,
PERSIST_CURRENT,
device,
this,
PERSIST_DELAY);
}
mIndex.put(device, getValidIndex(10 * index));
}
}
public void applyDeviceVolume(int device) {
AudioSystem.setStreamVolumeIndex(mStreamType,
(getIndex(device, false /* lastAudible */) + 5)/10,
device);
}
public synchronized void applyAllVolumes() {
// apply default volume first: by convention this will reset all
// devices volumes in audio policy manager to the supplied value
AudioSystem.setStreamVolumeIndex(mStreamType,
(getIndex(AudioSystem.DEVICE_OUT_DEFAULT, false /* lastAudible */) + 5)/10,
AudioSystem.DEVICE_OUT_DEFAULT);
// then apply device specific volumes
Set set = mIndex.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry)i.next();
int device = ((Integer)entry.getKey()).intValue();
if (device != AudioSystem.DEVICE_OUT_DEFAULT) {
AudioSystem.setStreamVolumeIndex(mStreamType,
((Integer)entry.getValue() + 5)/10,
device);
}
}
}
public boolean adjustIndex(int deltaIndex, int device) {
return setIndex(getIndex(device,
false /* lastAudible */) + deltaIndex,
device,
true /* lastAudible */);
}
public synchronized boolean setIndex(int index, int device, boolean lastAudible) {
int oldIndex = getIndex(device, false /* lastAudible */);
index = getValidIndex(index);
mIndex.put(device, getValidIndex(index));
if (oldIndex != index) {
if (lastAudible) {
mLastAudibleIndex.put(device, index);
}
// Apply change to all streams using this one as alias
// if changing volume of current device, also change volume of current
// device on aliased stream
boolean currentDevice = (device == getDeviceForStream(mStreamType));
int numStreamTypes = AudioSystem.getNumStreamTypes();
for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
if (streamType != mStreamType &&
mStreamVolumeAlias[streamType] == mStreamType) {
int scaledIndex = rescaleIndex(index, mStreamType, streamType);
mStreamStates[streamType].setIndex(scaledIndex,
device,
lastAudible);
if (currentDevice) {
mStreamStates[streamType].setIndex(scaledIndex,
getDeviceForStream(streamType),
lastAudible);
}
}
}
return true;
} else {
return false;
}
}
public synchronized int getIndex(int device, boolean lastAudible) {
ConcurrentHashMap <Integer, Integer> indexes;
if (lastAudible) {
indexes = mLastAudibleIndex;
} else {
indexes = mIndex;
}
Integer index = indexes.get(device);
if (index == null) {
// there is always an entry for AudioSystem.DEVICE_OUT_DEFAULT
index = indexes.get(AudioSystem.DEVICE_OUT_DEFAULT);
}
return index.intValue();
}
public synchronized void setLastAudibleIndex(int index, int device) {
// Apply change to all streams using this one as alias
// if changing volume of current device, also change volume of current
// device on aliased stream
boolean currentDevice = (device == getDeviceForStream(mStreamType));
int numStreamTypes = AudioSystem.getNumStreamTypes();
for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
if (streamType != mStreamType &&
mStreamVolumeAlias[streamType] == mStreamType) {
int scaledIndex = rescaleIndex(index, mStreamType, streamType);
mStreamStates[streamType].setLastAudibleIndex(scaledIndex, device);
if (currentDevice) {
mStreamStates[streamType].setLastAudibleIndex(scaledIndex,
getDeviceForStream(streamType));
}
}
}
mLastAudibleIndex.put(device, getValidIndex(index));
}
public synchronized void adjustLastAudibleIndex(int deltaIndex, int device) {
setLastAudibleIndex(getIndex(device,
true /* lastAudible */) + deltaIndex,
device);
}
public int getMaxIndex() {
return mIndexMax;
}
// only called by setAllIndexes() which is already synchronized
public ConcurrentHashMap <Integer, Integer> getAllIndexes(boolean lastAudible) {
if (lastAudible) {
return mLastAudibleIndex;
} else {
return mIndex;
}
}
public synchronized void setAllIndexes(VolumeStreamState srcStream, boolean lastAudible) {
ConcurrentHashMap <Integer, Integer> indexes = srcStream.getAllIndexes(lastAudible);
Set set = indexes.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry)i.next();
int device = ((Integer)entry.getKey()).intValue();
int index = ((Integer)entry.getValue()).intValue();
index = rescaleIndex(index, srcStream.getStreamType(), mStreamType);
setIndex(index, device, lastAudible);
}
}
public synchronized void mute(IBinder cb, boolean state) {
VolumeDeathHandler handler = getDeathHandler(cb, state);
if (handler == null) {
Log.e(TAG, "Could not get client death handler for stream: "+mStreamType);
return;
}
handler.mute(state);
}
public int getStreamType() {
return mStreamType;
}
private int getValidIndex(int index) {
if (index < 0) {
return 0;
} else if (index > mIndexMax) {
return mIndexMax;
}
return index;
}
private class VolumeDeathHandler implements IBinder.DeathRecipient {
private IBinder mICallback; // To be notified of client's death
private int mMuteCount; // Number of active mutes for this client
VolumeDeathHandler(IBinder cb) {
mICallback = cb;
}
// must be called while synchronized on parent VolumeStreamState
public void mute(boolean state) {
if (state) {
if (mMuteCount == 0) {
// Register for client death notification
try {
// mICallback can be 0 if muted by AudioService
if (mICallback != null) {
mICallback.linkToDeath(this, 0);
}
mDeathHandlers.add(this);
// If the stream is not yet muted by any client, set level to 0
if (muteCount() == 0) {
Set set = mIndex.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry)i.next();
int device = ((Integer)entry.getKey()).intValue();
setIndex(0, device, false /* lastAudible */);
}
sendMsg(mAudioHandler,
MSG_SET_ALL_VOLUMES,
SENDMSG_QUEUE,
0,
0,
VolumeStreamState.this, 0);
}
} catch (RemoteException e) {
// Client has died!
binderDied();
return;
}
} else {
Log.w(TAG, "stream: "+mStreamType+" was already muted by this client");
}
mMuteCount++;
} else {
if (mMuteCount == 0) {
Log.e(TAG, "unexpected unmute for stream: "+mStreamType);
} else {
mMuteCount--;
if (mMuteCount == 0) {
// Unregister from client death notification
mDeathHandlers.remove(this);
// mICallback can be 0 if muted by AudioService
if (mICallback != null) {
mICallback.unlinkToDeath(this, 0);
}
if (muteCount() == 0) {
// If the stream is not muted any more, restore its volume if
// ringer mode allows it
if (!isStreamAffectedByRingerMode(mStreamType) ||
mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
Set set = mIndex.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry)i.next();
int device = ((Integer)entry.getKey()).intValue();
setIndex(getIndex(device,
true /* lastAudible */),
device,
false /* lastAudible */);
}
sendMsg(mAudioHandler,
MSG_SET_ALL_VOLUMES,
SENDMSG_QUEUE,
0,
0,
VolumeStreamState.this, 0);
}
}
}
}
}
}
public void binderDied() {
Log.w(TAG, "Volume service client died for stream: "+mStreamType);
if (mMuteCount != 0) {
// Reset all active mute requests from this client.
mMuteCount = 1;
mute(false);
}
}
}
private synchronized int muteCount() {
int count = 0;
int size = mDeathHandlers.size();
for (int i = 0; i < size; i++) {
count += mDeathHandlers.get(i).mMuteCount;
}
return count;
}
// only called by mute() which is already synchronized
private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) {
VolumeDeathHandler handler;
int size = mDeathHandlers.size();
for (int i = 0; i < size; i++) {
handler = mDeathHandlers.get(i);
if (cb == handler.mICallback) {
return handler;
}
}
// If this is the first mute request for this client, create a new
// client death handler. Otherwise, it is an out of sequence unmute request.
if (state) {
handler = new VolumeDeathHandler(cb);
} else {
Log.w(TAG, "stream was not muted by this client");
handler = null;
}
return handler;
}
private void dump(PrintWriter pw) {
pw.print(" Current: ");
Set set = mIndex.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry)i.next();
pw.print(Integer.toHexString(((Integer)entry.getKey()).intValue())
+ ": " + ((((Integer)entry.getValue()).intValue() + 5) / 10)+", ");
}
pw.print("\n Last audible: ");
set = mLastAudibleIndex.entrySet();
i = set.iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry)i.next();
pw.print(Integer.toHexString(((Integer)entry.getKey()).intValue())
+ ": " + ((((Integer)entry.getValue()).intValue() + 5) / 10)+", ");
}
}
}
/** Thread that handles native AudioSystem control. */
private class AudioSystemThread extends Thread {
AudioSystemThread() {
super("AudioService");
}
@Override
public void run() {
// Set this thread up so the handler will work on it
Looper.prepare();
synchronized(AudioService.this) {
mAudioHandler = new AudioHandler();
// Notify that the handler has been created
AudioService.this.notify();
}
// Listen for volume change requests that are set by VolumePanel
Looper.loop();
}
}
/** Handles internal volume messages in separate volume thread. */
private class AudioHandler extends Handler {
private void setDeviceVolume(VolumeStreamState streamState, int device) {
// Apply volume
streamState.applyDeviceVolume(device);
// Apply change to all streams using this one as alias
int numStreamTypes = AudioSystem.getNumStreamTypes();
for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
if (streamType != streamState.mStreamType &&
mStreamVolumeAlias[streamType] == streamState.mStreamType) {
mStreamStates[streamType].applyDeviceVolume(getDeviceForStream(streamType));
}
}
// Post a persist volume msg
sendMsg(mAudioHandler,
MSG_PERSIST_VOLUME,
SENDMSG_QUEUE,
PERSIST_CURRENT|PERSIST_LAST_AUDIBLE,
device,
streamState,
PERSIST_DELAY);
}
private void setAllVolumes(VolumeStreamState streamState) {
// Apply volume
streamState.applyAllVolumes();
// Apply change to all streams using this one as alias
int numStreamTypes = AudioSystem.getNumStreamTypes();
for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
if (streamType != streamState.mStreamType &&
mStreamVolumeAlias[streamType] == streamState.mStreamType) {
mStreamStates[streamType].applyAllVolumes();
}
}
}
private void persistVolume(VolumeStreamState streamState,
int persistType,
int device) {
if ((persistType & PERSIST_CURRENT) != 0) {
System.putInt(mContentResolver,
streamState.getSettingNameForDevice(false /* lastAudible */, device),
(streamState.getIndex(device, false /* lastAudible */) + 5)/ 10);
}
if ((persistType & PERSIST_LAST_AUDIBLE) != 0) {
System.putInt(mContentResolver,
streamState.getSettingNameForDevice(true /* lastAudible */, device),
(streamState.getIndex(device, true /* lastAudible */) + 5) / 10);
}
}
private void persistRingerMode(int ringerMode) {
System.putInt(mContentResolver, System.MODE_RINGER, ringerMode);
}
private void playSoundEffect(int effectType, int volume) {
synchronized (mSoundEffectsLock) {
if (mSoundPool == null) {
return;
}
float volFloat;
// use default if volume is not specified by caller
if (volume < 0) {
volFloat = (float)Math.pow(10, SOUND_EFFECT_VOLUME_DB/20);
} else {
volFloat = (float) volume / 1000.0f;
}
if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) {
mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], volFloat, volFloat, 0, 0, 1.0f);
} else {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]];
mediaPlayer.setDataSource(filePath);
mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
mediaPlayer.prepare();
mediaPlayer.setVolume(volFloat, volFloat);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
cleanupPlayer(mp);
}
});
mediaPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
cleanupPlayer(mp);
return true;
}
});
mediaPlayer.start();
} catch (IOException ex) {
Log.w(TAG, "MediaPlayer IOException: "+ex);
} catch (IllegalArgumentException ex) {
Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex);
} catch (IllegalStateException ex) {
Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
}
}
}
}
private void onHandlePersistMediaButtonReceiver(ComponentName receiver) {
Settings.System.putString(mContentResolver, Settings.System.MEDIA_BUTTON_RECEIVER,
receiver == null ? "" : receiver.flattenToString());
}
private void cleanupPlayer(MediaPlayer mp) {
if (mp != null) {
try {
mp.stop();
mp.release();
} catch (IllegalStateException ex) {
Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
}
}
}
private void setForceUse(int usage, int config) {
AudioSystem.setForceUse(usage, config);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SET_DEVICE_VOLUME:
setDeviceVolume((VolumeStreamState) msg.obj, msg.arg1);
break;
case MSG_SET_ALL_VOLUMES:
setAllVolumes((VolumeStreamState) msg.obj);
break;
case MSG_PERSIST_VOLUME:
persistVolume((VolumeStreamState) msg.obj, msg.arg1, msg.arg2);
break;
case MSG_PERSIST_MASTER_VOLUME:
Settings.System.putFloat(mContentResolver, Settings.System.VOLUME_MASTER,
(float)msg.arg1 / (float)1000.0);
break;
case MSG_PERSIST_MASTER_VOLUME_MUTE:
Settings.System.putInt(mContentResolver, Settings.System.VOLUME_MASTER_MUTE,
msg.arg1);
break;
case MSG_PERSIST_RINGER_MODE:
// note that the value persisted is the current ringer mode, not the
// value of ringer mode as of the time the request was made to persist
persistRingerMode(getRingerMode());
break;
case MSG_MEDIA_SERVER_DIED:
if (!mMediaServerOk) {
Log.e(TAG, "Media server died.");
// Force creation of new IAudioFlinger interface so that we are notified
// when new media_server process is back to life.
AudioSystem.setErrorCallback(mAudioSystemCallback);
sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SENDMSG_NOOP, 0, 0,
null, 500);
}
break;
case MSG_MEDIA_SERVER_STARTED:
Log.e(TAG, "Media server started.");
// indicate to audio HAL that we start the reconfiguration phase after a media
// server crash
// Note that MSG_MEDIA_SERVER_STARTED message is only received when the media server
// process restarts after a crash, not the first time it is started.
AudioSystem.setParameters("restarting=true");
// Restore device connection states
synchronized (mConnectedDevices) {
Set set = mConnectedDevices.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry device = (Map.Entry)i.next();
AudioSystem.setDeviceConnectionState(
((Integer)device.getKey()).intValue(),
AudioSystem.DEVICE_STATE_AVAILABLE,
(String)device.getValue());
}
}
// Restore call state
AudioSystem.setPhoneState(mMode);
// Restore forced usage for communcations and record
AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm);
AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm);
// Restore stream volumes
int numStreamTypes = AudioSystem.getNumStreamTypes();
for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
VolumeStreamState streamState = mStreamStates[streamType];
AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10);
streamState.applyAllVolumes();
}
// Restore ringer mode
setRingerModeInt(getRingerMode(), false);
// Restore master volume
restoreMasterVolume();
// Reset device orientation (if monitored for this device)
if (SystemProperties.getBoolean("ro.audio.monitorOrientation", false)) {
setOrientationForAudioSystem();
}
synchronized (mBluetoothA2dpEnabledLock) {
AudioSystem.setForceUse(AudioSystem.FOR_MEDIA,
mBluetoothA2dpEnabled ?
AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP);
}
// indicate the end of reconfiguration phase to audio HAL
AudioSystem.setParameters("restarting=false");
break;
case MSG_LOAD_SOUND_EFFECTS:
loadSoundEffects();
break;
case MSG_PLAY_SOUND_EFFECT:
playSoundEffect(msg.arg1, msg.arg2);
break;
case MSG_BTA2DP_DOCK_TIMEOUT:
// msg.obj == address of BTA2DP device
synchronized (mConnectedDevices) {
makeA2dpDeviceUnavailableNow( (String) msg.obj );
}
break;
case MSG_SET_FORCE_USE:
setForceUse(msg.arg1, msg.arg2);
break;
case MSG_PERSIST_MEDIABUTTONRECEIVER:
onHandlePersistMediaButtonReceiver( (ComponentName) msg.obj );
break;
case MSG_RCDISPLAY_CLEAR:
onRcDisplayClear();
break;
case MSG_RCDISPLAY_UPDATE:
// msg.obj is guaranteed to be non null
onRcDisplayUpdate( (RemoteControlStackEntry) msg.obj, msg.arg1);
break;
case MSG_BT_HEADSET_CNCT_FAILED:
resetBluetoothSco();
break;
case MSG_SET_WIRED_DEVICE_CONNECTION_STATE:
onSetWiredDeviceConnectionState(msg.arg1, msg.arg2, (String)msg.obj);
mMediaEventWakeLock.release();
break;
case MSG_SET_A2DP_CONNECTION_STATE:
onSetA2dpConnectionState((BluetoothDevice)msg.obj, msg.arg1);
mMediaEventWakeLock.release();
break;
case MSG_REPORT_NEW_ROUTES: {
int N = mRoutesObservers.beginBroadcast();
if (N > 0) {
AudioRoutesInfo routes;
synchronized (mCurAudioRoutes) {
routes = new AudioRoutesInfo(mCurAudioRoutes);
}
while (N > 0) {
N--;
IAudioRoutesObserver obs = mRoutesObservers.getBroadcastItem(N);
try {
obs.dispatchAudioRoutesChanged(routes);
} catch (RemoteException e) {
}
}
}
mRoutesObservers.finishBroadcast();
break;
}
case MSG_REEVALUATE_REMOTE:
onReevaluateRemote();
break;
case MSG_RCC_NEW_PLAYBACK_INFO:
onNewPlaybackInfoForRcc(msg.arg1 /* rccId */, msg.arg2 /* key */,
((Integer)msg.obj).intValue() /* value */);
break;
case MSG_RCC_NEW_VOLUME_OBS:
onRegisterVolumeObserverForRcc(msg.arg1 /* rccId */,
(IRemoteVolumeObserver)msg.obj /* rvo */);
break;
}
}
}
private class SettingsObserver extends ContentObserver {
SettingsObserver() {
super(new Handler());
mContentResolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this);
mContentResolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.VOLUME_LINK_NOTIFICATION), false, this);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
// FIXME This synchronized is not necessary if mSettingsLock only protects mRingerMode.
// However there appear to be some missing locks around mRingerModeMutedStreams
// and mRingerModeAffectedStreams, so will leave this synchronized for now.
// mRingerModeMutedStreams and mMuteAffectedStreams are safe (only accessed once).
synchronized (mSettingsLock) {
int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver,
Settings.System.MODE_RINGER_STREAMS_AFFECTED,
((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
(1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)));
if (mVoiceCapable) {
ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC);
} else {
ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC);
}
if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
/*
* Ensure all stream types that should be affected by ringer mode
* are in the proper state.
*/
mRingerModeAffectedStreams = ringerModeAffectedStreams;
setRingerModeInt(getRingerMode(), false);
}
boolean linkNotificationWithVolume = Settings.System.getInt(mContentResolver,
Settings.System.VOLUME_LINK_NOTIFICATION, 1) == 1;
if (linkNotificationWithVolume) {
STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
STREAM_VOLUME_ALIAS_NON_VOICE[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
} else {
STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION;
STREAM_VOLUME_ALIAS_NON_VOICE[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION;
}
updateStreamVolumeAlias(false);
}
}
}
// must be called synchronized on mConnectedDevices
private void makeA2dpDeviceAvailable(String address) {
// enable A2DP before notifying A2DP connection to avoid unecessary processing in
// audio policy manager
setBluetoothA2dpOnInt(true);
AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
AudioSystem.DEVICE_STATE_AVAILABLE,
address);
// Reset A2DP suspend state each time a new sink is connected
AudioSystem.setParameters("A2dpSuspended=false");
mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP),
address);
}
private void sendBecomingNoisyIntent() {
mContext.sendBroadcast(new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
}
// must be called synchronized on mConnectedDevices
private void makeA2dpDeviceUnavailableNow(String address) {
if (noDelayInATwoDP)
sendBecomingNoisyIntent();
AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
AudioSystem.DEVICE_STATE_UNAVAILABLE,
address);
mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
}
// must be called synchronized on mConnectedDevices
private void makeA2dpDeviceUnavailableLater(String address) {
// prevent any activity on the A2DP audio output to avoid unwanted
// reconnection of the sink.
AudioSystem.setParameters("A2dpSuspended=true");
// the device will be made unavailable later, so consider it disconnected right away
mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
// send the delayed message to make the device unavailable later
Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address);
mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS);
}
// must be called synchronized on mConnectedDevices
private void cancelA2dpDeviceTimeout() {
mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT);
}
// must be called synchronized on mConnectedDevices
private boolean hasScheduledA2dpDockTimeout() {
return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT);
}
private void onSetA2dpConnectionState(BluetoothDevice btDevice, int state)
{
if (btDevice == null) {
return;
}
String address = btDevice.getAddress();
if (!BluetoothAdapter.checkBluetoothAddress(address)) {
address = "";
}
synchronized (mConnectedDevices) {
boolean isConnected =
(mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) &&
mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP).equals(address));
if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
if (btDevice.isBluetoothDock()) {
if (state == BluetoothProfile.STATE_DISCONNECTED) {
// introduction of a delay for transient disconnections of docks when
// power is rapidly turned off/on, this message will be canceled if
// we reconnect the dock under a preset delay
makeA2dpDeviceUnavailableLater(address);
// the next time isConnected is evaluated, it will be false for the dock
}
} else {
makeA2dpDeviceUnavailableNow(address);
}
synchronized (mCurAudioRoutes) {
if (mCurAudioRoutes.mBluetoothName != null) {
mCurAudioRoutes.mBluetoothName = null;
sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
SENDMSG_NOOP, 0, 0, null, 0);
}
}
} else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
if (btDevice.isBluetoothDock()) {
// this could be a reconnection after a transient disconnection
cancelA2dpDeviceTimeout();
mDockAddress = address;
} else {
// this could be a connection of another A2DP device before the timeout of
// a dock: cancel the dock timeout, and make the dock unavailable now
if(hasScheduledA2dpDockTimeout()) {
cancelA2dpDeviceTimeout();
makeA2dpDeviceUnavailableNow(mDockAddress);
}
}
makeA2dpDeviceAvailable(address);
synchronized (mCurAudioRoutes) {
String name = btDevice.getAliasName();
if (!TextUtils.equals(mCurAudioRoutes.mBluetoothName, name)) {
mCurAudioRoutes.mBluetoothName = name;
sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
SENDMSG_NOOP, 0, 0, null, 0);
}
}
}
}
}
private boolean handleDeviceConnection(boolean connected, int device, String params) {
synchronized (mConnectedDevices) {
boolean isConnected = (mConnectedDevices.containsKey(device) &&
(params.isEmpty() || mConnectedDevices.get(device).equals(params)));
if (isConnected && !connected) {
AudioSystem.setDeviceConnectionState(device,
AudioSystem.DEVICE_STATE_UNAVAILABLE,
mConnectedDevices.get(device));
mConnectedDevices.remove(device);
return true;
} else if (!isConnected && connected) {
AudioSystem.setDeviceConnectionState(device,
AudioSystem.DEVICE_STATE_AVAILABLE,
params);
mConnectedDevices.put(new Integer(device), params);
return true;
}
}
return false;
}
// Devices which removal triggers intent ACTION_AUDIO_BECOMING_NOISY. The intent is only
// sent if none of these devices is connected.
int mBecomingNoisyIntentDevices =
AudioSystem.DEVICE_OUT_WIRED_HEADSET | AudioSystem.DEVICE_OUT_WIRED_HEADPHONE |
AudioSystem.DEVICE_OUT_ALL_A2DP;
// must be called before removing the device from mConnectedDevices
private int checkSendBecomingNoisyIntent(int device, int state) {
int delay = 0;
if ((state == 0) && ((device & mBecomingNoisyIntentDevices) != 0)) {
int devices = 0;
for (int dev : mConnectedDevices.keySet()) {
if ((dev & mBecomingNoisyIntentDevices) != 0) {
devices |= dev;
}
}
if (devices == device) {
delay = 1000;
sendBecomingNoisyIntent();
}
}
if (mAudioHandler.hasMessages(MSG_SET_A2DP_CONNECTION_STATE) ||
mAudioHandler.hasMessages(MSG_SET_WIRED_DEVICE_CONNECTION_STATE)) {
delay = 1000;
}
return delay;
}
private void sendDeviceConnectionIntent(int device, int state, String name)
{
Intent intent = new Intent();
intent.putExtra("state", state);
intent.putExtra("name", name);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
int connType = 0;
if (device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) {
connType = AudioRoutesInfo.MAIN_HEADSET;
intent.setAction(Intent.ACTION_HEADSET_PLUG);
intent.putExtra("microphone", 1);
} else if (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE) {
connType = AudioRoutesInfo.MAIN_HEADPHONES;
intent.setAction(Intent.ACTION_HEADSET_PLUG);
intent.putExtra("microphone", 0);
} else if (device == AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET) {
connType = AudioRoutesInfo.MAIN_DOCK_SPEAKERS;
intent.setAction(Intent.ACTION_ANALOG_AUDIO_DOCK_PLUG);
} else if (device == AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET) {
connType = AudioRoutesInfo.MAIN_DOCK_SPEAKERS;
intent.setAction(Intent.ACTION_DIGITAL_AUDIO_DOCK_PLUG);
} else if (device == AudioSystem.DEVICE_OUT_AUX_DIGITAL) {
connType = AudioRoutesInfo.MAIN_HDMI;
intent.setAction(Intent.ACTION_HDMI_AUDIO_PLUG);
}
synchronized (mCurAudioRoutes) {
if (connType != 0) {
int newConn = mCurAudioRoutes.mMainType;
if (state != 0) {
newConn |= connType;
} else {
newConn &= ~connType;
}
if (newConn != mCurAudioRoutes.mMainType) {
mCurAudioRoutes.mMainType = newConn;
sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES,
SENDMSG_NOOP, 0, 0, null, 0);
}
}
}
ActivityManagerNative.broadcastStickyIntent(intent, null);
}
private void onSetWiredDeviceConnectionState(int device, int state, String name)
{
synchronized (mConnectedDevices) {
if ((state == 0) && ((device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) ||
(device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE))) {
setBluetoothA2dpOnInt(true);
}
handleDeviceConnection((state == 1), device, "");
if ((state != 0) && ((device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) ||
(device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE))) {
setBluetoothA2dpOnInt(false);
}
sendDeviceConnectionIntent(device, state, name);
}
}
/* cache of the address of the last dock the device was connected to */
private String mDockAddress;
/**
* Receiver for misc intent broadcasts the Phone app cares about.
*/
private class AudioServiceBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int device;
int state;
if (action.equals(Intent.ACTION_DOCK_EVENT)) {
int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
Intent.EXTRA_DOCK_STATE_UNDOCKED);
int config;
switch (dockState) {
case Intent.EXTRA_DOCK_STATE_DESK:
config = AudioSystem.FORCE_BT_DESK_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_CAR:
config = AudioSystem.FORCE_BT_CAR_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_LE_DESK:
config = AudioSystem.FORCE_ANALOG_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_HE_DESK:
config = AudioSystem.FORCE_DIGITAL_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_UNDOCKED:
default:
config = AudioSystem.FORCE_NONE;
}
AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
} else if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED) && noDelayInATwoDP) {
state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
BluetoothProfile.STATE_DISCONNECTED);
BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
onSetA2dpConnectionState(btDevice, state);
} else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
BluetoothProfile.STATE_DISCONNECTED);
device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
String address = null;
BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (btDevice == null) {
return;
}
address = btDevice.getAddress();
BluetoothClass btClass = btDevice.getBluetoothClass();
if (btClass != null) {
switch (btClass.getDeviceClass()) {
case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
break;
case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
break;
}
}
if (!BluetoothAdapter.checkBluetoothAddress(address)) {
address = "";
}
boolean connected = (state == BluetoothProfile.STATE_CONNECTED);
if (handleDeviceConnection(connected, device, address)) {
synchronized (mScoClients) {
if (connected) {
mBluetoothHeadsetDevice = btDevice;
} else {
mBluetoothHeadsetDevice = null;
resetBluetoothSco();
}
}
}
} else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
//Save and restore volumes for headset and speaker
state = intent.getIntExtra("state", 0);
int lastVolume;
if (state == 1) {
//avoids connection glitches
if (noDelayInATwoDP)
setBluetoothA2dpOnInt(false);
// Headset plugged in
// Avoid connection glitches
// Volume restore capping
final boolean capVolumeRestore = Settings.System.getInt(mContentResolver,
Settings.System.SAFE_HEADSET_VOLUME_RESTORE, 1) == 1;
if (capVolumeRestore) {
for (int stream = 0; stream < AudioSystem.getNumStreamTypes(); stream++) {
if (stream == mStreamVolumeAlias[stream]) {
final int volume = getStreamVolume(stream);
final int restoreCap = rescaleIndex(HEADSET_VOLUME_RESTORE_CAP,
AudioSystem.STREAM_MUSIC, stream);
if (volume > restoreCap) {
setStreamVolume(stream, restoreCap, 0);
}
}
}
}
} else {
+ //avoid connection glitches
+ if (noDelayInATwoDP)
+ setBluetoothA2dpOnInt(true);
// Headset disconnected
}
} else if (action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) ||
action.equals(Intent.ACTION_USB_AUDIO_DEVICE_PLUG)) {
state = intent.getIntExtra("state", 0);
int alsaCard = intent.getIntExtra("card", -1);
int alsaDevice = intent.getIntExtra("device", -1);
String params = (alsaCard == -1 && alsaDevice == -1 ? ""
: "card=" + alsaCard + ";device=" + alsaDevice);
device = action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) ?
AudioSystem.DEVICE_OUT_USB_ACCESSORY : AudioSystem.DEVICE_OUT_USB_DEVICE;
Log.v(TAG, "Broadcast Receiver: Got "
+ (action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) ?
"ACTION_USB_AUDIO_ACCESSORY_PLUG" : "ACTION_USB_AUDIO_DEVICE_PLUG")
+ ", state = " + state + ", card: " + alsaCard + ", device: " + alsaDevice);
handleDeviceConnection((state == 1), device, params);
} else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
boolean broadcast = false;
int scoAudioState = AudioManager.SCO_AUDIO_STATE_ERROR;
synchronized (mScoClients) {
int btState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
// broadcast intent if the connection was initated by AudioService
if (!mScoClients.isEmpty() &&
(mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
broadcast = true;
}
switch (btState) {
case BluetoothHeadset.STATE_AUDIO_CONNECTED:
scoAudioState = AudioManager.SCO_AUDIO_STATE_CONNECTED;
if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
}
break;
case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
scoAudioState = AudioManager.SCO_AUDIO_STATE_DISCONNECTED;
mScoAudioState = SCO_STATE_INACTIVE;
clearAllScoClients(0, false);
break;
case BluetoothHeadset.STATE_AUDIO_CONNECTING:
if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
}
default:
// do not broadcast CONNECTING or invalid state
broadcast = false;
break;
}
}
if (broadcast) {
broadcastScoConnectionState(scoAudioState);
//FIXME: this is to maintain compatibility with deprecated intent
// AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, scoAudioState);
mContext.sendStickyBroadcast(newIntent);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
mBootCompleted = true;
sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_NOOP,
0, 0, null, 0);
mKeyguardManager =
(KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
mScoConnectionState = AudioManager.SCO_AUDIO_STATE_ERROR;
resetBluetoothSco();
getBluetoothHeadset();
//FIXME: this is to maintain compatibility with deprecated intent
// AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,
AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
mContext.sendStickyBroadcast(newIntent);
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null) {
adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
BluetoothProfile.A2DP);
}
} else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
// a package is being removed, not replaced
String packageName = intent.getData().getSchemeSpecificPart();
if (packageName != null) {
removeMediaButtonReceiverForPackage(packageName);
}
}
} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
AudioSystem.setParameters("screen_state=on");
} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
AudioSystem.setParameters("screen_state=off");
} else if (action.equalsIgnoreCase(Intent.ACTION_CONFIGURATION_CHANGED)) {
handleConfigurationChanged(context);
}
}
}
private void showVolumeChangeUi(final int streamType, final int flags) {
if (mUiContext != null && mVolumePanel != null) {
mVolumePanel.postVolumeChanged(streamType, flags);
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
if (mUiContext == null) {
mUiContext = ThemeUtils.createUiContext(mContext);
}
final Context context = mUiContext != null ? mUiContext : mContext;
mVolumePanel = new VolumePanel(context, AudioService.this);
mVolumePanel.postVolumeChanged(streamType, flags);
}
});
}
}
//==========================================================================================
// AudioFocus
//==========================================================================================
/* constant to identify focus stack entry that is used to hold the focus while the phone
* is ringing or during a call. Used by com.android.internal.telephony.CallManager when
* entering and exiting calls.
*/
public final static String IN_VOICE_COMM_FOCUS_ID = "AudioFocus_For_Phone_Ring_And_Calls";
private final static Object mAudioFocusLock = new Object();
private final static Object mRingingLock = new Object();
private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//Log.v(TAG, " CALL_STATE_RINGING");
synchronized(mRingingLock) {
mIsRinging = true;
}
} else if ((state == TelephonyManager.CALL_STATE_OFFHOOK)
|| (state == TelephonyManager.CALL_STATE_IDLE)) {
synchronized(mRingingLock) {
mIsRinging = false;
}
}
}
};
private void notifyTopOfAudioFocusStack() {
// notify the top of the stack it gained focus
if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
if (canReassignAudioFocus()) {
try {
mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
AudioManager.AUDIOFOCUS_GAIN, mFocusStack.peek().mClientId);
} catch (RemoteException e) {
Log.e(TAG, "Failure to signal gain of audio control focus due to "+ e);
e.printStackTrace();
}
}
}
}
private static class FocusStackEntry {
public int mStreamType = -1;// no stream type
public IAudioFocusDispatcher mFocusDispatcher = null;
public IBinder mSourceRef = null;
public String mClientId;
public int mFocusChangeType;
public AudioFocusDeathHandler mHandler;
public String mPackageName;
public int mCallingUid;
public FocusStackEntry() {
}
public FocusStackEntry(int streamType, int duration,
IAudioFocusDispatcher afl, IBinder source, String id, AudioFocusDeathHandler hdlr,
String pn, int uid) {
mStreamType = streamType;
mFocusDispatcher = afl;
mSourceRef = source;
mClientId = id;
mFocusChangeType = duration;
mHandler = hdlr;
mPackageName = pn;
mCallingUid = uid;
}
public void unlinkToDeath() {
try {
if (mSourceRef != null && mHandler != null) {
mSourceRef.unlinkToDeath(mHandler, 0);
mHandler = null;
}
} catch (java.util.NoSuchElementException e) {
Log.e(TAG, "Encountered " + e + " in FocusStackEntry.unlinkToDeath()");
}
}
@Override
protected void finalize() throws Throwable {
unlinkToDeath(); // unlink exception handled inside method
super.finalize();
}
}
private final Stack<FocusStackEntry> mFocusStack = new Stack<FocusStackEntry>();
/**
* Helper function:
* Display in the log the current entries in the audio focus stack
*/
private void dumpFocusStack(PrintWriter pw) {
pw.println("\nAudio Focus stack entries:");
synchronized(mAudioFocusLock) {
Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
while(stackIterator.hasNext()) {
FocusStackEntry fse = stackIterator.next();
pw.println(" source:" + fse.mSourceRef + " -- client: " + fse.mClientId
+ " -- duration: " + fse.mFocusChangeType
+ " -- uid: " + fse.mCallingUid);
}
}
}
/**
* Helper function:
* Called synchronized on mAudioFocusLock
* Remove a focus listener from the focus stack.
* @param focusListenerToRemove the focus listener
* @param signal if true and the listener was at the top of the focus stack, i.e. it was holding
* focus, notify the next item in the stack it gained focus.
*/
private void removeFocusStackEntry(String clientToRemove, boolean signal) {
// is the current top of the focus stack abandoning focus? (because of request, not death)
if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientToRemove))
{
//Log.i(TAG, " removeFocusStackEntry() removing top of stack");
FocusStackEntry fse = mFocusStack.pop();
fse.unlinkToDeath();
if (signal) {
// notify the new top of the stack it gained focus
notifyTopOfAudioFocusStack();
// there's a new top of the stack, let the remote control know
synchronized(mRCStack) {
checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
}
}
} else {
// focus is abandoned by a client that's not at the top of the stack,
// no need to update focus.
Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
while(stackIterator.hasNext()) {
FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
if(fse.mClientId.equals(clientToRemove)) {
Log.i(TAG, " AudioFocus abandonAudioFocus(): removing entry for "
+ fse.mClientId);
stackIterator.remove();
fse.unlinkToDeath();
}
}
}
}
/**
* Helper function:
* Called synchronized on mAudioFocusLock
* Remove focus listeners from the focus stack for a particular client when it has died.
*/
private void removeFocusStackEntryForClient(IBinder cb) {
// is the owner of the audio focus part of the client to remove?
boolean isTopOfStackForClientToRemove = !mFocusStack.isEmpty() &&
mFocusStack.peek().mSourceRef.equals(cb);
Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
while(stackIterator.hasNext()) {
FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
if(fse.mSourceRef.equals(cb)) {
Log.i(TAG, " AudioFocus abandonAudioFocus(): removing entry for "
+ fse.mClientId);
stackIterator.remove();
// the client just died, no need to unlink to its death
}
}
if (isTopOfStackForClientToRemove) {
// we removed an entry at the top of the stack:
// notify the new top of the stack it gained focus.
notifyTopOfAudioFocusStack();
// there's a new top of the stack, let the remote control know
synchronized(mRCStack) {
checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
}
}
}
/**
* Helper function:
* Returns true if the system is in a state where the focus can be reevaluated, false otherwise.
*/
private boolean canReassignAudioFocus() {
// focus requests are rejected during a phone call or when the phone is ringing
// this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus
if (!mFocusStack.isEmpty() && IN_VOICE_COMM_FOCUS_ID.equals(mFocusStack.peek().mClientId)) {
return false;
}
return true;
}
/**
* Inner class to monitor audio focus client deaths, and remove them from the audio focus
* stack if necessary.
*/
private class AudioFocusDeathHandler implements IBinder.DeathRecipient {
private IBinder mCb; // To be notified of client's death
AudioFocusDeathHandler(IBinder cb) {
mCb = cb;
}
public void binderDied() {
synchronized(mAudioFocusLock) {
Log.w(TAG, " AudioFocus audio focus client died");
removeFocusStackEntryForClient(mCb);
}
}
public IBinder getBinder() {
return mCb;
}
}
/** @see AudioManager#requestAudioFocus(IAudioFocusDispatcher, int, int) */
public int requestAudioFocus(int mainStreamType, int focusChangeHint, IBinder cb,
IAudioFocusDispatcher fd, String clientId, String callingPackageName) {
Log.i(TAG, " AudioFocus requestAudioFocus() from " + clientId);
// the main stream type for the audio focus request is currently not used. It may
// potentially be used to handle multiple stream type-dependent audio focuses.
// we need a valid binder callback for clients
if (!cb.pingBinder()) {
Log.e(TAG, " AudioFocus DOA client for requestAudioFocus(), aborting.");
return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
}
synchronized(mAudioFocusLock) {
if (!canReassignAudioFocus()) {
return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
}
// handle the potential premature death of the new holder of the focus
// (premature death == death before abandoning focus)
// Register for client death notification
AudioFocusDeathHandler afdh = new AudioFocusDeathHandler(cb);
try {
cb.linkToDeath(afdh, 0);
} catch (RemoteException e) {
// client has already died!
Log.w(TAG, "AudioFocus requestAudioFocus() could not link to "+cb+" binder death");
return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
}
if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientId)) {
// if focus is already owned by this client and the reason for acquiring the focus
// hasn't changed, don't do anything
if (mFocusStack.peek().mFocusChangeType == focusChangeHint) {
// unlink death handler so it can be gc'ed.
// linkToDeath() creates a JNI global reference preventing collection.
cb.unlinkToDeath(afdh, 0);
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
// the reason for the audio focus request has changed: remove the current top of
// stack and respond as if we had a new focus owner
FocusStackEntry fse = mFocusStack.pop();
fse.unlinkToDeath();
}
// notify current top of stack it is losing focus
if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
try {
mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
-1 * focusChangeHint, // loss and gain codes are inverse of each other
mFocusStack.peek().mClientId);
} catch (RemoteException e) {
Log.e(TAG, " Failure to signal loss of focus due to "+ e);
e.printStackTrace();
}
}
// focus requester might already be somewhere below in the stack, remove it
removeFocusStackEntry(clientId, false /* signal */);
// push focus requester at the top of the audio focus stack
mFocusStack.push(new FocusStackEntry(mainStreamType, focusChangeHint, fd, cb,
clientId, afdh, callingPackageName, Binder.getCallingUid()));
// there's a new top of the stack, let the remote control know
synchronized(mRCStack) {
checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
}
}//synchronized(mAudioFocusLock)
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
/** @see AudioManager#abandonAudioFocus(IAudioFocusDispatcher) */
public int abandonAudioFocus(IAudioFocusDispatcher fl, String clientId) {
Log.i(TAG, " AudioFocus abandonAudioFocus() from " + clientId);
try {
// this will take care of notifying the new focus owner if needed
synchronized(mAudioFocusLock) {
removeFocusStackEntry(clientId, true);
}
} catch (java.util.ConcurrentModificationException cme) {
// Catching this exception here is temporary. It is here just to prevent
// a crash seen when the "Silent" notification is played. This is believed to be fixed
// but this try catch block is left just to be safe.
Log.e(TAG, "FATAL EXCEPTION AudioFocus abandonAudioFocus() caused " + cme);
cme.printStackTrace();
}
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
public void unregisterAudioFocusClient(String clientId) {
synchronized(mAudioFocusLock) {
removeFocusStackEntry(clientId, false);
}
}
//==========================================================================================
// RemoteControl
//==========================================================================================
public void dispatchMediaKeyEvent(KeyEvent keyEvent) {
filterMediaKeyEvent(keyEvent, false /*needWakeLock*/);
}
public void dispatchMediaKeyEventUnderWakelock(KeyEvent keyEvent) {
filterMediaKeyEvent(keyEvent, true /*needWakeLock*/);
}
private void filterMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
// sanity check on the incoming key event
if (!isValidMediaKeyEvent(keyEvent)) {
Log.e(TAG, "not dispatching invalid media key event " + keyEvent);
return;
}
// event filtering for telephony
synchronized(mRingingLock) {
synchronized(mRCStack) {
if ((mMediaReceiverForCalls != null) &&
(mIsRinging || (getMode() == AudioSystem.MODE_IN_CALL))) {
dispatchMediaKeyEventForCalls(keyEvent, needWakeLock);
return;
}
}
}
// event filtering based on voice-based interactions
if (isValidVoiceInputKeyCode(keyEvent.getKeyCode())) {
filterVoiceInputKeyEvent(keyEvent, needWakeLock);
} else {
dispatchMediaKeyEvent(keyEvent, needWakeLock);
}
}
/**
* Handles the dispatching of the media button events to the telephony package.
* Precondition: mMediaReceiverForCalls != null
* @param keyEvent a non-null KeyEvent whose key code is one of the supported media buttons
* @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held while this key event
* is dispatched.
*/
private void dispatchMediaKeyEventForCalls(KeyEvent keyEvent, boolean needWakeLock) {
Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
keyIntent.setPackage(mMediaReceiverForCalls.getPackageName());
if (needWakeLock) {
mMediaEventWakeLock.acquire();
keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED, WAKELOCK_RELEASE_ON_FINISHED);
}
mContext.sendOrderedBroadcast(keyIntent, null, mKeyEventDone,
mAudioHandler, Activity.RESULT_OK, null, null);
}
/**
* Handles the dispatching of the media button events to one of the registered listeners,
* or if there was none, broadcast an ACTION_MEDIA_BUTTON intent to the rest of the system.
* @param keyEvent a non-null KeyEvent whose key code is one of the supported media buttons
* @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held while this key event
* is dispatched.
*/
private void dispatchMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
if (needWakeLock) {
mMediaEventWakeLock.acquire();
}
Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
synchronized(mRCStack) {
if (!mRCStack.empty()) {
// send the intent that was registered by the client
try {
mRCStack.peek().mMediaIntent.send(mContext,
needWakeLock ? WAKELOCK_RELEASE_ON_FINISHED : 0 /*code*/,
keyIntent, AudioService.this, mAudioHandler);
} catch (CanceledException e) {
Log.e(TAG, "Error sending pending intent " + mRCStack.peek());
e.printStackTrace();
}
} else {
// legacy behavior when nobody registered their media button event receiver
// through AudioManager
if (needWakeLock) {
keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED, WAKELOCK_RELEASE_ON_FINISHED);
}
mContext.sendOrderedBroadcast(keyIntent, null, mKeyEventDone,
mAudioHandler, Activity.RESULT_OK, null, null);
}
}
}
/**
* The different actions performed in response to a voice button key event.
*/
private final static int VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS = 1;
private final static int VOICEBUTTON_ACTION_START_VOICE_INPUT = 2;
private final static int VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS = 3;
private final Object mVoiceEventLock = new Object();
private boolean mVoiceButtonDown;
private boolean mVoiceButtonHandled;
/**
* Filter key events that may be used for voice-based interactions
* @param keyEvent a non-null KeyEvent whose key code is that of one of the supported
* media buttons that can be used to trigger voice-based interactions.
* @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held while this key event
* is dispatched.
*/
private void filterVoiceInputKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
if (DEBUG_RC) {
Log.v(TAG, "voice input key event: " + keyEvent + ", needWakeLock=" + needWakeLock);
}
int voiceButtonAction = VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS;
int keyAction = keyEvent.getAction();
synchronized (mVoiceEventLock) {
if (keyAction == KeyEvent.ACTION_DOWN) {
if (keyEvent.getRepeatCount() == 0) {
// initial down
mVoiceButtonDown = true;
mVoiceButtonHandled = false;
} else if (mVoiceButtonDown && !mVoiceButtonHandled
&& (keyEvent.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
// long-press, start voice-based interactions
mVoiceButtonHandled = true;
voiceButtonAction = VOICEBUTTON_ACTION_START_VOICE_INPUT;
}
} else if (keyAction == KeyEvent.ACTION_UP) {
if (mVoiceButtonDown) {
// voice button up
mVoiceButtonDown = false;
if (!mVoiceButtonHandled && !keyEvent.isCanceled()) {
voiceButtonAction = VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS;
}
}
}
}//synchronized (mVoiceEventLock)
// take action after media button event filtering for voice-based interactions
switch (voiceButtonAction) {
case VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS:
if (DEBUG_RC) Log.v(TAG, " ignore key event");
break;
case VOICEBUTTON_ACTION_START_VOICE_INPUT:
if (DEBUG_RC) Log.v(TAG, " start voice-based interactions");
// then start the voice-based interactions
startVoiceBasedInteractions(needWakeLock);
break;
case VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS:
if (DEBUG_RC) Log.v(TAG, " send simulated key event");
sendSimulatedMediaButtonEvent(keyEvent, needWakeLock);
break;
}
}
private void sendSimulatedMediaButtonEvent(KeyEvent originalKeyEvent, boolean needWakeLock) {
// send DOWN event
KeyEvent keyEvent = KeyEvent.changeAction(originalKeyEvent, KeyEvent.ACTION_DOWN);
dispatchMediaKeyEvent(keyEvent, needWakeLock);
// send UP event
keyEvent = KeyEvent.changeAction(originalKeyEvent, KeyEvent.ACTION_UP);
dispatchMediaKeyEvent(keyEvent, needWakeLock);
}
private static boolean isValidMediaKeyEvent(KeyEvent keyEvent) {
if (keyEvent == null) {
return false;
}
final int keyCode = keyEvent.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_MUTE:
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_MEDIA_PLAY:
case KeyEvent.KEYCODE_MEDIA_PAUSE:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_MEDIA_STOP:
case KeyEvent.KEYCODE_MEDIA_NEXT:
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
case KeyEvent.KEYCODE_MEDIA_REWIND:
case KeyEvent.KEYCODE_MEDIA_RECORD:
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
case KeyEvent.KEYCODE_MEDIA_CLOSE:
case KeyEvent.KEYCODE_MEDIA_EJECT:
break;
default:
return false;
}
return true;
}
/**
* Checks whether the given key code is one that can trigger the launch of voice-based
* interactions.
* @param keyCode the key code associated with the key event
* @return true if the key is one of the supported voice-based interaction triggers
*/
private static boolean isValidVoiceInputKeyCode(int keyCode) {
if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK) {
return true;
} else {
return false;
}
}
/**
* Tell the system to start voice-based interactions / voice commands
*/
private void startVoiceBasedInteractions(boolean needWakeLock) {
Intent voiceIntent = null;
// select which type of search to launch:
// - screen on and device unlocked: action is ACTION_WEB_SEARCH
// - device locked or screen off: action is ACTION_VOICE_SEARCH_HANDS_FREE
// with EXTRA_SECURE set to true if the device is securely locked
PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
boolean isLocked = mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
if (!isLocked && pm.isScreenOn()) {
voiceIntent = new Intent(android.speech.RecognizerIntent.ACTION_WEB_SEARCH);
} else {
voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE,
isLocked && mKeyguardManager.isKeyguardSecure());
}
// start the search activity
if (needWakeLock) {
mMediaEventWakeLock.acquire();
}
try {
if (voiceIntent != null) {
voiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
mContext.startActivity(voiceIntent);
}
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity for search: " + e);
} finally {
if (needWakeLock) {
mMediaEventWakeLock.release();
}
}
}
private PowerManager.WakeLock mMediaEventWakeLock;
private static final int WAKELOCK_RELEASE_ON_FINISHED = 1980; //magic number
// only set when wakelock was acquired, no need to check value when received
private static final String EXTRA_WAKELOCK_ACQUIRED =
"android.media.AudioService.WAKELOCK_ACQUIRED";
public void onSendFinished(PendingIntent pendingIntent, Intent intent,
int resultCode, String resultData, Bundle resultExtras) {
if (resultCode == WAKELOCK_RELEASE_ON_FINISHED) {
mMediaEventWakeLock.release();
}
}
BroadcastReceiver mKeyEventDone = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (intent == null) {
return;
}
Bundle extras = intent.getExtras();
if (extras == null) {
return;
}
if (extras.containsKey(EXTRA_WAKELOCK_ACQUIRED)) {
mMediaEventWakeLock.release();
}
}
};
private final Object mCurrentRcLock = new Object();
/**
* The one remote control client which will receive a request for display information.
* This object may be null.
* Access protected by mCurrentRcLock.
*/
private IRemoteControlClient mCurrentRcClient = null;
private final static int RC_INFO_NONE = 0;
private final static int RC_INFO_ALL =
RemoteControlClient.FLAG_INFORMATION_REQUEST_ALBUM_ART |
RemoteControlClient.FLAG_INFORMATION_REQUEST_KEY_MEDIA |
RemoteControlClient.FLAG_INFORMATION_REQUEST_METADATA |
RemoteControlClient.FLAG_INFORMATION_REQUEST_PLAYSTATE;
/**
* A monotonically increasing generation counter for mCurrentRcClient.
* Only accessed with a lock on mCurrentRcLock.
* No value wrap-around issues as we only act on equal values.
*/
private int mCurrentRcClientGen = 0;
/**
* Inner class to monitor remote control client deaths, and remove the client for the
* remote control stack if necessary.
*/
private class RcClientDeathHandler implements IBinder.DeathRecipient {
private IBinder mCb; // To be notified of client's death
private PendingIntent mMediaIntent;
RcClientDeathHandler(IBinder cb, PendingIntent pi) {
mCb = cb;
mMediaIntent = pi;
}
public void binderDied() {
Log.w(TAG, " RemoteControlClient died");
// remote control client died, make sure the displays don't use it anymore
// by setting its remote control client to null
registerRemoteControlClient(mMediaIntent, null/*rcClient*/, null/*ignored*/);
// the dead client was maybe handling remote playback, reevaluate
postReevaluateRemote();
}
public IBinder getBinder() {
return mCb;
}
}
/**
* A global counter for RemoteControlClient identifiers
*/
private static int sLastRccId = 0;
private class RemotePlaybackState {
int mRccId;
int mVolume;
int mVolumeMax;
int mVolumeHandling;
private RemotePlaybackState(int id, int vol, int volMax) {
mRccId = id;
mVolume = vol;
mVolumeMax = volMax;
mVolumeHandling = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME_HANDLING;
}
}
/**
* Internal cache for the playback information of the RemoteControlClient whose volume gets to
* be controlled by the volume keys ("main"), so we don't have to iterate over the RC stack
* every time we need this info.
*/
private RemotePlaybackState mMainRemote;
/**
* Indicates whether the "main" RemoteControlClient is considered active.
* Use synchronized on mMainRemote.
*/
private boolean mMainRemoteIsActive;
/**
* Indicates whether there is remote playback going on. True even if there is no "active"
* remote playback (mMainRemoteIsActive is false), but a RemoteControlClient has declared it
* handles remote playback.
* Use synchronized on mMainRemote.
*/
private boolean mHasRemotePlayback;
private static class RemoteControlStackEntry {
public int mRccId = RemoteControlClient.RCSE_ID_UNREGISTERED;
/**
* The target for the ACTION_MEDIA_BUTTON events.
* Always non null.
*/
public PendingIntent mMediaIntent;
/**
* The registered media button event receiver.
* Always non null.
*/
public ComponentName mReceiverComponent;
public String mCallingPackageName;
public int mCallingUid;
/**
* Provides access to the information to display on the remote control.
* May be null (when a media button event receiver is registered,
* but no remote control client has been registered) */
public IRemoteControlClient mRcClient;
public RcClientDeathHandler mRcClientDeathHandler;
/**
* Information only used for non-local playback
*/
public int mPlaybackType;
public int mPlaybackVolume;
public int mPlaybackVolumeMax;
public int mPlaybackVolumeHandling;
public int mPlaybackStream;
public int mPlaybackState;
public IRemoteVolumeObserver mRemoteVolumeObs;
public void resetPlaybackInfo() {
mPlaybackType = RemoteControlClient.PLAYBACK_TYPE_LOCAL;
mPlaybackVolume = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME;
mPlaybackVolumeMax = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME;
mPlaybackVolumeHandling = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME_HANDLING;
mPlaybackStream = AudioManager.STREAM_MUSIC;
mPlaybackState = RemoteControlClient.PLAYSTATE_STOPPED;
mRemoteVolumeObs = null;
}
/** precondition: mediaIntent != null, eventReceiver != null */
public RemoteControlStackEntry(PendingIntent mediaIntent, ComponentName eventReceiver) {
mMediaIntent = mediaIntent;
mReceiverComponent = eventReceiver;
mCallingUid = -1;
mRcClient = null;
mRccId = ++sLastRccId;
resetPlaybackInfo();
}
public void unlinkToRcClientDeath() {
if ((mRcClientDeathHandler != null) && (mRcClientDeathHandler.mCb != null)) {
try {
mRcClientDeathHandler.mCb.unlinkToDeath(mRcClientDeathHandler, 0);
mRcClientDeathHandler = null;
} catch (java.util.NoSuchElementException e) {
// not much we can do here
Log.e(TAG, "Encountered " + e + " in unlinkToRcClientDeath()");
e.printStackTrace();
}
}
}
@Override
protected void finalize() throws Throwable {
unlinkToRcClientDeath();// unlink exception handled inside method
super.finalize();
}
}
/**
* The stack of remote control event receivers.
* Code sections and methods that modify the remote control event receiver stack are
* synchronized on mRCStack, but also BEFORE on mFocusLock as any change in either
* stack, audio focus or RC, can lead to a change in the remote control display
*/
private final Stack<RemoteControlStackEntry> mRCStack = new Stack<RemoteControlStackEntry>();
/**
* The component the telephony package can register so telephony calls have priority to
* handle media button events
*/
private ComponentName mMediaReceiverForCalls = null;
/**
* Helper function:
* Display in the log the current entries in the remote control focus stack
*/
private void dumpRCStack(PrintWriter pw) {
pw.println("\nRemote Control stack entries:");
synchronized(mRCStack) {
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
pw.println(" pi: " + rcse.mMediaIntent +
" -- ercvr: " + rcse.mReceiverComponent +
" -- client: " + rcse.mRcClient +
" -- uid: " + rcse.mCallingUid +
" -- type: " + rcse.mPlaybackType +
" state: " + rcse.mPlaybackState);
}
}
}
/**
* Helper function:
* Display in the log the current entries in the remote control stack, focusing
* on RemoteControlClient data
*/
private void dumpRCCStack(PrintWriter pw) {
pw.println("\nRemote Control Client stack entries:");
synchronized(mRCStack) {
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
pw.println(" uid: " + rcse.mCallingUid +
" -- id: " + rcse.mRccId +
" -- type: " + rcse.mPlaybackType +
" -- state: " + rcse.mPlaybackState +
" -- vol handling: " + rcse.mPlaybackVolumeHandling +
" -- vol: " + rcse.mPlaybackVolume +
" -- volMax: " + rcse.mPlaybackVolumeMax +
" -- volObs: " + rcse.mRemoteVolumeObs);
}
}
synchronized (mMainRemote) {
pw.println("\nRemote Volume State:");
pw.println(" has remote: " + mHasRemotePlayback);
pw.println(" is remote active: " + mMainRemoteIsActive);
pw.println(" rccId: " + mMainRemote.mRccId);
pw.println(" volume handling: "
+ ((mMainRemote.mVolumeHandling == RemoteControlClient.PLAYBACK_VOLUME_FIXED) ?
"PLAYBACK_VOLUME_FIXED(0)" : "PLAYBACK_VOLUME_VARIABLE(1)"));
pw.println(" volume: " + mMainRemote.mVolume);
pw.println(" volume steps: " + mMainRemote.mVolumeMax);
}
}
/**
* Helper function:
* Remove any entry in the remote control stack that has the same package name as packageName
* Pre-condition: packageName != null
*/
private void removeMediaButtonReceiverForPackage(String packageName) {
synchronized(mRCStack) {
if (mRCStack.empty()) {
return;
} else {
RemoteControlStackEntry oldTop = mRCStack.peek();
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
// iterate over the stack entries
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
if (packageName.equalsIgnoreCase(rcse.mReceiverComponent.getPackageName())) {
// a stack entry is from the package being removed, remove it from the stack
stackIterator.remove();
rcse.unlinkToRcClientDeath();
}
}
if (mRCStack.empty()) {
// no saved media button receiver
mAudioHandler.sendMessage(
mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0,
null));
} else if (oldTop != mRCStack.peek()) {
// the top of the stack has changed, save it in the system settings
// by posting a message to persist it
mAudioHandler.sendMessage(
mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0,
mRCStack.peek().mReceiverComponent));
}
}
}
}
/**
* Helper function:
* Restore remote control receiver from the system settings.
*/
private void restoreMediaButtonReceiver() {
String receiverName = Settings.System.getString(mContentResolver,
Settings.System.MEDIA_BUTTON_RECEIVER);
if ((null != receiverName) && !receiverName.isEmpty()) {
ComponentName eventReceiver = ComponentName.unflattenFromString(receiverName);
// construct a PendingIntent targeted to the restored component name
// for the media button and register it
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
// the associated intent will be handled by the component being registered
mediaButtonIntent.setComponent(eventReceiver);
PendingIntent pi = PendingIntent.getBroadcast(mContext,
0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
registerMediaButtonIntent(pi, eventReceiver);
}
}
/**
* Helper function:
* Set the new remote control receiver at the top of the RC focus stack.
* precondition: mediaIntent != null, target != null
*/
private void pushMediaButtonReceiver(PendingIntent mediaIntent, ComponentName target) {
// already at top of stack?
if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(mediaIntent)) {
return;
}
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
RemoteControlStackEntry rcse = null;
boolean wasInsideStack = false;
while(stackIterator.hasNext()) {
rcse = (RemoteControlStackEntry)stackIterator.next();
if(rcse.mMediaIntent.equals(mediaIntent)) {
wasInsideStack = true;
stackIterator.remove();
break;
}
}
if (!wasInsideStack) {
rcse = new RemoteControlStackEntry(mediaIntent, target);
}
mRCStack.push(rcse);
// post message to persist the default media button receiver
mAudioHandler.sendMessage( mAudioHandler.obtainMessage(
MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0, target/*obj*/) );
}
/**
* Helper function:
* Remove the remote control receiver from the RC focus stack.
* precondition: pi != null
*/
private void removeMediaButtonReceiver(PendingIntent pi) {
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
if(rcse.mMediaIntent.equals(pi)) {
stackIterator.remove();
rcse.unlinkToRcClientDeath();
break;
}
}
}
/**
* Helper function:
* Called synchronized on mRCStack
*/
private boolean isCurrentRcController(PendingIntent pi) {
if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(pi)) {
return true;
}
return false;
}
//==========================================================================================
// Remote control display / client
//==========================================================================================
/**
* Update the remote control displays with the new "focused" client generation
*/
private void setNewRcClientOnDisplays_syncRcsCurrc(int newClientGeneration,
PendingIntent newMediaIntent, boolean clearing) {
// NOTE: Only one IRemoteControlDisplay supported in this implementation
if (mRcDisplay != null) {
try {
mRcDisplay.setCurrentClientId(
newClientGeneration, newMediaIntent, clearing);
} catch (RemoteException e) {
Log.e(TAG, "Dead display in setNewRcClientOnDisplays_syncRcsCurrc() "+e);
// if we had a display before, stop monitoring its death
rcDisplay_stopDeathMonitor_syncRcStack();
mRcDisplay = null;
}
}
}
/**
* Update the remote control clients with the new "focused" client generation
*/
private void setNewRcClientGenerationOnClients_syncRcsCurrc(int newClientGeneration) {
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry se = stackIterator.next();
if ((se != null) && (se.mRcClient != null)) {
try {
se.mRcClient.setCurrentClientGenerationId(newClientGeneration);
} catch (RemoteException e) {
Log.w(TAG, "Dead client in setNewRcClientGenerationOnClients_syncRcsCurrc()"+e);
stackIterator.remove();
se.unlinkToRcClientDeath();
}
}
}
}
/**
* Update the displays and clients with the new "focused" client generation and name
* @param newClientGeneration the new generation value matching a client update
* @param newClientEventReceiver the media button event receiver associated with the client.
* May be null, which implies there is no registered media button event receiver.
* @param clearing true if the new client generation value maps to a remote control update
* where the display should be cleared.
*/
private void setNewRcClient_syncRcsCurrc(int newClientGeneration,
PendingIntent newMediaIntent, boolean clearing) {
// send the new valid client generation ID to all displays
setNewRcClientOnDisplays_syncRcsCurrc(newClientGeneration, newMediaIntent, clearing);
// send the new valid client generation ID to all clients
setNewRcClientGenerationOnClients_syncRcsCurrc(newClientGeneration);
}
/**
* Called when processing MSG_RCDISPLAY_CLEAR event
*/
private void onRcDisplayClear() {
if (DEBUG_RC) Log.i(TAG, "Clear remote control display");
synchronized(mRCStack) {
synchronized(mCurrentRcLock) {
mCurrentRcClientGen++;
// synchronously update the displays and clients with the new client generation
setNewRcClient_syncRcsCurrc(mCurrentRcClientGen,
null /*newMediaIntent*/, true /*clearing*/);
}
}
}
/**
* Called when processing MSG_RCDISPLAY_UPDATE event
*/
private void onRcDisplayUpdate(RemoteControlStackEntry rcse, int flags /* USED ?*/) {
synchronized(mRCStack) {
synchronized(mCurrentRcLock) {
if ((mCurrentRcClient != null) && (mCurrentRcClient.equals(rcse.mRcClient))) {
if (DEBUG_RC) Log.i(TAG, "Display/update remote control ");
mCurrentRcClientGen++;
// synchronously update the displays and clients with
// the new client generation
setNewRcClient_syncRcsCurrc(mCurrentRcClientGen,
rcse.mMediaIntent /*newMediaIntent*/,
false /*clearing*/);
// tell the current client that it needs to send info
try {
mCurrentRcClient.onInformationRequested(mCurrentRcClientGen,
flags, mArtworkExpectedWidth, mArtworkExpectedHeight);
} catch (RemoteException e) {
Log.e(TAG, "Current valid remote client is dead: "+e);
mCurrentRcClient = null;
}
} else {
// the remote control display owner has changed between the
// the message to update the display was sent, and the time it
// gets to be processed (now)
}
}
}
}
/**
* Helper function:
* Called synchronized on mRCStack
*/
private void clearRemoteControlDisplay_syncAfRcs() {
synchronized(mCurrentRcLock) {
mCurrentRcClient = null;
}
// will cause onRcDisplayClear() to be called in AudioService's handler thread
mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_RCDISPLAY_CLEAR) );
}
/**
* Helper function for code readability: only to be called from
* checkUpdateRemoteControlDisplay_syncAfRcs() which checks the preconditions for
* this method.
* Preconditions:
* - called synchronized mAudioFocusLock then on mRCStack
* - mRCStack.isEmpty() is false
*/
private void updateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) {
RemoteControlStackEntry rcse = mRCStack.peek();
int infoFlagsAboutToBeUsed = infoChangedFlags;
// this is where we enforce opt-in for information display on the remote controls
// with the new AudioManager.registerRemoteControlClient() API
if (rcse.mRcClient == null) {
//Log.w(TAG, "Can't update remote control display with null remote control client");
clearRemoteControlDisplay_syncAfRcs();
return;
}
synchronized(mCurrentRcLock) {
if (!rcse.mRcClient.equals(mCurrentRcClient)) {
// new RC client, assume every type of information shall be queried
infoFlagsAboutToBeUsed = RC_INFO_ALL;
}
mCurrentRcClient = rcse.mRcClient;
}
// will cause onRcDisplayUpdate() to be called in AudioService's handler thread
mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_RCDISPLAY_UPDATE,
infoFlagsAboutToBeUsed /* arg1 */, 0, rcse /* obj, != null */) );
}
/**
* Helper function:
* Called synchronized on mAudioFocusLock, then mRCStack
* Check whether the remote control display should be updated, triggers the update if required
* @param infoChangedFlags the flags corresponding to the remote control client information
* that has changed, if applicable (checking for the update conditions might trigger a
* clear, rather than an update event).
*/
private void checkUpdateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) {
// determine whether the remote control display should be refreshed
// if either stack is empty, there is a mismatch, so clear the RC display
if (mRCStack.isEmpty() || mFocusStack.isEmpty()) {
clearRemoteControlDisplay_syncAfRcs();
return;
}
// if the top of the two stacks belong to different packages, there is a mismatch, clear
if ((mRCStack.peek().mCallingPackageName != null)
&& (mFocusStack.peek().mPackageName != null)
&& !(mRCStack.peek().mCallingPackageName.compareTo(
mFocusStack.peek().mPackageName) == 0)) {
clearRemoteControlDisplay_syncAfRcs();
return;
}
// if the audio focus didn't originate from the same Uid as the one in which the remote
// control information will be retrieved, clear
if (mRCStack.peek().mCallingUid != mFocusStack.peek().mCallingUid) {
clearRemoteControlDisplay_syncAfRcs();
return;
}
// refresh conditions were verified: update the remote controls
// ok to call: synchronized mAudioFocusLock then on mRCStack, mRCStack is not empty
updateRemoteControlDisplay_syncAfRcs(infoChangedFlags);
}
/**
* see AudioManager.registerMediaButtonIntent(PendingIntent pi, ComponentName c)
* precondition: mediaIntent != null, target != null
*/
public void registerMediaButtonIntent(PendingIntent mediaIntent, ComponentName eventReceiver) {
Log.i(TAG, " Remote Control registerMediaButtonIntent() for " + mediaIntent);
synchronized(mAudioFocusLock) {
synchronized(mRCStack) {
pushMediaButtonReceiver(mediaIntent, eventReceiver);
// new RC client, assume every type of information shall be queried
checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
}
}
}
/**
* see AudioManager.unregisterMediaButtonIntent(PendingIntent mediaIntent)
* precondition: mediaIntent != null, eventReceiver != null
*/
public void unregisterMediaButtonIntent(PendingIntent mediaIntent, ComponentName eventReceiver)
{
Log.i(TAG, " Remote Control unregisterMediaButtonIntent() for " + mediaIntent);
synchronized(mAudioFocusLock) {
synchronized(mRCStack) {
boolean topOfStackWillChange = isCurrentRcController(mediaIntent);
removeMediaButtonReceiver(mediaIntent);
if (topOfStackWillChange) {
// current RC client will change, assume every type of info needs to be queried
checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
}
}
}
}
/**
* see AudioManager.registerMediaButtonEventReceiverForCalls(ComponentName c)
* precondition: c != null
*/
public void registerMediaButtonEventReceiverForCalls(ComponentName c) {
if (mContext.checkCallingPermission("android.permission.MODIFY_PHONE_STATE")
!= PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, "Invalid permissions to register media button receiver for calls");
return;
}
synchronized(mRCStack) {
mMediaReceiverForCalls = c;
}
}
/**
* see AudioManager.unregisterMediaButtonEventReceiverForCalls()
*/
public void unregisterMediaButtonEventReceiverForCalls() {
if (mContext.checkCallingPermission("android.permission.MODIFY_PHONE_STATE")
!= PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, "Invalid permissions to unregister media button receiver for calls");
return;
}
synchronized(mRCStack) {
mMediaReceiverForCalls = null;
}
}
/**
* see AudioManager.registerRemoteControlClient(ComponentName eventReceiver, ...)
* @return the unique ID of the RemoteControlStackEntry associated with the RemoteControlClient
* Note: using this method with rcClient == null is a way to "disable" the IRemoteControlClient
* without modifying the RC stack, but while still causing the display to refresh (will
* become blank as a result of this)
*/
public int registerRemoteControlClient(PendingIntent mediaIntent,
IRemoteControlClient rcClient, String callingPackageName) {
if (DEBUG_RC) Log.i(TAG, "Register remote control client rcClient="+rcClient);
int rccId = RemoteControlClient.RCSE_ID_UNREGISTERED;
synchronized(mAudioFocusLock) {
synchronized(mRCStack) {
// store the new display information
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
if(rcse.mMediaIntent.equals(mediaIntent)) {
// already had a remote control client?
if (rcse.mRcClientDeathHandler != null) {
// stop monitoring the old client's death
rcse.unlinkToRcClientDeath();
}
// save the new remote control client
rcse.mRcClient = rcClient;
rcse.mCallingPackageName = callingPackageName;
rcse.mCallingUid = Binder.getCallingUid();
if (rcClient == null) {
// here rcse.mRcClientDeathHandler is null;
rcse.resetPlaybackInfo();
break;
}
rccId = rcse.mRccId;
// there is a new (non-null) client:
// 1/ give the new client the current display (if any)
if (mRcDisplay != null) {
try {
rcse.mRcClient.plugRemoteControlDisplay(mRcDisplay);
} catch (RemoteException e) {
Log.e(TAG, "Error connecting remote control display to client: "+e);
e.printStackTrace();
}
}
// 2/ monitor the new client's death
IBinder b = rcse.mRcClient.asBinder();
RcClientDeathHandler rcdh =
new RcClientDeathHandler(b, rcse.mMediaIntent);
try {
b.linkToDeath(rcdh, 0);
} catch (RemoteException e) {
// remote control client is DOA, disqualify it
Log.w(TAG, "registerRemoteControlClient() has a dead client " + b);
rcse.mRcClient = null;
}
rcse.mRcClientDeathHandler = rcdh;
break;
}
}
// if the eventReceiver is at the top of the stack
// then check for potential refresh of the remote controls
if (isCurrentRcController(mediaIntent)) {
checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
}
}
}
return rccId;
}
/**
* see AudioManager.unregisterRemoteControlClient(PendingIntent pi, ...)
* rcClient is guaranteed non-null
*/
public void unregisterRemoteControlClient(PendingIntent mediaIntent,
IRemoteControlClient rcClient) {
synchronized(mAudioFocusLock) {
synchronized(mRCStack) {
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
if ((rcse.mMediaIntent.equals(mediaIntent))
&& rcClient.equals(rcse.mRcClient)) {
// we found the IRemoteControlClient to unregister
// stop monitoring its death
rcse.unlinkToRcClientDeath();
// reset the client-related fields
rcse.mRcClient = null;
rcse.mCallingPackageName = null;
}
}
}
}
}
/**
* The remote control displays.
* Access synchronized on mRCStack
* NOTE: Only one IRemoteControlDisplay supported in this implementation
*/
private IRemoteControlDisplay mRcDisplay;
private RcDisplayDeathHandler mRcDisplayDeathHandler;
private int mArtworkExpectedWidth = -1;
private int mArtworkExpectedHeight = -1;
/**
* Inner class to monitor remote control display deaths, and unregister them from the list
* of displays if necessary.
*/
private class RcDisplayDeathHandler implements IBinder.DeathRecipient {
private IBinder mCb; // To be notified of client's death
public RcDisplayDeathHandler(IBinder b) {
if (DEBUG_RC) Log.i(TAG, "new RcDisplayDeathHandler for "+b);
mCb = b;
}
public void binderDied() {
synchronized(mRCStack) {
Log.w(TAG, "RemoteControl: display died");
mRcDisplay = null;
}
}
public void unlinkToRcDisplayDeath() {
if (DEBUG_RC) Log.i(TAG, "unlinkToRcDisplayDeath for "+mCb);
try {
mCb.unlinkToDeath(this, 0);
} catch (java.util.NoSuchElementException e) {
// not much we can do here, the display was being unregistered anyway
Log.e(TAG, "Encountered " + e + " in unlinkToRcDisplayDeath()");
e.printStackTrace();
}
}
}
private void rcDisplay_stopDeathMonitor_syncRcStack() {
if (mRcDisplay != null) { // implies (mRcDisplayDeathHandler != null)
// we had a display before, stop monitoring its death
mRcDisplayDeathHandler.unlinkToRcDisplayDeath();
}
}
private void rcDisplay_startDeathMonitor_syncRcStack() {
if (mRcDisplay != null) {
// new non-null display, monitor its death
IBinder b = mRcDisplay.asBinder();
mRcDisplayDeathHandler = new RcDisplayDeathHandler(b);
try {
b.linkToDeath(mRcDisplayDeathHandler, 0);
} catch (RemoteException e) {
// remote control display is DOA, disqualify it
Log.w(TAG, "registerRemoteControlDisplay() has a dead client " + b);
mRcDisplay = null;
}
}
}
/**
* Register an IRemoteControlDisplay.
* Notify all IRemoteControlClient of the new display and cause the RemoteControlClient
* at the top of the stack to update the new display with its information.
* Since only one IRemoteControlDisplay is supported, this will unregister the previous display.
* @param rcd the IRemoteControlDisplay to register. No effect if null.
*/
public void registerRemoteControlDisplay(IRemoteControlDisplay rcd) {
if (DEBUG_RC) Log.d(TAG, ">>> registerRemoteControlDisplay("+rcd+")");
synchronized(mAudioFocusLock) {
synchronized(mRCStack) {
if ((mRcDisplay == rcd) || (rcd == null)) {
return;
}
// if we had a display before, stop monitoring its death
rcDisplay_stopDeathMonitor_syncRcStack();
mRcDisplay = rcd;
// new display, start monitoring its death
rcDisplay_startDeathMonitor_syncRcStack();
// let all the remote control clients there is a new display
// no need to unplug the previous because we only support one display
// and the clients don't track the death of the display
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
if(rcse.mRcClient != null) {
try {
rcse.mRcClient.plugRemoteControlDisplay(mRcDisplay);
} catch (RemoteException e) {
Log.e(TAG, "Error connecting remote control display to client: " + e);
e.printStackTrace();
}
}
}
// we have a new display, of which all the clients are now aware: have it be updated
checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
}
}
}
/**
* Unregister an IRemoteControlDisplay.
* Since only one IRemoteControlDisplay is supported, this has no effect if the one to
* unregister is not the current one.
* @param rcd the IRemoteControlDisplay to unregister. No effect if null.
*/
public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {
if (DEBUG_RC) Log.d(TAG, "<<< unregisterRemoteControlDisplay("+rcd+")");
synchronized(mRCStack) {
// only one display here, so you can only unregister the current display
if ((rcd == null) || (rcd != mRcDisplay)) {
if (DEBUG_RC) Log.w(TAG, " trying to unregister unregistered RCD");
return;
}
// if we had a display before, stop monitoring its death
rcDisplay_stopDeathMonitor_syncRcStack();
mRcDisplay = null;
// disconnect this remote control display from all the clients
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
if(rcse.mRcClient != null) {
try {
rcse.mRcClient.unplugRemoteControlDisplay(rcd);
} catch (RemoteException e) {
Log.e(TAG, "Error disconnecting remote control display to client: " + e);
e.printStackTrace();
}
}
}
}
}
public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) {
synchronized(mRCStack) {
// NOTE: Only one IRemoteControlDisplay supported in this implementation
mArtworkExpectedWidth = w;
mArtworkExpectedHeight = h;
}
}
public void setPlaybackInfoForRcc(int rccId, int what, int value) {
sendMsg(mAudioHandler, MSG_RCC_NEW_PLAYBACK_INFO, SENDMSG_QUEUE,
rccId /* arg1 */, what /* arg2 */, Integer.valueOf(value) /* obj */, 0 /* delay */);
}
// handler for MSG_RCC_NEW_PLAYBACK_INFO
private void onNewPlaybackInfoForRcc(int rccId, int key, int value) {
if(DEBUG_RC) Log.d(TAG, "onNewPlaybackInfoForRcc(id=" + rccId +
", what=" + key + ",val=" + value + ")");
synchronized(mRCStack) {
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
if (rcse.mRccId == rccId) {
switch (key) {
case RemoteControlClient.PLAYBACKINFO_PLAYBACK_TYPE:
rcse.mPlaybackType = value;
postReevaluateRemote();
break;
case RemoteControlClient.PLAYBACKINFO_VOLUME:
rcse.mPlaybackVolume = value;
synchronized (mMainRemote) {
if (rccId == mMainRemote.mRccId) {
mMainRemote.mVolume = value;
mVolumePanel.postHasNewRemotePlaybackInfo();
}
}
break;
case RemoteControlClient.PLAYBACKINFO_VOLUME_MAX:
rcse.mPlaybackVolumeMax = value;
synchronized (mMainRemote) {
if (rccId == mMainRemote.mRccId) {
mMainRemote.mVolumeMax = value;
mVolumePanel.postHasNewRemotePlaybackInfo();
}
}
break;
case RemoteControlClient.PLAYBACKINFO_VOLUME_HANDLING:
rcse.mPlaybackVolumeHandling = value;
synchronized (mMainRemote) {
if (rccId == mMainRemote.mRccId) {
mMainRemote.mVolumeHandling = value;
mVolumePanel.postHasNewRemotePlaybackInfo();
}
}
break;
case RemoteControlClient.PLAYBACKINFO_USES_STREAM:
rcse.mPlaybackStream = value;
break;
case RemoteControlClient.PLAYBACKINFO_PLAYSTATE:
rcse.mPlaybackState = value;
synchronized (mMainRemote) {
if (rccId == mMainRemote.mRccId) {
mMainRemoteIsActive = isPlaystateActive(value);
postReevaluateRemote();
}
}
break;
default:
Log.e(TAG, "unhandled key " + key + " for RCC " + rccId);
break;
}
return;
}
}
}
}
public void registerRemoteVolumeObserverForRcc(int rccId, IRemoteVolumeObserver rvo) {
sendMsg(mAudioHandler, MSG_RCC_NEW_VOLUME_OBS, SENDMSG_QUEUE,
rccId /* arg1 */, 0, rvo /* obj */, 0 /* delay */);
}
// handler for MSG_RCC_NEW_VOLUME_OBS
private void onRegisterVolumeObserverForRcc(int rccId, IRemoteVolumeObserver rvo) {
synchronized(mRCStack) {
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
if (rcse.mRccId == rccId) {
rcse.mRemoteVolumeObs = rvo;
break;
}
}
}
}
/**
* Checks if a remote client is active on the supplied stream type. Update the remote stream
* volume state if found and playing
* @param streamType
* @return false if no remote playing is currently playing
*/
private boolean checkUpdateRemoteStateIfActive(int streamType) {
synchronized(mRCStack) {
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
if ((rcse.mPlaybackType == RemoteControlClient.PLAYBACK_TYPE_REMOTE)
&& isPlaystateActive(rcse.mPlaybackState)
&& (rcse.mPlaybackStream == streamType)) {
if (DEBUG_RC) Log.d(TAG, "remote playback active on stream " + streamType
+ ", vol =" + rcse.mPlaybackVolume);
synchronized (mMainRemote) {
mMainRemote.mRccId = rcse.mRccId;
mMainRemote.mVolume = rcse.mPlaybackVolume;
mMainRemote.mVolumeMax = rcse.mPlaybackVolumeMax;
mMainRemote.mVolumeHandling = rcse.mPlaybackVolumeHandling;
mMainRemoteIsActive = true;
}
return true;
}
}
}
synchronized (mMainRemote) {
mMainRemoteIsActive = false;
}
return false;
}
/**
* Returns true if the given playback state is considered "active", i.e. it describes a state
* where playback is happening, or about to
* @param playState the playback state to evaluate
* @return true if active, false otherwise (inactive or unknown)
*/
private static boolean isPlaystateActive(int playState) {
switch (playState) {
case RemoteControlClient.PLAYSTATE_PLAYING:
case RemoteControlClient.PLAYSTATE_BUFFERING:
case RemoteControlClient.PLAYSTATE_FAST_FORWARDING:
case RemoteControlClient.PLAYSTATE_REWINDING:
case RemoteControlClient.PLAYSTATE_SKIPPING_BACKWARDS:
case RemoteControlClient.PLAYSTATE_SKIPPING_FORWARDS:
return true;
default:
return false;
}
}
private void adjustRemoteVolume(int streamType, int direction, int flags) {
int rccId = RemoteControlClient.RCSE_ID_UNREGISTERED;
boolean volFixed = false;
synchronized (mMainRemote) {
if (!mMainRemoteIsActive) {
if (DEBUG_VOL) Log.w(TAG, "adjustRemoteVolume didn't find an active client");
return;
}
rccId = mMainRemote.mRccId;
volFixed = (mMainRemote.mVolumeHandling ==
RemoteControlClient.PLAYBACK_VOLUME_FIXED);
}
// unlike "local" stream volumes, we can't compute the new volume based on the direction,
// we can only notify the remote that volume needs to be updated, and we'll get an async'
// update through setPlaybackInfoForRcc()
if (!volFixed) {
sendVolumeUpdateToRemote(rccId, direction);
}
// fire up the UI
mVolumePanel.postRemoteVolumeChanged(streamType, flags);
}
private void sendVolumeUpdateToRemote(int rccId, int direction) {
if (DEBUG_VOL) { Log.d(TAG, "sendVolumeUpdateToRemote(rccId="+rccId+" , dir="+direction); }
if (direction == 0) {
// only handling discrete events
return;
}
IRemoteVolumeObserver rvo = null;
synchronized (mRCStack) {
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
//FIXME OPTIMIZE store this info in mMainRemote so we don't have to iterate?
if (rcse.mRccId == rccId) {
rvo = rcse.mRemoteVolumeObs;
break;
}
}
}
if (rvo != null) {
try {
rvo.dispatchRemoteVolumeUpdate(direction, -1);
} catch (RemoteException e) {
Log.e(TAG, "Error dispatching relative volume update", e);
}
}
}
public int getRemoteStreamMaxVolume() {
synchronized (mMainRemote) {
if (mMainRemote.mRccId == RemoteControlClient.RCSE_ID_UNREGISTERED) {
return 0;
}
return mMainRemote.mVolumeMax;
}
}
public int getRemoteStreamVolume() {
synchronized (mMainRemote) {
if (mMainRemote.mRccId == RemoteControlClient.RCSE_ID_UNREGISTERED) {
return 0;
}
return mMainRemote.mVolume;
}
}
public void setRemoteStreamVolume(int vol) {
if (DEBUG_VOL) { Log.d(TAG, "setRemoteStreamVolume(vol="+vol+")"); }
int rccId = RemoteControlClient.RCSE_ID_UNREGISTERED;
synchronized (mMainRemote) {
if (mMainRemote.mRccId == RemoteControlClient.RCSE_ID_UNREGISTERED) {
return;
}
rccId = mMainRemote.mRccId;
}
IRemoteVolumeObserver rvo = null;
synchronized (mRCStack) {
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
if (rcse.mRccId == rccId) {
//FIXME OPTIMIZE store this info in mMainRemote so we don't have to iterate?
rvo = rcse.mRemoteVolumeObs;
break;
}
}
}
if (rvo != null) {
try {
rvo.dispatchRemoteVolumeUpdate(0, vol);
} catch (RemoteException e) {
Log.e(TAG, "Error dispatching absolute volume update", e);
}
}
}
/**
* Call to make AudioService reevaluate whether it's in a mode where remote players should
* have their volume controlled. In this implementation this is only to reset whether
* VolumePanel should display remote volumes
*/
private void postReevaluateRemote() {
sendMsg(mAudioHandler, MSG_REEVALUATE_REMOTE, SENDMSG_QUEUE, 0, 0, null, 0);
}
private void onReevaluateRemote() {
if (DEBUG_VOL) { Log.w(TAG, "onReevaluateRemote()"); }
// is there a registered RemoteControlClient that is handling remote playback
boolean hasRemotePlayback = false;
synchronized (mRCStack) {
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = stackIterator.next();
if (rcse.mPlaybackType == RemoteControlClient.PLAYBACK_TYPE_REMOTE) {
hasRemotePlayback = true;
break;
}
}
}
synchronized (mMainRemote) {
if (mHasRemotePlayback != hasRemotePlayback) {
mHasRemotePlayback = hasRemotePlayback;
mVolumePanel.postRemoteSliderVisibility(hasRemotePlayback);
}
}
}
//==========================================================================================
// Device orientation
//==========================================================================================
/**
* Handles device configuration changes that may map to a change in the orientation.
* This feature is optional, and is defined by the definition and value of the
* "ro.audio.monitorOrientation" system property.
*/
private void handleConfigurationChanged(Context context) {
try {
// reading new orientation "safely" (i.e. under try catch) in case anything
// goes wrong when obtaining resources and configuration
int newOrientation = context.getResources().getConfiguration().orientation;
if (newOrientation != mDeviceOrientation) {
mDeviceOrientation = newOrientation;
setOrientationForAudioSystem();
}
} catch (Exception e) {
Log.e(TAG, "Error retrieving device orientation: " + e);
}
}
private void setOrientationForAudioSystem() {
switch (mDeviceOrientation) {
case Configuration.ORIENTATION_LANDSCAPE:
//Log.i(TAG, "orientation is landscape");
AudioSystem.setParameters("orientation=landscape");
break;
case Configuration.ORIENTATION_PORTRAIT:
//Log.i(TAG, "orientation is portrait");
AudioSystem.setParameters("orientation=portrait");
break;
case Configuration.ORIENTATION_SQUARE:
//Log.i(TAG, "orientation is square");
AudioSystem.setParameters("orientation=square");
break;
case Configuration.ORIENTATION_UNDEFINED:
//Log.i(TAG, "orientation is undefined");
AudioSystem.setParameters("orientation=undefined");
break;
default:
Log.e(TAG, "Unknown orientation");
}
}
// Handles request to override default use of A2DP for media.
public void setBluetoothA2dpOnInt(boolean on) {
synchronized (mBluetoothA2dpEnabledLock) {
mBluetoothA2dpEnabled = on;
sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE,
AudioSystem.FOR_MEDIA,
mBluetoothA2dpEnabled ? AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP,
null, 0);
}
}
@Override
public void setRingtonePlayer(IRingtonePlayer player) {
mContext.enforceCallingOrSelfPermission(REMOTE_AUDIO_PLAYBACK, null);
mRingtonePlayer = player;
}
@Override
public IRingtonePlayer getRingtonePlayer() {
return mRingtonePlayer;
}
@Override
public AudioRoutesInfo startWatchingRoutes(IAudioRoutesObserver observer) {
synchronized (mCurAudioRoutes) {
AudioRoutesInfo routes = new AudioRoutesInfo(mCurAudioRoutes);
mRoutesObservers.register(observer);
return routes;
}
}
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
dumpFocusStack(pw);
dumpRCStack(pw);
dumpRCCStack(pw);
dumpStreamStates(pw);
pw.println("\nAudio routes:");
pw.print(" mMainType=0x"); pw.println(Integer.toHexString(mCurAudioRoutes.mMainType));
pw.print(" mBluetoothName="); pw.println(mCurAudioRoutes.mBluetoothName);
}
}
| true | true | public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int device;
int state;
if (action.equals(Intent.ACTION_DOCK_EVENT)) {
int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
Intent.EXTRA_DOCK_STATE_UNDOCKED);
int config;
switch (dockState) {
case Intent.EXTRA_DOCK_STATE_DESK:
config = AudioSystem.FORCE_BT_DESK_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_CAR:
config = AudioSystem.FORCE_BT_CAR_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_LE_DESK:
config = AudioSystem.FORCE_ANALOG_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_HE_DESK:
config = AudioSystem.FORCE_DIGITAL_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_UNDOCKED:
default:
config = AudioSystem.FORCE_NONE;
}
AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
} else if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED) && noDelayInATwoDP) {
state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
BluetoothProfile.STATE_DISCONNECTED);
BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
onSetA2dpConnectionState(btDevice, state);
} else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
BluetoothProfile.STATE_DISCONNECTED);
device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
String address = null;
BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (btDevice == null) {
return;
}
address = btDevice.getAddress();
BluetoothClass btClass = btDevice.getBluetoothClass();
if (btClass != null) {
switch (btClass.getDeviceClass()) {
case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
break;
case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
break;
}
}
if (!BluetoothAdapter.checkBluetoothAddress(address)) {
address = "";
}
boolean connected = (state == BluetoothProfile.STATE_CONNECTED);
if (handleDeviceConnection(connected, device, address)) {
synchronized (mScoClients) {
if (connected) {
mBluetoothHeadsetDevice = btDevice;
} else {
mBluetoothHeadsetDevice = null;
resetBluetoothSco();
}
}
}
} else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
//Save and restore volumes for headset and speaker
state = intent.getIntExtra("state", 0);
int lastVolume;
if (state == 1) {
//avoids connection glitches
if (noDelayInATwoDP)
setBluetoothA2dpOnInt(false);
// Headset plugged in
// Avoid connection glitches
// Volume restore capping
final boolean capVolumeRestore = Settings.System.getInt(mContentResolver,
Settings.System.SAFE_HEADSET_VOLUME_RESTORE, 1) == 1;
if (capVolumeRestore) {
for (int stream = 0; stream < AudioSystem.getNumStreamTypes(); stream++) {
if (stream == mStreamVolumeAlias[stream]) {
final int volume = getStreamVolume(stream);
final int restoreCap = rescaleIndex(HEADSET_VOLUME_RESTORE_CAP,
AudioSystem.STREAM_MUSIC, stream);
if (volume > restoreCap) {
setStreamVolume(stream, restoreCap, 0);
}
}
}
}
} else {
// Headset disconnected
}
} else if (action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) ||
action.equals(Intent.ACTION_USB_AUDIO_DEVICE_PLUG)) {
state = intent.getIntExtra("state", 0);
int alsaCard = intent.getIntExtra("card", -1);
int alsaDevice = intent.getIntExtra("device", -1);
String params = (alsaCard == -1 && alsaDevice == -1 ? ""
: "card=" + alsaCard + ";device=" + alsaDevice);
device = action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) ?
AudioSystem.DEVICE_OUT_USB_ACCESSORY : AudioSystem.DEVICE_OUT_USB_DEVICE;
Log.v(TAG, "Broadcast Receiver: Got "
+ (action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) ?
"ACTION_USB_AUDIO_ACCESSORY_PLUG" : "ACTION_USB_AUDIO_DEVICE_PLUG")
+ ", state = " + state + ", card: " + alsaCard + ", device: " + alsaDevice);
handleDeviceConnection((state == 1), device, params);
} else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
boolean broadcast = false;
int scoAudioState = AudioManager.SCO_AUDIO_STATE_ERROR;
synchronized (mScoClients) {
int btState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
// broadcast intent if the connection was initated by AudioService
if (!mScoClients.isEmpty() &&
(mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
broadcast = true;
}
switch (btState) {
case BluetoothHeadset.STATE_AUDIO_CONNECTED:
scoAudioState = AudioManager.SCO_AUDIO_STATE_CONNECTED;
if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
}
break;
case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
scoAudioState = AudioManager.SCO_AUDIO_STATE_DISCONNECTED;
mScoAudioState = SCO_STATE_INACTIVE;
clearAllScoClients(0, false);
break;
case BluetoothHeadset.STATE_AUDIO_CONNECTING:
if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
}
default:
// do not broadcast CONNECTING or invalid state
broadcast = false;
break;
}
}
if (broadcast) {
broadcastScoConnectionState(scoAudioState);
//FIXME: this is to maintain compatibility with deprecated intent
// AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, scoAudioState);
mContext.sendStickyBroadcast(newIntent);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
mBootCompleted = true;
sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_NOOP,
0, 0, null, 0);
mKeyguardManager =
(KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
mScoConnectionState = AudioManager.SCO_AUDIO_STATE_ERROR;
resetBluetoothSco();
getBluetoothHeadset();
//FIXME: this is to maintain compatibility with deprecated intent
// AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,
AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
mContext.sendStickyBroadcast(newIntent);
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null) {
adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
BluetoothProfile.A2DP);
}
} else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
// a package is being removed, not replaced
String packageName = intent.getData().getSchemeSpecificPart();
if (packageName != null) {
removeMediaButtonReceiverForPackage(packageName);
}
}
} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
AudioSystem.setParameters("screen_state=on");
} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
AudioSystem.setParameters("screen_state=off");
} else if (action.equalsIgnoreCase(Intent.ACTION_CONFIGURATION_CHANGED)) {
handleConfigurationChanged(context);
}
}
| public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int device;
int state;
if (action.equals(Intent.ACTION_DOCK_EVENT)) {
int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
Intent.EXTRA_DOCK_STATE_UNDOCKED);
int config;
switch (dockState) {
case Intent.EXTRA_DOCK_STATE_DESK:
config = AudioSystem.FORCE_BT_DESK_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_CAR:
config = AudioSystem.FORCE_BT_CAR_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_LE_DESK:
config = AudioSystem.FORCE_ANALOG_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_HE_DESK:
config = AudioSystem.FORCE_DIGITAL_DOCK;
break;
case Intent.EXTRA_DOCK_STATE_UNDOCKED:
default:
config = AudioSystem.FORCE_NONE;
}
AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
} else if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED) && noDelayInATwoDP) {
state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
BluetoothProfile.STATE_DISCONNECTED);
BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
onSetA2dpConnectionState(btDevice, state);
} else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
BluetoothProfile.STATE_DISCONNECTED);
device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
String address = null;
BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (btDevice == null) {
return;
}
address = btDevice.getAddress();
BluetoothClass btClass = btDevice.getBluetoothClass();
if (btClass != null) {
switch (btClass.getDeviceClass()) {
case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
break;
case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
break;
}
}
if (!BluetoothAdapter.checkBluetoothAddress(address)) {
address = "";
}
boolean connected = (state == BluetoothProfile.STATE_CONNECTED);
if (handleDeviceConnection(connected, device, address)) {
synchronized (mScoClients) {
if (connected) {
mBluetoothHeadsetDevice = btDevice;
} else {
mBluetoothHeadsetDevice = null;
resetBluetoothSco();
}
}
}
} else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
//Save and restore volumes for headset and speaker
state = intent.getIntExtra("state", 0);
int lastVolume;
if (state == 1) {
//avoids connection glitches
if (noDelayInATwoDP)
setBluetoothA2dpOnInt(false);
// Headset plugged in
// Avoid connection glitches
// Volume restore capping
final boolean capVolumeRestore = Settings.System.getInt(mContentResolver,
Settings.System.SAFE_HEADSET_VOLUME_RESTORE, 1) == 1;
if (capVolumeRestore) {
for (int stream = 0; stream < AudioSystem.getNumStreamTypes(); stream++) {
if (stream == mStreamVolumeAlias[stream]) {
final int volume = getStreamVolume(stream);
final int restoreCap = rescaleIndex(HEADSET_VOLUME_RESTORE_CAP,
AudioSystem.STREAM_MUSIC, stream);
if (volume > restoreCap) {
setStreamVolume(stream, restoreCap, 0);
}
}
}
}
} else {
//avoid connection glitches
if (noDelayInATwoDP)
setBluetoothA2dpOnInt(true);
// Headset disconnected
}
} else if (action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) ||
action.equals(Intent.ACTION_USB_AUDIO_DEVICE_PLUG)) {
state = intent.getIntExtra("state", 0);
int alsaCard = intent.getIntExtra("card", -1);
int alsaDevice = intent.getIntExtra("device", -1);
String params = (alsaCard == -1 && alsaDevice == -1 ? ""
: "card=" + alsaCard + ";device=" + alsaDevice);
device = action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) ?
AudioSystem.DEVICE_OUT_USB_ACCESSORY : AudioSystem.DEVICE_OUT_USB_DEVICE;
Log.v(TAG, "Broadcast Receiver: Got "
+ (action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) ?
"ACTION_USB_AUDIO_ACCESSORY_PLUG" : "ACTION_USB_AUDIO_DEVICE_PLUG")
+ ", state = " + state + ", card: " + alsaCard + ", device: " + alsaDevice);
handleDeviceConnection((state == 1), device, params);
} else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
boolean broadcast = false;
int scoAudioState = AudioManager.SCO_AUDIO_STATE_ERROR;
synchronized (mScoClients) {
int btState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
// broadcast intent if the connection was initated by AudioService
if (!mScoClients.isEmpty() &&
(mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
broadcast = true;
}
switch (btState) {
case BluetoothHeadset.STATE_AUDIO_CONNECTED:
scoAudioState = AudioManager.SCO_AUDIO_STATE_CONNECTED;
if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
}
break;
case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
scoAudioState = AudioManager.SCO_AUDIO_STATE_DISCONNECTED;
mScoAudioState = SCO_STATE_INACTIVE;
clearAllScoClients(0, false);
break;
case BluetoothHeadset.STATE_AUDIO_CONNECTING:
if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
}
default:
// do not broadcast CONNECTING or invalid state
broadcast = false;
break;
}
}
if (broadcast) {
broadcastScoConnectionState(scoAudioState);
//FIXME: this is to maintain compatibility with deprecated intent
// AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, scoAudioState);
mContext.sendStickyBroadcast(newIntent);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
mBootCompleted = true;
sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_NOOP,
0, 0, null, 0);
mKeyguardManager =
(KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
mScoConnectionState = AudioManager.SCO_AUDIO_STATE_ERROR;
resetBluetoothSco();
getBluetoothHeadset();
//FIXME: this is to maintain compatibility with deprecated intent
// AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,
AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
mContext.sendStickyBroadcast(newIntent);
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null) {
adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
BluetoothProfile.A2DP);
}
} else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
// a package is being removed, not replaced
String packageName = intent.getData().getSchemeSpecificPart();
if (packageName != null) {
removeMediaButtonReceiverForPackage(packageName);
}
}
} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
AudioSystem.setParameters("screen_state=on");
} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
AudioSystem.setParameters("screen_state=off");
} else if (action.equalsIgnoreCase(Intent.ACTION_CONFIGURATION_CHANGED)) {
handleConfigurationChanged(context);
}
}
|
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/RoutingEntry.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/RoutingEntry.java
index f806f55f..b0858507 100644
--- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/RoutingEntry.java
+++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/RoutingEntry.java
@@ -1,468 +1,468 @@
/*******************************************************************************
* Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management
* Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
******************************************************************************/
package de.tuilmenau.ics.fog.routing.hierarchical;
import de.tuilmenau.ics.fog.routing.RouteSegment;
import de.tuilmenau.ics.fog.routing.hierarchical.management.AbstractRoutingGraph;
import de.tuilmenau.ics.fog.routing.hierarchical.management.AbstractRoutingGraphLink;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.L2Address;
import de.tuilmenau.ics.fog.ui.Logging;
/**
* HRM Routing: The class describes a routing entry consisting of
* 1.) Destination: either a node or an aggregated address (a cluster)
* 2.) Next hop: either a node or an aggregated address (a cluster)
* 3.) Hop count: the hop costs this route causes
* 4.) Utilization: the route usage, e.g., 0.59 for 59%
* 5.) Min. delay [ms]: the additional delay, which is caused minimal from this route
* 6.) Max. data rate [Kb/s]: the data rate, which is possible via this route under optimal circumstances
*/
public class RoutingEntry implements RouteSegment
{
private static final long serialVersionUID = 1328799038900154655L;
/**
* Defines a constant value for "no hop costs".
*/
public static final int NO_HOP_COSTS = 0;
/**
* Defines a constant value for "no utilization".
*/
public static final float NO_UTILIZATION = -1;
/**
* Defines a constant value for "no delay".
*/
public static final long NO_DELAY = -1;
/**
* Defines a constant value for "infinite data rate".
*/
public static final long INFINITE_DATARATE = -1;
/**
* Stores the destination of this route entry.
*/
private HRMID mDestination = null;
/**
* Stores the source of this route entry.
*/
private HRMID mSource = null;
/**
* Stores the next hop of this route entry.
*/
private HRMID mNextHop = null;
/**
* Stores the hop costs the described route causes.
*/
private int mHopCount = NO_HOP_COSTS;
/**
* Stores the utilization of the described route.
*/
private float mUtilization = NO_UTILIZATION;
/**
* Stores the minimum additional delay[ms] the described route causes.
*/
private long mMinDelay = NO_DELAY;
/**
* Stores the maximum data rate[Kb/s] the described route might provide.
*/
private long mMaxDataRate = INFINITE_DATARATE;
/**
* Stores if the route describes a local loop.
* (for GUI only)
*/
private boolean mLocalLoop = false;
/**
* Stores if the route describes a link to a neighbor node.
* (for GUI only)
*/
private boolean mRouteToDirectNeighbor = false;
/**
* Stores the L2 address of the next hop if known
*/
private L2Address mNextHopL2Address = null;
/**
* Stores the cause for this entry.
* This variable is not part of the concept. It is only for GUI/debugging use.
*/
private String mCause = null;
/**
* Stores if this entry belongs to an HRG instance.
* This variable is not part of the concept. It is only used to simplify the implementation. Otherwise, the same class has to be duplicated with very minor differences in order to be used within a HRG
*/
private boolean mBelongstoHRG = false;
/**
* Constructor
*
* @param pSource the source of this route
* @param pDestination the destination of this route
* @param pNextHop the next hop for this route
* @param pHopCount the hop costs
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
private RoutingEntry(HRMID pSource, HRMID pDestination, HRMID pNextHop, int pHopCount, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
mDestination = pDestination;
mSource = pSource;
mNextHop = pNextHop;
mHopCount = pHopCount;
mUtilization = pUtilization;
mMinDelay = pMinDelay;
mMaxDataRate = pMaxDataRate;
mLocalLoop = false;
mRouteToDirectNeighbor = false;
mCause = pCause;
}
/**
* Constructor
*
* @param pDestination the destination of this route
* @param pNextHop the next hop for this route
* @param pHopCount the hop costs
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
private RoutingEntry(HRMID pDestination, HRMID pNextHop, int pHopCount, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
this(null, pDestination, pNextHop, pHopCount, pUtilization, pMinDelay, pMaxDataRate, pCause);
}
/**
* Factory function: creates a routing loop, which is used for routing traffic on the local host.
*
* @param pLoopAddress the address which defines the destination and next hop of this route
* @param pCause the cause for this routing table entry
*/
public static RoutingEntry createLocalhostEntry(HRMID pLoopAddress, String pCause)
{
// create instance
RoutingEntry tEntry = new RoutingEntry(null, pLoopAddress, pLoopAddress, NO_HOP_COSTS, NO_UTILIZATION, NO_DELAY, INFINITE_DATARATE, pCause);
// mark as local loop
tEntry.mLocalLoop = true;
// set the source of this route
tEntry.mSource = pLoopAddress;
// return with the entry
return tEntry;
}
/**
* Factory function: creates a general route
*
* @param pSource the source of the route
* @param pDestination the direct neighbor
* @param pNextHop the next hop for the route
* @param pHopCount the hop costs
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
public static RoutingEntry create(HRMID pSource, HRMID pDestination, HRMID pNextHop, int pHopCount, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
// create instance
RoutingEntry tEntry = new RoutingEntry(pSource, pDestination, pNextHop, pHopCount, pUtilization, pMinDelay, pMaxDataRate, pCause);
// return with the entry
return tEntry;
}
/**
* Factory function: creates a route to a direct neighbor.
*
* @param pSource the source of the route
* @param pDestination the direct neighbor
* @param pNextHop the next hop for the route
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
public static RoutingEntry createRouteToDirectNeighbor(HRMID pSource, HRMID pDestination, HRMID pNextHop, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
// create instance
RoutingEntry tEntry = create(pSource, pDestination, pNextHop, HRMConfig.Routing.HOP_COSTS_TO_A_DIRECT_NEIGHBOR, pUtilization, pMinDelay, pMaxDataRate, pCause);
// mark as local loop
tEntry.mRouteToDirectNeighbor = true;
// return with the entry
return tEntry;
}
/**
* Factory function: creates a route to a direct neighbor.
*
* @param pSource the source of the route
* @param pDirectNeighbor the direct neighbor
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
public static RoutingEntry createRouteToDirectNeighbor(HRMID pSource, HRMID pDirectNeighbor, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
// return with the entry
return createRouteToDirectNeighbor(pSource, pDirectNeighbor, pDirectNeighbor, pUtilization, pMinDelay, pMaxDataRate, pCause);
}
/**
* Factory function: creates a route to a direct neighbor.
*
* @param pDirectNeighbor the destination of the direct neighbor
* @param pUtilization the utilization of the described route
* @param pMinDelay the minimum additional delay the described route causes
* @param pMaxDataRate the maximum data rate the described route might provide
* @param pCause the cause for this routing table entry
*/
public static RoutingEntry createRouteToDirectNeighbor(HRMID pDirectNeighbor, float pUtilization, long pMinDelay, long pMaxDataRate, String pCause)
{
// return with the entry
return createRouteToDirectNeighbor(null, pDirectNeighbor, pUtilization, pMinDelay, pMaxDataRate, pCause);
}
/**
* Assigns the entry to an HRG instance
*/
public void assignToHRG(AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> pMHierarchicalRoutingGraph)
{
mBelongstoHRG = true;
}
/**
* Extends the cause string
*
* @param pCause the additional cause string
*/
public void extendCause(String pCause)
{
mCause += ", " + pCause;
}
/**
* Returns the cause for this entry
*
* @return the cause
*/
public String getCause()
{
return mCause;
}
/**
* Defines the L2 address of the next hop
*
* @param pDestL2Address the L2 address of the next hop
*/
public void setNextHopL2Address(L2Address pNextHopL2Address)
{
mNextHopL2Address = pNextHopL2Address;
}
/**
* Returns the L2 address of the next hop of this route (if known)
*
* @return the L2 address of the next hop, returns null if none is known
*/
public L2Address getNextHopL2Address()
{
return mNextHopL2Address;
}
/**
* Returns the source of the route
*
* @return the source
*/
public HRMID getSource()
{
return mSource;
}
/**
* Returns the destination of the route
*
* @return the destination
*/
public HRMID getDest()
{
return mDestination;
}
/**
* Returns the next hop of this route
*
* @return the next hop
*/
public HRMID getNextHop()
{
return mNextHop;
}
/**
* Returns the hop costs of this route
*
* @return the hop costs
*/
public int getHopCount()
{
return mHopCount;
}
/**
* Returns the utilization of this route
*
* @return the utilization
*/
public float getUtilization()
{
return mUtilization;
}
/**
* Returns the minimum additional delay this route causes.
*
* @return the minimum additional delay
*/
public long getMinDelay()
{
return mMinDelay;
}
/**
* Returns the maximum data rate this route might provide.
*
* @return the maximum data rate
*/
public long getMaxDataRate()
{
return mMaxDataRate;
}
/**
* Determines if the route describes a local loop.
* (for GUI only)
*
* @return true if the route is a local loop, otherwise false
*/
public boolean isLocalLoop()
{
return mLocalLoop;
}
/**
* Determines if the route ends at a direct neighbor.
* (for GUI only)
*
* @return true if the route is such a route, otherwise false
*/
public boolean isRouteToDirectNeighbor()
{
return mRouteToDirectNeighbor;
}
/**
* Creates an identical duplicate
*
* @return the identical duplicate
*/
public RoutingEntry clone()
{
// create object copy
RoutingEntry tResult = new RoutingEntry(mSource, mDestination, mNextHop, mHopCount, mUtilization, mMinDelay, mMaxDataRate, mCause);
// update the flag "route to direct neighbor"
tResult.mRouteToDirectNeighbor = mRouteToDirectNeighbor;
// update flag "route to local host"
tResult.mLocalLoop = mLocalLoop;
// update next hop L2 address
tResult.mNextHopL2Address = mNextHopL2Address;
return tResult;
}
/**
* Returns if both objects address the same cluster/coordinator
*
* @return true or false
*/
@Override
public boolean equals(Object pObj)
{
//Logging.trace(this, "Comparing routing entry with: " + pObj);
if(pObj instanceof RoutingEntry){
RoutingEntry tOther = (RoutingEntry)pObj;
- if(((getDest() == null) || (getDest().equals(tOther.getDest()))) &&
- ((getNextHop() == null) || (getNextHop().equals(tOther.getNextHop()))) &&
- ((getSource() == null) || (getSource().equals(tOther.getSource()))) &&
- ((getNextHopL2Address() == null) || (getNextHopL2Address().equals(tOther.getNextHopL2Address())))){
+ if(((getDest() == null) || (tOther.getDest() == null) || (getDest().equals(tOther.getDest()))) &&
+ ((getNextHop() == null) || (tOther.getNextHop() == null) || (getNextHop().equals(tOther.getNextHop()))) &&
+ ((getSource() == null) || (tOther.getSource() == null) || (getSource().equals(tOther.getSource()))) &&
+ ((getNextHopL2Address() == null) || (tOther.getNextHopL2Address() == null) || (getNextHopL2Address().equals(tOther.getNextHopL2Address())))){
//Logging.trace(this, " ..true");
return true;
}
}
//Logging.trace(this, " ..false");
return false;
}
/**
* Returns the size of a serialized representation
*
* @return the size
*/
@Override
public int getSerialisedSize()
{
// TODO: implement me
return 0;
}
/**
* Returns an object describing string
*
* @return the describing string
*/
@Override
public String toString()
{
if(!mBelongstoHRG){
return "(" + (getSource() != null ? "Source=" + getSource() + ", " : "") + "Dest.=" + getDest() + ", Next=" + getNextHop() + (getNextHopL2Address() != null ? ", NextL2=" + getNextHopL2Address() : "") + ", Hops=" + (getHopCount() > 0 ? getHopCount() : "none") + (HRMConfig.QoS.REPORT_QOS_ATTRIBUTES_AUTOMATICALLY ? ", Util=" + (getUtilization() > 0 ? getUtilization() : "none") + ", MinDel=" + (getMinDelay() > 0 ? getMinDelay() : "none") + ", MaxDR=" + (getMaxDataRate() > 0 ? getMaxDataRate() : "inf.") : "") + (mCause != "" ? ", Cause=" + mCause :"") + ")";
}else{
return getSource() + " <==> " + getNextHop() + ", Dest.=" + getDest() + (getNextHopL2Address() != null ? ", NextL2=" + getNextHopL2Address() : "") + ", Hops=" + (getHopCount() > 0 ? getHopCount() : "none") + (HRMConfig.QoS.REPORT_QOS_ATTRIBUTES_AUTOMATICALLY ? ", Util=" + (getUtilization() > 0 ? getUtilization() : "none") + ", MinDel=" + (getMinDelay() > 0 ? getMinDelay() : "none") + ", MaxDR=" + (getMaxDataRate() > 0 ? getMaxDataRate() : "inf.") : "") + (mCause != "" ? ", Cause=" + mCause :"");
}
}
}
| true | true | public boolean equals(Object pObj)
{
//Logging.trace(this, "Comparing routing entry with: " + pObj);
if(pObj instanceof RoutingEntry){
RoutingEntry tOther = (RoutingEntry)pObj;
if(((getDest() == null) || (getDest().equals(tOther.getDest()))) &&
((getNextHop() == null) || (getNextHop().equals(tOther.getNextHop()))) &&
((getSource() == null) || (getSource().equals(tOther.getSource()))) &&
((getNextHopL2Address() == null) || (getNextHopL2Address().equals(tOther.getNextHopL2Address())))){
//Logging.trace(this, " ..true");
return true;
}
}
//Logging.trace(this, " ..false");
return false;
}
| public boolean equals(Object pObj)
{
//Logging.trace(this, "Comparing routing entry with: " + pObj);
if(pObj instanceof RoutingEntry){
RoutingEntry tOther = (RoutingEntry)pObj;
if(((getDest() == null) || (tOther.getDest() == null) || (getDest().equals(tOther.getDest()))) &&
((getNextHop() == null) || (tOther.getNextHop() == null) || (getNextHop().equals(tOther.getNextHop()))) &&
((getSource() == null) || (tOther.getSource() == null) || (getSource().equals(tOther.getSource()))) &&
((getNextHopL2Address() == null) || (tOther.getNextHopL2Address() == null) || (getNextHopL2Address().equals(tOther.getNextHopL2Address())))){
//Logging.trace(this, " ..true");
return true;
}
}
//Logging.trace(this, " ..false");
return false;
}
|
diff --git a/opal-core-ws/src/main/java/org/obiba/opal/web/magma/DatasourcesResource.java b/opal-core-ws/src/main/java/org/obiba/opal/web/magma/DatasourcesResource.java
index f3f025d65..3c740c07f 100644
--- a/opal-core-ws/src/main/java/org/obiba/opal/web/magma/DatasourcesResource.java
+++ b/opal-core-ws/src/main/java/org/obiba/opal/web/magma/DatasourcesResource.java
@@ -1,117 +1,117 @@
/*******************************************************************************
* Copyright 2008(c) The OBiBa Consortium. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.obiba.opal.web.magma;
import java.net.URI;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import org.obiba.magma.Datasource;
import org.obiba.magma.DatasourceFactory;
import org.obiba.magma.MagmaEngine;
import org.obiba.magma.MagmaRuntimeException;
import org.obiba.magma.support.DatasourceParsingException;
import org.obiba.magma.support.Disposables;
import org.obiba.opal.web.magma.support.DatasourceFactoryRegistry;
import org.obiba.opal.web.magma.support.NoSuchDatasourceFactoryException;
import org.obiba.opal.web.model.Magma;
import org.obiba.opal.web.model.Magma.DatasourceDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.common.collect.Lists;
@Component
@Path("/datasources")
public class DatasourcesResource {
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(DatasourcesResource.class);
private final DatasourceFactoryRegistry datasourceFactoryRegistry;
@Autowired
public DatasourcesResource(DatasourceFactoryRegistry datasourceFactoryRegistry) {
if(datasourceFactoryRegistry == null) {
throw new IllegalArgumentException("datasourceFactoryRegistry cannot be null");
}
this.datasourceFactoryRegistry = datasourceFactoryRegistry;
}
@GET
public List<Magma.DatasourceDto> getDatasources() {
final List<Magma.DatasourceDto> datasources = Lists.newArrayList();
for(Datasource from : MagmaEngine.get().getDatasources()) {
URI dslink = UriBuilder.fromPath("/").path(DatasourceResource.class).build(from.getName());
Magma.DatasourceDto.Builder ds = Dtos.asDto(from).setLink(dslink.toString());
datasources.add(ds.build());
}
sortByName(datasources);
return datasources;
}
@POST
public Response createDatasource(@Context final UriInfo uriInfo, Magma.DatasourceFactoryDto factoryDto) {
String uid = null;
ResponseBuilder response = null;
try {
DatasourceFactory factory = datasourceFactoryRegistry.parse(factoryDto);
uid = MagmaEngine.get().addTransientDatasource(factory);
Datasource ds = MagmaEngine.get().getTransientDatasourceInstance(uid);
- UriBuilder ub = uriInfo.getBaseUriBuilder().path("datasource").path(uid);
+ UriBuilder ub = UriBuilder.fromPath("/").path("datasource").path(uid);
response = Response.created(ub.build()).entity(Dtos.asDto(ds).build());
Disposables.silentlyDispose(ds);
} catch(NoSuchDatasourceFactoryException e) {
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "UnidentifiedDatasourceFactory").build());
} catch(DatasourceParsingException pe) {
removeTransientDatasource(uid);
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "DatasourceCreationFailed", pe).build());
} catch(MagmaRuntimeException e) {
removeTransientDatasource(uid);
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "DatasourceCreationFailed", e).build());
}
return response.build();
}
private void removeTransientDatasource(String uid) {
if(uid != null) {
MagmaEngine.get().removeTransientDatasource(uid);
}
}
private void sortByName(List<Magma.DatasourceDto> datasources) {
// sort alphabetically
Collections.sort(datasources, new Comparator<Magma.DatasourceDto>() {
@Override
public int compare(DatasourceDto d1, DatasourceDto d2) {
return d1.getName().compareTo(d2.getName());
}
});
}
}
| true | true | public Response createDatasource(@Context final UriInfo uriInfo, Magma.DatasourceFactoryDto factoryDto) {
String uid = null;
ResponseBuilder response = null;
try {
DatasourceFactory factory = datasourceFactoryRegistry.parse(factoryDto);
uid = MagmaEngine.get().addTransientDatasource(factory);
Datasource ds = MagmaEngine.get().getTransientDatasourceInstance(uid);
UriBuilder ub = uriInfo.getBaseUriBuilder().path("datasource").path(uid);
response = Response.created(ub.build()).entity(Dtos.asDto(ds).build());
Disposables.silentlyDispose(ds);
} catch(NoSuchDatasourceFactoryException e) {
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "UnidentifiedDatasourceFactory").build());
} catch(DatasourceParsingException pe) {
removeTransientDatasource(uid);
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "DatasourceCreationFailed", pe).build());
} catch(MagmaRuntimeException e) {
removeTransientDatasource(uid);
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "DatasourceCreationFailed", e).build());
}
return response.build();
}
| public Response createDatasource(@Context final UriInfo uriInfo, Magma.DatasourceFactoryDto factoryDto) {
String uid = null;
ResponseBuilder response = null;
try {
DatasourceFactory factory = datasourceFactoryRegistry.parse(factoryDto);
uid = MagmaEngine.get().addTransientDatasource(factory);
Datasource ds = MagmaEngine.get().getTransientDatasourceInstance(uid);
UriBuilder ub = UriBuilder.fromPath("/").path("datasource").path(uid);
response = Response.created(ub.build()).entity(Dtos.asDto(ds).build());
Disposables.silentlyDispose(ds);
} catch(NoSuchDatasourceFactoryException e) {
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "UnidentifiedDatasourceFactory").build());
} catch(DatasourceParsingException pe) {
removeTransientDatasource(uid);
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "DatasourceCreationFailed", pe).build());
} catch(MagmaRuntimeException e) {
removeTransientDatasource(uid);
response = Response.status(Status.BAD_REQUEST).entity(ClientErrorDtos.getErrorMessage(Status.BAD_REQUEST, "DatasourceCreationFailed", e).build());
}
return response.build();
}
|
diff --git a/src/main/java/water/MRTask.java b/src/main/java/water/MRTask.java
index 2b814dcb1..676bd2a7b 100644
--- a/src/main/java/water/MRTask.java
+++ b/src/main/java/water/MRTask.java
@@ -1,78 +1,78 @@
package water;
import jsr166y.CountedCompleter;
/** Map/Reduce style distributed computation. */
public abstract class MRTask extends DRemoteTask {
transient private int _lo, _hi; // Range of keys to work on
transient private MRTask _left, _rite; // In-progress execution tree
public void init() {
_lo = 0;
_hi = _keys.length;
}
/** Run some useful function over this <strong>local</strong> key, and
* record the results in the <em>this<em> MRTask. */
abstract public void map( Key key );
long _reservedMem = 0;
boolean _hasReservedMem = false;
/** Do all the keys in the list associated with this Node. Roll up the
* results into <em>this<em> MRTask. */
@Override public final void compute2() {
if( _hi-_lo >= 2 ) { // Multi-key case: just divide-and-conquer to 1 key
final int mid = (_lo+_hi)>>>1; // Mid-point
assert _left == null && _rite == null;
MRTask l = (MRTask)clone();
MRTask r = (MRTask)clone();
if(!_hasReservedMem){ // try to reserve memory needed for computing subtree rooted at this node.
long memReq = (_hi - _lo + 1)*(ValueArray.CHUNK_SZ + memReqPerChunk());
if(_hasReservedMem = MemoryManager.tryReserveTaskMem(memReq))
_reservedMem = memReq; // remember the amount of memory reserved to free it when done
}
_left = l;
_rite = r;
// pass the memory allocation info on
// (pass only the hasMemory flag, the actual amount of reserved memory is stored only by the node which successfully reserved it and which will free it when done)
_left._hasReservedMem = _hasReservedMem;
_rite._hasReservedMem = _hasReservedMem;
_left._hi = mid; // Reset mid-point
_rite._lo = mid; // Also set self mid-point
if(_hasReservedMem) { // we have enough memory => run in parallel
setPendingCount(2);
_left.fork(); // Runs in another thread/FJ instance
_rite.fork(); // Runs in another thread/FJ instance
} else {
// not enough memory => go single threaded
// single threaded execution means this can not be set as completer of _left
// if pending count was > 0, it would hang after _left finished, as our only thread would be waiting for _rite which would never execute.
// if pending count was = 0, it would go on and execute onCompletion before _rite completes
_left.setCompleter(null);
_rite.setCompleter(null);
- _left.invoke();
- _rite.invoke();
+ _left.compute2();
+ _rite.compute2();
}
} else {
if( _hi > _lo ) // Single key?
map(_keys[_lo]); // Get it, run it locally
}
tryComplete(); // And this task is complete
}
@Override public final void onCompletion( CountedCompleter caller ) {
// Reduce results into 'this' so they collapse going up the execution tree.
// NULL out child-references so we don't accidentally keep large subtrees
// alive: each one may be holding large partial results.
if( _left != null ) reduceAlsoBlock(_left); _left = null;
if( _rite != null ) reduceAlsoBlock(_rite); _rite = null;
MemoryManager.freeTaskMem(_reservedMem);
}
@Override public final boolean onExceptionalCompletion(Throwable ex, CountedCompleter caller ) {
MemoryManager.freeTaskMem(_reservedMem);
return super.onExceptionalCompletion(ex, caller);
}
}
| true | true | @Override public final void compute2() {
if( _hi-_lo >= 2 ) { // Multi-key case: just divide-and-conquer to 1 key
final int mid = (_lo+_hi)>>>1; // Mid-point
assert _left == null && _rite == null;
MRTask l = (MRTask)clone();
MRTask r = (MRTask)clone();
if(!_hasReservedMem){ // try to reserve memory needed for computing subtree rooted at this node.
long memReq = (_hi - _lo + 1)*(ValueArray.CHUNK_SZ + memReqPerChunk());
if(_hasReservedMem = MemoryManager.tryReserveTaskMem(memReq))
_reservedMem = memReq; // remember the amount of memory reserved to free it when done
}
_left = l;
_rite = r;
// pass the memory allocation info on
// (pass only the hasMemory flag, the actual amount of reserved memory is stored only by the node which successfully reserved it and which will free it when done)
_left._hasReservedMem = _hasReservedMem;
_rite._hasReservedMem = _hasReservedMem;
_left._hi = mid; // Reset mid-point
_rite._lo = mid; // Also set self mid-point
if(_hasReservedMem) { // we have enough memory => run in parallel
setPendingCount(2);
_left.fork(); // Runs in another thread/FJ instance
_rite.fork(); // Runs in another thread/FJ instance
} else {
// not enough memory => go single threaded
// single threaded execution means this can not be set as completer of _left
// if pending count was > 0, it would hang after _left finished, as our only thread would be waiting for _rite which would never execute.
// if pending count was = 0, it would go on and execute onCompletion before _rite completes
_left.setCompleter(null);
_rite.setCompleter(null);
_left.invoke();
_rite.invoke();
}
} else {
if( _hi > _lo ) // Single key?
map(_keys[_lo]); // Get it, run it locally
}
tryComplete(); // And this task is complete
}
| @Override public final void compute2() {
if( _hi-_lo >= 2 ) { // Multi-key case: just divide-and-conquer to 1 key
final int mid = (_lo+_hi)>>>1; // Mid-point
assert _left == null && _rite == null;
MRTask l = (MRTask)clone();
MRTask r = (MRTask)clone();
if(!_hasReservedMem){ // try to reserve memory needed for computing subtree rooted at this node.
long memReq = (_hi - _lo + 1)*(ValueArray.CHUNK_SZ + memReqPerChunk());
if(_hasReservedMem = MemoryManager.tryReserveTaskMem(memReq))
_reservedMem = memReq; // remember the amount of memory reserved to free it when done
}
_left = l;
_rite = r;
// pass the memory allocation info on
// (pass only the hasMemory flag, the actual amount of reserved memory is stored only by the node which successfully reserved it and which will free it when done)
_left._hasReservedMem = _hasReservedMem;
_rite._hasReservedMem = _hasReservedMem;
_left._hi = mid; // Reset mid-point
_rite._lo = mid; // Also set self mid-point
if(_hasReservedMem) { // we have enough memory => run in parallel
setPendingCount(2);
_left.fork(); // Runs in another thread/FJ instance
_rite.fork(); // Runs in another thread/FJ instance
} else {
// not enough memory => go single threaded
// single threaded execution means this can not be set as completer of _left
// if pending count was > 0, it would hang after _left finished, as our only thread would be waiting for _rite which would never execute.
// if pending count was = 0, it would go on and execute onCompletion before _rite completes
_left.setCompleter(null);
_rite.setCompleter(null);
_left.compute2();
_rite.compute2();
}
} else {
if( _hi > _lo ) // Single key?
map(_keys[_lo]); // Get it, run it locally
}
tryComplete(); // And this task is complete
}
|
diff --git a/src/utils/UiHelpers.java b/src/utils/UiHelpers.java
index e271d98..9aa0268 100644
--- a/src/utils/UiHelpers.java
+++ b/src/utils/UiHelpers.java
@@ -1,170 +1,170 @@
package utils;
import daos.ConferenceDao;
import model.User;
public class UiHelpers {
public static StringBuilder GetAllJsAndCss()
{
StringBuilder sb = new StringBuilder();
sb.append("<link type=\"text/css\" href=\"css/main.css\" rel=\"stylesheet\" />");
sb.append("<link type=\"text/css\" href=\"css/tables/tableList.css\" rel=\"stylesheet\" />");
sb.append("<link type=\"text/css\" href=\"css/cupertino/jquery-ui-1.8.18.custom.css\" rel=\"stylesheet\" />");
sb.append("<link type=\"text/css\" href=\"css/jNotify.jquery.css\" rel=\"stylesheet\" />");
sb.append("<script type=\"text/javascript\" src=\"js/jquery-1.7.1.min.js\"></script>");
sb.append("<script type=\"text/javascript\" src=\"js/jquery-ui-1.8.18.custom.min.js\"></script>");
sb.append("<script type=\"text/javascript\" src=\"js/jquery.validate.js\"></script>");
sb.append("<script type=\"text/javascript\" src=\"js/jNotify.jquery.js\"></script>");
return sb;
}
public static StringBuilder GetHeader()
{
StringBuilder sb = new StringBuilder();
//Header start
//--------------------------------------------------------------------
sb.append("<div id=\"vn_header_div\">");
//Logo image
//--------------------------------------------------------------------
sb.append("<div id=\"vn_header_logo\">");
sb.append("<img width=\"97\" height=\"56\" border=\"0\" alt=\"\" src=\"/conf4u/resources/imgs/conf4u_logo.png\">");
sb.append("</div>");
//--------------------------------------------------------------------
//Top links
//--------------------------------------------------------------------
sb.append("<div id=\"vn_header_toprightlinks\">");
sb.append("<div class=\"vn_header_toprightlink\">");
sb.append("<a class=\"isnormal\" href=\"LoginServlet?action=logout\">Log off</a>");
sb.append("</div>");
sb.append("</div>");
//--------------------------------------------------------------------
sb.append("</div>");
//--------------------------------------------------------------------
sb.append("<div class=\"clearboth\"></div>");
return sb;
}
public static StringBuilder GetTabs(User requstingUser, String chosenTab)
{
StringBuilder sb = new StringBuilder();
//Tabs starts
//--------------------------------------------------------------------
sb.append("<div id=\"navHIDDENBYTAL\">");
sb.append("<div id=\"vn_header_tabs\">");
sb.append("<ul>");
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Users tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_USERS == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"users.jsp\">");
sb.append("<span>Users</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Conferences tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_CONFERENCES == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"conference.jsp\">");
sb.append("<span>Conferences</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Companies tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_COMPANIES == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"company.jsp\">");
sb.append("<span>Companies</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Locations tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_LOCATIONS == chosenTab ? " class=\"focuslink\"" : ""));
- sb.append("<a href=\"location.jsp\">");
+ sb.append("<a href=\"locations.jsp\">");
sb.append("<span>Locations</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Reception tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_RECEPTION == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"reception.jsp\">");
sb.append("<span>Reception</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
sb.append("</ul>");
sb.append("</div>");
sb.append("</div>");
sb.append("<div id=\"bottomNav\"> </div>");
//--------------------------------------------------------------------
sb.append("<div class=\"clearboth\"></div>");
return sb;
}
public static StringBuilder GetHeader(User requstingUser)
{
StringBuilder sb = new StringBuilder();
//Header start
//--------------------------------------------------------------------
sb.append("<div id=\"vn_header_div\">");
//Logo image
//--------------------------------------------------------------------
sb.append("<div id=\"vn_header_logo\">");
sb.append("<img width=\"97\" height=\"56\" border=\"0\" alt=\"\" src=\"/conf4u/resources/imgs/conf4u_logo.png\">");
sb.append("</div>");
//--------------------------------------------------------------------
//Top links
//--------------------------------------------------------------------
sb.append("<div id=\"vn_header_toprightlinks\">");
sb.append("<div class=\"vn_header_toprightlink\">");
sb.append("<a class=\"isnormal\"> connected as: " + requstingUser.getName() + "</a><br />");
sb.append("<a class=\"isbold\" href=\"LoginServlet?action=logout\">Log off</a>");
sb.append("</div>");
sb.append("</div>");
//--------------------------------------------------------------------
sb.append("</div>");
//--------------------------------------------------------------------
sb.append("<div class=\"clearboth\"></div>");
return sb;
}
}
| true | true | public static StringBuilder GetTabs(User requstingUser, String chosenTab)
{
StringBuilder sb = new StringBuilder();
//Tabs starts
//--------------------------------------------------------------------
sb.append("<div id=\"navHIDDENBYTAL\">");
sb.append("<div id=\"vn_header_tabs\">");
sb.append("<ul>");
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Users tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_USERS == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"users.jsp\">");
sb.append("<span>Users</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Conferences tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_CONFERENCES == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"conference.jsp\">");
sb.append("<span>Conferences</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Companies tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_COMPANIES == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"company.jsp\">");
sb.append("<span>Companies</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Locations tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_LOCATIONS == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"location.jsp\">");
sb.append("<span>Locations</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Reception tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_RECEPTION == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"reception.jsp\">");
sb.append("<span>Reception</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
sb.append("</ul>");
sb.append("</div>");
sb.append("</div>");
sb.append("<div id=\"bottomNav\"> </div>");
//--------------------------------------------------------------------
sb.append("<div class=\"clearboth\"></div>");
return sb;
}
| public static StringBuilder GetTabs(User requstingUser, String chosenTab)
{
StringBuilder sb = new StringBuilder();
//Tabs starts
//--------------------------------------------------------------------
sb.append("<div id=\"navHIDDENBYTAL\">");
sb.append("<div id=\"vn_header_tabs\">");
sb.append("<ul>");
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Users tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_USERS == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"users.jsp\">");
sb.append("<span>Users</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Conferences tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_CONFERENCES == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"conference.jsp\">");
sb.append("<span>Conferences</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Companies tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_COMPANIES == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"company.jsp\">");
sb.append("<span>Companies</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Locations tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_LOCATIONS == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"locations.jsp\">");
sb.append("<span>Locations</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
if (requstingUser.isAdmin() || ConferenceDao.getInstance().getUserHighestRole(requstingUser).getValue() >= 3)
{
//Reception tab
//--------------------------------------------------------------------
sb.append(String.format("<li%s>", ProjConst.TAB_RECEPTION == chosenTab ? " class=\"focuslink\"" : ""));
sb.append("<a href=\"reception.jsp\">");
sb.append("<span>Reception</span>");
sb.append("</a>");
sb.append("</li>");
//--------------------------------------------------------------------
}
sb.append("</ul>");
sb.append("</div>");
sb.append("</div>");
sb.append("<div id=\"bottomNav\"> </div>");
//--------------------------------------------------------------------
sb.append("<div class=\"clearboth\"></div>");
return sb;
}
|
diff --git a/src/java/org/apache/log4j/spi/location/LegacyExtractor.java b/src/java/org/apache/log4j/spi/location/LegacyExtractor.java
index 3079be48..e0687320 100644
--- a/src/java/org/apache/log4j/spi/location/LegacyExtractor.java
+++ b/src/java/org/apache/log4j/spi/location/LegacyExtractor.java
@@ -1,205 +1,210 @@
/*
* Copyright 1999,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.log4j.spi.location;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.PlatformInfo;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Extract location information from a throwable. The techniques used here
* work on all JDK platforms including those prior to JDK 1.4.
*
* @since 1.3
* @author Ceki Gülcü
*/
public class LegacyExtractor {
private static StringWriter sw = new StringWriter();
private static PrintWriter pw = new PrintWriter(sw);
private LegacyExtractor() {
}
static void extract(LocationInfo li, Throwable t, String fqnOfCallingClass) {
+ // on AS400, package path separator in stack trace is not dot '.',
+ // but slash '/'
+ if (PlatformInfo.isOnAS400()) {
+ fqnOfCallingClass = fqnOfCallingClass.replace('.', '/');
+ }
String s;
// Protect against multiple access to sw.
synchronized (sw) {
t.printStackTrace(pw);
s = sw.toString();
sw.getBuffer().setLength(0);
}
//System.out.println("s is ["+s+"].");
int ibegin;
//System.out.println("s is ["+s+"].");
int iend;
// Given the current structure of log4j, the line
// containing 'fqnOfCallingClass', usually "org.apache.log4j.Logger."
// should be printed just before the caller.
// This method of searching may not be fastest but it's safer
// than counting the stack depth which is not guaranteed to be
// constant across JVM implementations.
ibegin = s.lastIndexOf(fqnOfCallingClass);
if (ibegin == -1) {
return;
}
ibegin = s.indexOf(Layout.LINE_SEP, ibegin);
if (ibegin == -1) {
return;
}
ibegin += Layout.LINE_SEP_LEN;
// determine end of line
iend = s.indexOf(Layout.LINE_SEP, ibegin);
if (iend == -1) {
return;
}
// VA has a different stack trace format which doesn't
- // need to skip the inital 'at'
- if (!PlatformInfo.isInVisualAge()) {
+ // need to skip the inital 'at'. The same applied to AS400.
+ if ((!PlatformInfo.isInVisualAge()) && (!PlatformInfo.isOnAS400())) {
// back up to first blank character
ibegin = s.lastIndexOf("at ", iend);
if (ibegin == -1) {
return;
}
// Add 3 to skip "at ";
ibegin += 3;
}
// everything between is the requested stack item
li.fullInfo = s.substring(ibegin, iend);
setFileName(li, li.fullInfo );
setClassName(li, li.fullInfo );
setMethodName(li, li.fullInfo );
setLineNumber(li, li.fullInfo );
}
/**
* Make a best-effort attemt at setting the fike name of the caller.
* This information may not always be available.
*/
static void setFileName(LocationInfo li, String fullInfo) {
if (fullInfo == null) {
li.fileName = LocationInfo.NA;
} else {
int iend = fullInfo.lastIndexOf(':');
if (iend == -1) {
li.fileName = LocationInfo.NA;
} else {
int ibegin = fullInfo.lastIndexOf('(', iend - 1);
li.fileName = fullInfo.substring(ibegin + 1, iend);
}
}
}
/**
* Make a best-effort attemt at setting the class name of the caller.
* This information may not always be available.
*/
static void setClassName(LocationInfo li, String fullInfo) {
if (fullInfo == null) {
li.className = LocationInfo.NA;
return;
}
// Starting the search from '(' is safer because there is
// potentially a dot between the parentheses.
int iend = fullInfo.lastIndexOf('(');
if (iend == -1) {
li.className = LocationInfo.NA;
} else {
iend = fullInfo.lastIndexOf('.', iend);
// This is because a stack trace in VisualAge looks like:
//java.lang.RuntimeException
// java.lang.Throwable()
// java.lang.Exception()
// java.lang.RuntimeException()
// void test.test.B.print()
// void test.test.A.printIndirect()
// void test.test.Run.main(java.lang.String [])
int ibegin = 0;
if (PlatformInfo.isInVisualAge()) {
ibegin = fullInfo.lastIndexOf(' ', iend) + 1;
}
if (iend == -1) {
li.className = LocationInfo.NA;
} else {
li.className = fullInfo.substring(ibegin, iend);
}
}
}
/**
* Make a best-effort attemt at setting the line number of the caller.
* This information may not always be available.
*/
static void setLineNumber(LocationInfo li, String fullInfo) {
if (fullInfo == null) {
li.lineNumber = LocationInfo.NA;
} else {
int iend = fullInfo.lastIndexOf(')');
int ibegin = fullInfo.lastIndexOf(':', iend - 1);
if (ibegin == -1) {
li.lineNumber = LocationInfo.NA;
} else {
li.lineNumber = fullInfo.substring(ibegin + 1, iend);
}
}
}
/**
* Make a best-effort attemt at setting the method name of the caller.
* This information may not always be available.
*/
static void setMethodName(LocationInfo li, String fullInfo) {
if (fullInfo == null) {
li.methodName = LocationInfo.NA;
} else {
int iend = fullInfo.lastIndexOf('(');
int ibegin = fullInfo.lastIndexOf('.', iend);
if (ibegin == -1) {
li.methodName = LocationInfo.NA;
} else {
li.methodName = fullInfo.substring(ibegin + 1, iend);
}
}
}
}
| false | true | static void extract(LocationInfo li, Throwable t, String fqnOfCallingClass) {
String s;
// Protect against multiple access to sw.
synchronized (sw) {
t.printStackTrace(pw);
s = sw.toString();
sw.getBuffer().setLength(0);
}
//System.out.println("s is ["+s+"].");
int ibegin;
//System.out.println("s is ["+s+"].");
int iend;
// Given the current structure of log4j, the line
// containing 'fqnOfCallingClass', usually "org.apache.log4j.Logger."
// should be printed just before the caller.
// This method of searching may not be fastest but it's safer
// than counting the stack depth which is not guaranteed to be
// constant across JVM implementations.
ibegin = s.lastIndexOf(fqnOfCallingClass);
if (ibegin == -1) {
return;
}
ibegin = s.indexOf(Layout.LINE_SEP, ibegin);
if (ibegin == -1) {
return;
}
ibegin += Layout.LINE_SEP_LEN;
// determine end of line
iend = s.indexOf(Layout.LINE_SEP, ibegin);
if (iend == -1) {
return;
}
// VA has a different stack trace format which doesn't
// need to skip the inital 'at'
if (!PlatformInfo.isInVisualAge()) {
// back up to first blank character
ibegin = s.lastIndexOf("at ", iend);
if (ibegin == -1) {
return;
}
// Add 3 to skip "at ";
ibegin += 3;
}
// everything between is the requested stack item
li.fullInfo = s.substring(ibegin, iend);
setFileName(li, li.fullInfo );
setClassName(li, li.fullInfo );
setMethodName(li, li.fullInfo );
setLineNumber(li, li.fullInfo );
}
| static void extract(LocationInfo li, Throwable t, String fqnOfCallingClass) {
// on AS400, package path separator in stack trace is not dot '.',
// but slash '/'
if (PlatformInfo.isOnAS400()) {
fqnOfCallingClass = fqnOfCallingClass.replace('.', '/');
}
String s;
// Protect against multiple access to sw.
synchronized (sw) {
t.printStackTrace(pw);
s = sw.toString();
sw.getBuffer().setLength(0);
}
//System.out.println("s is ["+s+"].");
int ibegin;
//System.out.println("s is ["+s+"].");
int iend;
// Given the current structure of log4j, the line
// containing 'fqnOfCallingClass', usually "org.apache.log4j.Logger."
// should be printed just before the caller.
// This method of searching may not be fastest but it's safer
// than counting the stack depth which is not guaranteed to be
// constant across JVM implementations.
ibegin = s.lastIndexOf(fqnOfCallingClass);
if (ibegin == -1) {
return;
}
ibegin = s.indexOf(Layout.LINE_SEP, ibegin);
if (ibegin == -1) {
return;
}
ibegin += Layout.LINE_SEP_LEN;
// determine end of line
iend = s.indexOf(Layout.LINE_SEP, ibegin);
if (iend == -1) {
return;
}
// VA has a different stack trace format which doesn't
// need to skip the inital 'at'. The same applied to AS400.
if ((!PlatformInfo.isInVisualAge()) && (!PlatformInfo.isOnAS400())) {
// back up to first blank character
ibegin = s.lastIndexOf("at ", iend);
if (ibegin == -1) {
return;
}
// Add 3 to skip "at ";
ibegin += 3;
}
// everything between is the requested stack item
li.fullInfo = s.substring(ibegin, iend);
setFileName(li, li.fullInfo );
setClassName(li, li.fullInfo );
setMethodName(li, li.fullInfo );
setLineNumber(li, li.fullInfo );
}
|
diff --git a/insulae-deployable/src/main/java/com/warspite/insulae/jetty/JettyRunner.java b/insulae-deployable/src/main/java/com/warspite/insulae/jetty/JettyRunner.java
index 869e107..134af58 100644
--- a/insulae-deployable/src/main/java/com/warspite/insulae/jetty/JettyRunner.java
+++ b/insulae-deployable/src/main/java/com/warspite/insulae/jetty/JettyRunner.java
@@ -1,153 +1,154 @@
package com.warspite.insulae.jetty;
import java.io.File;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.warspite.common.cli.CliListener;
import com.warspite.common.servlets.sessions.SessionKeeper;
import com.warspite.insulae.mechanisms.geography.*;
import com.warspite.insulae.mechanisms.industry.*;
import com.warspite.insulae.servlets.world.*;
import com.warspite.insulae.servlets.account.*;
import com.warspite.insulae.servlets.geography.*;
import com.warspite.insulae.servlets.industry.*;
import com.warspite.insulae.database.InsulaeDatabase;
public class JettyRunner extends Thread implements CliListener {
private final String API_PATH = "/api";
private final Logger logger = LoggerFactory.getLogger(getClass());
private final SessionKeeper sessionKeeper;
private Server server;
private boolean online = false;
private boolean halt = false;
private boolean aborted = false;
private final int serverPort;
private final InsulaeDatabase db;
private final File warFile;
public JettyRunner(final int serverPort, final SessionKeeper sessionKeeper, final InsulaeDatabase db, final File warFile) {
this.serverPort = serverPort;
this.sessionKeeper = sessionKeeper;
this.db = db;
this.warFile = warFile;
}
public boolean isOnline() {
return online;
}
public void setHalt(final boolean halt) {
this.halt = halt;
}
public boolean hasAborted() {
return aborted;
}
@Override
public void run() {
try {
startServer();
synchronized(this) {
while(!halt) {
Thread.sleep(250);
}
}
}
catch (Exception e) {
logger.error("Failure while running Jetty server.", e);
aborted = true;
}
finally {
try {
stopServer();
}
catch (Exception e) {
logger.error("Failed to stop Jetty server.", e);
}
}
}
private Server createServer() {
logger.info("Jetty launching at port " + serverPort + ", WAR " + warFile);
final WebAppContext webapp = new WebAppContext();
final PathFinder pathFinder = new PathFinder(db, PathFinder.AREA_TRANSITION_COST());
final ItemTransactor itemTransactor = new ItemTransactor(db);
final ActionPerformer actionPerformer = new ActionPerformer(db, itemTransactor);
webapp.setContextPath("/");
webapp.setWar(warFile.getAbsolutePath());
webapp.addServlet(new ServletHolder(new AccountServlet(db, sessionKeeper)), API_PATH + "/account/Account");
webapp.addServlet(new ServletHolder(new SessionServlet(db, sessionKeeper)), API_PATH + "/account/Session");
webapp.addServlet(new ServletHolder(new RealmServlet(db, sessionKeeper)), API_PATH + "/world/Realm");
webapp.addServlet(new ServletHolder(new RaceServlet(db, sessionKeeper)), API_PATH + "/world/Race");
webapp.addServlet(new ServletHolder(new SexServlet(db, sessionKeeper)), API_PATH + "/world/Sex");
webapp.addServlet(new ServletHolder(new AvatarServlet(db, sessionKeeper)), API_PATH + "/world/Avatar");
webapp.addServlet(new ServletHolder(new AreaServlet(db, sessionKeeper)), API_PATH + "/geography/Area");
webapp.addServlet(new ServletHolder(new LocationServlet(db, sessionKeeper)), API_PATH + "/geography/Location");
webapp.addServlet(new ServletHolder(new LocationTypeServlet(db, sessionKeeper)), API_PATH + "/geography/LocationType");
webapp.addServlet(new ServletHolder(new TransportationTypeServlet(db, sessionKeeper)), API_PATH + "/geography/TransportationType");
webapp.addServlet(new ServletHolder(new TransportationCostServlet(db, sessionKeeper)), API_PATH + "/geography/TransportationCost");
webapp.addServlet(new ServletHolder(new LocationNeighborServlet(db, sessionKeeper)), API_PATH + "/geography/LocationNeighbor");
webapp.addServlet(new ServletHolder(new BuildingTypeServlet(db, sessionKeeper)), API_PATH + "/industry/BuildingType");
webapp.addServlet(new ServletHolder(new BuildingServlet(db, sessionKeeper, pathFinder)), API_PATH + "/industry/Building");
webapp.addServlet(new ServletHolder(new ItemTypeServlet(db, sessionKeeper)), API_PATH + "/industry/ItemType");
webapp.addServlet(new ServletHolder(new ItemStorageServlet(db, sessionKeeper)), API_PATH + "/industry/ItemStorage");
webapp.addServlet(new ServletHolder(new ActionServlet(db, sessionKeeper, actionPerformer)), API_PATH + "/industry/Action");
webapp.addServlet(new ServletHolder(new ActionItemCostServlet(db, sessionKeeper)), API_PATH + "/industry/ActionItemCost");
+ webapp.addServlet(new ServletHolder(new ActionItemOutputServlet(db, sessionKeeper)), API_PATH + "/industry/ActionItemOutput");
final Server server = new Server(serverPort);
server.setHandler(webapp);
logger.debug("Jetty server created.");
return server;
}
private void startServer() throws Exception {
if( server == null ) {
try {
logger.debug("Creating Jetty server.");
server = createServer();
logger.debug("Jetty server created.");
}
catch(Throwable e) {
logger.error("Failed to create Jetty server.", e);
aborted = true;
return;
}
}
logger.debug("Starting Jetty server.");
server.start();
sessionKeeper.start();
online = true;
halt = false;
logger.debug("Jetty server started.");
}
private void stopServer() throws Exception {
if(server == null) {
logger.debug("Tried to stop Jetty server, but there is no server to stop.");
return;
}
logger.debug("Stopping Jetty server.");
server.stop();
sessionKeeper.stop();
online = false;
halt = false;
logger.debug("Jetty server stopped.");
}
}
| true | true | private Server createServer() {
logger.info("Jetty launching at port " + serverPort + ", WAR " + warFile);
final WebAppContext webapp = new WebAppContext();
final PathFinder pathFinder = new PathFinder(db, PathFinder.AREA_TRANSITION_COST());
final ItemTransactor itemTransactor = new ItemTransactor(db);
final ActionPerformer actionPerformer = new ActionPerformer(db, itemTransactor);
webapp.setContextPath("/");
webapp.setWar(warFile.getAbsolutePath());
webapp.addServlet(new ServletHolder(new AccountServlet(db, sessionKeeper)), API_PATH + "/account/Account");
webapp.addServlet(new ServletHolder(new SessionServlet(db, sessionKeeper)), API_PATH + "/account/Session");
webapp.addServlet(new ServletHolder(new RealmServlet(db, sessionKeeper)), API_PATH + "/world/Realm");
webapp.addServlet(new ServletHolder(new RaceServlet(db, sessionKeeper)), API_PATH + "/world/Race");
webapp.addServlet(new ServletHolder(new SexServlet(db, sessionKeeper)), API_PATH + "/world/Sex");
webapp.addServlet(new ServletHolder(new AvatarServlet(db, sessionKeeper)), API_PATH + "/world/Avatar");
webapp.addServlet(new ServletHolder(new AreaServlet(db, sessionKeeper)), API_PATH + "/geography/Area");
webapp.addServlet(new ServletHolder(new LocationServlet(db, sessionKeeper)), API_PATH + "/geography/Location");
webapp.addServlet(new ServletHolder(new LocationTypeServlet(db, sessionKeeper)), API_PATH + "/geography/LocationType");
webapp.addServlet(new ServletHolder(new TransportationTypeServlet(db, sessionKeeper)), API_PATH + "/geography/TransportationType");
webapp.addServlet(new ServletHolder(new TransportationCostServlet(db, sessionKeeper)), API_PATH + "/geography/TransportationCost");
webapp.addServlet(new ServletHolder(new LocationNeighborServlet(db, sessionKeeper)), API_PATH + "/geography/LocationNeighbor");
webapp.addServlet(new ServletHolder(new BuildingTypeServlet(db, sessionKeeper)), API_PATH + "/industry/BuildingType");
webapp.addServlet(new ServletHolder(new BuildingServlet(db, sessionKeeper, pathFinder)), API_PATH + "/industry/Building");
webapp.addServlet(new ServletHolder(new ItemTypeServlet(db, sessionKeeper)), API_PATH + "/industry/ItemType");
webapp.addServlet(new ServletHolder(new ItemStorageServlet(db, sessionKeeper)), API_PATH + "/industry/ItemStorage");
webapp.addServlet(new ServletHolder(new ActionServlet(db, sessionKeeper, actionPerformer)), API_PATH + "/industry/Action");
webapp.addServlet(new ServletHolder(new ActionItemCostServlet(db, sessionKeeper)), API_PATH + "/industry/ActionItemCost");
final Server server = new Server(serverPort);
server.setHandler(webapp);
logger.debug("Jetty server created.");
return server;
}
| private Server createServer() {
logger.info("Jetty launching at port " + serverPort + ", WAR " + warFile);
final WebAppContext webapp = new WebAppContext();
final PathFinder pathFinder = new PathFinder(db, PathFinder.AREA_TRANSITION_COST());
final ItemTransactor itemTransactor = new ItemTransactor(db);
final ActionPerformer actionPerformer = new ActionPerformer(db, itemTransactor);
webapp.setContextPath("/");
webapp.setWar(warFile.getAbsolutePath());
webapp.addServlet(new ServletHolder(new AccountServlet(db, sessionKeeper)), API_PATH + "/account/Account");
webapp.addServlet(new ServletHolder(new SessionServlet(db, sessionKeeper)), API_PATH + "/account/Session");
webapp.addServlet(new ServletHolder(new RealmServlet(db, sessionKeeper)), API_PATH + "/world/Realm");
webapp.addServlet(new ServletHolder(new RaceServlet(db, sessionKeeper)), API_PATH + "/world/Race");
webapp.addServlet(new ServletHolder(new SexServlet(db, sessionKeeper)), API_PATH + "/world/Sex");
webapp.addServlet(new ServletHolder(new AvatarServlet(db, sessionKeeper)), API_PATH + "/world/Avatar");
webapp.addServlet(new ServletHolder(new AreaServlet(db, sessionKeeper)), API_PATH + "/geography/Area");
webapp.addServlet(new ServletHolder(new LocationServlet(db, sessionKeeper)), API_PATH + "/geography/Location");
webapp.addServlet(new ServletHolder(new LocationTypeServlet(db, sessionKeeper)), API_PATH + "/geography/LocationType");
webapp.addServlet(new ServletHolder(new TransportationTypeServlet(db, sessionKeeper)), API_PATH + "/geography/TransportationType");
webapp.addServlet(new ServletHolder(new TransportationCostServlet(db, sessionKeeper)), API_PATH + "/geography/TransportationCost");
webapp.addServlet(new ServletHolder(new LocationNeighborServlet(db, sessionKeeper)), API_PATH + "/geography/LocationNeighbor");
webapp.addServlet(new ServletHolder(new BuildingTypeServlet(db, sessionKeeper)), API_PATH + "/industry/BuildingType");
webapp.addServlet(new ServletHolder(new BuildingServlet(db, sessionKeeper, pathFinder)), API_PATH + "/industry/Building");
webapp.addServlet(new ServletHolder(new ItemTypeServlet(db, sessionKeeper)), API_PATH + "/industry/ItemType");
webapp.addServlet(new ServletHolder(new ItemStorageServlet(db, sessionKeeper)), API_PATH + "/industry/ItemStorage");
webapp.addServlet(new ServletHolder(new ActionServlet(db, sessionKeeper, actionPerformer)), API_PATH + "/industry/Action");
webapp.addServlet(new ServletHolder(new ActionItemCostServlet(db, sessionKeeper)), API_PATH + "/industry/ActionItemCost");
webapp.addServlet(new ServletHolder(new ActionItemOutputServlet(db, sessionKeeper)), API_PATH + "/industry/ActionItemOutput");
final Server server = new Server(serverPort);
server.setHandler(webapp);
logger.debug("Jetty server created.");
return server;
}
|
diff --git a/vo/src/main/uk/ac/starlink/vo/VORegResource.java b/vo/src/main/uk/ac/starlink/vo/VORegResource.java
index 7573f4a9e..6305efd34 100644
--- a/vo/src/main/uk/ac/starlink/vo/VORegResource.java
+++ b/vo/src/main/uk/ac/starlink/vo/VORegResource.java
@@ -1,97 +1,111 @@
package uk.ac.starlink.vo;
import java.util.ArrayList;
import java.util.List;
import net.ivoa.registry.search.VOResource;
import net.ivoa.registry.search.Metadata;
/**
* RegResource implementation based on a <code>VOResource</code> object.
*
* @author Mark Taylor
* @since 17 Dec 2008
*/
public class VORegResource implements RegResource {
private final String shortName_;
private final String title_;
private final String identifier_;
private final String publisher_;
private final String contact_;
private final String referenceUrl_;
private final RegCapabilityInterface[] capabilities_;
/**
* Constructor.
*
* @param resource resource object
*/
public VORegResource( VOResource resource ) {
shortName_ = resource.getParameter( "shortName" );
title_ = resource.getParameter( "title" );
identifier_ = resource.getParameter( "identifier" );
publisher_ = resource.getParameter( "curation/publisher" );
- contact_ = resource.getParameter( "curation/contact" );
+ String contactName = resource.getParameter( "curation/contact/name" );
+ String contactEmail = resource.getParameter( "curation/contact/email" );
+ if ( contactEmail != null && contactEmail.trim().length() > 0 &&
+ contactName != null && contactName.trim().length() > 0 ) {
+ contact_ = contactName + " <" + contactEmail + ">";
+ }
+ else if ( contactEmail != null && contactEmail.trim().length() > 0 ) {
+ contact_ = contactEmail;
+ }
+ else if ( contactName != null && contactName.trim().length() > 0 ) {
+ contact_ = contactName;
+ }
+ else {
+ contact_ = null;
+ }
referenceUrl_ = resource.getParameter( "content/referenceURL" );
Metadata[] capBlocks = resource.getBlocks( "capability" );
List capList = new ArrayList();
for ( int ic = 0; ic < capBlocks.length; ic++ ) {
Metadata capBlock = capBlocks[ ic ];
final String standardId = capBlock.getParameter( "@standardID" );
final String description = capBlock.getParameter( "description" );
Metadata[] intfs = capBlock.getBlocks( "interface" );
for ( int ii = 0; ii < intfs.length; ii++ ) {
Metadata intf = intfs[ ii ];
final String accessUrl = intf.getParameter( "accessURL" );
final String version = intf.getParameter( "@version" );
final String role = intf.getParameter( "@role" );
RegCapabilityInterface rci = new RegCapabilityInterface() {
public String getAccessUrl() {
return accessUrl;
}
public String getStandardId() {
return standardId;
}
public String getDescription() {
return description;
}
public String getVersion() {
return version;
}
};
capList.add( "std".equals( role ) ? 0 : capList.size(),
rci );
}
}
capabilities_ = (RegCapabilityInterface[])
capList.toArray( new RegCapabilityInterface[ 0 ] );
}
public String getShortName() {
return shortName_;
}
public String getTitle() {
return title_;
}
public String getIdentifier() {
return identifier_;
}
public String getPublisher() {
return publisher_;
}
public String getContact() {
return contact_;
}
public String getReferenceUrl() {
return referenceUrl_;
}
public RegCapabilityInterface[] getCapabilities() {
return capabilities_;
}
}
| true | true | public VORegResource( VOResource resource ) {
shortName_ = resource.getParameter( "shortName" );
title_ = resource.getParameter( "title" );
identifier_ = resource.getParameter( "identifier" );
publisher_ = resource.getParameter( "curation/publisher" );
contact_ = resource.getParameter( "curation/contact" );
referenceUrl_ = resource.getParameter( "content/referenceURL" );
Metadata[] capBlocks = resource.getBlocks( "capability" );
List capList = new ArrayList();
for ( int ic = 0; ic < capBlocks.length; ic++ ) {
Metadata capBlock = capBlocks[ ic ];
final String standardId = capBlock.getParameter( "@standardID" );
final String description = capBlock.getParameter( "description" );
Metadata[] intfs = capBlock.getBlocks( "interface" );
for ( int ii = 0; ii < intfs.length; ii++ ) {
Metadata intf = intfs[ ii ];
final String accessUrl = intf.getParameter( "accessURL" );
final String version = intf.getParameter( "@version" );
final String role = intf.getParameter( "@role" );
RegCapabilityInterface rci = new RegCapabilityInterface() {
public String getAccessUrl() {
return accessUrl;
}
public String getStandardId() {
return standardId;
}
public String getDescription() {
return description;
}
public String getVersion() {
return version;
}
};
capList.add( "std".equals( role ) ? 0 : capList.size(),
rci );
}
}
capabilities_ = (RegCapabilityInterface[])
capList.toArray( new RegCapabilityInterface[ 0 ] );
}
| public VORegResource( VOResource resource ) {
shortName_ = resource.getParameter( "shortName" );
title_ = resource.getParameter( "title" );
identifier_ = resource.getParameter( "identifier" );
publisher_ = resource.getParameter( "curation/publisher" );
String contactName = resource.getParameter( "curation/contact/name" );
String contactEmail = resource.getParameter( "curation/contact/email" );
if ( contactEmail != null && contactEmail.trim().length() > 0 &&
contactName != null && contactName.trim().length() > 0 ) {
contact_ = contactName + " <" + contactEmail + ">";
}
else if ( contactEmail != null && contactEmail.trim().length() > 0 ) {
contact_ = contactEmail;
}
else if ( contactName != null && contactName.trim().length() > 0 ) {
contact_ = contactName;
}
else {
contact_ = null;
}
referenceUrl_ = resource.getParameter( "content/referenceURL" );
Metadata[] capBlocks = resource.getBlocks( "capability" );
List capList = new ArrayList();
for ( int ic = 0; ic < capBlocks.length; ic++ ) {
Metadata capBlock = capBlocks[ ic ];
final String standardId = capBlock.getParameter( "@standardID" );
final String description = capBlock.getParameter( "description" );
Metadata[] intfs = capBlock.getBlocks( "interface" );
for ( int ii = 0; ii < intfs.length; ii++ ) {
Metadata intf = intfs[ ii ];
final String accessUrl = intf.getParameter( "accessURL" );
final String version = intf.getParameter( "@version" );
final String role = intf.getParameter( "@role" );
RegCapabilityInterface rci = new RegCapabilityInterface() {
public String getAccessUrl() {
return accessUrl;
}
public String getStandardId() {
return standardId;
}
public String getDescription() {
return description;
}
public String getVersion() {
return version;
}
};
capList.add( "std".equals( role ) ? 0 : capList.size(),
rci );
}
}
capabilities_ = (RegCapabilityInterface[])
capList.toArray( new RegCapabilityInterface[ 0 ] );
}
|
diff --git a/src/org/pentaho/platform/dataaccess/datasource/wizard/service/impl/ModelerService.java b/src/org/pentaho/platform/dataaccess/datasource/wizard/service/impl/ModelerService.java
index f28d93b0..2a748124 100644
--- a/src/org/pentaho/platform/dataaccess/datasource/wizard/service/impl/ModelerService.java
+++ b/src/org/pentaho/platform/dataaccess/datasource/wizard/service/impl/ModelerService.java
@@ -1,273 +1,274 @@
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program 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.
*
* Copyright 2009-2010 Pentaho Corporation. All rights reserved.
*
* Created Sep, 2010
* @author jdixon
*/
package org.pentaho.platform.dataaccess.datasource.wizard.service.impl;
import java.io.File;
import java.util.ArrayList;
import java.util.Locale;
import mondrian.xmla.DataSourcesConfig.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.pentaho.agilebi.modeler.IModelerSource;
import org.pentaho.agilebi.modeler.ModelerMessagesHolder;
import org.pentaho.agilebi.modeler.ModelerWorkspace;
import org.pentaho.agilebi.modeler.gwt.BogoPojo;
import org.pentaho.agilebi.modeler.gwt.GwtModelerWorkspaceHelper;
import org.pentaho.agilebi.modeler.services.IModelerService;
import org.pentaho.agilebi.modeler.util.SpoonModelerMessages;
import org.pentaho.agilebi.modeler.util.TableModelerSource;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.metadata.model.Domain;
import org.pentaho.metadata.model.LogicalModel;
import org.pentaho.metadata.model.SqlPhysicalModel;
import org.pentaho.metadata.repository.IMetadataDomainRepository;
import org.pentaho.metadata.util.MondrianModelExporter;
import org.pentaho.metadata.util.XmiParser;
import org.pentaho.platform.api.engine.IApplicationContext;
import org.pentaho.platform.api.engine.IPentahoObjectFactory;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.api.repository.ISolutionRepository;
import org.pentaho.platform.dataaccess.datasource.wizard.service.agile.AgileHelper;
import org.pentaho.platform.dataaccess.datasource.wizard.service.impl.utils.InlineSqlModelerSource;
import org.pentaho.platform.engine.core.solution.ActionInfo;
import org.pentaho.platform.engine.core.system.PentahoBase;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.engine.services.metadata.MetadataPublisher;
import org.pentaho.platform.plugin.action.kettle.KettleSystemListener;
import org.pentaho.platform.plugin.action.mondrian.catalog.IMondrianCatalogService;
import org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalog;
import org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCube;
import org.pentaho.platform.plugin.action.mondrian.catalog.MondrianDataSource;
import org.pentaho.platform.plugin.action.mondrian.catalog.MondrianSchema;
/**
* User: nbaker
* Date: Jul 16, 2010
*/
public class ModelerService extends PentahoBase implements IModelerService {
private static final Log logger = LogFactory.getLog(ModelerService.class);
public static final String TMP_FILE_PATH = File.separatorChar + "system" + File.separatorChar + File.separatorChar + "tmp" + File.separatorChar;
public Log getLogger() {
return logger;
}
static {
try {
// try to set the modelermessages. at this point, just give it the spoon messages. no need to give it
// GWT messages, this is a server-side function.
ModelerMessagesHolder.setMessages(new SpoonModelerMessages());
} catch (IllegalStateException e) {
logger.debug(e.getMessage(), e);
}
}
protected void initKettle(){
try {
KettleSystemListener.environmentInit(PentahoSessionHolder.getSession());
if(Props.isInitialized() == false){
Props.init(Props.TYPE_PROPERTIES_EMPTY);
}
} catch (KettleException e) {
logger.error(e);
e.printStackTrace();
throw new IllegalStateException("Failed to initialize Kettle system"); //$NON-NLS-1$
}
}
//TODO: remove this method in favor so specific calls
@Deprecated
public Domain generateDomain(String connectionName, String tableName, String dbType, String query, String datasourceName) throws Exception {
initKettle();
try{
DatabaseMeta database = AgileHelper.getDatabaseMeta();
IModelerSource source;
if(tableName != null){
source = new TableModelerSource(database, tableName, null, datasourceName);
} else {
source = new InlineSqlModelerSource(connectionName, dbType, query, datasourceName);
}
return source.generateDomain();
} catch(Exception e){
logger.error(e);
throw new Exception(e.getLocalizedMessage());
}
}
public Domain generateCSVDomain(String tableName, String datasourceName) throws Exception {
initKettle();
try{
DatabaseMeta database = AgileHelper.getDatabaseMeta();
IModelerSource source = new TableModelerSource(database, tableName, null, datasourceName);
return source.generateDomain();
} catch(Exception e){
logger.error(e);
throw new Exception(e.getLocalizedMessage());
}
}
public BogoPojo gwtWorkaround ( BogoPojo pojo){
return new BogoPojo();
}
public String serializeModels(Domain domain, String name) throws Exception {
return serializeModels(domain, name, true);
}
public String serializeModels(Domain domain, String name, boolean doOlap) throws Exception {
String domainId = null;
initKettle();
try {
ModelerWorkspace model = new ModelerWorkspace(new GwtModelerWorkspaceHelper());
model.setModelName(name);
model.setDomain(domain);
String solutionStorage = AgileHelper.getDatasourceSolutionStorage();
String metadataLocation = "resources" + ISolutionRepository.SEPARATOR + "metadata"; //$NON-NLS-1$ //$NON-NLS-2$
String path = solutionStorage + ISolutionRepository.SEPARATOR + metadataLocation + ISolutionRepository.SEPARATOR;
domainId = path + name + ".xmi"; //$NON-NLS-1$
+ domain.setId(domainId);
IApplicationContext appContext = PentahoSystem.getApplicationContext();
if (appContext != null) {
path = PentahoSystem.getApplicationContext().getSolutionPath(path);
}
File pathDir = new File(path);
if (!pathDir.exists()) {
pathDir.mkdirs();
}
IPentahoObjectFactory pentahoObjectFactory = PentahoSystem.getObjectFactory();
IPentahoSession session = pentahoObjectFactory.get(IPentahoSession.class, "systemStartupSession", null); //$NON-NLS-1$
ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, session);
LogicalModel lModel = domain.getLogicalModels().get(0);
String catName = lModel.getName(Locale.getDefault().toString());
cleanseExistingCatalog(catName, session);
if(doOlap){
lModel.setProperty("MondrianCatalogRef", catName); //$NON-NLS-1$
}
XmiParser parser = new XmiParser();
String reportXML = parser.generateXmi(model.getDomain());
// Serialize domain to xmi.
String base = PentahoSystem.getApplicationContext().getSolutionRootPath();
String parentPath = ActionInfo.buildSolutionPath(solutionStorage, metadataLocation, ""); //$NON-NLS-1$
int status = repository.publish(base, '/' + parentPath, name + ".xmi", reportXML.getBytes("UTF-8"), true); //$NON-NLS-1$ //$NON-NLS-2$
if (status != ISolutionRepository.FILE_ADD_SUCCESSFUL) {
throw new RuntimeException("Unable to save to repository. Status: " + status); //$NON-NLS-1$
}
// Serialize domain to olap schema.
if(doOlap){
MondrianModelExporter exporter = new MondrianModelExporter(lModel, Locale.getDefault().toString());
String mondrianSchema = exporter.createMondrianModelXML();
Document schemaDoc = DocumentHelper.parseText(mondrianSchema);
byte[] schemaBytes = schemaDoc.asXML().getBytes("UTF-8"); //$NON-NLS-1$
status = repository.publish(base, '/' + parentPath, name + ".mondrian.xml", schemaBytes, true); //$NON-NLS-1$
if (status != ISolutionRepository.FILE_ADD_SUCCESSFUL) {
throw new RuntimeException("Unable to save to repository. Status: " + status); //$NON-NLS-1$
}
// Refresh Metadata
PentahoSystem.publish(session, MetadataPublisher.class.getName());
// Write this catalog to the default Pentaho DataSource and refresh the cache.
File file = new File(path + name + ".mondrian.xml"); //$NON-NLS-1$
String catConnectStr = "Provider=mondrian;DataSource=" + ((SqlPhysicalModel) domain.getPhysicalModels().get(0)).getDatasource().getDatabaseName(); //$NON-NLS-1$
String catDef = "solution:" + solutionStorage + ISolutionRepository.SEPARATOR //$NON-NLS-1$
+ "resources" + ISolutionRepository.SEPARATOR + "metadata" + ISolutionRepository.SEPARATOR + file.getName(); //$NON-NLS-1$//$NON-NLS-2$
addCatalog(catName, catConnectStr, catDef, session);
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
throw e;
}
return domainId;
}
private void cleanseExistingCatalog(String catName, IPentahoSession session) {
// If mondrian catalog exists delete it to avoid duplicates and orphan entries in the datasources.xml registry.
//IPentahoSession session = PentahoSessionHolder.getSession();
if(session != null) {
IMondrianCatalogService service = PentahoSystem.get(IMondrianCatalogService.class, null);
MondrianCatalog catalog = service.getCatalog(catName, session);
if(catalog != null) {
service.removeCatalog(catName, session);
}
}
}
private void addCatalog(String catName, String catConnectStr, String catDef, IPentahoSession session) {
IMondrianCatalogService mondrianCatalogService = PentahoSystem.get(IMondrianCatalogService.class, "IMondrianCatalogService", session); //$NON-NLS-1$
String dsUrl = PentahoSystem.getApplicationContext().getBaseUrl();
if (!dsUrl.endsWith("/")) { //$NON-NLS-1$
dsUrl += "/"; //$NON-NLS-1$
}
dsUrl += "Xmla"; //$NON-NLS-1$
MondrianDataSource ds = new MondrianDataSource(
"Provider=Mondrian;DataSource=Pentaho", //$NON-NLS-1$
"Pentaho BI Platform Datasources", //$NON-NLS-1$
dsUrl,
"Provider=Mondrian", // no default jndi datasource should be specified //$NON-NLS-1$
"PentahoXMLA", //$NON-NLS-1$
DataSource.PROVIDER_TYPE_MDP,
DataSource.AUTH_MODE_UNAUTHENTICATED,
null
);
MondrianCatalog cat = new MondrianCatalog(
catName,
catConnectStr,
catDef,
ds,
new MondrianSchema(catName, new ArrayList<MondrianCube>())
);
mondrianCatalogService.addCatalog(cat, true, session);
}
public Domain loadDomain(String id) throws Exception {
IMetadataDomainRepository repo = PentahoSystem.get(IMetadataDomainRepository.class);
return repo.getDomain(id);
}
}
| true | true | public String serializeModels(Domain domain, String name, boolean doOlap) throws Exception {
String domainId = null;
initKettle();
try {
ModelerWorkspace model = new ModelerWorkspace(new GwtModelerWorkspaceHelper());
model.setModelName(name);
model.setDomain(domain);
String solutionStorage = AgileHelper.getDatasourceSolutionStorage();
String metadataLocation = "resources" + ISolutionRepository.SEPARATOR + "metadata"; //$NON-NLS-1$ //$NON-NLS-2$
String path = solutionStorage + ISolutionRepository.SEPARATOR + metadataLocation + ISolutionRepository.SEPARATOR;
domainId = path + name + ".xmi"; //$NON-NLS-1$
IApplicationContext appContext = PentahoSystem.getApplicationContext();
if (appContext != null) {
path = PentahoSystem.getApplicationContext().getSolutionPath(path);
}
File pathDir = new File(path);
if (!pathDir.exists()) {
pathDir.mkdirs();
}
IPentahoObjectFactory pentahoObjectFactory = PentahoSystem.getObjectFactory();
IPentahoSession session = pentahoObjectFactory.get(IPentahoSession.class, "systemStartupSession", null); //$NON-NLS-1$
ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, session);
LogicalModel lModel = domain.getLogicalModels().get(0);
String catName = lModel.getName(Locale.getDefault().toString());
cleanseExistingCatalog(catName, session);
if(doOlap){
lModel.setProperty("MondrianCatalogRef", catName); //$NON-NLS-1$
}
XmiParser parser = new XmiParser();
String reportXML = parser.generateXmi(model.getDomain());
// Serialize domain to xmi.
String base = PentahoSystem.getApplicationContext().getSolutionRootPath();
String parentPath = ActionInfo.buildSolutionPath(solutionStorage, metadataLocation, ""); //$NON-NLS-1$
int status = repository.publish(base, '/' + parentPath, name + ".xmi", reportXML.getBytes("UTF-8"), true); //$NON-NLS-1$ //$NON-NLS-2$
if (status != ISolutionRepository.FILE_ADD_SUCCESSFUL) {
throw new RuntimeException("Unable to save to repository. Status: " + status); //$NON-NLS-1$
}
// Serialize domain to olap schema.
if(doOlap){
MondrianModelExporter exporter = new MondrianModelExporter(lModel, Locale.getDefault().toString());
String mondrianSchema = exporter.createMondrianModelXML();
Document schemaDoc = DocumentHelper.parseText(mondrianSchema);
byte[] schemaBytes = schemaDoc.asXML().getBytes("UTF-8"); //$NON-NLS-1$
status = repository.publish(base, '/' + parentPath, name + ".mondrian.xml", schemaBytes, true); //$NON-NLS-1$
if (status != ISolutionRepository.FILE_ADD_SUCCESSFUL) {
throw new RuntimeException("Unable to save to repository. Status: " + status); //$NON-NLS-1$
}
// Refresh Metadata
PentahoSystem.publish(session, MetadataPublisher.class.getName());
// Write this catalog to the default Pentaho DataSource and refresh the cache.
File file = new File(path + name + ".mondrian.xml"); //$NON-NLS-1$
String catConnectStr = "Provider=mondrian;DataSource=" + ((SqlPhysicalModel) domain.getPhysicalModels().get(0)).getDatasource().getDatabaseName(); //$NON-NLS-1$
String catDef = "solution:" + solutionStorage + ISolutionRepository.SEPARATOR //$NON-NLS-1$
+ "resources" + ISolutionRepository.SEPARATOR + "metadata" + ISolutionRepository.SEPARATOR + file.getName(); //$NON-NLS-1$//$NON-NLS-2$
addCatalog(catName, catConnectStr, catDef, session);
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
throw e;
}
return domainId;
}
| public String serializeModels(Domain domain, String name, boolean doOlap) throws Exception {
String domainId = null;
initKettle();
try {
ModelerWorkspace model = new ModelerWorkspace(new GwtModelerWorkspaceHelper());
model.setModelName(name);
model.setDomain(domain);
String solutionStorage = AgileHelper.getDatasourceSolutionStorage();
String metadataLocation = "resources" + ISolutionRepository.SEPARATOR + "metadata"; //$NON-NLS-1$ //$NON-NLS-2$
String path = solutionStorage + ISolutionRepository.SEPARATOR + metadataLocation + ISolutionRepository.SEPARATOR;
domainId = path + name + ".xmi"; //$NON-NLS-1$
domain.setId(domainId);
IApplicationContext appContext = PentahoSystem.getApplicationContext();
if (appContext != null) {
path = PentahoSystem.getApplicationContext().getSolutionPath(path);
}
File pathDir = new File(path);
if (!pathDir.exists()) {
pathDir.mkdirs();
}
IPentahoObjectFactory pentahoObjectFactory = PentahoSystem.getObjectFactory();
IPentahoSession session = pentahoObjectFactory.get(IPentahoSession.class, "systemStartupSession", null); //$NON-NLS-1$
ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, session);
LogicalModel lModel = domain.getLogicalModels().get(0);
String catName = lModel.getName(Locale.getDefault().toString());
cleanseExistingCatalog(catName, session);
if(doOlap){
lModel.setProperty("MondrianCatalogRef", catName); //$NON-NLS-1$
}
XmiParser parser = new XmiParser();
String reportXML = parser.generateXmi(model.getDomain());
// Serialize domain to xmi.
String base = PentahoSystem.getApplicationContext().getSolutionRootPath();
String parentPath = ActionInfo.buildSolutionPath(solutionStorage, metadataLocation, ""); //$NON-NLS-1$
int status = repository.publish(base, '/' + parentPath, name + ".xmi", reportXML.getBytes("UTF-8"), true); //$NON-NLS-1$ //$NON-NLS-2$
if (status != ISolutionRepository.FILE_ADD_SUCCESSFUL) {
throw new RuntimeException("Unable to save to repository. Status: " + status); //$NON-NLS-1$
}
// Serialize domain to olap schema.
if(doOlap){
MondrianModelExporter exporter = new MondrianModelExporter(lModel, Locale.getDefault().toString());
String mondrianSchema = exporter.createMondrianModelXML();
Document schemaDoc = DocumentHelper.parseText(mondrianSchema);
byte[] schemaBytes = schemaDoc.asXML().getBytes("UTF-8"); //$NON-NLS-1$
status = repository.publish(base, '/' + parentPath, name + ".mondrian.xml", schemaBytes, true); //$NON-NLS-1$
if (status != ISolutionRepository.FILE_ADD_SUCCESSFUL) {
throw new RuntimeException("Unable to save to repository. Status: " + status); //$NON-NLS-1$
}
// Refresh Metadata
PentahoSystem.publish(session, MetadataPublisher.class.getName());
// Write this catalog to the default Pentaho DataSource and refresh the cache.
File file = new File(path + name + ".mondrian.xml"); //$NON-NLS-1$
String catConnectStr = "Provider=mondrian;DataSource=" + ((SqlPhysicalModel) domain.getPhysicalModels().get(0)).getDatasource().getDatabaseName(); //$NON-NLS-1$
String catDef = "solution:" + solutionStorage + ISolutionRepository.SEPARATOR //$NON-NLS-1$
+ "resources" + ISolutionRepository.SEPARATOR + "metadata" + ISolutionRepository.SEPARATOR + file.getName(); //$NON-NLS-1$//$NON-NLS-2$
addCatalog(catName, catConnectStr, catDef, session);
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
throw e;
}
return domainId;
}
|
diff --git a/de.jutzig.jabylon.rest.ui/src/main/java/de/jutzig/jabylon/rest/ui/security/CDOAuthenticatedSession.java b/de.jutzig.jabylon.rest.ui/src/main/java/de/jutzig/jabylon/rest/ui/security/CDOAuthenticatedSession.java
index 9b670aa8..e8b16e80 100644
--- a/de.jutzig.jabylon.rest.ui/src/main/java/de/jutzig/jabylon/rest/ui/security/CDOAuthenticatedSession.java
+++ b/de.jutzig.jabylon.rest.ui/src/main/java/de/jutzig/jabylon/rest/ui/security/CDOAuthenticatedSession.java
@@ -1,196 +1,195 @@
/**
*
*/
package de.jutzig.jabylon.rest.ui.security;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.Request;
import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.util.CommitException;
import org.eclipse.emf.cdo.view.CDOView;
import org.eclipse.emf.common.util.EList;
import org.eclipse.equinox.security.auth.ILoginContext;
import org.eclipse.equinox.security.auth.LoginContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.jutzig.jabylon.cdo.connector.Modification;
import de.jutzig.jabylon.cdo.connector.TransactionUtil;
import de.jutzig.jabylon.cdo.server.ServerConstants;
import de.jutzig.jabylon.rest.ui.Activator;
import de.jutzig.jabylon.rest.ui.model.EObjectModel;
import de.jutzig.jabylon.security.CommonPermissions;
import de.jutzig.jabylon.security.JabylonSecurityBundle;
import de.jutzig.jabylon.users.Permission;
import de.jutzig.jabylon.users.Role;
import de.jutzig.jabylon.users.User;
import de.jutzig.jabylon.users.UserManagement;
import de.jutzig.jabylon.users.UsersFactory;
/**
* @author Johannes Utzig ([email protected])
*
*/
public class CDOAuthenticatedSession extends AuthenticatedWebSession {
private static final long serialVersionUID = 1L;
private IModel<User> user;
private static final Logger logger = LoggerFactory.getLogger(CDOAuthenticatedSession.class);
private static final String JAAS_CONFIG_FILE = "jaas.config"; //$NON-NLS-1$
public CDOAuthenticatedSession(Request request) {
super(request);
}
/* (non-Javadoc)
* @see org.apache.wicket.authroles.authentication.AuthenticatedWebSession#authenticate(java.lang.String, java.lang.String)
*/
@Override
public boolean authenticate(final String username, final String password) {
Map<String, ILoginContext> contexts = createLoginContexts(new CallbackHandler() {
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
Callback cb = callbacks[i];
if(cb instanceof NameCallback) {
((NameCallback) cb).setName(username); //$NON-NLS-1$
} else if (cb instanceof PasswordCallback) {
((PasswordCallback) cb).setPassword(password.toCharArray()); //$NON-NLS-1$
}
}
}
});
for (Entry<String, ILoginContext> entry : contexts.entrySet()) {
try {
entry.getValue().login();
logger.info("{} Login for user {} successful",entry.getKey(),username);
//TODO: this could be handled without two lookups
CDOView view = Activator.getDefault().getRepositoryConnector().openView();
CDOResource resource = view.getResource(ServerConstants.USERS_RESOURCE);
UserManagement userManagement = (UserManagement) resource.getContents().get(0);
userManagement = (UserManagement) Activator.getDefault().getRepositoryLookup().resolve(userManagement.cdoID());
User user = userManagement.findUserByName(username);
if(user==null) {
logger.info("User {} logged in for the first time. Creating DB Entry");
final User newUser = UsersFactory.eINSTANCE.createUser();
newUser.setName(username);
Role anonymousRole = userManagement.findRoleByName("Anonymous");
if(anonymousRole==null)
throw new RuntimeException("Anonymous role must always exist");
newUser.getRoles().add(anonymousRole);
user = TransactionUtil.commit(userManagement, new Modification<UserManagement, User>() {
@Override
public User apply(UserManagement object) {
object.getUsers().add(newUser);
return newUser;
}
});
- userManagement.getUsers().add(user);
}
this.user = new EObjectModel<User>(user);
view.close();
return true;
} catch (LoginException e) {
logger.error(entry.getKey()+" Login for user "+username+" failed: "+e.getMessage());
} catch (CommitException e) {
logger.error("Failed to commit new user after first login from " + entry.getKey(),e);
}
}
return false;
}
private Map<String,ILoginContext> createLoginContexts(CallbackHandler callbackHandler) {
URL configUrl = getJAASConfig();
Map<String,ILoginContext> contexts = new LinkedHashMap<String,ILoginContext>();
contexts.put("DB",LoginContextFactory.createContext("DB", configUrl, callbackHandler));
contexts.put("LDAP",LoginContextFactory.createContext("LDAP", configUrl, callbackHandler));
return contexts;
}
private URL getJAASConfig() {
String configArea = System.getProperty("osgi.configuration.area","configuration");
try {
URI uri = new URI(configArea);
File jaasConfig = new File(new File(uri), JAAS_CONFIG_FILE);
if(jaasConfig.isFile()) {
return jaasConfig.toURI().toURL();
}
} catch (Exception e) {
logger.error("invalid jaas url", e);
}
//fallback
return JabylonSecurityBundle.getBundleContext().getBundle().getEntry("META-INF/"+JAAS_CONFIG_FILE);
}
/* (non-Javadoc)
* @see org.apache.wicket.authroles.authentication.AbstractAuthenticatedWebSession#getRoles()
*/
@Override
public Roles getRoles() {
// TODO Auto-generated method stub
if(isSignedIn())
{
//in our case permissions are wicket roles
EList<Permission> permissions = user.getObject().getAllPermissions();
return createRoles(permissions);
}
return getAnonymousRoles();
}
private Roles createRoles(EList<Permission> permissions) {
List<String> roleNames = new ArrayList<String>(permissions.size());
for (Permission permission : permissions) {
roleNames.add(permission.getName());
}
return new Roles(roleNames.toArray(new String[permissions.size()]));
}
private Roles getAnonymousRoles() {
logger.info("Computing Anonymous Roles");
//TODO: this could be handled without two lookups
CDOView view = Activator.getDefault().getRepositoryConnector().openView();
CDOResource resource = view.getResource(ServerConstants.USERS_RESOURCE);
UserManagement userManagement = (UserManagement) resource.getContents().get(0);
userManagement = (UserManagement) Activator.getDefault().getRepositoryLookup().resolve(userManagement.cdoID());
Role role = userManagement.findRoleByName(CommonPermissions.ROLE_ANONYMOUS);
Roles roles = createRoles(role.getAllPermissions());
view.close();
return roles;
}
public User getUser() {
if(user == null)
return null;
return user.getObject();
}
}
| true | true | public boolean authenticate(final String username, final String password) {
Map<String, ILoginContext> contexts = createLoginContexts(new CallbackHandler() {
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
Callback cb = callbacks[i];
if(cb instanceof NameCallback) {
((NameCallback) cb).setName(username); //$NON-NLS-1$
} else if (cb instanceof PasswordCallback) {
((PasswordCallback) cb).setPassword(password.toCharArray()); //$NON-NLS-1$
}
}
}
});
for (Entry<String, ILoginContext> entry : contexts.entrySet()) {
try {
entry.getValue().login();
logger.info("{} Login for user {} successful",entry.getKey(),username);
//TODO: this could be handled without two lookups
CDOView view = Activator.getDefault().getRepositoryConnector().openView();
CDOResource resource = view.getResource(ServerConstants.USERS_RESOURCE);
UserManagement userManagement = (UserManagement) resource.getContents().get(0);
userManagement = (UserManagement) Activator.getDefault().getRepositoryLookup().resolve(userManagement.cdoID());
User user = userManagement.findUserByName(username);
if(user==null) {
logger.info("User {} logged in for the first time. Creating DB Entry");
final User newUser = UsersFactory.eINSTANCE.createUser();
newUser.setName(username);
Role anonymousRole = userManagement.findRoleByName("Anonymous");
if(anonymousRole==null)
throw new RuntimeException("Anonymous role must always exist");
newUser.getRoles().add(anonymousRole);
user = TransactionUtil.commit(userManagement, new Modification<UserManagement, User>() {
@Override
public User apply(UserManagement object) {
object.getUsers().add(newUser);
return newUser;
}
});
userManagement.getUsers().add(user);
}
this.user = new EObjectModel<User>(user);
view.close();
return true;
} catch (LoginException e) {
logger.error(entry.getKey()+" Login for user "+username+" failed: "+e.getMessage());
} catch (CommitException e) {
logger.error("Failed to commit new user after first login from " + entry.getKey(),e);
}
}
return false;
}
| public boolean authenticate(final String username, final String password) {
Map<String, ILoginContext> contexts = createLoginContexts(new CallbackHandler() {
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
Callback cb = callbacks[i];
if(cb instanceof NameCallback) {
((NameCallback) cb).setName(username); //$NON-NLS-1$
} else if (cb instanceof PasswordCallback) {
((PasswordCallback) cb).setPassword(password.toCharArray()); //$NON-NLS-1$
}
}
}
});
for (Entry<String, ILoginContext> entry : contexts.entrySet()) {
try {
entry.getValue().login();
logger.info("{} Login for user {} successful",entry.getKey(),username);
//TODO: this could be handled without two lookups
CDOView view = Activator.getDefault().getRepositoryConnector().openView();
CDOResource resource = view.getResource(ServerConstants.USERS_RESOURCE);
UserManagement userManagement = (UserManagement) resource.getContents().get(0);
userManagement = (UserManagement) Activator.getDefault().getRepositoryLookup().resolve(userManagement.cdoID());
User user = userManagement.findUserByName(username);
if(user==null) {
logger.info("User {} logged in for the first time. Creating DB Entry");
final User newUser = UsersFactory.eINSTANCE.createUser();
newUser.setName(username);
Role anonymousRole = userManagement.findRoleByName("Anonymous");
if(anonymousRole==null)
throw new RuntimeException("Anonymous role must always exist");
newUser.getRoles().add(anonymousRole);
user = TransactionUtil.commit(userManagement, new Modification<UserManagement, User>() {
@Override
public User apply(UserManagement object) {
object.getUsers().add(newUser);
return newUser;
}
});
}
this.user = new EObjectModel<User>(user);
view.close();
return true;
} catch (LoginException e) {
logger.error(entry.getKey()+" Login for user "+username+" failed: "+e.getMessage());
} catch (CommitException e) {
logger.error("Failed to commit new user after first login from " + entry.getKey(),e);
}
}
return false;
}
|
diff --git a/src/main/java/de/webfilesys/SubdirExistCache.java b/src/main/java/de/webfilesys/SubdirExistCache.java
index 7773d95..c043b7c 100644
--- a/src/main/java/de/webfilesys/SubdirExistCache.java
+++ b/src/main/java/de/webfilesys/SubdirExistCache.java
@@ -1,139 +1,142 @@
package de.webfilesys;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import de.webfilesys.graphics.ThumbnailThread;
public class SubdirExistCache {
private HashMap<String, Integer> subdirExists = null;
private static SubdirExistCache instance = null;
private SubdirExistCache()
{
subdirExists = new HashMap<String, Integer>(100);
}
public static SubdirExistCache getInstance()
{
if (instance == null)
{
instance = new SubdirExistCache();
}
return instance;
}
/**
* Does a (sub)folder with the given path exist?
* @param path filesystem path of the folder
* @return null if not known, Integer(1) if folder exists, Integer(0) if folder does NOT exist
*/
public Integer existsSubdir(String path)
{
return((Integer) subdirExists.get(path));
}
/**
* Are there any subfolders in the folder with the given path?
* @param path filesystem path of the folder
* @param newVal 1 if subfolders exist, 0 if NO subfolders exist
*/
public void setExistsSubdir(String path, Integer newVal)
{
synchronized (subdirExists)
{
subdirExists.put(path, newVal);
}
}
/**
* Remove a folder and all subfolders from the subdir exist cache.
* @param path the root of the folder tree
*/
public void cleanupExistSubdir(String path)
{
synchronized (subdirExists)
{
Iterator<String> keyIter = subdirExists.keySet().iterator();
ArrayList<String> keysToRemove = new ArrayList<String>();
while (keyIter.hasNext())
{
String key = keyIter.next();
if (key.startsWith(path))
{
if (key.equals(path) ||
(key.charAt(path.length()) == '/') ||
(key.charAt(path.length()) == File.separatorChar))
{
keysToRemove.add(key);
}
}
}
for (int i = keysToRemove.size() - 1; i >= 0; i--)
{
subdirExists.remove(keysToRemove.get(i));
}
}
}
public void initialReadSubdirs(int operatingSystemType)
{
String rootDirPath;
if ((operatingSystemType == WebFileSys.OS_OS2) || (operatingSystemType == WebFileSys.OS_WIN))
{
rootDirPath = new String("C:\\");
}
else
{
rootDirPath = new String("/");
}
File rootDir = new File(rootDirPath);
File[] rootFileList = rootDir.listFiles();
if (rootFileList != null)
{
synchronized (subdirExists)
{
for (int i = 0; i < rootFileList.length; i++)
{
File tempFile = rootFileList[i];
if (tempFile.isDirectory())
{
File subDir = tempFile;
File[] subFileList = subDir.listFiles();
boolean hasSubdirs = false;
- for (int k = 0; (!hasSubdirs) && (k < subFileList.length); k++)
+ if (subFileList != null)
{
- if (subFileList[k].isDirectory())
- {
- if (!subFileList[k].getName().equals(ThumbnailThread.THUMBNAIL_SUBDIR))
- {
- hasSubdirs = true;
- }
- }
+ for (int k = 0; (!hasSubdirs) && (k < subFileList.length); k++)
+ {
+ if (subFileList[k].isDirectory())
+ {
+ if (!subFileList[k].getName().equals(ThumbnailThread.THUMBNAIL_SUBDIR))
+ {
+ hasSubdirs = true;
+ }
+ }
+ }
}
if (hasSubdirs)
{
setExistsSubdir(subDir.getAbsolutePath(), new Integer(1));
}
else
{
setExistsSubdir(subDir.getAbsolutePath(), new Integer(0));
}
}
}
}
}
}
}
| false | true | public void initialReadSubdirs(int operatingSystemType)
{
String rootDirPath;
if ((operatingSystemType == WebFileSys.OS_OS2) || (operatingSystemType == WebFileSys.OS_WIN))
{
rootDirPath = new String("C:\\");
}
else
{
rootDirPath = new String("/");
}
File rootDir = new File(rootDirPath);
File[] rootFileList = rootDir.listFiles();
if (rootFileList != null)
{
synchronized (subdirExists)
{
for (int i = 0; i < rootFileList.length; i++)
{
File tempFile = rootFileList[i];
if (tempFile.isDirectory())
{
File subDir = tempFile;
File[] subFileList = subDir.listFiles();
boolean hasSubdirs = false;
for (int k = 0; (!hasSubdirs) && (k < subFileList.length); k++)
{
if (subFileList[k].isDirectory())
{
if (!subFileList[k].getName().equals(ThumbnailThread.THUMBNAIL_SUBDIR))
{
hasSubdirs = true;
}
}
}
if (hasSubdirs)
{
setExistsSubdir(subDir.getAbsolutePath(), new Integer(1));
}
else
{
setExistsSubdir(subDir.getAbsolutePath(), new Integer(0));
}
}
}
}
}
}
| public void initialReadSubdirs(int operatingSystemType)
{
String rootDirPath;
if ((operatingSystemType == WebFileSys.OS_OS2) || (operatingSystemType == WebFileSys.OS_WIN))
{
rootDirPath = new String("C:\\");
}
else
{
rootDirPath = new String("/");
}
File rootDir = new File(rootDirPath);
File[] rootFileList = rootDir.listFiles();
if (rootFileList != null)
{
synchronized (subdirExists)
{
for (int i = 0; i < rootFileList.length; i++)
{
File tempFile = rootFileList[i];
if (tempFile.isDirectory())
{
File subDir = tempFile;
File[] subFileList = subDir.listFiles();
boolean hasSubdirs = false;
if (subFileList != null)
{
for (int k = 0; (!hasSubdirs) && (k < subFileList.length); k++)
{
if (subFileList[k].isDirectory())
{
if (!subFileList[k].getName().equals(ThumbnailThread.THUMBNAIL_SUBDIR))
{
hasSubdirs = true;
}
}
}
}
if (hasSubdirs)
{
setExistsSubdir(subDir.getAbsolutePath(), new Integer(1));
}
else
{
setExistsSubdir(subDir.getAbsolutePath(), new Integer(0));
}
}
}
}
}
}
|
diff --git a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java
index e99dfe8a7..2d6a96e8c 100644
--- a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java
+++ b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java
@@ -1,247 +1,247 @@
/*******************************************************************************
* Copyright (c) 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.p2.installer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.internal.provisional.p2.installer.IInstallOperation;
import org.eclipse.equinox.internal.provisional.p2.installer.InstallDescription;
import org.eclipse.equinox.p2.artifact.repository.IArtifactRepositoryManager;
import org.eclipse.equinox.p2.director.IDirector;
import org.eclipse.equinox.p2.engine.IProfileRegistry;
import org.eclipse.equinox.p2.engine.Profile;
import org.eclipse.equinox.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery;
import org.eclipse.equinox.p2.metadata.repository.IMetadataRepositoryManager;
import org.eclipse.equinox.p2.query.Collector;
import org.eclipse.equinox.p2.query.Query;
import org.eclipse.osgi.service.environment.EnvironmentInfo;
import org.eclipse.osgi.service.resolver.VersionRange;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.*;
/**
* This operation performs installation or update of an Eclipse-based product.
*/
public class InstallUpdateProductOperation implements IInstallOperation {
/**
* This constant comes from value of FrameworkAdmin.SERVICE_PROP_KEY_LAUNCHER_NAME.
* This profile property is being used as a short term solution for branding of the launcher.
*/
private static final String PROP_LAUNCHER_NAME = "org.eclipse.equinox.frameworkhandler.launcher.name";
private IArtifactRepositoryManager artifactRepoMan;
private BundleContext bundleContext;
private IDirector director;
private final InstallDescription installDescription;
private boolean isInstall = true;
private IMetadataRepositoryManager metadataRepoMan;
private IProfileRegistry profileRegistry;
private IStatus result;
private ArrayList serviceReferences = new ArrayList();
public InstallUpdateProductOperation(BundleContext context, InstallDescription description) {
this.bundleContext = context;
this.installDescription = description;
}
/**
* Determine what top level installable units should be installed by the director
*/
private IInstallableUnit[] computeUnitsToInstall() throws CoreException {
return new IInstallableUnit[] {findUnit(installDescription.getRootId(), installDescription.getRootVersion())};
}
/**
* This profile is being updated; return the units to uninstall from the profile.
*/
private IInstallableUnit[] computeUnitsToUninstall(Profile profile) {
ArrayList units = new ArrayList();
for (Iterator it = profile.getInstallableUnits(); it.hasNext();)
units.add(it.next());
return (IInstallableUnit[]) units.toArray(new IInstallableUnit[units.size()]);
}
/**
* Create and return the profile into which units will be installed.
*/
private Profile createProfile() {
Profile profile = getProfile();
if (profile == null) {
profile = new Profile(installDescription.getProductName());
profile.setValue(Profile.PROP_INSTALL_FOLDER, installDescription.getInstallLocation().toString());
profile.setValue(Profile.PROP_FLAVOR, installDescription.getFlavor());
profile.setValue(PROP_LAUNCHER_NAME, installDescription.getLauncherName());
EnvironmentInfo info = (EnvironmentInfo) ServiceHelper.getService(InstallerActivator.getDefault().getContext(), EnvironmentInfo.class.getName());
String env = "osgi.os=" + info.getOS() + ",osgi.ws=" + info.getWS() + ",osgi.arch=" + info.getOSArch();
profile.setValue(Profile.PROP_ENVIRONMENTS, env);
profileRegistry.addProfile(profile);
}
return profile;
}
/**
* Performs the actual product install or update.
*/
private void doInstall(SubMonitor monitor) throws CoreException {
prepareMetadataRepository();
prepareArtifactRepository();
Profile p = createProfile();
IInstallableUnit[] toInstall = computeUnitsToInstall();
monitor.worked(5);
IStatus s;
if (isInstall) {
monitor.setTaskName(NLS.bind("Installing {0}", installDescription.getProductName()));
- s = director.install(toInstall, p, monitor.newChild(90));
+ s = director.install(toInstall, p, null, monitor.newChild(90));
} else {
monitor.setTaskName(NLS.bind("Updating {0}", installDescription.getProductName()));
IInstallableUnit[] toUninstall = computeUnitsToUninstall(p);
- s = director.replace(toUninstall, toInstall, p, monitor.newChild(90));
+ s = director.replace(toUninstall, toInstall, p, null, monitor.newChild(90));
}
if (!s.isOK())
throw new CoreException(s);
}
/**
* Throws an exception of severity error with the given error message.
*/
private CoreException fail(String message) {
return fail(message, null);
}
/**
* Throws an exception of severity error with the given error message.
*/
private CoreException fail(String message, Throwable throwable) {
return new CoreException(new Status(IStatus.ERROR, InstallerActivator.PI_INSTALLER, message, throwable));
}
/**
* Finds and returns the installable unit with the given id, and optionally the
* given version.
*/
private IInstallableUnit findUnit(String id, Version version) throws CoreException {
if (id == null)
throw fail("Installable unit id not specified");
VersionRange range = VersionRange.emptyRange;
if (version != null && !version.equals(Version.emptyVersion))
range = new VersionRange(version, true, version, true);
Query query = new InstallableUnitQuery(id, range);
Collector collector = new Collector();
Iterator matches = metadataRepoMan.query(query, collector, null).iterator();
if (matches.hasNext())
return (IInstallableUnit) matches.next();
throw fail("Installable unit not found: " + id);
}
/**
* Returns the profile being installed into.
*/
private Profile getProfile() {
return profileRegistry.getProfile(installDescription.getProductName());
}
/**
* Returns the result of the install operation, or <code>null</code> if
* no install operation has been run.
*/
public IStatus getResult() {
return result;
}
private Object getService(String name) throws CoreException {
ServiceReference ref = bundleContext.getServiceReference(name);
if (ref == null)
throw fail("Install requires a service that is not available: " + name);
Object service = bundleContext.getService(ref);
if (service == null)
throw fail("Install requires a service implementation that is not available: " + name);
serviceReferences.add(ref);
return service;
}
/* (non-Javadoc)
* @see org.eclipse.equinox.internal.provisional.p2.installer.IInstallOperation#install(org.eclipse.core.runtime.IProgressMonitor)
*/
public IStatus install(IProgressMonitor pm) {
SubMonitor monitor = SubMonitor.convert(pm, "Preparing to install", 100);
try {
try {
preInstall();
isInstall = getProfile() == null;
doInstall(monitor);
result = new Status(IStatus.OK, InstallerActivator.PI_INSTALLER, isInstall ? "Install complete" : "Update complete", null);
monitor.setTaskName("Some final housekeeping");
} finally {
postInstall();
}
} catch (CoreException e) {
result = e.getStatus();
} finally {
monitor.done();
}
return result;
}
/**
* Returns whether this operation represents the product being installed
* for the first time, in a new profile.
*/
public boolean isFirstInstall() {
return isInstall;
}
private void postInstall() {
for (Iterator it = serviceReferences.iterator(); it.hasNext();) {
ServiceReference sr = (ServiceReference) it.next();
bundleContext.ungetService(sr);
}
serviceReferences.clear();
}
private void preInstall() throws CoreException {
if (System.getProperty("eclipse.p2.data.area") == null) //$NON-NLS-1$
System.setProperty("eclipse.p2.data.area", installDescription.getInstallLocation().append("installer").toString()); //$NON-NLS-1$ //$NON-NLS-2$
if (System.getProperty("eclipse.p2.cache") == null) //$NON-NLS-1$
System.setProperty("eclipse.p2.cache", installDescription.getInstallLocation().toString()); //$NON-NLS-1$
//start up p2
try {
InstallerActivator.getDefault().getBundle("org.eclipse.equinox.p2.exemplarysetup").start(Bundle.START_ACTIVATION_POLICY);
} catch (BundleException e) {
throw fail("Unable to start p2", e);
}
//obtain required services
serviceReferences.clear();
director = (IDirector) getService(IDirector.class.getName());
metadataRepoMan = (IMetadataRepositoryManager) getService(IMetadataRepositoryManager.class.getName());
artifactRepoMan = (IArtifactRepositoryManager) getService(IArtifactRepositoryManager.class.getName());
profileRegistry = (IProfileRegistry) getService(IProfileRegistry.class.getName());
}
private void prepareArtifactRepository() {
URL artifactRepo = installDescription.getArtifactRepository();
if (artifactRepo != null)
artifactRepoMan.loadRepository(artifactRepo, null);
}
private void prepareMetadataRepository() {
URL metadataRepo = installDescription.getMetadataRepository();
if (metadataRepo != null)
metadataRepoMan.loadRepository(metadataRepo, null);
}
}
| false | true | private void doInstall(SubMonitor monitor) throws CoreException {
prepareMetadataRepository();
prepareArtifactRepository();
Profile p = createProfile();
IInstallableUnit[] toInstall = computeUnitsToInstall();
monitor.worked(5);
IStatus s;
if (isInstall) {
monitor.setTaskName(NLS.bind("Installing {0}", installDescription.getProductName()));
s = director.install(toInstall, p, monitor.newChild(90));
} else {
monitor.setTaskName(NLS.bind("Updating {0}", installDescription.getProductName()));
IInstallableUnit[] toUninstall = computeUnitsToUninstall(p);
s = director.replace(toUninstall, toInstall, p, monitor.newChild(90));
}
if (!s.isOK())
throw new CoreException(s);
}
| private void doInstall(SubMonitor monitor) throws CoreException {
prepareMetadataRepository();
prepareArtifactRepository();
Profile p = createProfile();
IInstallableUnit[] toInstall = computeUnitsToInstall();
monitor.worked(5);
IStatus s;
if (isInstall) {
monitor.setTaskName(NLS.bind("Installing {0}", installDescription.getProductName()));
s = director.install(toInstall, p, null, monitor.newChild(90));
} else {
monitor.setTaskName(NLS.bind("Updating {0}", installDescription.getProductName()));
IInstallableUnit[] toUninstall = computeUnitsToUninstall(p);
s = director.replace(toUninstall, toInstall, p, null, monitor.newChild(90));
}
if (!s.isOK())
throw new CoreException(s);
}
|
diff --git a/LaTeXDraw/src/net/sf/latexdraw/glib/views/pst/PSTCodeGenerator.java b/LaTeXDraw/src/net/sf/latexdraw/glib/views/pst/PSTCodeGenerator.java
index e2242ba..2f10a3c 100644
--- a/LaTeXDraw/src/net/sf/latexdraw/glib/views/pst/PSTCodeGenerator.java
+++ b/LaTeXDraw/src/net/sf/latexdraw/glib/views/pst/PSTCodeGenerator.java
@@ -1,240 +1,242 @@
package net.sf.latexdraw.glib.views.pst;
import java.util.HashMap;
import java.util.Map;
import net.sf.latexdraw.glib.models.interfaces.IDrawing;
import net.sf.latexdraw.glib.models.interfaces.IPoint;
import net.sf.latexdraw.glib.models.interfaces.IShape;
import net.sf.latexdraw.glib.views.latex.DviPsColors;
import net.sf.latexdraw.glib.views.latex.LaTeXGenerator;
import net.sf.latexdraw.glib.views.synchroniser.ViewsSynchroniserHandler;
import net.sf.latexdraw.util.LNumber;
/**
* Defines a PSTricks generator; it manages the PSTricks views and the latex additional code.
* <br>
* This file is part of LaTeXDraw.<br>
* Copyright (c) 2005-2011 Arnaud BLOUIN<br>
* <br>
* LaTeXDraw is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later version.
* <br>
* LaTeXDraw is distributed without any warranty; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.<br>
* <br>
* 05/23/2010<br>
* @author Arnaud BLOUIN
* @since 3.0
*/
public class PSTCodeGenerator extends LaTeXGenerator {
public static final String PACKAGE_PSTRICKS = "% \\usepackage[usenames,dvipsnames]{pstricks}\n% \\usepackage{epsfig}\n% \\usepackage{pst-grad} % For gradients\n% \\usepackage{pst-plot} % For axes\n"; //$NON-NLS-1$
/** The PSTricks views. */
protected PSTViewsSynchroniser synchro;
/** The code cache. */
protected StringBuffer cache;
/** Defines if the latex parameters (position, caption, etc.) must be generated. */
protected boolean withLatexParams;
/** Defines if the comments must be generated. */
protected boolean withComments;
/**
* Creates and initialises the generator.
* @param drawing The shapes used to generate PST code.
* @param handler The handler that provides information to the generator.
* @param withLatexParams Defines if the latex parameters (position, caption, etc.) must be generated.
* @param withComments Defines if the comments must be generated.
* @throws IllegalArgumentException If the given drawing parameter is null.
* @since 3.0
*/
public PSTCodeGenerator(final IDrawing drawing, final ViewsSynchroniserHandler handler, final boolean withLatexParams,
final boolean withComments) {
super();
if(drawing==null)
throw new IllegalArgumentException();
this.withComments = withComments;
this.withLatexParams = withLatexParams;
synchro = new PSTViewsSynchroniser(handler, drawing);
cache = new StringBuffer();
}
/**
* @return the synchroniser.
* @since 3.0
*/
public PSTViewsSynchroniser getSynchro() {
return synchro;
}
/**
* @return the cache.
* @since 3.0
*/
public StringBuffer getCache() {
return cache;
}
@Override
public void update() {
emptyCache();
final IDrawing drawing = synchro.getDrawing();
StringBuffer code;
final String eol = System.getProperty("line.separator");//$NON-NLS-1$
String pkg = LaTeXGenerator.getPackages();
PSTShapeView<?> pstView;
final ViewsSynchroniserHandler handler = synchro.getHandler();
final IPoint origin = handler.getOriginDrawingPoint();
final IPoint tl = handler.getTopRightDrawingPoint();
final IPoint br = handler.getBottomLeftDrawingPoint();
final int ppc = handler.getPPCDrawing();
final Map<String, String> addedColours = new HashMap<String, String>();
final StringBuffer shapeCode = new StringBuffer();
if(drawing.isEmpty())
return ;
if(withComments && comment!=null && comment.length()>0)
cache.append(comment);
cache.append(PACKAGE_PSTRICKS);
- if(pkg.length()>0)
+ if(pkg.length()>0) {
+ pkg = "% User Packages:" + eol + "% " + pkg.replace(eol, eol + "% ");
cache.append(pkg).append(eol);
+ }
if(withLatexParams && positionVertToken!=VerticalPosition.NONE)
cache.append("\\begin{figure}[").append(positionVertToken.getToken()).append(']').append(eol);//$NON-NLS-1$
if(withLatexParams && positionHoriCentre)
cache.append("\\begin{center}").append(eol);//$NON-NLS-1$
cache.append("\\psscalebox{1 1} % Change this value to rescale the drawing.");//$NON-NLS-1$
cache.append(eol).append('{').append(eol);
cache.append("\\begin{pspicture}("); //$NON-NLS-1$
cache.append(0).append(',').append((float)LNumber.INSTANCE.getCutNumber((origin.getY()-br.getY())/ppc)).append(')').append('(');
cache.append((float)LNumber.INSTANCE.getCutNumber((tl.getX()-origin.getX())/ppc)).append(',').append((float)LNumber.INSTANCE.getCutNumber((origin.getY()-tl.getY())/ppc));
cache.append(')').append(eol);
for(IShape shape : drawing.getShapes()) {
pstView = synchro.getView(shape);
if(pstView!=null) {
code = pstView.getCache();
if(code!=null)
shapeCode.append(code).append(eol);
generateColourCode(pstView, addedColours);
}
}
cache.append(shapeCode).append("\\end{pspicture}").append(eol).append('}').append(eol); //$NON-NLS-1$
if(withLatexParams) {
if(positionHoriCentre)
cache.append("\\end{center}").append(eol);//$NON-NLS-1$
if(label.length()>0)
cache.append("\\label{").append(label).append('}');//$NON-NLS-1$
if(caption.length()>0)
cache.append("\\caption{").append(caption).append('}');//$NON-NLS-1$
if(positionVertToken!=VerticalPosition.NONE)
cache.append("\\end{figure}");//$NON-NLS-1$
}
}
/**
* Adds the PST colour code to the cache.
* @param pstView The shape which colour code will be generated.
* @param addedColours The PST colours already generated.
* @since 3.0
*/
private void generateColourCode(final PSTShapeView<?> pstView, final Map<String, String> addedColours) {
if(pstView.coloursName!=null)
for(String nameColour : pstView.coloursName)
if(addedColours.get(nameColour)==null && DviPsColors.INSTANCE.getPredefinedColour(nameColour)==null) {
addedColours.put(nameColour, nameColour);
cache.append(DviPsColors.INSTANCE.getUsercolourCode(nameColour));
}
}
/**
* Empties the cache.
* @since 3.0
*/
protected void emptyCache() {
if(cache!=null)
cache.delete(0, cache.length());
}
/**
* Updates the cache of every shapes and those of this generator.
* @since 3.0
*/
public void updateFull() {
synchro.updateFull();
update();
}
/**
* @return True: The latex parameters must be used by the generated code.
* @since 3.0
*/
public boolean isWithLatexParams() {
return withLatexParams;
}
/**
* Defines if the latex parameters must be used by the generated code.
* @param withLatexParams True: The latex parameters must be used by the generated code.
* @since 3.0
*/
public void setWithLatexParams(final boolean withLatexParams) {
this.withLatexParams = withLatexParams;
}
/**
* @return True: comments will be included.
* @since 3.0
*/
public boolean isWithComments() {
return withComments;
}
/**
* Defines if the code must contains comments.
* @param withComments True: comments will be included.
* @since 3.0
*/
public void setWithComments(final boolean withComments) {
this.withComments = withComments;
}
}
| false | true | public void update() {
emptyCache();
final IDrawing drawing = synchro.getDrawing();
StringBuffer code;
final String eol = System.getProperty("line.separator");//$NON-NLS-1$
String pkg = LaTeXGenerator.getPackages();
PSTShapeView<?> pstView;
final ViewsSynchroniserHandler handler = synchro.getHandler();
final IPoint origin = handler.getOriginDrawingPoint();
final IPoint tl = handler.getTopRightDrawingPoint();
final IPoint br = handler.getBottomLeftDrawingPoint();
final int ppc = handler.getPPCDrawing();
final Map<String, String> addedColours = new HashMap<String, String>();
final StringBuffer shapeCode = new StringBuffer();
if(drawing.isEmpty())
return ;
if(withComments && comment!=null && comment.length()>0)
cache.append(comment);
cache.append(PACKAGE_PSTRICKS);
if(pkg.length()>0)
cache.append(pkg).append(eol);
if(withLatexParams && positionVertToken!=VerticalPosition.NONE)
cache.append("\\begin{figure}[").append(positionVertToken.getToken()).append(']').append(eol);//$NON-NLS-1$
if(withLatexParams && positionHoriCentre)
cache.append("\\begin{center}").append(eol);//$NON-NLS-1$
cache.append("\\psscalebox{1 1} % Change this value to rescale the drawing.");//$NON-NLS-1$
cache.append(eol).append('{').append(eol);
cache.append("\\begin{pspicture}("); //$NON-NLS-1$
cache.append(0).append(',').append((float)LNumber.INSTANCE.getCutNumber((origin.getY()-br.getY())/ppc)).append(')').append('(');
cache.append((float)LNumber.INSTANCE.getCutNumber((tl.getX()-origin.getX())/ppc)).append(',').append((float)LNumber.INSTANCE.getCutNumber((origin.getY()-tl.getY())/ppc));
cache.append(')').append(eol);
for(IShape shape : drawing.getShapes()) {
pstView = synchro.getView(shape);
if(pstView!=null) {
code = pstView.getCache();
if(code!=null)
shapeCode.append(code).append(eol);
generateColourCode(pstView, addedColours);
}
}
cache.append(shapeCode).append("\\end{pspicture}").append(eol).append('}').append(eol); //$NON-NLS-1$
if(withLatexParams) {
if(positionHoriCentre)
cache.append("\\end{center}").append(eol);//$NON-NLS-1$
if(label.length()>0)
cache.append("\\label{").append(label).append('}');//$NON-NLS-1$
if(caption.length()>0)
cache.append("\\caption{").append(caption).append('}');//$NON-NLS-1$
if(positionVertToken!=VerticalPosition.NONE)
cache.append("\\end{figure}");//$NON-NLS-1$
}
}
| public void update() {
emptyCache();
final IDrawing drawing = synchro.getDrawing();
StringBuffer code;
final String eol = System.getProperty("line.separator");//$NON-NLS-1$
String pkg = LaTeXGenerator.getPackages();
PSTShapeView<?> pstView;
final ViewsSynchroniserHandler handler = synchro.getHandler();
final IPoint origin = handler.getOriginDrawingPoint();
final IPoint tl = handler.getTopRightDrawingPoint();
final IPoint br = handler.getBottomLeftDrawingPoint();
final int ppc = handler.getPPCDrawing();
final Map<String, String> addedColours = new HashMap<String, String>();
final StringBuffer shapeCode = new StringBuffer();
if(drawing.isEmpty())
return ;
if(withComments && comment!=null && comment.length()>0)
cache.append(comment);
cache.append(PACKAGE_PSTRICKS);
if(pkg.length()>0) {
pkg = "% User Packages:" + eol + "% " + pkg.replace(eol, eol + "% ");
cache.append(pkg).append(eol);
}
if(withLatexParams && positionVertToken!=VerticalPosition.NONE)
cache.append("\\begin{figure}[").append(positionVertToken.getToken()).append(']').append(eol);//$NON-NLS-1$
if(withLatexParams && positionHoriCentre)
cache.append("\\begin{center}").append(eol);//$NON-NLS-1$
cache.append("\\psscalebox{1 1} % Change this value to rescale the drawing.");//$NON-NLS-1$
cache.append(eol).append('{').append(eol);
cache.append("\\begin{pspicture}("); //$NON-NLS-1$
cache.append(0).append(',').append((float)LNumber.INSTANCE.getCutNumber((origin.getY()-br.getY())/ppc)).append(')').append('(');
cache.append((float)LNumber.INSTANCE.getCutNumber((tl.getX()-origin.getX())/ppc)).append(',').append((float)LNumber.INSTANCE.getCutNumber((origin.getY()-tl.getY())/ppc));
cache.append(')').append(eol);
for(IShape shape : drawing.getShapes()) {
pstView = synchro.getView(shape);
if(pstView!=null) {
code = pstView.getCache();
if(code!=null)
shapeCode.append(code).append(eol);
generateColourCode(pstView, addedColours);
}
}
cache.append(shapeCode).append("\\end{pspicture}").append(eol).append('}').append(eol); //$NON-NLS-1$
if(withLatexParams) {
if(positionHoriCentre)
cache.append("\\end{center}").append(eol);//$NON-NLS-1$
if(label.length()>0)
cache.append("\\label{").append(label).append('}');//$NON-NLS-1$
if(caption.length()>0)
cache.append("\\caption{").append(caption).append('}');//$NON-NLS-1$
if(positionVertToken!=VerticalPosition.NONE)
cache.append("\\end{figure}");//$NON-NLS-1$
}
}
|
diff --git a/org.caleydo.data.importer/src/org/caleydo/data/importer/tcga/EDataSetType.java b/org.caleydo.data.importer/src/org/caleydo/data/importer/tcga/EDataSetType.java
index 59396fea7..11ce03a5b 100644
--- a/org.caleydo.data.importer/src/org/caleydo/data/importer/tcga/EDataSetType.java
+++ b/org.caleydo.data.importer/src/org/caleydo/data/importer/tcga/EDataSetType.java
@@ -1,82 +1,84 @@
/*******************************************************************************
* Caleydo - visualization for molecular biology - http://caleydo.org
*
* Copyright(C) 2005, 2012 Graz University of Technology, Marc Streit, Alexander Lex, Christian Partl, Johannes Kepler
* University Linz </p>
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>
*******************************************************************************/
package org.caleydo.data.importer.tcga;
import org.caleydo.core.util.color.Color;
import org.caleydo.core.util.color.ColorManager;
/**
* A list of different dataset types that we are able to load for TCGA and which have a grouping. These are the dataset
* types that we want to compare between analysis runs.
*
* @author Marc Streit
*
*/
public enum EDataSetType {
mRNA("mRNA", ColorManager.get().getColorList(ColorManager.QUALITATIVE_COLORS).get(0)),
mRNAseq("mRNA-seq", ColorManager.get().getColorList(ColorManager.QUALITATIVE_COLORS).get(0)
.getColorWithSpecificBrighness(0.7f)),
microRNA("microRNA", ColorManager.get().getColorList(ColorManager.QUALITATIVE_COLORS).get(1)),
microRNAseq("microRNA-seq", ColorManager.get().getColorList(ColorManager.QUALITATIVE_COLORS).get(1)
.getColorWithSpecificBrighness(0.7f)),
methylation("Methylation", ColorManager.get().getColorList(ColorManager.QUALITATIVE_COLORS).get(2)),
RPPA("RPPA", ColorManager.get().getColorList(ColorManager.QUALITATIVE_COLORS).get(3)),
copyNumber("Copy Number", ColorManager.get().getColorList(ColorManager.QUALITATIVE_COLORS).get(4)),
mutation("Mutations", ColorManager.get().getColorList(ColorManager.QUALITATIVE_COLORS).get(5)),
clinical("Clinical", ColorManager.get().getColorList(ColorManager.QUALITATIVE_COLORS).get(6));
private Color color;
private String name;
private EDataSetType(String name, Color color) {
this.name = name;
this.color = color;
}
/**
* @return the color, see {@link #color}
*/
public Color getColor() {
return color;
}
/**
* @return the name, see {@link #name}
*/
public String getName() {
return name;
}
public String getTCGAAbbr() {
switch (this) {
case copyNumber:
return "CopyNumber";
case mutation:
return "Mutation";
case clinical:
return "Clinical";
+ case mRNAseq:
+ return "mRNAseq";
case microRNA:
return "miR";
case microRNAseq:
return "miRseq";
default:
return this.getName();
}
}
}
| true | true | public String getTCGAAbbr() {
switch (this) {
case copyNumber:
return "CopyNumber";
case mutation:
return "Mutation";
case clinical:
return "Clinical";
case microRNA:
return "miR";
case microRNAseq:
return "miRseq";
default:
return this.getName();
}
}
| public String getTCGAAbbr() {
switch (this) {
case copyNumber:
return "CopyNumber";
case mutation:
return "Mutation";
case clinical:
return "Clinical";
case mRNAseq:
return "mRNAseq";
case microRNA:
return "miR";
case microRNAseq:
return "miRseq";
default:
return this.getName();
}
}
|
diff --git a/oak-core/src/test/java/org/apache/jackrabbit/oak/query/index/TraversingIndexQueryTest.java b/oak-core/src/test/java/org/apache/jackrabbit/oak/query/index/TraversingIndexQueryTest.java
index 58b967f117..a2a3a190bc 100644
--- a/oak-core/src/test/java/org/apache/jackrabbit/oak/query/index/TraversingIndexQueryTest.java
+++ b/oak-core/src/test/java/org/apache/jackrabbit/oak/query/index/TraversingIndexQueryTest.java
@@ -1,207 +1,207 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.apache.jackrabbit.oak.query.index;
import org.apache.jackrabbit.oak.Oak;
import org.apache.jackrabbit.oak.api.ContentRepository;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.plugins.nodetype.write.InitialContent;
import org.apache.jackrabbit.oak.query.AbstractQueryTest;
import org.apache.jackrabbit.oak.spi.security.OpenSecurityProvider;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
/**
* Tests the query engine using the default index implementation: the
* {@link TraversingIndex}
*/
public class TraversingIndexQueryTest extends AbstractQueryTest {
@Override
protected ContentRepository createRepository() {
return new Oak()
.with(new OpenSecurityProvider())
.with(new InitialContent())
.createContentRepository();
}
@Test
public void sql1() throws Exception {
test("sql1.txt");
}
@Test
public void sql2() throws Exception {
test("sql2.txt");
}
@Test
public void testFullTextTerm() throws Exception {
//OAK-1024 allow '/' in a full-text query
Tree node = root.getTree("/").addChild("content");
node.setProperty("jcr:mimeType", "text/plain");
root.commit();
assertQuery("//*[jcr:contains(., 'text/plain')]", "xpath",
ImmutableList.of("/content"));
}
@Test
public void testFullTextTermName() throws Exception {
Tree c = root.getTree("/").addChild("content");
c.addChild("testFullTextTermNameSimple");
c.addChild("testFullTextTermNameFile.txt");
root.commit();
assertQuery("//*[jcr:contains(., 'testFullTextTermNameSimple')]",
"xpath",
ImmutableList.of("/content/testFullTextTermNameSimple"));
assertQuery("//*[jcr:contains(., 'testFullTextTermNameFile.txt')]",
"xpath",
ImmutableList.of("/content/testFullTextTermNameFile.txt"));
}
@Test
public void testMultiNotEqual() throws Exception {
Tree c = root.getTree("/").addChild("content");
c.addChild("one").setProperty("prop", "value");
c.addChild("two").setProperty("prop",
ImmutableList.of("aaa", "value", "bbb"), Type.STRINGS);
c.addChild("three").setProperty("prop",
ImmutableList.of("aaa", "bbb", "ccc"), Type.STRINGS);
root.commit();
assertQuery("//*[@prop != 'value']", "xpath",
ImmutableList.of("/content/two", "/content/three"));
}
@Test
public void testMultiAndEquals() throws Exception {
Tree c = root.getTree("/").addChild("content");
c.addChild("one").setProperty("prop", "aaa");
c.addChild("two").setProperty("prop",
ImmutableList.of("aaa", "bbb", "ccc"), Type.STRINGS);
c.addChild("three").setProperty("prop", ImmutableList.of("aaa", "bbb"),
Type.STRINGS);
root.commit();
assertQuery("//*[(@prop = 'aaa' and @prop = 'bbb' and @prop = 'ccc')]",
"xpath", ImmutableList.of("/content/two"));
}
@Test
public void testMultiAndLike() throws Exception {
Tree c = root.getTree("/").addChild("content");
c.addChild("one").setProperty("prop", "aaaBoom");
c.addChild("two").setProperty("prop",
ImmutableList.of("aaaBoom", "bbbBoom", "cccBoom"), Type.STRINGS);
c.addChild("three").setProperty("prop", ImmutableList.of("aaaBoom", "bbbBoom"),
Type.STRINGS);
root.commit();
assertQuery("//*[(jcr:like(@prop, 'aaa%') and jcr:like(@prop, 'bbb%') and jcr:like(@prop, 'ccc%'))]",
"xpath", ImmutableList.of("/content/two"));
}
@Test
public void testSubPropertyMultiAndEquals() throws Exception {
Tree c = root.getTree("/").addChild("content");
c.addChild("one").addChild("child").setProperty("prop", "aaa");
c.addChild("two")
.addChild("child")
.setProperty("prop", ImmutableList.of("aaa", "bbb", "ccc"),
Type.STRINGS);
c.addChild("three")
.addChild("child")
.setProperty("prop", ImmutableList.of("aaa", "bbb"),
Type.STRINGS);
root.commit();
assertQuery(
"//*[(child/@prop = 'aaa' and child/@prop = 'bbb' and child/@prop = 'ccc')]",
"xpath", ImmutableList.of("/content/two"));
}
@Test
public void testSubPropertyMultiAndLike() throws Exception {
Tree c = root.getTree("/").addChild("content");
c.addChild("one").addChild("child").setProperty("prop", "aaaBoom");
c.addChild("two")
.addChild("child")
.setProperty("prop", ImmutableList.of("aaaBoom", "bbbBoom", "cccBoom"),
Type.STRINGS);
c.addChild("three")
.addChild("child")
.setProperty("prop", ImmutableList.of("aaaBoom", "bbbBoom"),
Type.STRINGS);
root.commit();
assertQuery(
"//*[(jcr:like(child/@prop, 'aaa%') and jcr:like(child/@prop, 'bbb%') and jcr:like(child/@prop, 'ccc%'))]",
"xpath", ImmutableList.of("/content/two"));
}
@Test
public void testOak1301() throws Exception {
Tree t1 = root.getTree("/").addChild("home").addChild("users")
.addChild("testing").addChild("socialgraph_test_user_4");
t1.setProperty("jcr:primaryType", "rep:User");
t1.setProperty("rep:authorizableId", "socialgraph_test_user_4");
Tree s = t1.addChild("social");
s.setProperty("jcr:primaryType", "sling:Folder");
Tree r = s.addChild("relationships");
r.setProperty("jcr:primaryType", "sling:Folder");
Tree f = r.addChild("friend");
f.setProperty("jcr:primaryType", "sling:Folder");
Tree sg = f.addChild("socialgraph_test_group");
sg.setProperty("jcr:primaryType", "nt:unstructured");
sg.setProperty("id", "socialgraph_test_group");
Tree t2 = root.getTree("/").addChild("home").addChild("groups")
.addChild("testing").addChild("socialgraph_test_group");
root.commit();
// select [jcr:path], [jcr:score], * from [nt:base] as a where [id/*] =
// 'socialgraph_test_group' and isdescendantnode(a, '/home') /* xpath:
// /jcr:root/home//*[id='socialgraph_test_group'] */
assertQuery(
- "/jcr:root/home//*[id='socialgraph_test_group']",
+ "/jcr:root/home//*[@id='socialgraph_test_group']",
"xpath",
ImmutableList
.of("/home/users/testing/socialgraph_test_user_4/social/relationships/friend/socialgraph_test_group"));
// sql2 select c.[jcr:path] as [jcr:path], c.[jcr:score] as [jcr:score],
// c.* from [nt:base] as a inner join [nt:base] as b on ischildnode(b,
// a) inner join [nt:base] as c on isdescendantnode(c, b) where name(a)
// = 'social' and isdescendantnode(a, '/home') and name(b) =
// 'relationships' and c.[id/*] = 'socialgraph_test_group' /* xpath:
// /jcr:root/home//social/relationships//*[id='socialgraph_test_group']
// */
assertQuery(
- "/jcr:root/home//social/relationships//*[id='socialgraph_test_group']",
+ "/jcr:root/home//social/relationships//*[@id='socialgraph_test_group']",
"xpath",
ImmutableList
.of("/home/users/testing/socialgraph_test_user_4/social/relationships/friend/socialgraph_test_group"));
}
}
| false | true | public void testOak1301() throws Exception {
Tree t1 = root.getTree("/").addChild("home").addChild("users")
.addChild("testing").addChild("socialgraph_test_user_4");
t1.setProperty("jcr:primaryType", "rep:User");
t1.setProperty("rep:authorizableId", "socialgraph_test_user_4");
Tree s = t1.addChild("social");
s.setProperty("jcr:primaryType", "sling:Folder");
Tree r = s.addChild("relationships");
r.setProperty("jcr:primaryType", "sling:Folder");
Tree f = r.addChild("friend");
f.setProperty("jcr:primaryType", "sling:Folder");
Tree sg = f.addChild("socialgraph_test_group");
sg.setProperty("jcr:primaryType", "nt:unstructured");
sg.setProperty("id", "socialgraph_test_group");
Tree t2 = root.getTree("/").addChild("home").addChild("groups")
.addChild("testing").addChild("socialgraph_test_group");
root.commit();
// select [jcr:path], [jcr:score], * from [nt:base] as a where [id/*] =
// 'socialgraph_test_group' and isdescendantnode(a, '/home') /* xpath:
// /jcr:root/home//*[id='socialgraph_test_group'] */
assertQuery(
"/jcr:root/home//*[id='socialgraph_test_group']",
"xpath",
ImmutableList
.of("/home/users/testing/socialgraph_test_user_4/social/relationships/friend/socialgraph_test_group"));
// sql2 select c.[jcr:path] as [jcr:path], c.[jcr:score] as [jcr:score],
// c.* from [nt:base] as a inner join [nt:base] as b on ischildnode(b,
// a) inner join [nt:base] as c on isdescendantnode(c, b) where name(a)
// = 'social' and isdescendantnode(a, '/home') and name(b) =
// 'relationships' and c.[id/*] = 'socialgraph_test_group' /* xpath:
// /jcr:root/home//social/relationships//*[id='socialgraph_test_group']
// */
assertQuery(
"/jcr:root/home//social/relationships//*[id='socialgraph_test_group']",
"xpath",
ImmutableList
.of("/home/users/testing/socialgraph_test_user_4/social/relationships/friend/socialgraph_test_group"));
}
| public void testOak1301() throws Exception {
Tree t1 = root.getTree("/").addChild("home").addChild("users")
.addChild("testing").addChild("socialgraph_test_user_4");
t1.setProperty("jcr:primaryType", "rep:User");
t1.setProperty("rep:authorizableId", "socialgraph_test_user_4");
Tree s = t1.addChild("social");
s.setProperty("jcr:primaryType", "sling:Folder");
Tree r = s.addChild("relationships");
r.setProperty("jcr:primaryType", "sling:Folder");
Tree f = r.addChild("friend");
f.setProperty("jcr:primaryType", "sling:Folder");
Tree sg = f.addChild("socialgraph_test_group");
sg.setProperty("jcr:primaryType", "nt:unstructured");
sg.setProperty("id", "socialgraph_test_group");
Tree t2 = root.getTree("/").addChild("home").addChild("groups")
.addChild("testing").addChild("socialgraph_test_group");
root.commit();
// select [jcr:path], [jcr:score], * from [nt:base] as a where [id/*] =
// 'socialgraph_test_group' and isdescendantnode(a, '/home') /* xpath:
// /jcr:root/home//*[id='socialgraph_test_group'] */
assertQuery(
"/jcr:root/home//*[@id='socialgraph_test_group']",
"xpath",
ImmutableList
.of("/home/users/testing/socialgraph_test_user_4/social/relationships/friend/socialgraph_test_group"));
// sql2 select c.[jcr:path] as [jcr:path], c.[jcr:score] as [jcr:score],
// c.* from [nt:base] as a inner join [nt:base] as b on ischildnode(b,
// a) inner join [nt:base] as c on isdescendantnode(c, b) where name(a)
// = 'social' and isdescendantnode(a, '/home') and name(b) =
// 'relationships' and c.[id/*] = 'socialgraph_test_group' /* xpath:
// /jcr:root/home//social/relationships//*[id='socialgraph_test_group']
// */
assertQuery(
"/jcr:root/home//social/relationships//*[@id='socialgraph_test_group']",
"xpath",
ImmutableList
.of("/home/users/testing/socialgraph_test_user_4/social/relationships/friend/socialgraph_test_group"));
}
|
diff --git a/file-utils/src/main/java/org/daisy/saxon/functions/file/FileExists.java b/file-utils/src/main/java/org/daisy/saxon/functions/file/FileExists.java
index ec119e5..dd90fdd 100644
--- a/file-utils/src/main/java/org/daisy/saxon/functions/file/FileExists.java
+++ b/file-utils/src/main/java/org/daisy/saxon/functions/file/FileExists.java
@@ -1,59 +1,59 @@
package org.daisy.saxon.functions.file;
import java.io.File;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.om.SequenceIterator;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.tree.iter.SingletonIterator;
import net.sf.saxon.type.BuiltInAtomicType;
import net.sf.saxon.value.BooleanValue;
import net.sf.saxon.value.SequenceType;
import net.sf.saxon.value.StringValue;
@SuppressWarnings("serial")
public class FileExists extends ExtensionFunctionDefinition {
private static final StructuredQName funcname = new StructuredQName("pf",
"http://www.daisy.org/ns/pipeline/functions", "file-exists");
@Override
public SequenceType[] getArgumentTypes() {
return new SequenceType[] { SequenceType.SINGLE_STRING };
}
@Override
public StructuredQName getFunctionQName() {
return funcname;
}
@Override
public SequenceType getResultType(SequenceType[] arg0) {
return SequenceType.SINGLE_BOOLEAN;
}
@Override
public ExtensionFunctionCall makeCallExpression() {
return new ExtensionFunctionCall() {
@SuppressWarnings({ "unchecked", "rawtypes" })
public SequenceIterator call(SequenceIterator[] arguments,
XPathContext context) throws XPathException {
try {
String path = ((StringValue) arguments[0].next())
.getStringValue();
- boolean result = new File(path).exists();
+ boolean result = (path.isEmpty())?true:new File(path).exists();
return SingletonIterator.makeIterator(new BooleanValue(
result, BuiltInAtomicType.BOOLEAN));
} catch (Exception e) {
throw new XPathException("pf:file-exists failed", e);
}
}
};
}
}
| true | true | public ExtensionFunctionCall makeCallExpression() {
return new ExtensionFunctionCall() {
@SuppressWarnings({ "unchecked", "rawtypes" })
public SequenceIterator call(SequenceIterator[] arguments,
XPathContext context) throws XPathException {
try {
String path = ((StringValue) arguments[0].next())
.getStringValue();
boolean result = new File(path).exists();
return SingletonIterator.makeIterator(new BooleanValue(
result, BuiltInAtomicType.BOOLEAN));
} catch (Exception e) {
throw new XPathException("pf:file-exists failed", e);
}
}
};
}
| public ExtensionFunctionCall makeCallExpression() {
return new ExtensionFunctionCall() {
@SuppressWarnings({ "unchecked", "rawtypes" })
public SequenceIterator call(SequenceIterator[] arguments,
XPathContext context) throws XPathException {
try {
String path = ((StringValue) arguments[0].next())
.getStringValue();
boolean result = (path.isEmpty())?true:new File(path).exists();
return SingletonIterator.makeIterator(new BooleanValue(
result, BuiltInAtomicType.BOOLEAN));
} catch (Exception e) {
throw new XPathException("pf:file-exists failed", e);
}
}
};
}
|
diff --git a/src/main/java/com/lyncode/xoai/dataprovider/data/DefaultResumptionTokenFormat.java b/src/main/java/com/lyncode/xoai/dataprovider/data/DefaultResumptionTokenFormat.java
index 78fd1b8..e768050 100644
--- a/src/main/java/com/lyncode/xoai/dataprovider/data/DefaultResumptionTokenFormat.java
+++ b/src/main/java/com/lyncode/xoai/dataprovider/data/DefaultResumptionTokenFormat.java
@@ -1,106 +1,107 @@
package com.lyncode.xoai.dataprovider.data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.lyncode.xoai.dataprovider.core.ResumptionToken;
import com.lyncode.xoai.dataprovider.exceptions.BadResumptionToken;
import com.lyncode.xoai.util.Base64Utils;
public class DefaultResumptionTokenFormat extends AbstractResumptionTokenFormat {
private static Logger log = LogManager.getLogger(DefaultResumptionTokenFormat.class);
@Override
public ResumptionToken parse(String resumptionToken) throws BadResumptionToken {
+ if (resumptionToken == null) return new ResumptionToken();
int _offset = 0;
String _set = null;
Date _from = null;
Date _until = null;
String _metadataPrefix = null;
if (resumptionToken == null || resumptionToken.trim().equals("")) {
return new ResumptionToken();
} else {
String s = Base64Utils.decode(resumptionToken);
String[] pieces = s.split(Pattern.quote("|"));
try {
if (pieces.length > 0) {
_offset = Integer.parseInt(pieces[0].substring(2));
if (pieces.length > 1) {
_set = pieces[1].substring(2);
if (_set != null && _set.equals(""))
_set = null;
}
if (pieces.length > 2) {
_from = stringToDate(pieces[2].substring(2));
}
if (pieces.length > 3) {
_until = stringToDate(pieces[3].substring(2));
}
if (pieces.length > 4) {
_metadataPrefix = pieces[4].substring(2);
if (_metadataPrefix != null && _metadataPrefix.equals(""))
_metadataPrefix = null;
}
} else
throw new BadResumptionToken();
} catch (Exception ex) {
log.debug(ex.getMessage(), ex);
throw new BadResumptionToken();
}
}
return new ResumptionToken(_offset, _metadataPrefix, _set, _from, _until);
}
@Override
public String format(ResumptionToken resumptionToken) {
if (resumptionToken.isEmpty())
return "";
String s = "1:" + resumptionToken.getOffset();
s += "|2:";
if (resumptionToken.hasSet())
s += resumptionToken.getSet();
s += "|3:";
if (resumptionToken.hasFrom())
s += dateToString(resumptionToken.getFrom());
s += "|4:";
if (resumptionToken.hasUntil())
s += dateToString(resumptionToken.getUntil());
s += "|5:";
if (resumptionToken.hasMetadataPrefix())
s += resumptionToken.getMetadatePrefix();
return Base64Utils.encode(s);
}
private String dateToString(Date date) {
SimpleDateFormat formatDate = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
return formatDate.format(date);
}
private Date stringToDate(String string) {
SimpleDateFormat formatDate = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
return formatDate.parse(string);
} catch (ParseException ex) {
formatDate = new SimpleDateFormat(
"yyyy-MM-dd");
try {
return formatDate.parse(string);
} catch (ParseException ex1) {
return null;
}
}
}
}
| true | true | public ResumptionToken parse(String resumptionToken) throws BadResumptionToken {
int _offset = 0;
String _set = null;
Date _from = null;
Date _until = null;
String _metadataPrefix = null;
if (resumptionToken == null || resumptionToken.trim().equals("")) {
return new ResumptionToken();
} else {
String s = Base64Utils.decode(resumptionToken);
String[] pieces = s.split(Pattern.quote("|"));
try {
if (pieces.length > 0) {
_offset = Integer.parseInt(pieces[0].substring(2));
if (pieces.length > 1) {
_set = pieces[1].substring(2);
if (_set != null && _set.equals(""))
_set = null;
}
if (pieces.length > 2) {
_from = stringToDate(pieces[2].substring(2));
}
if (pieces.length > 3) {
_until = stringToDate(pieces[3].substring(2));
}
if (pieces.length > 4) {
_metadataPrefix = pieces[4].substring(2);
if (_metadataPrefix != null && _metadataPrefix.equals(""))
_metadataPrefix = null;
}
} else
throw new BadResumptionToken();
} catch (Exception ex) {
log.debug(ex.getMessage(), ex);
throw new BadResumptionToken();
}
}
return new ResumptionToken(_offset, _metadataPrefix, _set, _from, _until);
}
| public ResumptionToken parse(String resumptionToken) throws BadResumptionToken {
if (resumptionToken == null) return new ResumptionToken();
int _offset = 0;
String _set = null;
Date _from = null;
Date _until = null;
String _metadataPrefix = null;
if (resumptionToken == null || resumptionToken.trim().equals("")) {
return new ResumptionToken();
} else {
String s = Base64Utils.decode(resumptionToken);
String[] pieces = s.split(Pattern.quote("|"));
try {
if (pieces.length > 0) {
_offset = Integer.parseInt(pieces[0].substring(2));
if (pieces.length > 1) {
_set = pieces[1].substring(2);
if (_set != null && _set.equals(""))
_set = null;
}
if (pieces.length > 2) {
_from = stringToDate(pieces[2].substring(2));
}
if (pieces.length > 3) {
_until = stringToDate(pieces[3].substring(2));
}
if (pieces.length > 4) {
_metadataPrefix = pieces[4].substring(2);
if (_metadataPrefix != null && _metadataPrefix.equals(""))
_metadataPrefix = null;
}
} else
throw new BadResumptionToken();
} catch (Exception ex) {
log.debug(ex.getMessage(), ex);
throw new BadResumptionToken();
}
}
return new ResumptionToken(_offset, _metadataPrefix, _set, _from, _until);
}
|
diff --git a/rultor-users/src/main/java/com/rultor/users/mongo/MongoCoords.java b/rultor-users/src/main/java/com/rultor/users/mongo/MongoCoords.java
index 4fa08de57..fb39f0edb 100644
--- a/rultor-users/src/main/java/com/rultor/users/mongo/MongoCoords.java
+++ b/rultor-users/src/main/java/com/rultor/users/mongo/MongoCoords.java
@@ -1,153 +1,153 @@
/**
* Copyright (c) 2009-2013, rultor.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the rultor.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rultor.users.mongo;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.urn.URN;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.rultor.spi.Coordinates;
import com.rultor.tools.Time;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Coordinates in Mongo.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 1.0
*/
@Immutable
@ToString
@EqualsAndHashCode(of = { "urn", "name", "time" })
@Loggable(Loggable.DEBUG)
final class MongoCoords implements Coordinates {
/**
* MongoDB table column.
*/
public static final String ATTR_RULE = "rule";
/**
* MongoDB table column.
*/
public static final String ATTR_OWNER = "owner";
/**
* MongoDB table column.
*/
public static final String ATTR_SCHEDULED = "scheduled";
/**
* Owner.
*/
private final transient URN urn;
/**
* Name of the rule.
*/
private final transient String name;
/**
* Scheduled time.
*/
private final transient Time time;
/**
* Public ctor.
* @param object The object
*/
protected MongoCoords(final DBObject object) {
this(
URN.create(object.get(MongoCoords.ATTR_OWNER).toString()),
object.get(MongoCoords.ATTR_RULE).toString(),
- new Time(object.get(MongoCoords.ATTR_OWNER).toString())
+ new Time(object.get(MongoCoords.ATTR_SCHEDULED).toString())
);
}
/**
* Public ctor.
* @param coords Other coordinates
*/
protected MongoCoords(final Coordinates coords) {
this(coords.owner(), coords.rule(), coords.scheduled());
}
/**
* Public ctor.
* @param owner Owner
* @param rule Rule
* @param scheduled Scheduled
*/
private MongoCoords(final URN owner, final String rule,
final Time scheduled) {
this.urn = owner;
this.name = rule;
this.time = scheduled;
}
/**
* Make Mongo DBObject out of it.
* @return Object
*/
public DBObject asObject() {
return new BasicDBObject()
.append(MongoCoords.ATTR_OWNER, this.owner().toString())
.append(MongoCoords.ATTR_RULE, this.rule())
.append(MongoCoords.ATTR_SCHEDULED, this.scheduled().toString());
}
/**
* {@inheritDoc}
*/
@Override
public Time scheduled() {
return this.time;
}
/**
* {@inheritDoc}
*/
@Override
public URN owner() {
return this.urn;
}
/**
* {@inheritDoc}
*/
@Override
public String rule() {
return this.name;
}
}
| true | true | protected MongoCoords(final DBObject object) {
this(
URN.create(object.get(MongoCoords.ATTR_OWNER).toString()),
object.get(MongoCoords.ATTR_RULE).toString(),
new Time(object.get(MongoCoords.ATTR_OWNER).toString())
);
}
| protected MongoCoords(final DBObject object) {
this(
URN.create(object.get(MongoCoords.ATTR_OWNER).toString()),
object.get(MongoCoords.ATTR_RULE).toString(),
new Time(object.get(MongoCoords.ATTR_SCHEDULED).toString())
);
}
|
diff --git a/src/main/java/name/gyger/jmoney/web/OptionsController.java b/src/main/java/name/gyger/jmoney/web/OptionsController.java
index 715e95d..c0295a6 100644
--- a/src/main/java/name/gyger/jmoney/web/OptionsController.java
+++ b/src/main/java/name/gyger/jmoney/web/OptionsController.java
@@ -1,57 +1,57 @@
/*
* Copyright 2012 Johann Gyger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package name.gyger.jmoney.web;
import name.gyger.jmoney.service.OptionsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.inject.Inject;
@Controller
public class OptionsController {
private static final Logger log = LoggerFactory.getLogger(OptionsController.class);
@Inject
private OptionsService optionsService;
@RequestMapping(value = "/options/init", method = RequestMethod.PUT)
@ResponseBody
public void init() {
optionsService.init();
}
@RequestMapping(value = "/options/import", method = RequestMethod.POST)
public String importFile(@RequestParam("file") MultipartFile file) {
try {
optionsService.importFile(file.getInputStream());
return "redirect:/options.html#/options/import?success";
} catch (Exception e) {
log.error(e.getMessage(), e);
- return "redirect:/options.html#/options/import?failure";
+ return "redirect:/options.html#/options/import?error";
}
}
}
| true | true | public String importFile(@RequestParam("file") MultipartFile file) {
try {
optionsService.importFile(file.getInputStream());
return "redirect:/options.html#/options/import?success";
} catch (Exception e) {
log.error(e.getMessage(), e);
return "redirect:/options.html#/options/import?failure";
}
}
| public String importFile(@RequestParam("file") MultipartFile file) {
try {
optionsService.importFile(file.getInputStream());
return "redirect:/options.html#/options/import?success";
} catch (Exception e) {
log.error(e.getMessage(), e);
return "redirect:/options.html#/options/import?error";
}
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/Caption.java b/src/com/itmill/toolkit/terminal/gwt/client/Caption.java
index b9ea6afdb..1ffd59f4d 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/Caption.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/Caption.java
@@ -1,201 +1,202 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HTML;
import com.itmill.toolkit.terminal.gwt.client.ui.Icon;
public class Caption extends HTML {
public static final String CLASSNAME = "i-caption";
private final Paintable owner;
private Element errorIndicatorElement;
private Element requiredFieldIndicator;
private Icon icon;
private Element captionText;
private ErrorMessage errorMessage;
private final ApplicationConnection client;
/**
*
* @param component
* optional owner of caption. If not set, getOwner will
* return null
* @param client
*/
public Caption(Paintable component, ApplicationConnection client) {
super();
this.client = client;
owner = component;
setStyleName(CLASSNAME);
}
public void updateCaption(UIDL uidl) {
setVisible(!uidl.getBooleanAttribute("invisible"));
setStyleName(getElement(), "i-disabled", uidl.hasAttribute("disabled"));
boolean isEmpty = true;
if (uidl.hasAttribute("error")) {
isEmpty = false;
final UIDL errorUidl = uidl.getErrors();
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.insertChild(getElement(), errorIndicatorElement, 0);
}
if (errorMessage == null) {
errorMessage = new ErrorMessage();
}
errorMessage.updateFromUIDL(errorUidl);
} else if (errorIndicatorElement != null) {
DOM.removeChild(getElement(), errorIndicatorElement);
errorIndicatorElement = null;
}
if (uidl.hasAttribute("icon")) {
if (icon == null) {
icon = new Icon(client);
DOM.appendChild(getElement(), icon.getElement());
}
icon.setUri(uidl.getStringAttribute("icon"));
isEmpty = false;
} else {
if (icon != null) {
DOM.removeChild(getElement(), icon.getElement());
icon = null;
}
}
if (uidl.hasAttribute("caption")) {
if (captionText == null) {
captionText = DOM.createSpan();
DOM.appendChild(getElement(), captionText);
}
String c = uidl.getStringAttribute("caption");
if (c == null) {
c = "";
} else {
isEmpty = false;
}
DOM.setInnerText(captionText, c);
} else {
// TODO should span also be removed
}
if (uidl.hasAttribute("description")) {
if (captionText != null) {
DOM.setElementProperty(captionText, "title", uidl
.getStringAttribute("description"));
} else {
setTitle(uidl.getStringAttribute("description"));
}
}
if (uidl.getBooleanAttribute("required")) {
if (requiredFieldIndicator == null) {
requiredFieldIndicator = DOM.createSpan();
DOM.setInnerText(requiredFieldIndicator, "*");
DOM.setElementProperty(requiredFieldIndicator, "className",
"i-required-field-indicator");
DOM.appendChild(getElement(), requiredFieldIndicator);
}
} else {
if (requiredFieldIndicator != null) {
DOM.removeChild(getElement(), requiredFieldIndicator);
+ requiredFieldIndicator = null;
}
}
// Workaround for IE weirdness, sometimes returns bad height in some
// circumstances when Caption is empty. See #1444
// IE7 bugs more often. I wonder what happens when IE8 arrives...
if (Util.isIE()) {
if (isEmpty) {
setHeight("0px");
DOM.setStyleAttribute(getElement(), "overflow", "hidden");
} else {
setHeight("");
DOM.setStyleAttribute(getElement(), "overflow", "");
}
}
}
public void onBrowserEvent(Event event) {
final Element target = DOM.eventGetTarget(event);
if (errorIndicatorElement != null
&& DOM.compare(target, errorIndicatorElement)) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEOVER:
showErrorMessage();
break;
case Event.ONMOUSEOUT:
hideErrorMessage();
break;
case Event.ONCLICK:
ApplicationConnection.getConsole().log(
DOM.getInnerHTML(errorMessage.getElement()));
default:
break;
}
} else {
super.onBrowserEvent(event);
}
}
private void hideErrorMessage() {
if (errorMessage != null) {
errorMessage.hide();
}
}
private void showErrorMessage() {
if (errorMessage != null) {
errorMessage.showAt(errorIndicatorElement);
}
}
public static boolean isNeeded(UIDL uidl) {
if (uidl.getStringAttribute("caption") != null) {
return true;
}
if (uidl.hasAttribute("error")) {
return true;
}
if (uidl.hasAttribute("icon")) {
return true;
}
// TODO Description ??
return false;
}
/**
* Returns Paintable for which this Caption belongs to.
*
* @return owner Widget
*/
public Paintable getOwner() {
return owner;
}
}
| true | true | public void updateCaption(UIDL uidl) {
setVisible(!uidl.getBooleanAttribute("invisible"));
setStyleName(getElement(), "i-disabled", uidl.hasAttribute("disabled"));
boolean isEmpty = true;
if (uidl.hasAttribute("error")) {
isEmpty = false;
final UIDL errorUidl = uidl.getErrors();
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.insertChild(getElement(), errorIndicatorElement, 0);
}
if (errorMessage == null) {
errorMessage = new ErrorMessage();
}
errorMessage.updateFromUIDL(errorUidl);
} else if (errorIndicatorElement != null) {
DOM.removeChild(getElement(), errorIndicatorElement);
errorIndicatorElement = null;
}
if (uidl.hasAttribute("icon")) {
if (icon == null) {
icon = new Icon(client);
DOM.appendChild(getElement(), icon.getElement());
}
icon.setUri(uidl.getStringAttribute("icon"));
isEmpty = false;
} else {
if (icon != null) {
DOM.removeChild(getElement(), icon.getElement());
icon = null;
}
}
if (uidl.hasAttribute("caption")) {
if (captionText == null) {
captionText = DOM.createSpan();
DOM.appendChild(getElement(), captionText);
}
String c = uidl.getStringAttribute("caption");
if (c == null) {
c = "";
} else {
isEmpty = false;
}
DOM.setInnerText(captionText, c);
} else {
// TODO should span also be removed
}
if (uidl.hasAttribute("description")) {
if (captionText != null) {
DOM.setElementProperty(captionText, "title", uidl
.getStringAttribute("description"));
} else {
setTitle(uidl.getStringAttribute("description"));
}
}
if (uidl.getBooleanAttribute("required")) {
if (requiredFieldIndicator == null) {
requiredFieldIndicator = DOM.createSpan();
DOM.setInnerText(requiredFieldIndicator, "*");
DOM.setElementProperty(requiredFieldIndicator, "className",
"i-required-field-indicator");
DOM.appendChild(getElement(), requiredFieldIndicator);
}
} else {
if (requiredFieldIndicator != null) {
DOM.removeChild(getElement(), requiredFieldIndicator);
}
}
// Workaround for IE weirdness, sometimes returns bad height in some
// circumstances when Caption is empty. See #1444
// IE7 bugs more often. I wonder what happens when IE8 arrives...
if (Util.isIE()) {
if (isEmpty) {
setHeight("0px");
DOM.setStyleAttribute(getElement(), "overflow", "hidden");
} else {
setHeight("");
DOM.setStyleAttribute(getElement(), "overflow", "");
}
}
}
| public void updateCaption(UIDL uidl) {
setVisible(!uidl.getBooleanAttribute("invisible"));
setStyleName(getElement(), "i-disabled", uidl.hasAttribute("disabled"));
boolean isEmpty = true;
if (uidl.hasAttribute("error")) {
isEmpty = false;
final UIDL errorUidl = uidl.getErrors();
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.insertChild(getElement(), errorIndicatorElement, 0);
}
if (errorMessage == null) {
errorMessage = new ErrorMessage();
}
errorMessage.updateFromUIDL(errorUidl);
} else if (errorIndicatorElement != null) {
DOM.removeChild(getElement(), errorIndicatorElement);
errorIndicatorElement = null;
}
if (uidl.hasAttribute("icon")) {
if (icon == null) {
icon = new Icon(client);
DOM.appendChild(getElement(), icon.getElement());
}
icon.setUri(uidl.getStringAttribute("icon"));
isEmpty = false;
} else {
if (icon != null) {
DOM.removeChild(getElement(), icon.getElement());
icon = null;
}
}
if (uidl.hasAttribute("caption")) {
if (captionText == null) {
captionText = DOM.createSpan();
DOM.appendChild(getElement(), captionText);
}
String c = uidl.getStringAttribute("caption");
if (c == null) {
c = "";
} else {
isEmpty = false;
}
DOM.setInnerText(captionText, c);
} else {
// TODO should span also be removed
}
if (uidl.hasAttribute("description")) {
if (captionText != null) {
DOM.setElementProperty(captionText, "title", uidl
.getStringAttribute("description"));
} else {
setTitle(uidl.getStringAttribute("description"));
}
}
if (uidl.getBooleanAttribute("required")) {
if (requiredFieldIndicator == null) {
requiredFieldIndicator = DOM.createSpan();
DOM.setInnerText(requiredFieldIndicator, "*");
DOM.setElementProperty(requiredFieldIndicator, "className",
"i-required-field-indicator");
DOM.appendChild(getElement(), requiredFieldIndicator);
}
} else {
if (requiredFieldIndicator != null) {
DOM.removeChild(getElement(), requiredFieldIndicator);
requiredFieldIndicator = null;
}
}
// Workaround for IE weirdness, sometimes returns bad height in some
// circumstances when Caption is empty. See #1444
// IE7 bugs more often. I wonder what happens when IE8 arrives...
if (Util.isIE()) {
if (isEmpty) {
setHeight("0px");
DOM.setStyleAttribute(getElement(), "overflow", "hidden");
} else {
setHeight("");
DOM.setStyleAttribute(getElement(), "overflow", "");
}
}
}
|
diff --git a/gossip-server/src/gossip/gossip/action/GossipEventAction.java b/gossip-server/src/gossip/gossip/action/GossipEventAction.java
index 7ca16ba..62b4913 100644
--- a/gossip-server/src/gossip/gossip/action/GossipEventAction.java
+++ b/gossip-server/src/gossip/gossip/action/GossipEventAction.java
@@ -1,39 +1,41 @@
package gossip.gossip.action;
import gossip.gossip.service.GossipEventService;
import gossip.gossip.service.GossipNewsService;
import gossip.model.Event;
import gossip.model.News;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/gossip/event")
@Controller
public class GossipEventAction {
@Autowired
private GossipEventService eventService;
@Autowired
private GossipNewsService newsService;
//测试用
@RequestMapping("/detect")
public void detectEvent(){
Date now = new Date(System.currentTimeMillis());
//step0. 取出今天的新闻包括本周的未被识别为事件的新闻
List<News> newsToday = newsService.getNewsLast7Days(now);
System.out.println("newsToday need to compute is : "+newsToday.size());
//step1. 找出今天的events,标记没有存为事件的那些新闻
List<Event> eventsTody = eventService.computeEventFromNews(newsToday);
+ System.out.println("eventsToday is : "+eventsTody.size());
//step2. 找出前面7天的events
List<Event> eventsLast7Days = eventService.getEventsLast7Days(now);
+ System.out.println("eventsLast7Days is : "+eventsLast7Days.size());
//step3. 合并今天的与本周的,并找出新的
List<Event> newOrUpdatedEvents = eventService.mergeEvents(eventsLast7Days, eventsTody);
//step4. 插入or更新这些events
eventService.updateOrInsert(newOrUpdatedEvents);
}
}
| false | true | public void detectEvent(){
Date now = new Date(System.currentTimeMillis());
//step0. 取出今天的新闻包括本周的未被识别为事件的新闻
List<News> newsToday = newsService.getNewsLast7Days(now);
System.out.println("newsToday need to compute is : "+newsToday.size());
//step1. 找出今天的events,标记没有存为事件的那些新闻
List<Event> eventsTody = eventService.computeEventFromNews(newsToday);
//step2. 找出前面7天的events
List<Event> eventsLast7Days = eventService.getEventsLast7Days(now);
//step3. 合并今天的与本周的,并找出新的
List<Event> newOrUpdatedEvents = eventService.mergeEvents(eventsLast7Days, eventsTody);
//step4. 插入or更新这些events
eventService.updateOrInsert(newOrUpdatedEvents);
}
| public void detectEvent(){
Date now = new Date(System.currentTimeMillis());
//step0. 取出今天的新闻包括本周的未被识别为事件的新闻
List<News> newsToday = newsService.getNewsLast7Days(now);
System.out.println("newsToday need to compute is : "+newsToday.size());
//step1. 找出今天的events,标记没有存为事件的那些新闻
List<Event> eventsTody = eventService.computeEventFromNews(newsToday);
System.out.println("eventsToday is : "+eventsTody.size());
//step2. 找出前面7天的events
List<Event> eventsLast7Days = eventService.getEventsLast7Days(now);
System.out.println("eventsLast7Days is : "+eventsLast7Days.size());
//step3. 合并今天的与本周的,并找出新的
List<Event> newOrUpdatedEvents = eventService.mergeEvents(eventsLast7Days, eventsTody);
//step4. 插入or更新这些events
eventService.updateOrInsert(newOrUpdatedEvents);
}
|
diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/Slide.java b/src/scratchpad/src/org/apache/poi/hslf/model/Slide.java
index 7657528a0..5719c7e8a 100644
--- a/src/scratchpad/src/org/apache/poi/hslf/model/Slide.java
+++ b/src/scratchpad/src/org/apache/poi/hslf/model/Slide.java
@@ -1,126 +1,132 @@
/* ====================================================================
Copyright 2002-2004 Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hslf.model;
import java.util.*;
import org.apache.poi.hslf.record.*;
import org.apache.poi.hslf.record.SlideListWithText.*;
import org.apache.poi.util.LittleEndian;
/**
* This class represents a slide in a PowerPoint Document. It allows
* access to the text within, and the layout. For now, it only does
* the text side of things though
*
* @author Nick Burch
*/
public class Slide extends Sheet
{
private int _sheetNo;
private org.apache.poi.hslf.record.Slide _slide;
private SlideAtomsSet _atomSet;
private TextRun[] _runs;
private TextRun[] _otherRuns; // Any from the PPDrawing, shouldn't really be any though
private Notes _notes; // usermodel needs to set this
/**
* Constructs a Slide from the Slide record, and the SlideAtomsSet
* containing the text.
* Initialises TextRuns, to provide easier access to the text
*
* @param slide the Slide record we're based on
* @param notes the Notes sheet attached to us
* @param atomSet the SlideAtomsSet to get the text from
*/
public Slide(org.apache.poi.hslf.record.Slide slide, Notes notes, SlideAtomsSet atomSet) {
_slide = slide;
_notes = notes;
_atomSet = atomSet;
// Grab the sheet number
//_sheetNo = _slide.getSlideAtom().getSheetNumber();
_sheetNo = -1;
// Grab the TextRuns from the PPDrawing
_otherRuns = findTextRuns(_slide.getPPDrawing());
// For the text coming in from the SlideAtomsSet:
// Build up TextRuns from pairs of TextHeaderAtom and
// one of TextBytesAtom or TextCharsAtom
Vector textRuns = new Vector();
if(_atomSet != null) {
findTextRuns(_atomSet.getSlideRecords(),textRuns);
} else {
// No text on the slide, must just be pictures
}
// Build an array, more useful than a vector
- _runs = new TextRun[textRuns.size()];
- for(int i=0; i<_runs.length; i++) {
+ _runs = new TextRun[textRuns.size()+_otherRuns.length];
+ // Grab text from SlideListWithTexts entries
+ int i=0;
+ for(i=0; i<textRuns.size(); i++) {
_runs[i] = (TextRun)textRuns.get(i);
}
+ // Grab text from slide's PPDrawing
+ for(int k=0; k<_otherRuns.length; i++, k++) {
+ _runs[i] = _otherRuns[k];
+ }
}
/**
* Sets the Notes that are associated with this. Updates the
* references in the records to point to the new ID
*/
public void setNotes(Notes notes) {
_notes = notes;
// Update the Slide Atom's ID of where to point to
SlideAtom sa = _slide.getSlideAtom();
if(notes == null) {
// Set to 0
sa.setNotesID(0);
} else {
// Set to the value from the notes' sheet id
sa.setNotesID(notes.getSheetNumber());
}
}
// Accesser methods follow
/**
* Returns an array of all the TextRuns found
*/
public TextRun[] getTextRuns() { return _runs; }
/**
* Returns the sheet number
*/
public int getSheetNumber() { return _sheetNo; }
/**
* Returns the underlying slide record
*/
public org.apache.poi.hslf.record.Slide getSlideRecord() { return _slide; }
/**
* Returns the Notes Sheet for this slide, or null if there isn't one
*/
public Notes getNotesSheet() { return _notes; }
}
| false | true | public Slide(org.apache.poi.hslf.record.Slide slide, Notes notes, SlideAtomsSet atomSet) {
_slide = slide;
_notes = notes;
_atomSet = atomSet;
// Grab the sheet number
//_sheetNo = _slide.getSlideAtom().getSheetNumber();
_sheetNo = -1;
// Grab the TextRuns from the PPDrawing
_otherRuns = findTextRuns(_slide.getPPDrawing());
// For the text coming in from the SlideAtomsSet:
// Build up TextRuns from pairs of TextHeaderAtom and
// one of TextBytesAtom or TextCharsAtom
Vector textRuns = new Vector();
if(_atomSet != null) {
findTextRuns(_atomSet.getSlideRecords(),textRuns);
} else {
// No text on the slide, must just be pictures
}
// Build an array, more useful than a vector
_runs = new TextRun[textRuns.size()];
for(int i=0; i<_runs.length; i++) {
_runs[i] = (TextRun)textRuns.get(i);
}
}
| public Slide(org.apache.poi.hslf.record.Slide slide, Notes notes, SlideAtomsSet atomSet) {
_slide = slide;
_notes = notes;
_atomSet = atomSet;
// Grab the sheet number
//_sheetNo = _slide.getSlideAtom().getSheetNumber();
_sheetNo = -1;
// Grab the TextRuns from the PPDrawing
_otherRuns = findTextRuns(_slide.getPPDrawing());
// For the text coming in from the SlideAtomsSet:
// Build up TextRuns from pairs of TextHeaderAtom and
// one of TextBytesAtom or TextCharsAtom
Vector textRuns = new Vector();
if(_atomSet != null) {
findTextRuns(_atomSet.getSlideRecords(),textRuns);
} else {
// No text on the slide, must just be pictures
}
// Build an array, more useful than a vector
_runs = new TextRun[textRuns.size()+_otherRuns.length];
// Grab text from SlideListWithTexts entries
int i=0;
for(i=0; i<textRuns.size(); i++) {
_runs[i] = (TextRun)textRuns.get(i);
}
// Grab text from slide's PPDrawing
for(int k=0; k<_otherRuns.length; i++, k++) {
_runs[i] = _otherRuns[k];
}
}
|
diff --git a/src/org/mythtv/client/ui/dvr/GuideChannelFragment.java b/src/org/mythtv/client/ui/dvr/GuideChannelFragment.java
index 5ac2c55f..26c2be14 100644
--- a/src/org/mythtv/client/ui/dvr/GuideChannelFragment.java
+++ b/src/org/mythtv/client/ui/dvr/GuideChannelFragment.java
@@ -1,327 +1,332 @@
/**
*
*/
package org.mythtv.client.ui.dvr;
import java.util.ArrayList;
import java.util.List;
import org.mythtv.R;
import org.mythtv.client.ui.preferences.LocationProfile;
import org.mythtv.client.ui.util.MythtvListFragment;
import org.mythtv.db.channel.ChannelConstants;
import org.mythtv.db.channel.ChannelDaoHelper;
import org.mythtv.services.api.channel.ChannelInfo;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
/**
* @author dmfrey
*
*/
public class GuideChannelFragment extends MythtvListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = GuideChannelFragment.class.getSimpleName();
private SharedPreferences mSharedPreferences;
private boolean downloadIcons;
private ChannelDaoHelper mChannelDaoHelper = ChannelDaoHelper.getInstance();
private ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions options;
private ProgramGuideCursorAdapter mAdapter;
private OnChannelScrollListener mOnChannelScrollListener;
private LocationProfile mLocationProfile;
public interface OnChannelScrollListener {
void channelScroll( int first, int last, int screenCount, int totalCount );
void channelSelect( int channelId );
}
/**
*
*/
public GuideChannelFragment() { }
/**
* @param mOnChannelScrollListener the mOnChannelScrollListener to set
*/
public void setOnChannelScrollListener( OnChannelScrollListener listener ) {
this.mOnChannelScrollListener = listener;
}
public ChannelInfo getChannel( int position ) {
long id = mAdapter.getItemId( position );
return mChannelDaoHelper.findOne( getActivity(), mLocationProfile, id );
}
/* (non-Javadoc)
* @see android.support.v4.app.LoaderManager.LoaderCallbacks#onCreateLoader(int, android.os.Bundle)
*/
@Override
public Loader<Cursor> onCreateLoader( int id, Bundle args ) {
Log.v( TAG, "onCreateLoader : enter" );
String[] projection = null;
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
switch( id ) {
case 0 :
Log.v( TAG, "onCreateLoader : getting channels" );
projection = new String[] { ChannelConstants._ID, ChannelConstants.FIELD_CHAN_ID + " AS " + ChannelConstants.TABLE_NAME + "_" + ChannelConstants.FIELD_CHAN_ID, ChannelConstants.FIELD_CHAN_NUM + " AS " + ChannelConstants.TABLE_NAME + "_" + ChannelConstants.FIELD_CHAN_NUM, ChannelConstants.FIELD_CALLSIGN + " AS " + ChannelConstants.TABLE_NAME + "_" + ChannelConstants.FIELD_CALLSIGN };
selection = ChannelConstants.FIELD_VISIBLE + " = ? AND " + ChannelConstants.FIELD_MASTER_HOSTNAME + " = ?";
selectionArgs = new String[] { "1", mLocationProfile.getHostname() };
sortOrder = ChannelConstants.FIELD_CHAN_NUM_FORMATTED;
Log.v( TAG, "onCreateLoader : exit" );
return new CursorLoader( getActivity(), ChannelConstants.CONTENT_URI, projection, selection, selectionArgs, sortOrder );
default :
Log.v( TAG, "onCreateLoader : exit, invalid id" );
return null;
}
}
/* (non-Javadoc)
* @see android.support.v4.app.LoaderManager.LoaderCallbacks#onLoadFinished(android.support.v4.content.Loader, java.lang.Object)
*/
@Override
public void onLoadFinished( Loader<Cursor> loader, Cursor cursor ) {
Log.v( TAG, "onLoadFinished : enter" );
mAdapter.swapCursor( cursor );
Log.v( TAG, "onLoadFinished : exit" );
}
/* (non-Javadoc)
* @see android.support.v4.app.LoaderManager.LoaderCallbacks#onLoaderReset(android.support.v4.content.Loader)
*/
@Override
public void onLoaderReset( Loader<Cursor> loader ) {
Log.v( TAG, "onLoaderReset : enter" );
mAdapter.swapCursor( null );
Log.v( TAG, "onLoaderReset : exit" );
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
@Override
public void onActivityCreated( Bundle savedInstanceState ) {
Log.v( TAG, "onActivityCreated : enter" );
super.onActivityCreated( savedInstanceState );
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences( getActivity() );
downloadIcons = mSharedPreferences.getBoolean( "preference_program_guide_channel_icon_download", false );
Log.v( TAG, "download : downloadIcons=" + downloadIcons );
options = new DisplayImageOptions.Builder()
.cacheInMemory( true )
.cacheOnDisc( true )
.build();
mLocationProfile = mLocationProfileDaoHelper.findConnectedProfile( getActivity() );
mAdapter = new ProgramGuideCursorAdapter( getActivity() );
setListAdapter( mAdapter );
getLoaderManager().initLoader( 0, null, this );
getListView().setFastScrollEnabled( true );
getListView().setOnScrollListener( new PauseOnScrollListener( imageLoader, false, true, new OnScrollListener() {
/* (non-Javadoc)
* @see android.widget.AbsListView.OnScrollListener#onScroll(android.widget.AbsListView, int, int, int)
*/
@Override
public void onScroll( AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount ) {
Log.v( TAG, "onScroll : enter" );
//mOnChannelScrollListener.channelScroll( firstVisibleItem, visibleItemCount, totalItemCount );
Log.v( TAG, "onScroll : exit" );
}
/* (non-Javadoc)
* @see android.widget.AbsListView.OnScrollListener#onScrollStateChanged(android.widget.AbsListView, int)
*/
@Override
public void onScrollStateChanged( AbsListView view, int scrollState ) {
Log.v( TAG, "onScrollStateChanged : enter" );
Log.v( TAG, "onScrollStateChanged : scrollState=" + scrollState );
int first = view.getFirstVisiblePosition();
int last = view.getLastVisiblePosition();
int count = view.getChildCount();
if( scrollState == SCROLL_STATE_IDLE ) {
mOnChannelScrollListener.channelScroll( first, last, count, mAdapter.getCount() );
}
Log.v( TAG, "onScrollStateChanged : exit" );
}
}));
Log.v( TAG, "onActivityCreated : exit" );
}
// internal helpers
private class ProgramGuideCursorAdapter extends CursorAdapter {
private List<View> selectedViews = new ArrayList<View>();
private Drawable mBackground;
private Drawable mBackgroundSelected;
private ChannelInfo mSelectedChannel;
private LayoutInflater mInflater;
public ProgramGuideCursorAdapter( Context context ) {
super( context, null, false );
mInflater = LayoutInflater.from( context );
mBackground = getResources().getDrawable( R.drawable.program_guide_channel_header_back );
mBackgroundSelected = getResources().getDrawable( R.drawable.program_guide_channel_header_back_selected );
}
/* (non-Javadoc)
* @see android.support.v4.widget.CursorAdapter#bindView(android.view.View, android.content.Context, android.database.Cursor)
*/
@Override
public void bindView( View view, Context context, Cursor cursor ) {
final ChannelInfo channel = ChannelDaoHelper.convertCursorToChannelInfo( cursor );
final ViewHolder mHolder = (ViewHolder) view.getTag();
mHolder.channel.setText( channel.getChannelNumber() );
mHolder.callsign.setText( channel.getCallSign() );
- view.setBackgroundDrawable( mSelectedChannel != null && mSelectedChannel.getChannelId() == channel.getChannelId() ? mBackgroundSelected : mBackground );
+ if(mSelectedChannel == null || mSelectedChannel.getChannelId() != channel.getChannelId()){
+ view.setBackgroundDrawable( mBackground );
+ }else {
+ view.setBackgroundDrawable( mBackgroundSelected );
+ selectedViews.add(view);
+ }
if( downloadIcons ) {
String imageUri = mLocationProfileDaoHelper.findConnectedProfile( getActivity() ).getUrl() + "Guide/GetChannelIcon?ChanId=" + channel.getChannelId() + "&Width=32&Height=32";
imageLoader.displayImage( imageUri, mHolder.icon, options, new SimpleImageLoadingListener() {
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingComplete(android.graphics.Bitmap)
*/
@Override
public void onLoadingComplete( String imageUri, View view, Bitmap loadedImage ) {
/* mHolder.icon.setVisibility( View.GONE );
mHolder.icon.setVisibility( View.VISIBLE );
*/ }
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingFailed(com.nostra13.universalimageloader.core.assist.FailReason)
*/
@Override
public void onLoadingFailed( String imageUri, View view, FailReason failReason ) {
/* mHolder.icon.setVisibility( View.VISIBLE );
mHolder.icon.setVisibility( View.GONE );
*/ }
});
}
mHolder.row.setOnClickListener( new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick( View v ) {
mOnChannelScrollListener.channelSelect( channel.getChannelId() );
mSelectedChannel = channel;
for( View view : selectedViews ) {
view.setBackgroundDrawable( mBackground );
}
selectedViews.clear();
v.setBackgroundDrawable( mBackgroundSelected );
selectedViews.add( v );
}
});
}
/* (non-Javadoc)
* @see android.support.v4.widget.CursorAdapter#newView(android.content.Context, android.database.Cursor, android.view.ViewGroup)
*/
@Override
public View newView( Context context, Cursor cursor, ViewGroup parent ) {
View view = mInflater.inflate( R.layout.program_guide_channel_row, parent, false );
ViewHolder refHolder = new ViewHolder();
refHolder.row = (LinearLayout) view.findViewById( R.id.program_guide_channel );
refHolder.channel = (TextView) view.findViewById( R.id.program_guide_channel_number );
refHolder.icon = (ImageView) view.findViewById( R.id.program_guide_channel_icon );
refHolder.callsign = (TextView) view.findViewById( R.id.program_guide_channel_callsign );
view.setTag( refHolder );
return view;
}
}
private static class ViewHolder {
LinearLayout row;
TextView channel;
ImageView icon;
TextView callsign;
}
}
| true | true | public void bindView( View view, Context context, Cursor cursor ) {
final ChannelInfo channel = ChannelDaoHelper.convertCursorToChannelInfo( cursor );
final ViewHolder mHolder = (ViewHolder) view.getTag();
mHolder.channel.setText( channel.getChannelNumber() );
mHolder.callsign.setText( channel.getCallSign() );
view.setBackgroundDrawable( mSelectedChannel != null && mSelectedChannel.getChannelId() == channel.getChannelId() ? mBackgroundSelected : mBackground );
if( downloadIcons ) {
String imageUri = mLocationProfileDaoHelper.findConnectedProfile( getActivity() ).getUrl() + "Guide/GetChannelIcon?ChanId=" + channel.getChannelId() + "&Width=32&Height=32";
imageLoader.displayImage( imageUri, mHolder.icon, options, new SimpleImageLoadingListener() {
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingComplete(android.graphics.Bitmap)
*/
@Override
public void onLoadingComplete( String imageUri, View view, Bitmap loadedImage ) {
/* mHolder.icon.setVisibility( View.GONE );
mHolder.icon.setVisibility( View.VISIBLE );
*/ }
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingFailed(com.nostra13.universalimageloader.core.assist.FailReason)
*/
@Override
public void onLoadingFailed( String imageUri, View view, FailReason failReason ) {
/* mHolder.icon.setVisibility( View.VISIBLE );
mHolder.icon.setVisibility( View.GONE );
*/ }
});
}
mHolder.row.setOnClickListener( new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick( View v ) {
mOnChannelScrollListener.channelSelect( channel.getChannelId() );
mSelectedChannel = channel;
for( View view : selectedViews ) {
view.setBackgroundDrawable( mBackground );
}
selectedViews.clear();
v.setBackgroundDrawable( mBackgroundSelected );
selectedViews.add( v );
}
});
}
/* (non-Javadoc)
* @see android.support.v4.widget.CursorAdapter#newView(android.content.Context, android.database.Cursor, android.view.ViewGroup)
*/
@Override
public View newView( Context context, Cursor cursor, ViewGroup parent ) {
View view = mInflater.inflate( R.layout.program_guide_channel_row, parent, false );
ViewHolder refHolder = new ViewHolder();
refHolder.row = (LinearLayout) view.findViewById( R.id.program_guide_channel );
refHolder.channel = (TextView) view.findViewById( R.id.program_guide_channel_number );
refHolder.icon = (ImageView) view.findViewById( R.id.program_guide_channel_icon );
refHolder.callsign = (TextView) view.findViewById( R.id.program_guide_channel_callsign );
view.setTag( refHolder );
return view;
}
}
private static class ViewHolder {
LinearLayout row;
TextView channel;
ImageView icon;
TextView callsign;
}
}
| public void bindView( View view, Context context, Cursor cursor ) {
final ChannelInfo channel = ChannelDaoHelper.convertCursorToChannelInfo( cursor );
final ViewHolder mHolder = (ViewHolder) view.getTag();
mHolder.channel.setText( channel.getChannelNumber() );
mHolder.callsign.setText( channel.getCallSign() );
if(mSelectedChannel == null || mSelectedChannel.getChannelId() != channel.getChannelId()){
view.setBackgroundDrawable( mBackground );
}else {
view.setBackgroundDrawable( mBackgroundSelected );
selectedViews.add(view);
}
if( downloadIcons ) {
String imageUri = mLocationProfileDaoHelper.findConnectedProfile( getActivity() ).getUrl() + "Guide/GetChannelIcon?ChanId=" + channel.getChannelId() + "&Width=32&Height=32";
imageLoader.displayImage( imageUri, mHolder.icon, options, new SimpleImageLoadingListener() {
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingComplete(android.graphics.Bitmap)
*/
@Override
public void onLoadingComplete( String imageUri, View view, Bitmap loadedImage ) {
/* mHolder.icon.setVisibility( View.GONE );
mHolder.icon.setVisibility( View.VISIBLE );
*/ }
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingFailed(com.nostra13.universalimageloader.core.assist.FailReason)
*/
@Override
public void onLoadingFailed( String imageUri, View view, FailReason failReason ) {
/* mHolder.icon.setVisibility( View.VISIBLE );
mHolder.icon.setVisibility( View.GONE );
*/ }
});
}
mHolder.row.setOnClickListener( new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick( View v ) {
mOnChannelScrollListener.channelSelect( channel.getChannelId() );
mSelectedChannel = channel;
for( View view : selectedViews ) {
view.setBackgroundDrawable( mBackground );
}
selectedViews.clear();
v.setBackgroundDrawable( mBackgroundSelected );
selectedViews.add( v );
}
});
}
/* (non-Javadoc)
* @see android.support.v4.widget.CursorAdapter#newView(android.content.Context, android.database.Cursor, android.view.ViewGroup)
*/
@Override
public View newView( Context context, Cursor cursor, ViewGroup parent ) {
View view = mInflater.inflate( R.layout.program_guide_channel_row, parent, false );
ViewHolder refHolder = new ViewHolder();
refHolder.row = (LinearLayout) view.findViewById( R.id.program_guide_channel );
refHolder.channel = (TextView) view.findViewById( R.id.program_guide_channel_number );
refHolder.icon = (ImageView) view.findViewById( R.id.program_guide_channel_icon );
refHolder.callsign = (TextView) view.findViewById( R.id.program_guide_channel_callsign );
view.setTag( refHolder );
return view;
}
}
private static class ViewHolder {
LinearLayout row;
TextView channel;
ImageView icon;
TextView callsign;
}
}
|
diff --git a/src/com/gitblit/build/Build.java b/src/com/gitblit/build/Build.java
index 80c88f3..43cd26f 100644
--- a/src/com/gitblit/build/Build.java
+++ b/src/com/gitblit/build/Build.java
@@ -1,560 +1,560 @@
/*
* Copyright 2011 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit.build;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.gitblit.Constants;
import com.gitblit.utils.StringUtils;
/**
* The Build class downloads runtime and compile-time jar files from the Apache
* or Eclipse Maven repositories.
*
* It also generates the Keys class from the gitblit.properties file.
*
* Its important that this class have minimal compile dependencies since its
* called very early in the build script.
*
* @author James Moger
*
*/
public class Build {
public interface DownloadListener {
public void downloading(String name);
}
/**
* BuildType enumeration representing compile-time or runtime. This is used
* to download dependencies either for Gitblit GO runtime or for setting up
* a development environment.
*/
public static enum BuildType {
RUNTIME, COMPILETIME;
}
private static DownloadListener downloadListener;
public static void main(String... args) {
runtime();
compiletime();
buildSettingKeys();
}
public static void runtime() {
downloadFromApache(MavenObject.JCOMMANDER, BuildType.RUNTIME);
downloadFromApache(MavenObject.JETTY, BuildType.RUNTIME);
downloadFromApache(MavenObject.SERVLET, BuildType.RUNTIME);
downloadFromApache(MavenObject.SLF4JAPI, BuildType.RUNTIME);
downloadFromApache(MavenObject.SLF4LOG4J, BuildType.RUNTIME);
downloadFromApache(MavenObject.LOG4J, BuildType.RUNTIME);
downloadFromApache(MavenObject.WICKET, BuildType.RUNTIME);
downloadFromApache(MavenObject.WICKET_EXT, BuildType.RUNTIME);
downloadFromApache(MavenObject.WICKET_AUTH_ROLES, BuildType.RUNTIME);
downloadFromApache(MavenObject.WICKET_GOOGLE_CHARTS, BuildType.RUNTIME);
downloadFromApache(MavenObject.MARKDOWNPAPERS, BuildType.RUNTIME);
downloadFromApache(MavenObject.BOUNCYCASTLE, BuildType.RUNTIME);
downloadFromApache(MavenObject.BOUNCYCASTLE_MAIL, BuildType.RUNTIME);
downloadFromApache(MavenObject.JSCH, BuildType.RUNTIME);
downloadFromApache(MavenObject.ROME, BuildType.RUNTIME);
downloadFromApache(MavenObject.JDOM, BuildType.RUNTIME);
downloadFromApache(MavenObject.GSON, BuildType.RUNTIME);
downloadFromApache(MavenObject.MAIL, BuildType.RUNTIME);
downloadFromEclipse(MavenObject.JGIT, BuildType.RUNTIME);
downloadFromEclipse(MavenObject.JGIT_HTTP, BuildType.RUNTIME);
}
public static void compiletime() {
downloadFromApache(MavenObject.JUNIT, BuildType.RUNTIME);
downloadFromApache(MavenObject.JCOMMANDER, BuildType.COMPILETIME);
downloadFromApache(MavenObject.JETTY, BuildType.COMPILETIME);
downloadFromApache(MavenObject.SERVLET, BuildType.COMPILETIME);
downloadFromApache(MavenObject.SLF4JAPI, BuildType.COMPILETIME);
downloadFromApache(MavenObject.SLF4LOG4J, BuildType.COMPILETIME);
downloadFromApache(MavenObject.LOG4J, BuildType.COMPILETIME);
downloadFromApache(MavenObject.WICKET, BuildType.COMPILETIME);
downloadFromApache(MavenObject.WICKET_EXT, BuildType.COMPILETIME);
downloadFromApache(MavenObject.WICKET_AUTH_ROLES, BuildType.COMPILETIME);
downloadFromApache(MavenObject.WICKET_GOOGLE_CHARTS, BuildType.COMPILETIME);
downloadFromApache(MavenObject.MARKDOWNPAPERS, BuildType.COMPILETIME);
downloadFromApache(MavenObject.BOUNCYCASTLE, BuildType.COMPILETIME);
downloadFromApache(MavenObject.BOUNCYCASTLE_MAIL, BuildType.COMPILETIME);
downloadFromApache(MavenObject.JSCH, BuildType.COMPILETIME);
downloadFromApache(MavenObject.ROME, BuildType.COMPILETIME);
downloadFromApache(MavenObject.JDOM, BuildType.COMPILETIME);
downloadFromApache(MavenObject.GSON, BuildType.COMPILETIME);
downloadFromApache(MavenObject.MAIL, BuildType.COMPILETIME);
downloadFromEclipse(MavenObject.JGIT, BuildType.COMPILETIME);
downloadFromEclipse(MavenObject.JGIT_HTTP, BuildType.COMPILETIME);
// needed for site publishing
downloadFromApache(MavenObject.COMMONSNET, BuildType.RUNTIME);
}
public static void federationClient() {
downloadFromApache(MavenObject.JCOMMANDER, BuildType.RUNTIME);
downloadFromApache(MavenObject.SERVLET, BuildType.RUNTIME);
downloadFromApache(MavenObject.MAIL, BuildType.RUNTIME);
downloadFromApache(MavenObject.SLF4JAPI, BuildType.RUNTIME);
downloadFromApache(MavenObject.SLF4LOG4J, BuildType.RUNTIME);
downloadFromApache(MavenObject.LOG4J, BuildType.RUNTIME);
downloadFromApache(MavenObject.GSON, BuildType.RUNTIME);
downloadFromApache(MavenObject.JSCH, BuildType.RUNTIME);
downloadFromEclipse(MavenObject.JGIT, BuildType.RUNTIME);
}
public static void manager(DownloadListener listener) {
downloadListener = listener;
downloadFromApache(MavenObject.GSON, BuildType.RUNTIME);
downloadFromApache(MavenObject.ROME, BuildType.RUNTIME);
downloadFromApache(MavenObject.JDOM, BuildType.RUNTIME);
downloadFromApache(MavenObject.JSCH, BuildType.RUNTIME);
downloadFromEclipse(MavenObject.JGIT, BuildType.RUNTIME);
}
/**
* Builds the Keys class based on the gitblit.properties file and inserts
* the class source into the project source folder.
*/
public static void buildSettingKeys() {
// Load all keys
Properties properties = new Properties();
FileInputStream is = null;
try {
is = new FileInputStream(Constants.PROPERTIES_FILE);
properties.load(is);
} catch (Throwable t) {
t.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (Throwable t) {
// IGNORE
}
}
}
List<String> keys = new ArrayList<String>(properties.stringPropertyNames());
Collections.sort(keys);
// Determine static key group classes
Map<String, List<String>> staticClasses = new HashMap<String, List<String>>();
staticClasses.put("", new ArrayList<String>());
for (String key : keys) {
String clazz = "";
String field = key;
if (key.indexOf('.') > -1) {
clazz = key.substring(0, key.indexOf('.'));
field = key.substring(key.indexOf('.') + 1);
}
if (!staticClasses.containsKey(clazz)) {
staticClasses.put(clazz, new ArrayList<String>());
}
staticClasses.get(clazz).add(field);
}
// Assemble Keys source file
StringBuilder sb = new StringBuilder();
sb.append("package com.gitblit;\n");
sb.append('\n');
sb.append("/*\n");
sb.append(" * This class is auto-generated from the properties file.\n");
sb.append(" * Do not version control!\n");
sb.append(" */\n");
sb.append("public final class Keys {\n");
sb.append('\n');
List<String> classSet = new ArrayList<String>(staticClasses.keySet());
Collections.sort(classSet);
for (String clazz : classSet) {
List<String> keySet = staticClasses.get(clazz);
if (clazz.equals("")) {
// root keys
for (String key : keySet) {
sb.append(MessageFormat.format(
"\tpublic static final String {0} = \"{1}\";\n\n",
key.replace('.', '_'), key));
}
} else {
// class keys
sb.append(MessageFormat.format("\tpublic static final class {0} '{'\n\n", clazz));
sb.append(MessageFormat.format(
"\t\tpublic static final String _ROOT = \"{0}\";\n\n", clazz));
for (String key : keySet) {
sb.append(MessageFormat.format(
"\t\tpublic static final String {0} = \"{1}\";\n\n",
key.replace('.', '_'), clazz + "." + key));
}
sb.append("\t}\n\n");
}
}
sb.append('}');
// Save Keys class definition
try {
File file = new File("src/com/gitblit/Keys.java");
FileWriter fw = new FileWriter(file, false);
fw.write(sb.toString());
fw.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
/**
* Download a file from the official Apache Maven repository.
*
* @param mo
* the maven object to download.
* @return
*/
private static List<File> downloadFromApache(MavenObject mo, BuildType type) {
return downloadFromMaven("http://repo1.maven.org/maven2/", mo, type);
}
/**
* Download a file from the official Eclipse Maven repository.
*
* @param mo
* the maven object to download.
* @return
*/
private static List<File> downloadFromEclipse(MavenObject mo, BuildType type) {
return downloadFromMaven("http://download.eclipse.org/jgit/maven/", mo, type);
}
/**
* Download a file from a Maven repository.
*
* @param mo
* the maven object to download.
* @return
*/
private static List<File> downloadFromMaven(String mavenRoot, MavenObject mo, BuildType type) {
List<File> downloads = new ArrayList<File>();
String[] jars = { "" };
if (BuildType.RUNTIME.equals(type)) {
jars = new String[] { "" };
} else if (BuildType.COMPILETIME.equals(type)) {
jars = new String[] { "-sources", "-javadoc" };
}
for (String jar : jars) {
File targetFile = mo.getLocalFile("ext", jar);
if (targetFile.exists()) {
downloads.add(targetFile);
continue;
}
String expectedSHA1 = mo.getSHA1(jar);
if (expectedSHA1 == null) {
// skip this jar
continue;
}
float approximateLength = mo.getApproximateLength(jar);
String mavenURL = mavenRoot + mo.getRepositoryPath(jar);
if (!targetFile.getAbsoluteFile().getParentFile().exists()) {
boolean success = targetFile.getAbsoluteFile().getParentFile().mkdirs();
if (!success) {
throw new RuntimeException("Failed to create destination folder structure!");
}
}
if (downloadListener != null) {
downloadListener.downloading(mo.name + "...");
}
ByteArrayOutputStream buff = new ByteArrayOutputStream();
try {
URL url = new URL(mavenURL);
InputStream in = new BufferedInputStream(url.openStream());
byte[] buffer = new byte[4096];
int downloadedLen = 0;
float lastProgress = 0f;
updateDownload(0, targetFile);
while (true) {
int len = in.read(buffer);
if (len < 0) {
break;
}
downloadedLen += len;
buff.write(buffer, 0, len);
float progress = downloadedLen / approximateLength;
if (progress - lastProgress >= 0.1f) {
lastProgress = progress;
updateDownload(progress, targetFile);
if (downloadListener != null) {
- int percent = Math.round(100 * progress);
+ int percent = Math.min(100, Math.round(100 * progress));
downloadListener.downloading(mo.name + " (" + percent + "%)");
}
}
}
in.close();
updateDownload(1f, targetFile);
if (downloadListener != null) {
downloadListener.downloading(mo.name + " (100%)");
}
} catch (IOException e) {
throw new RuntimeException("Error downloading " + mavenURL + " to " + targetFile, e);
}
byte[] data = buff.toByteArray();
String calculatedSHA1 = StringUtils.getSHA1(data);
System.out.println();
if (expectedSHA1.length() == 0) {
updateProgress(0, "sha: " + calculatedSHA1);
System.out.println();
} else {
if (!calculatedSHA1.equals(expectedSHA1)) {
throw new RuntimeException("SHA1 checksum mismatch; got: " + calculatedSHA1);
}
}
try {
RandomAccessFile ra = new RandomAccessFile(targetFile, "rw");
ra.write(data);
ra.setLength(data.length);
ra.close();
} catch (IOException e) {
throw new RuntimeException("Error writing to file " + targetFile, e);
}
downloads.add(targetFile);
}
return downloads;
}
private static void updateDownload(float progress, File file) {
updateProgress(progress, "d/l: " + file.getName());
}
private static void updateProgress(float progress, String url) {
String anim = "==========";
int width = Math.round(anim.length() * progress);
System.out.print("\r[");
System.out.print(anim.substring(0, Math.min(width, anim.length())));
for (int i = 0; i < anim.length() - width; i++) {
System.out.print(' ');
}
System.out.print("] " + url);
}
/**
* MavenObject represents a complete maven artifact (binary, sources, and
* javadoc). MavenObjects can be downloaded and checksummed to confirm
* authenticity.
*/
private static class MavenObject {
public static final MavenObject JCOMMANDER = new MavenObject("jCommander", "com/beust",
"jcommander", "1.17", 34000, 32000, 141000,
"219a3540f3b27d7cc3b1d91d6ea046cd8723290e",
"0bb50eec177acf0e94d58e0cf07262fe5164331d",
"c7adc475ca40c288c93054e0f4fe58f3a98c0cb5");
public static final MavenObject JETTY = new MavenObject("Jetty",
"org/eclipse/jetty/aggregate", "jetty-webapp", "7.4.3.v20110701", 1000000, 680000,
2720000, "bde072b178f9650e2308f0babe58a4baaa469e3c",
"bc75f05dd4f7fa848720ac669b8b438ee4a6b146",
"dcd42f672e734521d1a6ccc0c2f9ecded1a1a281");
public static final MavenObject SERVLET = new MavenObject("Servlet 3.0", "org/glassfish",
"javax.servlet", "3.0.1", 84000, 211000, 0,
"58f17c941cd0607bb5edcbcafc491d02265ac9a1",
"63f2f8bcdd3f138020bbadd5c847e8f3847b77d2", null);
public static final MavenObject SLF4JAPI = new MavenObject("SLF4J API", "org/slf4j",
"slf4j-api", "1.6.1", 25500, 45000, 182000,
"6f3b8a24bf970f17289b234284c94f43eb42f0e4",
"46a386136c901748e6a3af67ebde6c22bc6b4524",
"e223571d77769cdafde59040da235842f3326453");
public static final MavenObject SLF4LOG4J = new MavenObject("SLF4J LOG4J", "org/slf4j",
"slf4j-log4j12", "1.6.1", 9800, 9500, 52400,
"bd245d6746cdd4e6203e976e21d597a46f115802",
"7a26b08b265f55622fa1fed3bda68bbd37a465ba",
"6e4b16bce7994e3692e82002f322a0dd2f32741e");
public static final MavenObject LOG4J = new MavenObject("Apache LOG4J", "log4j", "log4j",
"1.2.16", 481000, 471000, 1455000, "7999a63bfccbc7c247a9aea10d83d4272bd492c6",
"bf945d1dc995be7fe64923625f842fbb6bf443be",
"78aa1cbf0fa3b259abdc7d87f9f6788d785aac2a");
public static final MavenObject WICKET = new MavenObject("Apache Wicket",
"org/apache/wicket", "wicket", "1.4.19", 1960000, 1906000, 6818000,
"7e6af5cadaf6c9b7e068e45cf2ffbea3cc91592f",
"5e91cf00efaf2fedeef98e13464a4230e5966588",
"5dde8afbe5eb2314a704cb74938c1b651b2cf190");
public static final MavenObject WICKET_EXT = new MavenObject("Apache Wicket Extensions",
"org/apache/wicket", "wicket-extensions", "1.4.19", 1180000, 1118000, 1458000,
"c7a1d343e216cdc2e692b6fabc6eaeca9aa24ca4",
"6c2e2ad89b69fc9977c24467e3aa0d7f6c75a579",
"3a3082fb106173f7ca069a6f5969cc8d347d9f44");
public static final MavenObject WICKET_AUTH_ROLES = new MavenObject(
"Apache Wicket Auth Roles", "org/apache/wicket", "wicket-auth-roles", "1.4.19",
44000, 45000, 166000, "70c26ac4cd167bf7323372d2d49eb2a9beff73b9",
"ca219726c1768a9483e4a0bb6550881babfe46d6",
"17753908f8a9e997c464a69765b4682126fa1fd6");
public static final MavenObject WICKET_GOOGLE_CHARTS = new MavenObject(
"Apache Wicket Google Charts Add-On", "org/wicketstuff", "googlecharts", "1.4.18",
34000, 18750, 161000, "1f763cc8a04e62840b63787a77a479b04ad99c75",
"1521ed6397192c464e89787502f937bc96ece8f8",
"8b0398d58bce63ba7f7a9232c4ca24160c9b1a11");
public static final MavenObject JUNIT = new MavenObject("JUnit", "junit", "junit", "4.8.2",
237000, 0, 0, "c94f54227b08100974c36170dcb53329435fe5ad", "", "");
public static final MavenObject MARKDOWNPAPERS = new MavenObject("MarkdownPapers",
"org/tautua/markdownpapers", "markdownpapers-core", "1.2.5", 87000, 58000, 268000,
"295910b1893d73d4803f9ea2790ee1d10c466364",
"2170f358f29886aea8794c4bfdb6f1b27b152b9b",
"481599f34cb2abe4a9ebc771d8d81823375ec1ce");
public static final MavenObject BOUNCYCASTLE = new MavenObject("BouncyCastle",
"org/bouncycastle", "bcprov-jdk16", "1.46", 1900000, 1400000, 4670000,
"ce091790943599535cbb4de8ede84535b0c1260c",
"d2b70567594225923450d7e3f80cd022c852725e",
"873a6fe765f33fc27df498a5d1f5bf077e503b2f");
public static final MavenObject BOUNCYCASTLE_MAIL = new MavenObject("BouncyCastle Mail",
"org/bouncycastle", "bcmail-jdk16", "1.46", 502000, 420000, 482000,
"08a9233bfd6ad38ea32df5e6ff91035b650584b9",
"3ebd62bc56854767512dc5deec0a17795f2e671d",
"3b7c5f3938f202311bdca0bf7ed46bc0118af081");
public static final MavenObject JGIT = new MavenObject("JGit", "org/eclipse/jgit",
"org.eclipse.jgit", "1.1.0.201109151100-r", 1318000, 1354000, 3300000,
"bacc988346c839f79513d7bc7f5c88b22ea6e7a5",
"90abf988d98ce0d4b162f94f63fc99c435eba6b4",
"a46540a2857a0fdbf43debf3383295a897946c79");
public static final MavenObject JGIT_HTTP = new MavenObject("JGit", "org/eclipse/jgit",
"org.eclipse.jgit.http.server", "1.1.0.201109151100-r", 68000, 62000, 110000,
"3070161a89756aac2dfc2e26d89faf31fe894ab4",
"9cecb8e4351e616688cafbcca906f542d9b1f525",
"20aaab759acd8eb6cb6acbb1b2934a689fb3774d");
public static final MavenObject JSCH = new MavenObject("JSch", "com/jcraft", "jsch",
"0.1.44-1", 214000, 211000, 413000, "2e9ae08de5a71bd0e0d3ba2558598181bfa71d4e",
"e528f593b19b04d500992606f58b87fcfded8883",
"d0ffadd0a4ab909d94a577b5aad43c13b617ddcb");
public static final MavenObject COMMONSNET = new MavenObject("commons-net", "commons-net",
"commons-net", "1.4.0", 181000, 0, 0, "eb47e8cad2dd7f92fd7e77df1d1529cae87361f7",
"", "");
public static final MavenObject ROME = new MavenObject("rome", "rome", "rome", "0.9",
208000, 196000, 407000, "dee2705dd01e79a5a96a17225f5a1ae30470bb18",
"226f851dc44fd94fe70b9c471881b71f88949cbf",
"8d7d867b97eeb3a9196c3926da550ad042941c1b");
public static final MavenObject JDOM = new MavenObject("jdom", "org/jdom", "jdom", "1.1",
153000, 235000, 445000, "1d04c0f321ea337f3661cf7ede8f4c6f653a8fdd",
"a7ed425c4c46605b8f2bf2ee118c1609682f4f2c",
"f3df91edccba2f07a0fced70887c2f7b7836cb75");
public static final MavenObject GSON = new MavenObject("gson", "com/google/code/gson",
"gson", "1.7.1", 174000, 142000, 247000,
"0697e3a1fa094a983cd12f7f6f61abf9c6ea52e2",
"51f6f78aec2d30d0c2bfb4a5f00d456a6f7a5e7e",
"f0872fe17d484815328538b89909d5e46d85db74");
public static final MavenObject MAIL = new MavenObject("javax.mail", "javax/mail", "mail",
"1.4.3", 462000, 642000, 0, "8154bf8d666e6db154c548dc31a8d512c273f5ee",
"5875e2729de83a4e46391f8f979ec8bd03810c10", null);
public final String name;
public final String group;
public final String artifact;
public final String version;
public final int approxLibraryLen;
public final int approxSourcesLen;
public final int approxJavadocLen;
public final String librarySHA1;
public final String sourcesSHA1;
public final String javadocSHA1;
private MavenObject(String name, String group, String artifact, String version,
int approxLibraryLen, int approxSourcesLen, int approxJavadocLen,
String librarySHA1, String sourcesSHA1, String javadocSHA1) {
this.name = name;
this.group = group;
this.artifact = artifact;
this.version = version;
this.approxLibraryLen = approxLibraryLen;
this.approxSourcesLen = approxSourcesLen;
this.approxJavadocLen = approxJavadocLen;
this.librarySHA1 = librarySHA1;
this.sourcesSHA1 = sourcesSHA1;
this.javadocSHA1 = javadocSHA1;
}
private String getRepositoryPath(String jar) {
return group + "/" + artifact + "/" + version + "/" + artifact + "-" + version + jar
+ ".jar";
}
private File getLocalFile(String basePath, String jar) {
return new File(basePath, artifact + "-" + version + jar + ".jar");
}
private String getSHA1(String jar) {
if (jar.equals("")) {
return librarySHA1;
} else if (jar.equals("-sources")) {
return sourcesSHA1;
} else if (jar.equals("-javadoc")) {
return javadocSHA1;
}
return librarySHA1;
}
private int getApproximateLength(String jar) {
if (jar.equals("")) {
return approxLibraryLen;
} else if (jar.equals("-sources")) {
return approxSourcesLen;
} else if (jar.equals("-javadoc")) {
return approxJavadocLen;
}
return approxLibraryLen;
}
@Override
public String toString() {
return name;
}
}
}
| true | true | private static List<File> downloadFromMaven(String mavenRoot, MavenObject mo, BuildType type) {
List<File> downloads = new ArrayList<File>();
String[] jars = { "" };
if (BuildType.RUNTIME.equals(type)) {
jars = new String[] { "" };
} else if (BuildType.COMPILETIME.equals(type)) {
jars = new String[] { "-sources", "-javadoc" };
}
for (String jar : jars) {
File targetFile = mo.getLocalFile("ext", jar);
if (targetFile.exists()) {
downloads.add(targetFile);
continue;
}
String expectedSHA1 = mo.getSHA1(jar);
if (expectedSHA1 == null) {
// skip this jar
continue;
}
float approximateLength = mo.getApproximateLength(jar);
String mavenURL = mavenRoot + mo.getRepositoryPath(jar);
if (!targetFile.getAbsoluteFile().getParentFile().exists()) {
boolean success = targetFile.getAbsoluteFile().getParentFile().mkdirs();
if (!success) {
throw new RuntimeException("Failed to create destination folder structure!");
}
}
if (downloadListener != null) {
downloadListener.downloading(mo.name + "...");
}
ByteArrayOutputStream buff = new ByteArrayOutputStream();
try {
URL url = new URL(mavenURL);
InputStream in = new BufferedInputStream(url.openStream());
byte[] buffer = new byte[4096];
int downloadedLen = 0;
float lastProgress = 0f;
updateDownload(0, targetFile);
while (true) {
int len = in.read(buffer);
if (len < 0) {
break;
}
downloadedLen += len;
buff.write(buffer, 0, len);
float progress = downloadedLen / approximateLength;
if (progress - lastProgress >= 0.1f) {
lastProgress = progress;
updateDownload(progress, targetFile);
if (downloadListener != null) {
int percent = Math.round(100 * progress);
downloadListener.downloading(mo.name + " (" + percent + "%)");
}
}
}
in.close();
updateDownload(1f, targetFile);
if (downloadListener != null) {
downloadListener.downloading(mo.name + " (100%)");
}
} catch (IOException e) {
throw new RuntimeException("Error downloading " + mavenURL + " to " + targetFile, e);
}
byte[] data = buff.toByteArray();
String calculatedSHA1 = StringUtils.getSHA1(data);
System.out.println();
if (expectedSHA1.length() == 0) {
updateProgress(0, "sha: " + calculatedSHA1);
System.out.println();
} else {
if (!calculatedSHA1.equals(expectedSHA1)) {
throw new RuntimeException("SHA1 checksum mismatch; got: " + calculatedSHA1);
}
}
try {
RandomAccessFile ra = new RandomAccessFile(targetFile, "rw");
ra.write(data);
ra.setLength(data.length);
ra.close();
} catch (IOException e) {
throw new RuntimeException("Error writing to file " + targetFile, e);
}
downloads.add(targetFile);
}
return downloads;
}
| private static List<File> downloadFromMaven(String mavenRoot, MavenObject mo, BuildType type) {
List<File> downloads = new ArrayList<File>();
String[] jars = { "" };
if (BuildType.RUNTIME.equals(type)) {
jars = new String[] { "" };
} else if (BuildType.COMPILETIME.equals(type)) {
jars = new String[] { "-sources", "-javadoc" };
}
for (String jar : jars) {
File targetFile = mo.getLocalFile("ext", jar);
if (targetFile.exists()) {
downloads.add(targetFile);
continue;
}
String expectedSHA1 = mo.getSHA1(jar);
if (expectedSHA1 == null) {
// skip this jar
continue;
}
float approximateLength = mo.getApproximateLength(jar);
String mavenURL = mavenRoot + mo.getRepositoryPath(jar);
if (!targetFile.getAbsoluteFile().getParentFile().exists()) {
boolean success = targetFile.getAbsoluteFile().getParentFile().mkdirs();
if (!success) {
throw new RuntimeException("Failed to create destination folder structure!");
}
}
if (downloadListener != null) {
downloadListener.downloading(mo.name + "...");
}
ByteArrayOutputStream buff = new ByteArrayOutputStream();
try {
URL url = new URL(mavenURL);
InputStream in = new BufferedInputStream(url.openStream());
byte[] buffer = new byte[4096];
int downloadedLen = 0;
float lastProgress = 0f;
updateDownload(0, targetFile);
while (true) {
int len = in.read(buffer);
if (len < 0) {
break;
}
downloadedLen += len;
buff.write(buffer, 0, len);
float progress = downloadedLen / approximateLength;
if (progress - lastProgress >= 0.1f) {
lastProgress = progress;
updateDownload(progress, targetFile);
if (downloadListener != null) {
int percent = Math.min(100, Math.round(100 * progress));
downloadListener.downloading(mo.name + " (" + percent + "%)");
}
}
}
in.close();
updateDownload(1f, targetFile);
if (downloadListener != null) {
downloadListener.downloading(mo.name + " (100%)");
}
} catch (IOException e) {
throw new RuntimeException("Error downloading " + mavenURL + " to " + targetFile, e);
}
byte[] data = buff.toByteArray();
String calculatedSHA1 = StringUtils.getSHA1(data);
System.out.println();
if (expectedSHA1.length() == 0) {
updateProgress(0, "sha: " + calculatedSHA1);
System.out.println();
} else {
if (!calculatedSHA1.equals(expectedSHA1)) {
throw new RuntimeException("SHA1 checksum mismatch; got: " + calculatedSHA1);
}
}
try {
RandomAccessFile ra = new RandomAccessFile(targetFile, "rw");
ra.write(data);
ra.setLength(data.length);
ra.close();
} catch (IOException e) {
throw new RuntimeException("Error writing to file " + targetFile, e);
}
downloads.add(targetFile);
}
return downloads;
}
|
diff --git a/src/client/command/DeveloperCommands.java b/src/client/command/DeveloperCommands.java
index 5009e064..cc0f9777 100644
--- a/src/client/command/DeveloperCommands.java
+++ b/src/client/command/DeveloperCommands.java
@@ -1,382 +1,381 @@
package client.command;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import paranoia.BlacklistHandler;
import paranoia.ParanoiaInformation;
import paranoia.ParanoiaInformationHandler;
import constants.ParanoiaConstants;
import constants.ServerConstants;
import server.TimerManager;
import server.life.MapleLifeFactory;
import server.life.MapleMonster;
import server.life.MapleNPC;
import tools.DatabaseConnection;
import tools.MapleLogger;
import tools.MaplePacketCreator;
import tools.data.input.SeekableLittleEndianAccessor;
import net.server.Channel;
import net.server.Server;
import client.MapleCharacter;
import client.MapleClient;
public class DeveloperCommands extends EnumeratedCommands {
private static SeekableLittleEndianAccessor slea;
private static final int gmLevel = 4;
private static final char heading = '!';
@SuppressWarnings("unused")
public static boolean execute(MapleClient c, String[] sub, char heading) {
MapleCharacter chr = c.getPlayer();
Channel cserv = c.getChannelServer();
MapleCharacter victim; // For commands with targets.
ResultSet rs; // For commands with MySQL results.
MapleNPC npc;
int npcId = 0;
int mobTime = 0;
int xpos = 0;
int ypos = 0;
int fh = 0;
try {
Command command = Command.valueOf(sub[0]);
switch (command) {
default:
// chr.yellowMessage("Command: " + heading + sub[0] + ": does not exist.");
return false;
case coords:
xpos = chr.getPosition().x;
ypos = chr.getPosition().y;
fh = chr.getMap().getFootholds().findBelow(chr.getPosition()).getId();
chr.dropMessage("Position: (" + xpos + ", " + ypos + ")");
chr.dropMessage("Foothold ID: " + fh);
break;
case droprate:
c.getWorldServer().setDropRate(Integer.parseInt(sub[1]));
for (MapleCharacter mc : c.getWorldServer().getPlayerStorage().getAllCharacters()) {
mc.setRates();
}
Server.getInstance().broadcastMessage(chr.getWorld(), MaplePacketCreator.serverNotice(1, "[Notice] The drop rate has changed to " + sub[1] + "."));
chr.message("Done.");
break;
case exprate:
c.getWorldServer().setExpRate(Integer.parseInt(sub[1]));
for (MapleCharacter mc : c.getWorldServer().getPlayerStorage().getAllCharacters()) {
mc.setRates();
}
Server.getInstance().broadcastMessage(chr.getWorld(), MaplePacketCreator.serverNotice(1, "[Notice] The experience rate has changed to " + sub[1] + "."));
chr.message("Done.");
break;
case gc:
System.gc();
break;
case help:
if (sub.length > 1) {
if (sub[1].equalsIgnoreCase("dev")) {
if (sub.length > 2 && ServerConstants.PAGINATE_HELP) {
getHelp(Integer.parseInt(sub[2]), chr);
} else {
getHelp(chr);
}
break;
} else {
return false;
}
} else {
return false;
}
case horntail:
chr.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(8810026), chr.getPosition());
break;
case mesorate:
c.getWorldServer().setMesoRate(Integer.parseInt(sub[1]));
for (MapleCharacter mc : c.getWorldServer().getPlayerStorage().getAllCharacters()) {
mc.setRates();
}
Server.getInstance().broadcastMessage(chr.getWorld(), MaplePacketCreator.serverNotice(1, "[Notice] The meso rate has changed to " + sub[1] + "."));
chr.message("Done.");
break;
case npc:
npc = MapleLifeFactory.getNPC(Integer.parseInt(sub[1]));
if (npc != null) {
npc.setPosition(chr.getPosition());
npc.setCy(chr.getPosition().y);
npc.setRx0(chr.getPosition().x + 50);
npc.setRx1(chr.getPosition().x - 50);
npc.setFh(chr.getMap().getFootholds().findBelow(c.getPlayer().getPosition()).getId());
chr.getMap().addMapObject(npc);
chr.getMap().broadcastMessage(MaplePacketCreator.spawnNPC(npc));
}
break;
case packet:
chr.getMap().broadcastMessage(MaplePacketCreator.customPacket(joinStringFrom(sub, 1)));
break;
case paranoia:
if (ParanoiaConstants.ALLOW_QUERY_COMMAND) {
- try {
- String k = sub[1];
- if (k == "help") {
+ if (sub.length > 2) {
+ if (sub[1] == "help") {
chr.dropMessage("Paranoia Information Querying Help");
for (ParanoiaInformation pi : ParanoiaInformation.values()) {
chr.dropMessage(pi.name() + " - " + pi.explain());
}
} else {
- chr.dropMessage(ParanoiaInformationHandler.getFormattedValue(k));
+ chr.dropMessage(ParanoiaInformationHandler.getFormattedValue(sub[1]));
}
- } catch (ArrayIndexOutOfBoundsException e) {
+ } else {
chr.dropMessage("Usage: !paranoia value || !paranoia help");
}
} else {
chr.dropMessage("Paranoia Information Querying is forbidden by the server.");
}
break;
case pinkbean:
chr.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(8820009), chr.getPosition());
break;
case pmob:
npcId = Integer.parseInt(sub[1]);
mobTime = Integer.parseInt(sub[2]);
xpos = chr.getPosition().x;
ypos = chr.getPosition().y;
fh = chr.getMap().getFootholds().findBelow(chr.getPosition()).getId();
if (sub[2] == null) {
mobTime = 0;
}
MapleMonster mob = MapleLifeFactory.getMonster(npcId);
if (mob != null && !mob.getName().equals("MISSINGNO")) {
mob.setPosition(chr.getPosition());
mob.setCy(ypos);
mob.setRx0(xpos + 50);
mob.setRx1(xpos - 50);
mob.setFh(fh);
try {
Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO spawns ( idd, f, fh, cy, rx0, rx1, type, x, y, mid, mobtime ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");
ps.setInt(1, npcId);
ps.setInt(2, 0);
ps.setInt(3, fh);
ps.setInt(4, ypos);
ps.setInt(5, xpos + 50);
ps.setInt(6, xpos - 50);
ps.setString(7, "m");
ps.setInt(8, xpos);
ps.setInt(9, ypos);
ps.setInt(10, chr.getMapId());
ps.setInt(11, mobTime);
ps.executeUpdate();
} catch (SQLException e) {
chr.dropMessage("Failed to save mob to the database.");
}
chr.getMap().addMonsterSpawn(mob, mobTime, 0);
} else {
chr.dropMessage("You have entered an invalid mob ID.");
}
break;
case pnpc:
npcId = Integer.parseInt(sub[1]);
npc = MapleLifeFactory.getNPC(npcId);
xpos = chr.getPosition().x;
ypos = chr.getPosition().y;
fh = chr.getMap().getFootholds().findBelow(chr.getPosition()).getId();
if (npc != null && !npc.getName().equals("MISSINGNO")) {
npc.setPosition(chr.getPosition());
npc.setCy(ypos);
npc.setRx0(xpos + 50);
npc.setRx1(xpos - 50);
npc.setFh(fh);
try {
Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO spawns ( idd, f, fh, cy, rx0, rx1, type, x, y, mid ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");
ps.setInt(1, npcId);
ps.setInt(2, 0);
ps.setInt(3, fh);
ps.setInt(4, ypos);
ps.setInt(5, xpos + 50);
ps.setInt(6, xpos - 50);
ps.setString(7, "n");
ps.setInt(8, xpos);
ps.setInt(9, ypos);
ps.setInt(10, chr.getMapId());
ps.executeUpdate();
} catch (SQLException e) {
chr.dropMessage("Failed to save NPC to the database.");
}
chr.getMap().addMapObject(npc);
chr.getMap().broadcastMessage(MaplePacketCreator.spawnNPC(npc));
} else {
chr.dropMessage("You have entered an invalid NPC id.");
}
break;
case reloadblacklist:
if (ServerConstants.USE_PARANOIA && ParanoiaConstants.ENABLE_BLACKLISTING && ParanoiaConstants.ALLOW_RELOADBLACKLIST_COMMAND) {
BlacklistHandler.reloadBlacklist();
chr.message("Done.");
} else if (!ParanoiaConstants.ENABLE_BLACKLISTING) {
chr.dropMessage("Blacklisting is disabled on the server.");
} else if (!ParanoiaConstants.ALLOW_RELOADBLACKLIST_COMMAND) {
chr.dropMessage("Reloading blacklist is forbidden by the server.");
}
break;
case say:
if (sub.length > 2) {
victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
final String s = joinStringFrom(sub, 2);
victim.getMap().broadcastMessage(MaplePacketCreator.getChatText(victim.getId(), s, victim.isGM(), slea.readByte()));
} else {
chr.message("Usage: !say playerName multi-word message");
}
break;
case shutdown:
if (sub.length == 2) {
int time = 60000;
if (sub[1].equalsIgnoreCase("now")) {
time = 1;
} else {
time *= Integer.parseInt(sub[1]);
}
TimerManager.getInstance().schedule(Server.getInstance().shutdown(false), time);
} else {
chr.message("Usage: !shutdown time || !shutdown now");
}
break;
case sql:
if (sub[1] == "true") {
String name = sub[1];
final String query = joinStringFrom(sub, 2);
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
chr.dropMessage(String.valueOf(rs.getObject(name)));
}
rs.close();
ps.close();
} catch (SQLException e) {
chr.message("Query Failed: " + query);
}
} else {
final String query = joinStringFrom(sub, 1);
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement(query);
ps.executeUpdate();
ps.close();
chr.message("Completed: " + query);
} catch (SQLException e) {
chr.message("Query Failed: " + query);
}
}
break;
case updaterankings:
updateRankings();
break;
case zakum:
chr.getMap().spawnFakeMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800000), chr.getPosition());
for (int x = 8800003; x < 8800011; x++) {
chr.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(x), chr.getPosition());
}
break;
}
if (ServerConstants.USE_PARANOIA && ParanoiaConstants.PARANOIA_COMMAND_LOGGER && ParanoiaConstants.LOG_DEVELOPER_COMMANDS) {
MapleLogger.printFormatted(MapleLogger.PARANOIA_COMMAND, "[" + c.getPlayer().getName() + "] Used " + heading + sub[0] + ((sub.length > 1) ? " with parameters: " + joinStringFrom(sub, 1) : "."));
}
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
public static void setSLEA(SeekableLittleEndianAccessor slea) {
DeveloperCommands.slea = slea;
}
public static void updateRankings() {
try {
Connection con = (Connection) DatabaseConnection.getConnection();
PreparedStatement ps;
ResultSet rs;
ps = (PreparedStatement) con.prepareStatement("SELECT id, rank, rankMove FROM characters WHERE gm < 2 ORDER BY rebirths DESC, level DESC, name DESC");
rs = ps.executeQuery();
int n = 1;
while (rs.next()) {
ps = (PreparedStatement) con.prepareStatement("UPDATE characters SET rank = ?, rankMove = ? WHERE id = ?");
ps.setInt(1, n);
ps.setInt(2, rs.getInt("rank") - n);
ps.setInt(3, rs.getInt("id"));
ps.executeUpdate();
n++;
}
} catch (SQLException e) {
MapleLogger.print(MapleLogger.EXCEPTION_CAUGHT, e);
}
}
protected static void getHelp(MapleCharacter chr) {
DeveloperCommands.getHelp(-1, chr);
}
protected static void getHelp(int page, MapleCharacter chr) {
int pageNumber = (int) (Command.values().length / ServerConstants.ENTRIES_PER_PAGE);
if (Command.values().length % ServerConstants.ENTRIES_PER_PAGE > 0) {
pageNumber++;
}
if (page <= 0 || pageNumber == 1) {
chr.dropMessage(ServerConstants.SERVER_NAME + "'s DeveloperCommands Help");
for (Command cmd : Command.values()) {
chr.dropMessage(heading + cmd.name() + " - " + cmd.getDescription());
}
} else {
if (page > pageNumber) {
page = pageNumber;
}
int lastPageEntry = (Command.values().length - Math.max(0, Command.values().length - (page * ServerConstants.ENTRIES_PER_PAGE)));
lastPageEntry -= 1;
chr.dropMessage(ServerConstants.SERVER_NAME + "'s DeveloperCommands Help (Page " + page + " / " + pageNumber + ")");
for (int i = lastPageEntry; i <= lastPageEntry + ServerConstants.ENTRIES_PER_PAGE; i++) {
chr.dropMessage(heading + Command.values()[i].name() + " - " + Command.values()[i].getDescription());
}
}
}
public static int getRequiredStaffRank() {
return gmLevel;
}
public static char getHeading() {
return heading;
}
private static enum Command {
coords("Prints your current coordinates."),
droprate("Sets the server-wide drop rate."),
exprate("Sets the server-wide experience rate."),
gc("Runs the garbage collector."),
help("Displays this help message."),
horntail("Summons Horntail at your position."),
mesorate("Sets the server-wide meso rate."),
npc("Spawns an NPC at your position."),
packet("Executes a custom packet."),
paranoia("Gathers information about Paranoia."),
pmob("Permanently spawns a mob at your position."),
pnpc("Permanently spawns an NPC at your position."),
pinkbean("Summons Pinkbean at your position."),
reloadblacklist("Reloads the Paranoia blacklist."),
say("Forces a victim to say something."),
shutdown("Shutdowns the server."),
sql("Executes an SQL query."),
updaterankings("Forces an update of the rankings."),
zakum("Summons Zakum at your position.");
private final String description;
private Command(String description){
this.description = description;
}
public String getDescription() {
return this.description;
}
}
}
| false | true | public static boolean execute(MapleClient c, String[] sub, char heading) {
MapleCharacter chr = c.getPlayer();
Channel cserv = c.getChannelServer();
MapleCharacter victim; // For commands with targets.
ResultSet rs; // For commands with MySQL results.
MapleNPC npc;
int npcId = 0;
int mobTime = 0;
int xpos = 0;
int ypos = 0;
int fh = 0;
try {
Command command = Command.valueOf(sub[0]);
switch (command) {
default:
// chr.yellowMessage("Command: " + heading + sub[0] + ": does not exist.");
return false;
case coords:
xpos = chr.getPosition().x;
ypos = chr.getPosition().y;
fh = chr.getMap().getFootholds().findBelow(chr.getPosition()).getId();
chr.dropMessage("Position: (" + xpos + ", " + ypos + ")");
chr.dropMessage("Foothold ID: " + fh);
break;
case droprate:
c.getWorldServer().setDropRate(Integer.parseInt(sub[1]));
for (MapleCharacter mc : c.getWorldServer().getPlayerStorage().getAllCharacters()) {
mc.setRates();
}
Server.getInstance().broadcastMessage(chr.getWorld(), MaplePacketCreator.serverNotice(1, "[Notice] The drop rate has changed to " + sub[1] + "."));
chr.message("Done.");
break;
case exprate:
c.getWorldServer().setExpRate(Integer.parseInt(sub[1]));
for (MapleCharacter mc : c.getWorldServer().getPlayerStorage().getAllCharacters()) {
mc.setRates();
}
Server.getInstance().broadcastMessage(chr.getWorld(), MaplePacketCreator.serverNotice(1, "[Notice] The experience rate has changed to " + sub[1] + "."));
chr.message("Done.");
break;
case gc:
System.gc();
break;
case help:
if (sub.length > 1) {
if (sub[1].equalsIgnoreCase("dev")) {
if (sub.length > 2 && ServerConstants.PAGINATE_HELP) {
getHelp(Integer.parseInt(sub[2]), chr);
} else {
getHelp(chr);
}
break;
} else {
return false;
}
} else {
return false;
}
case horntail:
chr.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(8810026), chr.getPosition());
break;
case mesorate:
c.getWorldServer().setMesoRate(Integer.parseInt(sub[1]));
for (MapleCharacter mc : c.getWorldServer().getPlayerStorage().getAllCharacters()) {
mc.setRates();
}
Server.getInstance().broadcastMessage(chr.getWorld(), MaplePacketCreator.serverNotice(1, "[Notice] The meso rate has changed to " + sub[1] + "."));
chr.message("Done.");
break;
case npc:
npc = MapleLifeFactory.getNPC(Integer.parseInt(sub[1]));
if (npc != null) {
npc.setPosition(chr.getPosition());
npc.setCy(chr.getPosition().y);
npc.setRx0(chr.getPosition().x + 50);
npc.setRx1(chr.getPosition().x - 50);
npc.setFh(chr.getMap().getFootholds().findBelow(c.getPlayer().getPosition()).getId());
chr.getMap().addMapObject(npc);
chr.getMap().broadcastMessage(MaplePacketCreator.spawnNPC(npc));
}
break;
case packet:
chr.getMap().broadcastMessage(MaplePacketCreator.customPacket(joinStringFrom(sub, 1)));
break;
case paranoia:
if (ParanoiaConstants.ALLOW_QUERY_COMMAND) {
try {
String k = sub[1];
if (k == "help") {
chr.dropMessage("Paranoia Information Querying Help");
for (ParanoiaInformation pi : ParanoiaInformation.values()) {
chr.dropMessage(pi.name() + " - " + pi.explain());
}
} else {
chr.dropMessage(ParanoiaInformationHandler.getFormattedValue(k));
}
} catch (ArrayIndexOutOfBoundsException e) {
chr.dropMessage("Usage: !paranoia value || !paranoia help");
}
} else {
chr.dropMessage("Paranoia Information Querying is forbidden by the server.");
}
break;
case pinkbean:
chr.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(8820009), chr.getPosition());
break;
case pmob:
npcId = Integer.parseInt(sub[1]);
mobTime = Integer.parseInt(sub[2]);
xpos = chr.getPosition().x;
ypos = chr.getPosition().y;
fh = chr.getMap().getFootholds().findBelow(chr.getPosition()).getId();
if (sub[2] == null) {
mobTime = 0;
}
MapleMonster mob = MapleLifeFactory.getMonster(npcId);
if (mob != null && !mob.getName().equals("MISSINGNO")) {
mob.setPosition(chr.getPosition());
mob.setCy(ypos);
mob.setRx0(xpos + 50);
mob.setRx1(xpos - 50);
mob.setFh(fh);
try {
Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO spawns ( idd, f, fh, cy, rx0, rx1, type, x, y, mid, mobtime ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");
ps.setInt(1, npcId);
ps.setInt(2, 0);
ps.setInt(3, fh);
ps.setInt(4, ypos);
ps.setInt(5, xpos + 50);
ps.setInt(6, xpos - 50);
ps.setString(7, "m");
ps.setInt(8, xpos);
ps.setInt(9, ypos);
ps.setInt(10, chr.getMapId());
ps.setInt(11, mobTime);
ps.executeUpdate();
} catch (SQLException e) {
chr.dropMessage("Failed to save mob to the database.");
}
chr.getMap().addMonsterSpawn(mob, mobTime, 0);
} else {
chr.dropMessage("You have entered an invalid mob ID.");
}
break;
case pnpc:
npcId = Integer.parseInt(sub[1]);
npc = MapleLifeFactory.getNPC(npcId);
xpos = chr.getPosition().x;
ypos = chr.getPosition().y;
fh = chr.getMap().getFootholds().findBelow(chr.getPosition()).getId();
if (npc != null && !npc.getName().equals("MISSINGNO")) {
npc.setPosition(chr.getPosition());
npc.setCy(ypos);
npc.setRx0(xpos + 50);
npc.setRx1(xpos - 50);
npc.setFh(fh);
try {
Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO spawns ( idd, f, fh, cy, rx0, rx1, type, x, y, mid ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");
ps.setInt(1, npcId);
ps.setInt(2, 0);
ps.setInt(3, fh);
ps.setInt(4, ypos);
ps.setInt(5, xpos + 50);
ps.setInt(6, xpos - 50);
ps.setString(7, "n");
ps.setInt(8, xpos);
ps.setInt(9, ypos);
ps.setInt(10, chr.getMapId());
ps.executeUpdate();
} catch (SQLException e) {
chr.dropMessage("Failed to save NPC to the database.");
}
chr.getMap().addMapObject(npc);
chr.getMap().broadcastMessage(MaplePacketCreator.spawnNPC(npc));
} else {
chr.dropMessage("You have entered an invalid NPC id.");
}
break;
case reloadblacklist:
if (ServerConstants.USE_PARANOIA && ParanoiaConstants.ENABLE_BLACKLISTING && ParanoiaConstants.ALLOW_RELOADBLACKLIST_COMMAND) {
BlacklistHandler.reloadBlacklist();
chr.message("Done.");
} else if (!ParanoiaConstants.ENABLE_BLACKLISTING) {
chr.dropMessage("Blacklisting is disabled on the server.");
} else if (!ParanoiaConstants.ALLOW_RELOADBLACKLIST_COMMAND) {
chr.dropMessage("Reloading blacklist is forbidden by the server.");
}
break;
case say:
if (sub.length > 2) {
victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
final String s = joinStringFrom(sub, 2);
victim.getMap().broadcastMessage(MaplePacketCreator.getChatText(victim.getId(), s, victim.isGM(), slea.readByte()));
} else {
chr.message("Usage: !say playerName multi-word message");
}
break;
case shutdown:
if (sub.length == 2) {
int time = 60000;
if (sub[1].equalsIgnoreCase("now")) {
time = 1;
} else {
time *= Integer.parseInt(sub[1]);
}
TimerManager.getInstance().schedule(Server.getInstance().shutdown(false), time);
} else {
chr.message("Usage: !shutdown time || !shutdown now");
}
break;
case sql:
if (sub[1] == "true") {
String name = sub[1];
final String query = joinStringFrom(sub, 2);
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
chr.dropMessage(String.valueOf(rs.getObject(name)));
}
rs.close();
ps.close();
} catch (SQLException e) {
chr.message("Query Failed: " + query);
}
} else {
final String query = joinStringFrom(sub, 1);
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement(query);
ps.executeUpdate();
ps.close();
chr.message("Completed: " + query);
} catch (SQLException e) {
chr.message("Query Failed: " + query);
}
}
break;
case updaterankings:
updateRankings();
break;
case zakum:
chr.getMap().spawnFakeMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800000), chr.getPosition());
for (int x = 8800003; x < 8800011; x++) {
chr.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(x), chr.getPosition());
}
break;
}
if (ServerConstants.USE_PARANOIA && ParanoiaConstants.PARANOIA_COMMAND_LOGGER && ParanoiaConstants.LOG_DEVELOPER_COMMANDS) {
MapleLogger.printFormatted(MapleLogger.PARANOIA_COMMAND, "[" + c.getPlayer().getName() + "] Used " + heading + sub[0] + ((sub.length > 1) ? " with parameters: " + joinStringFrom(sub, 1) : "."));
}
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
| public static boolean execute(MapleClient c, String[] sub, char heading) {
MapleCharacter chr = c.getPlayer();
Channel cserv = c.getChannelServer();
MapleCharacter victim; // For commands with targets.
ResultSet rs; // For commands with MySQL results.
MapleNPC npc;
int npcId = 0;
int mobTime = 0;
int xpos = 0;
int ypos = 0;
int fh = 0;
try {
Command command = Command.valueOf(sub[0]);
switch (command) {
default:
// chr.yellowMessage("Command: " + heading + sub[0] + ": does not exist.");
return false;
case coords:
xpos = chr.getPosition().x;
ypos = chr.getPosition().y;
fh = chr.getMap().getFootholds().findBelow(chr.getPosition()).getId();
chr.dropMessage("Position: (" + xpos + ", " + ypos + ")");
chr.dropMessage("Foothold ID: " + fh);
break;
case droprate:
c.getWorldServer().setDropRate(Integer.parseInt(sub[1]));
for (MapleCharacter mc : c.getWorldServer().getPlayerStorage().getAllCharacters()) {
mc.setRates();
}
Server.getInstance().broadcastMessage(chr.getWorld(), MaplePacketCreator.serverNotice(1, "[Notice] The drop rate has changed to " + sub[1] + "."));
chr.message("Done.");
break;
case exprate:
c.getWorldServer().setExpRate(Integer.parseInt(sub[1]));
for (MapleCharacter mc : c.getWorldServer().getPlayerStorage().getAllCharacters()) {
mc.setRates();
}
Server.getInstance().broadcastMessage(chr.getWorld(), MaplePacketCreator.serverNotice(1, "[Notice] The experience rate has changed to " + sub[1] + "."));
chr.message("Done.");
break;
case gc:
System.gc();
break;
case help:
if (sub.length > 1) {
if (sub[1].equalsIgnoreCase("dev")) {
if (sub.length > 2 && ServerConstants.PAGINATE_HELP) {
getHelp(Integer.parseInt(sub[2]), chr);
} else {
getHelp(chr);
}
break;
} else {
return false;
}
} else {
return false;
}
case horntail:
chr.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(8810026), chr.getPosition());
break;
case mesorate:
c.getWorldServer().setMesoRate(Integer.parseInt(sub[1]));
for (MapleCharacter mc : c.getWorldServer().getPlayerStorage().getAllCharacters()) {
mc.setRates();
}
Server.getInstance().broadcastMessage(chr.getWorld(), MaplePacketCreator.serverNotice(1, "[Notice] The meso rate has changed to " + sub[1] + "."));
chr.message("Done.");
break;
case npc:
npc = MapleLifeFactory.getNPC(Integer.parseInt(sub[1]));
if (npc != null) {
npc.setPosition(chr.getPosition());
npc.setCy(chr.getPosition().y);
npc.setRx0(chr.getPosition().x + 50);
npc.setRx1(chr.getPosition().x - 50);
npc.setFh(chr.getMap().getFootholds().findBelow(c.getPlayer().getPosition()).getId());
chr.getMap().addMapObject(npc);
chr.getMap().broadcastMessage(MaplePacketCreator.spawnNPC(npc));
}
break;
case packet:
chr.getMap().broadcastMessage(MaplePacketCreator.customPacket(joinStringFrom(sub, 1)));
break;
case paranoia:
if (ParanoiaConstants.ALLOW_QUERY_COMMAND) {
if (sub.length > 2) {
if (sub[1] == "help") {
chr.dropMessage("Paranoia Information Querying Help");
for (ParanoiaInformation pi : ParanoiaInformation.values()) {
chr.dropMessage(pi.name() + " - " + pi.explain());
}
} else {
chr.dropMessage(ParanoiaInformationHandler.getFormattedValue(sub[1]));
}
} else {
chr.dropMessage("Usage: !paranoia value || !paranoia help");
}
} else {
chr.dropMessage("Paranoia Information Querying is forbidden by the server.");
}
break;
case pinkbean:
chr.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(8820009), chr.getPosition());
break;
case pmob:
npcId = Integer.parseInt(sub[1]);
mobTime = Integer.parseInt(sub[2]);
xpos = chr.getPosition().x;
ypos = chr.getPosition().y;
fh = chr.getMap().getFootholds().findBelow(chr.getPosition()).getId();
if (sub[2] == null) {
mobTime = 0;
}
MapleMonster mob = MapleLifeFactory.getMonster(npcId);
if (mob != null && !mob.getName().equals("MISSINGNO")) {
mob.setPosition(chr.getPosition());
mob.setCy(ypos);
mob.setRx0(xpos + 50);
mob.setRx1(xpos - 50);
mob.setFh(fh);
try {
Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO spawns ( idd, f, fh, cy, rx0, rx1, type, x, y, mid, mobtime ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");
ps.setInt(1, npcId);
ps.setInt(2, 0);
ps.setInt(3, fh);
ps.setInt(4, ypos);
ps.setInt(5, xpos + 50);
ps.setInt(6, xpos - 50);
ps.setString(7, "m");
ps.setInt(8, xpos);
ps.setInt(9, ypos);
ps.setInt(10, chr.getMapId());
ps.setInt(11, mobTime);
ps.executeUpdate();
} catch (SQLException e) {
chr.dropMessage("Failed to save mob to the database.");
}
chr.getMap().addMonsterSpawn(mob, mobTime, 0);
} else {
chr.dropMessage("You have entered an invalid mob ID.");
}
break;
case pnpc:
npcId = Integer.parseInt(sub[1]);
npc = MapleLifeFactory.getNPC(npcId);
xpos = chr.getPosition().x;
ypos = chr.getPosition().y;
fh = chr.getMap().getFootholds().findBelow(chr.getPosition()).getId();
if (npc != null && !npc.getName().equals("MISSINGNO")) {
npc.setPosition(chr.getPosition());
npc.setCy(ypos);
npc.setRx0(xpos + 50);
npc.setRx1(xpos - 50);
npc.setFh(fh);
try {
Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO spawns ( idd, f, fh, cy, rx0, rx1, type, x, y, mid ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");
ps.setInt(1, npcId);
ps.setInt(2, 0);
ps.setInt(3, fh);
ps.setInt(4, ypos);
ps.setInt(5, xpos + 50);
ps.setInt(6, xpos - 50);
ps.setString(7, "n");
ps.setInt(8, xpos);
ps.setInt(9, ypos);
ps.setInt(10, chr.getMapId());
ps.executeUpdate();
} catch (SQLException e) {
chr.dropMessage("Failed to save NPC to the database.");
}
chr.getMap().addMapObject(npc);
chr.getMap().broadcastMessage(MaplePacketCreator.spawnNPC(npc));
} else {
chr.dropMessage("You have entered an invalid NPC id.");
}
break;
case reloadblacklist:
if (ServerConstants.USE_PARANOIA && ParanoiaConstants.ENABLE_BLACKLISTING && ParanoiaConstants.ALLOW_RELOADBLACKLIST_COMMAND) {
BlacklistHandler.reloadBlacklist();
chr.message("Done.");
} else if (!ParanoiaConstants.ENABLE_BLACKLISTING) {
chr.dropMessage("Blacklisting is disabled on the server.");
} else if (!ParanoiaConstants.ALLOW_RELOADBLACKLIST_COMMAND) {
chr.dropMessage("Reloading blacklist is forbidden by the server.");
}
break;
case say:
if (sub.length > 2) {
victim = cserv.getPlayerStorage().getCharacterByName(sub[1]);
final String s = joinStringFrom(sub, 2);
victim.getMap().broadcastMessage(MaplePacketCreator.getChatText(victim.getId(), s, victim.isGM(), slea.readByte()));
} else {
chr.message("Usage: !say playerName multi-word message");
}
break;
case shutdown:
if (sub.length == 2) {
int time = 60000;
if (sub[1].equalsIgnoreCase("now")) {
time = 1;
} else {
time *= Integer.parseInt(sub[1]);
}
TimerManager.getInstance().schedule(Server.getInstance().shutdown(false), time);
} else {
chr.message("Usage: !shutdown time || !shutdown now");
}
break;
case sql:
if (sub[1] == "true") {
String name = sub[1];
final String query = joinStringFrom(sub, 2);
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
chr.dropMessage(String.valueOf(rs.getObject(name)));
}
rs.close();
ps.close();
} catch (SQLException e) {
chr.message("Query Failed: " + query);
}
} else {
final String query = joinStringFrom(sub, 1);
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement(query);
ps.executeUpdate();
ps.close();
chr.message("Completed: " + query);
} catch (SQLException e) {
chr.message("Query Failed: " + query);
}
}
break;
case updaterankings:
updateRankings();
break;
case zakum:
chr.getMap().spawnFakeMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800000), chr.getPosition());
for (int x = 8800003; x < 8800011; x++) {
chr.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(x), chr.getPosition());
}
break;
}
if (ServerConstants.USE_PARANOIA && ParanoiaConstants.PARANOIA_COMMAND_LOGGER && ParanoiaConstants.LOG_DEVELOPER_COMMANDS) {
MapleLogger.printFormatted(MapleLogger.PARANOIA_COMMAND, "[" + c.getPlayer().getName() + "] Used " + heading + sub[0] + ((sub.length > 1) ? " with parameters: " + joinStringFrom(sub, 1) : "."));
}
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
|
diff --git a/servlet/src/main/java/com/redshape/servlet/core/format/JSONFormatProcessor.java b/servlet/src/main/java/com/redshape/servlet/core/format/JSONFormatProcessor.java
index ae4b8e19..6729da7a 100644
--- a/servlet/src/main/java/com/redshape/servlet/core/format/JSONFormatProcessor.java
+++ b/servlet/src/main/java/com/redshape/servlet/core/format/JSONFormatProcessor.java
@@ -1,71 +1,71 @@
package com.redshape.servlet.core.format;
import com.redshape.servlet.core.IHttpRequest;
import com.redshape.servlet.core.SupportType;
import com.redshape.servlet.core.controllers.ProcessingException;
import net.sf.json.JSONObject;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: cyril
* Date: 7/10/12
* Time: 3:47 PM
* To change this template use File | Settings | File Templates.
*/
public class JSONFormatProcessor implements IRequestFormatProcessor {
public static final String MARKER_HEADER = "XMLHttpRequest";
@Override
public SupportType check(IHttpRequest request) throws ProcessingException {
try {
- if ( !request.isPost() ) {
+ if ( !request.isPost() || request.getBody().isEmpty() ) {
return SupportType.NO;
}
String requestedWith = request.getHeader("X-Requested-With");
if ( requestedWith != null && requestedWith.equals( MARKER_HEADER) ) {
return SupportType.SHOULD;
}
if ( request.getBody().startsWith("{")
&& request.getBody().endsWith("}") ) {
return SupportType.MAY;
}
return SupportType.NO;
} catch ( IOException e ) {
throw new ProcessingException( e.getMessage(), e );
}
}
protected JSONObject readJSONRequest( IHttpRequest request )
throws IOException {
String requestData = request.getBody();
if ( requestData.isEmpty() ) {
throw new IllegalArgumentException("Request is empty");
}
return this.readJSONRequest( requestData );
}
protected JSONObject readJSONRequest(String data) {
return JSONObject.fromObject(data);
}
@Override
public void process(IHttpRequest request) throws ProcessingException {
try {
JSONObject object = this.readJSONRequest( request );
for ( Object key : object.keySet() ) {
request.setParameter( String.valueOf( key ), object.get(key) );
}
} catch ( IOException e ) {
throw new ProcessingException( e.getMessage(), e );
}
}
}
| true | true | public SupportType check(IHttpRequest request) throws ProcessingException {
try {
if ( !request.isPost() ) {
return SupportType.NO;
}
String requestedWith = request.getHeader("X-Requested-With");
if ( requestedWith != null && requestedWith.equals( MARKER_HEADER) ) {
return SupportType.SHOULD;
}
if ( request.getBody().startsWith("{")
&& request.getBody().endsWith("}") ) {
return SupportType.MAY;
}
return SupportType.NO;
} catch ( IOException e ) {
throw new ProcessingException( e.getMessage(), e );
}
}
| public SupportType check(IHttpRequest request) throws ProcessingException {
try {
if ( !request.isPost() || request.getBody().isEmpty() ) {
return SupportType.NO;
}
String requestedWith = request.getHeader("X-Requested-With");
if ( requestedWith != null && requestedWith.equals( MARKER_HEADER) ) {
return SupportType.SHOULD;
}
if ( request.getBody().startsWith("{")
&& request.getBody().endsWith("}") ) {
return SupportType.MAY;
}
return SupportType.NO;
} catch ( IOException e ) {
throw new ProcessingException( e.getMessage(), e );
}
}
|
diff --git a/src/com/revolt/control/CreateShortcut.java b/src/com/revolt/control/CreateShortcut.java
index e7e6e00..57c7e68 100644
--- a/src/com/revolt/control/CreateShortcut.java
+++ b/src/com/revolt/control/CreateShortcut.java
@@ -1,92 +1,92 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.revolt.control;
import android.app.LauncherActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;
public class CreateShortcut extends LauncherActivity {
@Override
protected Intent getTargetIntent() {
Intent targetIntent = new Intent(Intent.ACTION_MAIN, null);
targetIntent.addCategory("com.revolt.control" +".SHORTCUT");
targetIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return targetIntent;
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent shortcutIntent = intentForPosition(position);
String intentClass = shortcutIntent.getComponent().getClassName();
shortcutIntent = new Intent();
shortcutIntent.setClass(getApplicationContext(), ReVoltControlActivity.class);
shortcutIntent.setAction("com.revolt.control.START_NEW_FRAGMENT");
shortcutIntent.putExtra("aokp_fragment_name", intentClass);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this, getProperShortcutIcon(intentClass)));
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, itemForPosition(position).label);
setResult(RESULT_OK, intent);
finish();
}
private int getProperShortcutIcon(String className) {
String c = className.substring(className.lastIndexOf(".") + 1);
if (c.equals("LEDControl")) {
return R.drawable.ic_revolt_led;
} else if (c.equals("Lockscreens")) {
return R.drawable.ic_revolt_lockscreens;
} else if (c.equals("Sound")) {
return R.drawable.ic_revolt_sound;
} else if (c.equals("Navbar")) {
return R.drawable.ic_revolt_navigation_bar;
} else if (c.equals("StatusBarBattery")) {
return R.drawable.ic_revolt_battery;
} else if (c.equals("StatusBarClock")) {
return R.drawable.ic_revolt_clock;
} else if (c.equals("StatusBarGeneral")) {
return R.drawable.ic_revolt_general;
} else if (c.equals("StatusBarToggles")) {
return R.drawable.ic_revolt_toggles;
} else if (c.equals("UserInterface")) {
return R.drawable.ic_revolt_general_ui;
} else if (c.equals("Weather")) {
return R.drawable.ic_revolt_weather;
} else if (c.equals("ScreenStateToggles")){
return R.drawable.ic_revolt_screen_state;
} else if (c.equals("WakeLockBlocker")){
- return R.drawable.ic_rom_control_wakelock_blocker;
+ return R.drawable.ic_revolt_wakelock_blocker;
} else {
return R.mipmap.ic_launcher;
}
}
@Override
protected boolean onEvaluateShowIcons() {
return false;
}
}
| true | true | private int getProperShortcutIcon(String className) {
String c = className.substring(className.lastIndexOf(".") + 1);
if (c.equals("LEDControl")) {
return R.drawable.ic_revolt_led;
} else if (c.equals("Lockscreens")) {
return R.drawable.ic_revolt_lockscreens;
} else if (c.equals("Sound")) {
return R.drawable.ic_revolt_sound;
} else if (c.equals("Navbar")) {
return R.drawable.ic_revolt_navigation_bar;
} else if (c.equals("StatusBarBattery")) {
return R.drawable.ic_revolt_battery;
} else if (c.equals("StatusBarClock")) {
return R.drawable.ic_revolt_clock;
} else if (c.equals("StatusBarGeneral")) {
return R.drawable.ic_revolt_general;
} else if (c.equals("StatusBarToggles")) {
return R.drawable.ic_revolt_toggles;
} else if (c.equals("UserInterface")) {
return R.drawable.ic_revolt_general_ui;
} else if (c.equals("Weather")) {
return R.drawable.ic_revolt_weather;
} else if (c.equals("ScreenStateToggles")){
return R.drawable.ic_revolt_screen_state;
} else if (c.equals("WakeLockBlocker")){
return R.drawable.ic_rom_control_wakelock_blocker;
} else {
return R.mipmap.ic_launcher;
}
}
| private int getProperShortcutIcon(String className) {
String c = className.substring(className.lastIndexOf(".") + 1);
if (c.equals("LEDControl")) {
return R.drawable.ic_revolt_led;
} else if (c.equals("Lockscreens")) {
return R.drawable.ic_revolt_lockscreens;
} else if (c.equals("Sound")) {
return R.drawable.ic_revolt_sound;
} else if (c.equals("Navbar")) {
return R.drawable.ic_revolt_navigation_bar;
} else if (c.equals("StatusBarBattery")) {
return R.drawable.ic_revolt_battery;
} else if (c.equals("StatusBarClock")) {
return R.drawable.ic_revolt_clock;
} else if (c.equals("StatusBarGeneral")) {
return R.drawable.ic_revolt_general;
} else if (c.equals("StatusBarToggles")) {
return R.drawable.ic_revolt_toggles;
} else if (c.equals("UserInterface")) {
return R.drawable.ic_revolt_general_ui;
} else if (c.equals("Weather")) {
return R.drawable.ic_revolt_weather;
} else if (c.equals("ScreenStateToggles")){
return R.drawable.ic_revolt_screen_state;
} else if (c.equals("WakeLockBlocker")){
return R.drawable.ic_revolt_wakelock_blocker;
} else {
return R.mipmap.ic_launcher;
}
}
|
diff --git a/wayback-core/src/main/java/org/archive/wayback/liveweb/FileRegion.java b/wayback-core/src/main/java/org/archive/wayback/liveweb/FileRegion.java
index 6874c48b4..a912ca457 100644
--- a/wayback-core/src/main/java/org/archive/wayback/liveweb/FileRegion.java
+++ b/wayback-core/src/main/java/org/archive/wayback/liveweb/FileRegion.java
@@ -1,66 +1,69 @@
/*
* This file is part of the Wayback archival access software
* (http://archive-access.sourceforge.net/projects/wayback/).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.archive.wayback.liveweb;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
/**
* @author brad
*
*/
public class FileRegion {
File file = null;
long start = -1;
long end = -1;
boolean isFake = false;
/**
* @return the number of bytes in this record, including headers. If the
* containing file is compressed, then this represents the number of
* compressed bytes.
*/
public long getLength() {
return end - start;
}
/**
* Copy this record to the provided OutputStream
* @param o the OutputStream where the bytes should be sent.
* @throws IOException for usual reasons
*/
public void copyToOutputStream(OutputStream o) throws IOException {
long left = end - start;
int BUFF_SIZE = 4096;
byte buf[] = new byte[BUFF_SIZE];
RandomAccessFile raf = new RandomAccessFile(file, "r");
- raf.seek(start);
- while(left > 0) {
- int amtToRead = (int) Math.min(left, BUFF_SIZE);
- int amtRead = raf.read(buf, 0, amtToRead);
- if(amtRead < 0) {
- throw new IOException("Not enough to read! EOF before expected region end");
+ try {
+ raf.seek(start);
+ while(left > 0) {
+ int amtToRead = (int) Math.min(left, BUFF_SIZE);
+ int amtRead = raf.read(buf, 0, amtToRead);
+ if(amtRead < 0) {
+ throw new IOException("Not enough to read! EOF before expected region end");
+ }
+ o.write(buf,0,amtRead);
+ left -= amtRead;
}
- o.write(buf,0,amtRead);
- left -= amtRead;
+ } finally {
+ raf.close();
}
- raf.close();
}
}
| false | true | public void copyToOutputStream(OutputStream o) throws IOException {
long left = end - start;
int BUFF_SIZE = 4096;
byte buf[] = new byte[BUFF_SIZE];
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(start);
while(left > 0) {
int amtToRead = (int) Math.min(left, BUFF_SIZE);
int amtRead = raf.read(buf, 0, amtToRead);
if(amtRead < 0) {
throw new IOException("Not enough to read! EOF before expected region end");
}
o.write(buf,0,amtRead);
left -= amtRead;
}
raf.close();
}
| public void copyToOutputStream(OutputStream o) throws IOException {
long left = end - start;
int BUFF_SIZE = 4096;
byte buf[] = new byte[BUFF_SIZE];
RandomAccessFile raf = new RandomAccessFile(file, "r");
try {
raf.seek(start);
while(left > 0) {
int amtToRead = (int) Math.min(left, BUFF_SIZE);
int amtRead = raf.read(buf, 0, amtToRead);
if(amtRead < 0) {
throw new IOException("Not enough to read! EOF before expected region end");
}
o.write(buf,0,amtRead);
left -= amtRead;
}
} finally {
raf.close();
}
}
|
diff --git a/oxalis-commons/src/test/java/eu/peppol/security/OcspValidatorCacheTest.java b/oxalis-commons/src/test/java/eu/peppol/security/OcspValidatorCacheTest.java
index 17e8f488..e8a3dc21 100644
--- a/oxalis-commons/src/test/java/eu/peppol/security/OcspValidatorCacheTest.java
+++ b/oxalis-commons/src/test/java/eu/peppol/security/OcspValidatorCacheTest.java
@@ -1,35 +1,35 @@
package eu.peppol.security;
import eu.peppol.security.OcspValidatorCache;
import org.testng.annotations.Test;
import java.math.BigInteger;
import static org.testng.Assert.assertEquals;
/**
* User: nigel
* Date: Dec 6, 2011
* Time: 9:09:13 PM
*/
@Test
public class OcspValidatorCacheTest {
public void test01() throws Exception {
OcspValidatorCache cache = OcspValidatorCache.getInstance();
- cache.setTimoutForTesting(10);
+ cache.setTimoutForTesting(20);
BigInteger serialNumber = new BigInteger("1000");
assertEquals(cache.isKnownValidCertificate(serialNumber), false);
cache.setKnownValidCertificate(serialNumber);
assertEquals(cache.isKnownValidCertificate(serialNumber), true);
Thread.sleep(5);
assertEquals(cache.isKnownValidCertificate(serialNumber), true);
- Thread.sleep(10);
+ Thread.sleep(11);
assertEquals(cache.isKnownValidCertificate(serialNumber), false);
}
}
| false | true | public void test01() throws Exception {
OcspValidatorCache cache = OcspValidatorCache.getInstance();
cache.setTimoutForTesting(10);
BigInteger serialNumber = new BigInteger("1000");
assertEquals(cache.isKnownValidCertificate(serialNumber), false);
cache.setKnownValidCertificate(serialNumber);
assertEquals(cache.isKnownValidCertificate(serialNumber), true);
Thread.sleep(5);
assertEquals(cache.isKnownValidCertificate(serialNumber), true);
Thread.sleep(10);
assertEquals(cache.isKnownValidCertificate(serialNumber), false);
}
| public void test01() throws Exception {
OcspValidatorCache cache = OcspValidatorCache.getInstance();
cache.setTimoutForTesting(20);
BigInteger serialNumber = new BigInteger("1000");
assertEquals(cache.isKnownValidCertificate(serialNumber), false);
cache.setKnownValidCertificate(serialNumber);
assertEquals(cache.isKnownValidCertificate(serialNumber), true);
Thread.sleep(5);
assertEquals(cache.isKnownValidCertificate(serialNumber), true);
Thread.sleep(11);
assertEquals(cache.isKnownValidCertificate(serialNumber), false);
}
|
diff --git a/plugins/org.jboss.tools.ws.ui/src/org/jboss/tools/ws/ui/wizards/JBossWSAnnotatedClassWizardPage.java b/plugins/org.jboss.tools.ws.ui/src/org/jboss/tools/ws/ui/wizards/JBossWSAnnotatedClassWizardPage.java
index e2a920de..ac44ad2d 100644
--- a/plugins/org.jboss.tools.ws.ui/src/org/jboss/tools/ws/ui/wizards/JBossWSAnnotatedClassWizardPage.java
+++ b/plugins/org.jboss.tools.ws.ui/src/org/jboss/tools/ws/ui/wizards/JBossWSAnnotatedClassWizardPage.java
@@ -1,807 +1,807 @@
/*******************************************************************************
* Copyright (c) 2010 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.ws.ui.wizards;
import java.util.ArrayList;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.PackageFragment;
import org.eclipse.jdt.ui.IJavaElementSearchConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.jst.j2ee.project.JavaEEProjectUtilities;
import org.eclipse.jst.j2ee.project.facet.IJ2EEFacetConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
import org.jboss.tools.ws.creation.core.data.ServiceModel;
import org.jboss.tools.ws.creation.core.utils.JBossWSCreationUtils;
import org.jboss.tools.ws.creation.core.utils.RestEasyLibUtils;
import org.jboss.tools.ws.ui.messages.JBossWSUIMessages;
@SuppressWarnings("restriction")
public class JBossWSAnnotatedClassWizardPage extends WizardPage {
private JBossWSAnnotatedClassWizard wizard;
private Combo projects;
private boolean bHasChanged = false;
private Button optJAXWS;
private Button optJAXRS;
private Text packageName;
private Text className;
private Text appClassName;
private Text name;
private Button updateWebXML;
private Button addJarsIfFound;
private Button btnPackageBrowse;
private Button btnServiceClassBrowse;
private Button btnAppClassBrowse;
protected JBossWSAnnotatedClassWizardPage(String pageName) {
super(pageName);
this
.setTitle(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_PageTitle);
this
.setDescription(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_PageDescription);
}
private void createWsTechComposite(Composite parent) {
Group wsTechGroup = new Group(parent, SWT.NONE);
wsTechGroup
.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_WS_Tech_Group);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
wsTechGroup.setLayout(new GridLayout(2, false));
wsTechGroup.setLayoutData(gd);
Composite wsTechComposite = new Composite (wsTechGroup, SWT.NONE);
GridLayout gl = new GridLayout(2, true);
gl.marginTop = -5;
gl.marginBottom = -5;
wsTechComposite.setLayout(gl);
GridData gridData = new GridData();
gridData.horizontalIndent = -5;
gridData.grabExcessHorizontalSpace = true;
gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
wsTechComposite.setLayoutData(gridData);
optJAXWS = new Button(wsTechComposite, SWT.RADIO);
optJAXWS.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_JAXWS_Button);
optJAXWS.setLayoutData(new GridData(SWT.FILL, SWT.NULL, true, false));
optJAXRS = new Button(wsTechComposite, SWT.RADIO);
optJAXRS.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_JAXRS_Button);
optJAXRS.setLayoutData(new GridData(SWT.FILL, SWT.NULL, true, false));
//default
optJAXWS.setSelection(true);
optJAXWS.addSelectionListener(new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
wizard.setJAXWS(true);
appClassName.setEnabled(!wizard.isJAXWS());
btnAppClassBrowse.setEnabled(!wizard.isJAXWS());
updateDefaultValues();
setPageComplete(isPageComplete());
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
optJAXRS.addSelectionListener(new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
wizard.setJAXWS(false);
appClassName.setEnabled(!wizard.isJAXWS());
btnAppClassBrowse.setEnabled(!wizard.isJAXWS());
updateDefaultValues();
setPageComplete(isPageComplete());
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
}
private String testDefaultServiceName( String currentName) {
ServiceModel model = wizard.getServiceModel();
JBossWSGenerateWizardValidator.setServiceModel(model);
IStatus status = JBossWSGenerateWizardValidator.isWSNameValid();
try {
if (status.getSeverity() == IStatus.ERROR
&& !JavaEEProjectUtilities.isDynamicWebProject(wizard
.getProject())) {
return currentName;
}
} catch (NullPointerException npe) {
return currentName;
}
String testName = currentName;
int i = 1;
while (status != null) {
testName = currentName + i;
wizard.setServiceName(testName);
model = wizard.getServiceModel();
JBossWSGenerateWizardValidator.setServiceModel(model);
status = JBossWSGenerateWizardValidator.isWSNameValid();
i++;
}
return testName;
}
private String testDefaultAppClassName(String currentName) {
ServiceModel model = wizard.getServiceModel();
JBossRSGenerateWizardValidator.setServiceModel(model);
if (wizard.getProject() == null) {
return currentName;
} else {
boolean isDynamicWebProject = false;
try {
if (wizard.getProject().getNature(
"org.eclipse.wst.common.project.facet.core.nature") != null) { //$NON-NLS-1$
isDynamicWebProject = true;
}
} catch (CoreException e) {
// ignore
}
if (!isDynamicWebProject) {
return currentName;
}
}
String testName = currentName;
IStatus status = JBossRSGenerateWizardValidator.isAppClassNameValid(
model.getCustomPackage() + '.' + currentName);
int i = 1;
while (status != null && status.getSeverity() == IStatus.ERROR) {
testName = currentName + i;
wizard.setClassName(testName);
model = wizard.getServiceModel();
JBossWSGenerateWizardValidator.setServiceModel(model);
status = JBossWSGenerateWizardValidator.isWSClassValid(testName,
wizard.getProject());
i++;
}
return testName;
}
private String testDefaultClassName(String currentName) {
ServiceModel model = wizard.getServiceModel();
JBossWSGenerateWizardValidator.setServiceModel(model);
if (wizard.getProject() == null) {
return currentName;
} else {
boolean isDynamicWebProject = false;
try {
if (wizard.getProject().getNature(
"org.eclipse.wst.common.project.facet.core.nature") != null) { //$NON-NLS-1$
isDynamicWebProject = true;
}
} catch (CoreException e) {
// ignore
}
if (!isDynamicWebProject) {
return currentName;
}
}
String testName = currentName;
IStatus status = JBossWSGenerateWizardValidator.isWSClassValid(
testName, wizard.getProject());
int i = 1;
while (status != null && status.getSeverity() == IStatus.ERROR) {
testName = currentName + i;
wizard.setClassName(testName);
model = wizard.getServiceModel();
JBossWSGenerateWizardValidator.setServiceModel(model);
status = JBossWSGenerateWizardValidator.isWSClassValid(testName,
wizard.getProject());
i++;
}
return testName;
}
private void updateDefaultValues() {
String testName = null;
if (wizard.isJAXWS()) {
if (className != null && className.getText().trim().length() == 0) {
testName = testDefaultClassName(JBossWSAnnotatedClassWizard.WSCLASSDEFAULT);
className.setText(testName);
wizard.setClassName(testName);
}
if (name != null && name.getText().trim().length() == 0) {
testName = testDefaultServiceName(JBossWSAnnotatedClassWizard.WSNAMEDEFAULT);
name.setText(testName);
wizard.setServiceName(testName);
}
appClassName.setText(""); //$NON-NLS-1$
wizard.setAppClassName(""); //$NON-NLS-1$
} else {
if (className != null && className.getText().trim().length() == 0) {
testName = testDefaultClassName(JBossWSAnnotatedClassWizard.RSCLASSDEFAULT);
className.setText(testName);
wizard.setClassName(testName);
}
if (name != null && name.getText().trim().length() == 0) {
testName = testDefaultServiceName(JBossWSAnnotatedClassWizard.RSNAMEDEFAULT);
name.setText(testName);
wizard.setServiceName(testName);
}
if (appClassName != null && appClassName.getText().trim().length() == 0) {
testName = testDefaultAppClassName(JBossWSAnnotatedClassWizard.RSAPPCLASSDEFAULT);
appClassName.setText(testName);
wizard.setAppClassName(testName);
}
}
if (packageName != null && packageName.getText().trim().length() == 0) {
packageName.setText(JBossWSAnnotatedClassWizard.PACKAGEDEFAULT);
wizard.setPackageName(packageName.getText());
}
}
private void createProjectGroup ( Composite parent ) {
Group group = new Group(parent, SWT.NONE);
group
.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_Project_Group);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
group.setLayout(new GridLayout(2, false));
group.setLayoutData(gd);
projects = new Combo(group, SWT.BORDER | SWT.DROP_DOWN);
projects
.setToolTipText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_Projects_Combo_Tooltip);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
projects.setLayoutData(gd);
refreshProjectList(wizard.getServiceModel().getWebProjectName());
projects.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
wizard.setProject(projects.getText());
setWebXMLSelectionValueBasedOnProjectFacet();
bHasChanged = true;
setPageComplete(isPageComplete());
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
}
private void createApplicationGroup(Composite parent) {
GridData gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalSpan = 2;
gd.horizontalIndent = -5;
gd.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
Group group = new Group(parent, SWT.NONE);
group.setLayout(new GridLayout(2, false));
group.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_Web_Service_Group);
group.setLayoutData(gd);
new Label(group, SWT.NONE)
.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_Service_Name_field);
name = new Text(group, SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
name.setLayoutData(gd);
// name.setText(wizard.getServiceName());
name.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
wizard.setServiceName(name.getText());
bHasChanged = true;
setPageComplete(isPageComplete());
}
});
updateWebXML = new Button(group, SWT.CHECK);
updateWebXML.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_Update_Web_xml_checkbox);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
updateWebXML.setLayoutData(gd);
updateWebXML.setSelection(wizard.getUpdateWebXML());
updateWebXML.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
wizard.setUpdateWebXML(updateWebXML.getSelection());
name.setEnabled(wizard.getUpdateWebXML());
setPageComplete(isPageComplete());
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
addJarsIfFound = new Button(group, SWT.CHECK);
addJarsIfFound.setText(JBossWSUIMessages.JBossRSGenerateWizardPage_AddJarsIfFoundCheckbox);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
addJarsIfFound.setLayoutData(gd);
addJarsIfFound.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
wizard.setAddJarsFromRootRuntime(updateWebXML.getSelection());
setPageComplete(isPageComplete());
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
setWebXMLSelectionValueBasedOnProjectFacet();
}
private void createImplementationGroup(Composite parent) {
GridData gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalSpan = 2;
gd.horizontalIndent = -5;
gd.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
Group group = new Group(parent, SWT.NONE);
group.setLayout(new GridLayout(3, false));
group.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_Service_implementation_group);
group.setLayoutData(gd);
new Label(group, SWT.NONE)
.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_package_name_field);
packageName = new Text(group, SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
packageName.setLayoutData(gd);
packageName.setText(wizard.getPackageName());
packageName.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
wizard.setPackageName(packageName.getText());
setPageComplete(isPageComplete());
}
});
btnPackageBrowse = new Button(group, SWT.PUSH);
btnPackageBrowse.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_package_browse_btn);
btnPackageBrowse.addSelectionListener(new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
if (wizard.getProject() == null) {
return;
}
IJavaProject project = JavaCore.create( wizard.getProject());
if (project == null) {
return;
}
try {
SelectionDialog dialog =
JavaUI.createPackageDialog(
getShell(),
project,
IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS);
if (dialog.open() == Window.OK) {
if (dialog.getResult() != null && dialog.getResult().length == 1) {
String fqClassName = ((PackageFragment) dialog.getResult()[0]).getElementName();
packageName.setText(fqClassName);
setPageComplete(isPageComplete());
}
}
} catch (JavaModelException e1) {
e1.printStackTrace();
}
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
new Label(group, SWT.NONE)
.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_Service_class_field);
className = new Text(group, SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
className.setLayoutData(gd);
// className.setText(wizard.getClassName());
className.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
wizard.setClassName(className.getText());
setPageComplete(isPageComplete());
}
});
btnServiceClassBrowse = new Button(group, SWT.PUSH);
btnServiceClassBrowse.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_Service_class_Browse_btn);
btnServiceClassBrowse.addSelectionListener(new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
if (wizard.getProject() == null) {
return;
}
try {
SelectionDialog dialog =
JavaUI.createTypeDialog(
getShell(),
null,
wizard.getProject(),
IJavaElementSearchConstants.CONSIDER_CLASSES,
false);
if (dialog.open() == Window.OK) {
if (dialog.getResult() != null && dialog.getResult().length == 1) {
String fqClassName = ((IType) dialog.getResult()[0]).getElementName();
className.setText(fqClassName);
setPageComplete(isPageComplete());
}
}
} catch (JavaModelException e1) {
e1.printStackTrace();
}
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
new Label(group, SWT.NONE)
.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_Application_Class_field);
appClassName = new Text(group, SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
appClassName.setLayoutData(gd);
// appClassName.setText(wizard.getAppClassName());
appClassName.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
wizard.setAppClassName(appClassName.getText());
setPageComplete(isPageComplete());
}
});
btnAppClassBrowse = new Button(group, SWT.PUSH);
btnAppClassBrowse.setText(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_Application_Class_Browse_btn);
btnAppClassBrowse.addSelectionListener(new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
if (wizard.getProject() == null) {
return;
}
try {
SelectionDialog dialog =
JavaUI.createTypeDialog(
getShell(),
null,
wizard.getProject(),
IJavaElementSearchConstants.CONSIDER_CLASSES,
false);
if (dialog.open() == Window.OK) {
if (dialog.getResult() != null && dialog.getResult().length == 1) {
String fqClassName = ((IType) dialog.getResult()[0]).getElementName();
appClassName.setText(fqClassName);
setPageComplete(isPageComplete());
}
}
} catch (JavaModelException e1) {
e1.printStackTrace();
}
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
public void createControl(Composite parent) {
Composite composite = createDialogArea(parent);
this.wizard = (JBossWSAnnotatedClassWizard) this.getWizard();
createWsTechComposite(composite);
createProjectGroup(composite);
createApplicationGroup(composite);
createImplementationGroup(composite);
appClassName.setEnabled(!wizard.isJAXWS());
btnAppClassBrowse.setEnabled(!wizard.isJAXWS());
updateDefaultValues();
setControl(composite);
}
private void refreshProjectList(String projectName) {
String[] projectNames = getProjects();
boolean foundInitialProject = false;
projects.removeAll();
for (int i = 0; i < projectNames.length; i++) {
projects.add(projectNames[i]);
if (projectNames[i].equals(projectName)) {
foundInitialProject = true;
}
}
if (foundInitialProject)
projects.setText(projectName);
}
public IWizardPage getNextPage() {
return super.getNextPage();
}
private Composite createDialogArea(Composite parent) {
// create a composite with standard margins and spacing
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = 7;
layout.marginWidth = 7;
layout.verticalSpacing = 4;
layout.horizontalSpacing = 4;
layout.numColumns = 2;
composite.setLayout(layout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
return composite;
}
@Override
public boolean isPageComplete() {
return validate();
}
private void setWebXMLSelectionValueBasedOnProjectFacet () {
try {
if (((JBossWSAnnotatedClassWizard)this.getWizard()).getProject() == null) {
return;
}
IFacetedProject facetProject =
ProjectFacetsManager.create(((JBossWSAnnotatedClassWizard)this.getWizard()).getProject());
if (facetProject == null) {
// then we're not a dynamic web project, do nothing
return;
}
IProjectFacetVersion version =
facetProject.getProjectFacetVersion(IJ2EEFacetConstants.DYNAMIC_WEB_FACET);
if (version == null) {
// then we're not a dynamic web project, do nothing
return;
}
Double versionDouble = Double.valueOf(version.getVersionString());
if (versionDouble.doubleValue() == 3 || versionDouble.doubleValue() > 3) {
// dynamic web project 3.0, web.xml not needed
updateWebXML.setSelection(false);
} else if (versionDouble.doubleValue() < 3){
// dynamic web project < 3.0
updateWebXML.setSelection(true);
}
} catch (CoreException e1) {
// ignore
} catch (NumberFormatException nfe) {
// ignore
}
}
private boolean validate() {
ServiceModel model = wizard.getServiceModel();
if (wizard.isJAXWS()) {
setMessage(JBossWSUIMessages.JBossWS_GenerateWizard_GenerateWizardPage_Description);
setErrorMessage(null);
JBossWSGenerateWizardValidator.setServiceModel(model);
addJarsIfFound.setEnabled(false);
if (!projects.isDisposed() && projects.getText().length() > 0) {
model.setWebProjectName(projects.getText());
}
if (((JBossWSAnnotatedClassWizard) this.getWizard()).getProject() == null) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoProjectSelected);
return false;
}
try {
IFacetedProject facetProject =
ProjectFacetsManager.create(((JBossWSAnnotatedClassWizard)this.getWizard()).getProject());
if (facetProject == null || facetProject.getProjectFacetVersion(IJ2EEFacetConstants.DYNAMIC_WEB_FACET) == null) {
// then we're not a dynamic web project
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
} catch (CoreException e1) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
// project not a dynamic web project
IFile web = ((JBossWSAnnotatedClassWizard) this.getWizard()).getWebFile();
if (web == null || !web.exists()) {
if (updateWebXML.getSelection()) {
setMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoWebXML,
DialogPage.WARNING);
return true;
}
}
try {
if ("" .equals(JBossWSCreationUtils.getJavaProjectSrcLocation(((JBossWSAnnotatedClassWizard) this.getWizard()).getProject()))) { //$NON-NLS-1$
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoSrcInProject);
return false;
}
} catch (JavaModelException e) {
e.printStackTrace();
}
IStatus status = JBossWSGenerateWizardValidator.isWSNameValid();
if (status != null) {
setErrorMessage(status.getMessage());
return false;
}
IStatus classNameStatus = JBossWSGenerateWizardValidator.isWSClassValid(model
.getCustomClassName(), wizard.getProject());
if (classNameStatus != null) {
if (classNameStatus.getSeverity() == IStatus.ERROR) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
// setErrorMessage(classNameStatus.getMessage());
return true;
} else if (classNameStatus.getSeverity() == IStatus.WARNING) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
}
}
setMessage(JBossWSUIMessages.JBossWS_GenerateWizard_GenerateWizardPage_Description);
setErrorMessage(null);
return true;
} else {
setMessage(JBossWSUIMessages.JBossWS_GenerateWizard_GenerateWizardPage_Description);
setErrorMessage(null);
JBossRSGenerateWizardValidator.setServiceModel(model);
if (!projects.isDisposed() && projects.getText().length() > 0) {
model.setWebProjectName(projects.getText());
}
setErrorMessage(null);
// no project selected
if (((JBossWSAnnotatedClassWizard) this.getWizard()).getProject() == null) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoProjectSelected);
return false;
}
try {
IFacetedProject facetProject =
ProjectFacetsManager.create(((JBossWSAnnotatedClassWizard)this.getWizard()).getProject());
- if (facetProject.getProjectFacetVersion(IJ2EEFacetConstants.DYNAMIC_WEB_FACET) == null) {
+ if (facetProject == null || facetProject.getProjectFacetVersion(IJ2EEFacetConstants.DYNAMIC_WEB_FACET) == null) {
// then we're not a dynamic web project
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
} catch (CoreException e1) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
// project not a dynamic web project
IFile web = ((JBossWSAnnotatedClassWizard) this.getWizard()).getWebFile();
if (web == null || !web.exists()) {
if (updateWebXML.getSelection()) {
setMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoWebXML,
DialogPage.WARNING);
return true;
}
}
IStatus reNoREDirectoryInRuntimeRoot = RestEasyLibUtils.doesRuntimeHaveRootLevelRestEasyDir(
((JBossWSAnnotatedClassWizard) this.getWizard()).getProject());
addJarsIfFound.setEnabled(reNoREDirectoryInRuntimeRoot.getSeverity() == IStatus.OK);
IStatus reInstalledStatus =
RestEasyLibUtils.doesRuntimeSupportRestEasy(((JBossWSAnnotatedClassWizard) this.getWizard()).getProject());
if (reInstalledStatus.getSeverity() != IStatus.OK && !addJarsIfFound.getSelection()){
setMessage(JBossWSUIMessages.JBossRSGenerateWizardPage_Error_RestEasyJarsNotFoundInRuntime, DialogPage.WARNING);
return true;
}
// no source folder in web project
try {
if ("" .equals(JBossWSCreationUtils.getJavaProjectSrcLocation(((JBossWSAnnotatedClassWizard) this.getWizard()).getProject()))) { //$NON-NLS-1$
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoSrcInProject);
return false;
}
} catch (JavaModelException e) {
e.printStackTrace();
}
// already has a REST sample installed - can't use wizard again
if (wizard.getUpdateWebXML()) {
IStatus alreadyHasREST = JBossRSGenerateWizardValidator.RESTAppExists();
if (alreadyHasREST != null) {
if (alreadyHasREST.getSeverity() == IStatus.ERROR) {
setErrorMessage(alreadyHasREST.getMessage());
return false;
} else if (alreadyHasREST.getSeverity() == IStatus.WARNING) {
setMessage(alreadyHasREST.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
}
}
}
// Check the service class name
IStatus classNameStatus = JBossRSGenerateWizardValidator.isWSClassValid(model
.getCustomClassName(), wizard.getProject());
if (classNameStatus != null) {
if (classNameStatus.getSeverity() == IStatus.ERROR) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
// setErrorMessage(classNameStatus.getMessage());
// return false;
} else if (classNameStatus.getSeverity() == IStatus.WARNING) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
}
}
// check the application class name
IStatus appClassNameStatus = JBossRSGenerateWizardValidator.isAppClassNameValid(
model.getCustomPackage() + '.' + model.getApplicationClassName());
if (appClassNameStatus != null) {
if (appClassNameStatus.getSeverity() == IStatus.ERROR) {
setMessage(appClassNameStatus.getMessage(), DialogPage.ERROR);
return false;
} else if (appClassNameStatus.getSeverity() == IStatus.WARNING) {
setMessage(appClassNameStatus.getMessage(), DialogPage.WARNING);
return true;
}
}
}
setMessage(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_PageDescription);
setErrorMessage(null);
return true;
}
private String[] getProjects() {
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
.getProjects();
ArrayList<String> dynamicProjects = new ArrayList<String>();
for (int i = 0; i < projects.length; i++) {
boolean isDynamicWebProject = JavaEEProjectUtilities
.isDynamicWebProject(projects[i]);
if (isDynamicWebProject) {
dynamicProjects.add(projects[i].getName());
}
}
return dynamicProjects.toArray(new String[dynamicProjects.size()]);
}
protected boolean hasChanged() {
return bHasChanged;
}
}
| true | true | private boolean validate() {
ServiceModel model = wizard.getServiceModel();
if (wizard.isJAXWS()) {
setMessage(JBossWSUIMessages.JBossWS_GenerateWizard_GenerateWizardPage_Description);
setErrorMessage(null);
JBossWSGenerateWizardValidator.setServiceModel(model);
addJarsIfFound.setEnabled(false);
if (!projects.isDisposed() && projects.getText().length() > 0) {
model.setWebProjectName(projects.getText());
}
if (((JBossWSAnnotatedClassWizard) this.getWizard()).getProject() == null) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoProjectSelected);
return false;
}
try {
IFacetedProject facetProject =
ProjectFacetsManager.create(((JBossWSAnnotatedClassWizard)this.getWizard()).getProject());
if (facetProject == null || facetProject.getProjectFacetVersion(IJ2EEFacetConstants.DYNAMIC_WEB_FACET) == null) {
// then we're not a dynamic web project
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
} catch (CoreException e1) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
// project not a dynamic web project
IFile web = ((JBossWSAnnotatedClassWizard) this.getWizard()).getWebFile();
if (web == null || !web.exists()) {
if (updateWebXML.getSelection()) {
setMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoWebXML,
DialogPage.WARNING);
return true;
}
}
try {
if ("" .equals(JBossWSCreationUtils.getJavaProjectSrcLocation(((JBossWSAnnotatedClassWizard) this.getWizard()).getProject()))) { //$NON-NLS-1$
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoSrcInProject);
return false;
}
} catch (JavaModelException e) {
e.printStackTrace();
}
IStatus status = JBossWSGenerateWizardValidator.isWSNameValid();
if (status != null) {
setErrorMessage(status.getMessage());
return false;
}
IStatus classNameStatus = JBossWSGenerateWizardValidator.isWSClassValid(model
.getCustomClassName(), wizard.getProject());
if (classNameStatus != null) {
if (classNameStatus.getSeverity() == IStatus.ERROR) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
// setErrorMessage(classNameStatus.getMessage());
return true;
} else if (classNameStatus.getSeverity() == IStatus.WARNING) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
}
}
setMessage(JBossWSUIMessages.JBossWS_GenerateWizard_GenerateWizardPage_Description);
setErrorMessage(null);
return true;
} else {
setMessage(JBossWSUIMessages.JBossWS_GenerateWizard_GenerateWizardPage_Description);
setErrorMessage(null);
JBossRSGenerateWizardValidator.setServiceModel(model);
if (!projects.isDisposed() && projects.getText().length() > 0) {
model.setWebProjectName(projects.getText());
}
setErrorMessage(null);
// no project selected
if (((JBossWSAnnotatedClassWizard) this.getWizard()).getProject() == null) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoProjectSelected);
return false;
}
try {
IFacetedProject facetProject =
ProjectFacetsManager.create(((JBossWSAnnotatedClassWizard)this.getWizard()).getProject());
if (facetProject.getProjectFacetVersion(IJ2EEFacetConstants.DYNAMIC_WEB_FACET) == null) {
// then we're not a dynamic web project
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
} catch (CoreException e1) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
// project not a dynamic web project
IFile web = ((JBossWSAnnotatedClassWizard) this.getWizard()).getWebFile();
if (web == null || !web.exists()) {
if (updateWebXML.getSelection()) {
setMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoWebXML,
DialogPage.WARNING);
return true;
}
}
IStatus reNoREDirectoryInRuntimeRoot = RestEasyLibUtils.doesRuntimeHaveRootLevelRestEasyDir(
((JBossWSAnnotatedClassWizard) this.getWizard()).getProject());
addJarsIfFound.setEnabled(reNoREDirectoryInRuntimeRoot.getSeverity() == IStatus.OK);
IStatus reInstalledStatus =
RestEasyLibUtils.doesRuntimeSupportRestEasy(((JBossWSAnnotatedClassWizard) this.getWizard()).getProject());
if (reInstalledStatus.getSeverity() != IStatus.OK && !addJarsIfFound.getSelection()){
setMessage(JBossWSUIMessages.JBossRSGenerateWizardPage_Error_RestEasyJarsNotFoundInRuntime, DialogPage.WARNING);
return true;
}
// no source folder in web project
try {
if ("" .equals(JBossWSCreationUtils.getJavaProjectSrcLocation(((JBossWSAnnotatedClassWizard) this.getWizard()).getProject()))) { //$NON-NLS-1$
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoSrcInProject);
return false;
}
} catch (JavaModelException e) {
e.printStackTrace();
}
// already has a REST sample installed - can't use wizard again
if (wizard.getUpdateWebXML()) {
IStatus alreadyHasREST = JBossRSGenerateWizardValidator.RESTAppExists();
if (alreadyHasREST != null) {
if (alreadyHasREST.getSeverity() == IStatus.ERROR) {
setErrorMessage(alreadyHasREST.getMessage());
return false;
} else if (alreadyHasREST.getSeverity() == IStatus.WARNING) {
setMessage(alreadyHasREST.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
}
}
}
// Check the service class name
IStatus classNameStatus = JBossRSGenerateWizardValidator.isWSClassValid(model
.getCustomClassName(), wizard.getProject());
if (classNameStatus != null) {
if (classNameStatus.getSeverity() == IStatus.ERROR) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
// setErrorMessage(classNameStatus.getMessage());
// return false;
} else if (classNameStatus.getSeverity() == IStatus.WARNING) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
}
}
// check the application class name
IStatus appClassNameStatus = JBossRSGenerateWizardValidator.isAppClassNameValid(
model.getCustomPackage() + '.' + model.getApplicationClassName());
if (appClassNameStatus != null) {
if (appClassNameStatus.getSeverity() == IStatus.ERROR) {
setMessage(appClassNameStatus.getMessage(), DialogPage.ERROR);
return false;
} else if (appClassNameStatus.getSeverity() == IStatus.WARNING) {
setMessage(appClassNameStatus.getMessage(), DialogPage.WARNING);
return true;
}
}
}
setMessage(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_PageDescription);
setErrorMessage(null);
return true;
}
| private boolean validate() {
ServiceModel model = wizard.getServiceModel();
if (wizard.isJAXWS()) {
setMessage(JBossWSUIMessages.JBossWS_GenerateWizard_GenerateWizardPage_Description);
setErrorMessage(null);
JBossWSGenerateWizardValidator.setServiceModel(model);
addJarsIfFound.setEnabled(false);
if (!projects.isDisposed() && projects.getText().length() > 0) {
model.setWebProjectName(projects.getText());
}
if (((JBossWSAnnotatedClassWizard) this.getWizard()).getProject() == null) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoProjectSelected);
return false;
}
try {
IFacetedProject facetProject =
ProjectFacetsManager.create(((JBossWSAnnotatedClassWizard)this.getWizard()).getProject());
if (facetProject == null || facetProject.getProjectFacetVersion(IJ2EEFacetConstants.DYNAMIC_WEB_FACET) == null) {
// then we're not a dynamic web project
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
} catch (CoreException e1) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
// project not a dynamic web project
IFile web = ((JBossWSAnnotatedClassWizard) this.getWizard()).getWebFile();
if (web == null || !web.exists()) {
if (updateWebXML.getSelection()) {
setMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoWebXML,
DialogPage.WARNING);
return true;
}
}
try {
if ("" .equals(JBossWSCreationUtils.getJavaProjectSrcLocation(((JBossWSAnnotatedClassWizard) this.getWizard()).getProject()))) { //$NON-NLS-1$
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoSrcInProject);
return false;
}
} catch (JavaModelException e) {
e.printStackTrace();
}
IStatus status = JBossWSGenerateWizardValidator.isWSNameValid();
if (status != null) {
setErrorMessage(status.getMessage());
return false;
}
IStatus classNameStatus = JBossWSGenerateWizardValidator.isWSClassValid(model
.getCustomClassName(), wizard.getProject());
if (classNameStatus != null) {
if (classNameStatus.getSeverity() == IStatus.ERROR) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
// setErrorMessage(classNameStatus.getMessage());
return true;
} else if (classNameStatus.getSeverity() == IStatus.WARNING) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
}
}
setMessage(JBossWSUIMessages.JBossWS_GenerateWizard_GenerateWizardPage_Description);
setErrorMessage(null);
return true;
} else {
setMessage(JBossWSUIMessages.JBossWS_GenerateWizard_GenerateWizardPage_Description);
setErrorMessage(null);
JBossRSGenerateWizardValidator.setServiceModel(model);
if (!projects.isDisposed() && projects.getText().length() > 0) {
model.setWebProjectName(projects.getText());
}
setErrorMessage(null);
// no project selected
if (((JBossWSAnnotatedClassWizard) this.getWizard()).getProject() == null) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoProjectSelected);
return false;
}
try {
IFacetedProject facetProject =
ProjectFacetsManager.create(((JBossWSAnnotatedClassWizard)this.getWizard()).getProject());
if (facetProject == null || facetProject.getProjectFacetVersion(IJ2EEFacetConstants.DYNAMIC_WEB_FACET) == null) {
// then we're not a dynamic web project
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
} catch (CoreException e1) {
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NotDynamicWebProject2);
return false;
}
// project not a dynamic web project
IFile web = ((JBossWSAnnotatedClassWizard) this.getWizard()).getWebFile();
if (web == null || !web.exists()) {
if (updateWebXML.getSelection()) {
setMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoWebXML,
DialogPage.WARNING);
return true;
}
}
IStatus reNoREDirectoryInRuntimeRoot = RestEasyLibUtils.doesRuntimeHaveRootLevelRestEasyDir(
((JBossWSAnnotatedClassWizard) this.getWizard()).getProject());
addJarsIfFound.setEnabled(reNoREDirectoryInRuntimeRoot.getSeverity() == IStatus.OK);
IStatus reInstalledStatus =
RestEasyLibUtils.doesRuntimeSupportRestEasy(((JBossWSAnnotatedClassWizard) this.getWizard()).getProject());
if (reInstalledStatus.getSeverity() != IStatus.OK && !addJarsIfFound.getSelection()){
setMessage(JBossWSUIMessages.JBossRSGenerateWizardPage_Error_RestEasyJarsNotFoundInRuntime, DialogPage.WARNING);
return true;
}
// no source folder in web project
try {
if ("" .equals(JBossWSCreationUtils.getJavaProjectSrcLocation(((JBossWSAnnotatedClassWizard) this.getWizard()).getProject()))) { //$NON-NLS-1$
setErrorMessage(JBossWSUIMessages.Error_JBossWS_GenerateWizard_NoSrcInProject);
return false;
}
} catch (JavaModelException e) {
e.printStackTrace();
}
// already has a REST sample installed - can't use wizard again
if (wizard.getUpdateWebXML()) {
IStatus alreadyHasREST = JBossRSGenerateWizardValidator.RESTAppExists();
if (alreadyHasREST != null) {
if (alreadyHasREST.getSeverity() == IStatus.ERROR) {
setErrorMessage(alreadyHasREST.getMessage());
return false;
} else if (alreadyHasREST.getSeverity() == IStatus.WARNING) {
setMessage(alreadyHasREST.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
}
}
}
// Check the service class name
IStatus classNameStatus = JBossRSGenerateWizardValidator.isWSClassValid(model
.getCustomClassName(), wizard.getProject());
if (classNameStatus != null) {
if (classNameStatus.getSeverity() == IStatus.ERROR) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
// setErrorMessage(classNameStatus.getMessage());
// return false;
} else if (classNameStatus.getSeverity() == IStatus.WARNING) {
setMessage(classNameStatus.getMessage(), DialogPage.WARNING);
setErrorMessage(null);
return true;
}
}
// check the application class name
IStatus appClassNameStatus = JBossRSGenerateWizardValidator.isAppClassNameValid(
model.getCustomPackage() + '.' + model.getApplicationClassName());
if (appClassNameStatus != null) {
if (appClassNameStatus.getSeverity() == IStatus.ERROR) {
setMessage(appClassNameStatus.getMessage(), DialogPage.ERROR);
return false;
} else if (appClassNameStatus.getSeverity() == IStatus.WARNING) {
setMessage(appClassNameStatus.getMessage(), DialogPage.WARNING);
return true;
}
}
}
setMessage(JBossWSUIMessages.JBossWSAnnotatedClassWizardPage_PageDescription);
setErrorMessage(null);
return true;
}
|
diff --git a/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java b/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java
index eb68dcb7a..bab0d7281 100644
--- a/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java
+++ b/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java
@@ -1,684 +1,688 @@
/*
* Copyright 2013 Jeanfrancois Arcand
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.websocket;
import org.atmosphere.config.service.Singleton;
import org.atmosphere.config.service.WebSocketHandlerService;
import org.atmosphere.cpr.Action;
import org.atmosphere.cpr.AsynchronousProcessor;
import org.atmosphere.cpr.AtmosphereConfig;
import org.atmosphere.cpr.AtmosphereFramework;
import org.atmosphere.cpr.AtmosphereMappingException;
import org.atmosphere.cpr.AtmosphereRequest;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEventImpl;
import org.atmosphere.cpr.AtmosphereResourceEventListener;
import org.atmosphere.cpr.AtmosphereResourceFactory;
import org.atmosphere.cpr.AtmosphereResourceImpl;
import org.atmosphere.cpr.AtmosphereResponse;
import org.atmosphere.cpr.HeaderConfig;
import org.atmosphere.util.DefaultEndpointMapper;
import org.atmosphere.util.EndpointMapper;
import org.atmosphere.util.ExecutorsFactory;
import org.atmosphere.util.VoidExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.atmosphere.cpr.ApplicationConfig.RECYCLE_ATMOSPHERE_REQUEST_RESPONSE;
import static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;
import static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROTOCOL_EXECUTION;
import static org.atmosphere.cpr.FrameworkConfig.ASYNCHRONOUS_HOOK;
import static org.atmosphere.cpr.FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE;
import static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.CLOSE;
import static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.CONNECT;
import static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.MESSAGE;
/**
* Like the {@link org.atmosphere.cpr.AsynchronousProcessor} class, this class is responsible for dispatching WebSocket request to the
* proper {@link org.atmosphere.websocket.WebSocket} implementation. This class can be extended in order to support any protocol
* running on top websocket.
*
* @author Jeanfrancois Arcand
*/
public class DefaultWebSocketProcessor implements WebSocketProcessor, Serializable {
private static final Logger logger = LoggerFactory.getLogger(DefaultWebSocketProcessor.class);
private final AtmosphereFramework framework;
private final WebSocketProtocol webSocketProtocol;
private final AtomicBoolean loggedMsg = new AtomicBoolean(false);
private final boolean destroyable;
private final boolean executeAsync;
private ExecutorService asyncExecutor;
private ScheduledExecutorService scheduler;
private final Map<String, WebSocketHandler> handlers = new ConcurrentHashMap<String, WebSocketHandler>();
private final EndpointMapper<WebSocketHandler> mapper = new DefaultEndpointMapper<WebSocketHandler>();
private boolean wildcardMapping = false;
// 2MB - like maxPostSize
private int byteBufferMaxSize = 2097152;
private int charBufferMaxSize = 2097152;
public DefaultWebSocketProcessor(AtmosphereFramework framework) {
this.framework = framework;
this.webSocketProtocol = framework.getWebSocketProtocol();
String s = framework.getAtmosphereConfig().getInitParameter(RECYCLE_ATMOSPHERE_REQUEST_RESPONSE);
if (s != null && Boolean.valueOf(s)) {
destroyable = true;
} else {
destroyable = false;
}
s = framework.getAtmosphereConfig().getInitParameter(WEBSOCKET_PROTOCOL_EXECUTION);
if (s != null && Boolean.valueOf(s)) {
executeAsync = true;
} else {
executeAsync = false;
}
AtmosphereConfig config = framework.getAtmosphereConfig();
if (executeAsync) {
asyncExecutor = ExecutorsFactory.getAsyncOperationExecutor(config, "WebSocket");
} else {
asyncExecutor = VoidExecutorService.VOID;
}
scheduler = ExecutorsFactory.getScheduler(config);
optimizeMapping();
}
@Override
public boolean handshake(HttpServletRequest request) {
if (request != null) {
logger.trace("Processing request {}", request);
}
return true;
}
@Override
public WebSocketProcessor registerWebSocketHandler(String path, WebSocketHandler webSockethandler) {
handlers.put(path, webSockethandler);
return this;
}
@Override
public final void open(final WebSocket webSocket, final AtmosphereRequest request, final AtmosphereResponse response) throws IOException {
if (!loggedMsg.getAndSet(true)) {
logger.debug("Atmosphere detected WebSocket: {}", webSocket.getClass().getName());
}
// TODO: Fix this. Instead add an Interceptor.
if (framework.getAtmosphereConfig().handlers().size() == 0) {
framework.addAtmosphereHandler("/*", AtmosphereFramework.REFLECTOR_ATMOSPHEREHANDLER);
}
request.headers(configureHeader(request)).setAttribute(WebSocket.WEBSOCKET_SUSPEND, true);
AtmosphereResource r = AtmosphereResourceFactory.getDefault().create(framework.getAtmosphereConfig(),
response,
framework.getAsyncSupport());
request.setAttribute(INJECTED_ATMOSPHERE_RESOURCE, r);
request.setAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID, r.uuid());
webSocket.resource(r);
webSocketProtocol.onOpen(webSocket);
// We must dispatch to execute AtmosphereInterceptor
dispatch(webSocket, request, response);
if (handlers.size() != 0) {
WebSocketHandler handler = mapper.map(request, handlers);
if (handler == null) {
logger.debug("No WebSocketHandler maps request for {} with mapping {}", request.getRequestURI(), handlers);
throw new AtmosphereMappingException("No AtmosphereHandler maps request for " + request.getRequestURI());
}
handler = postProcessMapping(webSocket, request, handler);
// Force suspend.
webSocket.webSocketHandler(handler).resource().suspend(-1);
handler.onOpen(webSocket);
}
request.removeAttribute(INJECTED_ATMOSPHERE_RESOURCE);
if (webSocket.resource() != null) {
final AsynchronousProcessor.AsynchronousProcessorHook hook =
new AsynchronousProcessor.AsynchronousProcessorHook((AtmosphereResourceImpl) webSocket.resource());
request.setAttribute(ASYNCHRONOUS_HOOK, hook);
final Action action = ((AtmosphereResourceImpl) webSocket.resource()).action();
if (action.timeout() != -1 && !framework.getAsyncSupport().getContainerName().contains("Netty")) {
final AtomicReference<Future<?>> f = new AtomicReference();
f.set(scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (WebSocket.class.isAssignableFrom(webSocket.getClass())
&& System.currentTimeMillis() - WebSocket.class.cast(webSocket).lastWriteTimeStampInMilliseconds() > action.timeout()) {
hook.timedOut();
f.get().cancel(true);
}
}
}, action.timeout(), action.timeout(), TimeUnit.MILLISECONDS));
}
} else {
logger.warn("AtmosphereResource was null");
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent("", CONNECT, webSocket));
}
protected WebSocketHandler postProcessMapping(WebSocket webSocket, AtmosphereRequest request, WebSocketHandler w) {
if (!wildcardMapping()) return w;
String path;
String pathInfo = null;
try {
pathInfo = request.getPathInfo();
} catch (IllegalStateException ex) {
// http://java.net/jira/browse/GRIZZLY-1301
}
if (pathInfo != null) {
path = request.getServletPath() + pathInfo;
} else {
path = request.getServletPath();
}
if (path == null || path.isEmpty()) {
path = "/";
}
synchronized (handlers) {
if (handlers.get(path) == null) {
// AtmosphereHandlerService
if (w.getClass().getAnnotation(WebSocketHandlerService.class) != null) {
String targetPath = w.getClass().getAnnotation(WebSocketHandlerService.class).path();
if (targetPath.indexOf("{") != -1 && targetPath.indexOf("}") != -1) {
try {
boolean singleton = w.getClass().getAnnotation(Singleton.class) != null;
if (!singleton) {
registerWebSocketHandler(path, framework.newClassInstance(w.getClass()));
} else {
registerWebSocketHandler(path, w);
}
w = handlers.get(path);
} catch (Throwable e) {
logger.warn("Unable to create WebSocketHandler", e);
}
}
}
}
}
webSocket.resource().setBroadcaster(framework.getBroadcasterFactory().lookup(path, true));
return w;
}
private void dispatch(final WebSocket webSocket, List<AtmosphereRequest> list) {
if (list == null) return;
for (final AtmosphereRequest r : list) {
if (r != null) {
boolean b = r.dispatchRequestAsynchronously();
asyncExecutor.execute(new Runnable() {
@Override
public void run() {
AtmosphereResponse w = new AtmosphereResponse(webSocket, r, destroyable);
try {
dispatch(webSocket, r, w);
} finally {
r.destroy();
w.destroy();
}
}
});
}
}
}
@Override
public void invokeWebSocketProtocol(final WebSocket webSocket, String webSocketMessage) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
if (webSocketHandler == null) {
if (!WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = webSocketProtocol.onMessage(webSocket, webSocketMessage);
dispatch(webSocket, list);
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new StringReader(webSocketMessage));
return;
}
} else {
if (!WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
try {
webSocketHandler.onTextMessage(webSocket, webSocketMessage);
} catch (Exception ex) {
handleException(ex, webSocket, webSocketHandler);
}
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new StringReader(webSocketMessage));
return;
}
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent(webSocketMessage, MESSAGE, webSocket));
}
@Override
public void invokeWebSocketProtocol(WebSocket webSocket, byte[] data, int offset, int length) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
if (webSocketHandler == null) {
if (!WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = webSocketProtocol.onMessage(webSocket, data, offset, length);
dispatch(webSocket, list);
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new ByteArrayInputStream(data, offset, length));
return;
}
} else {
if (!WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
try {
webSocketHandler.onByteMessage(webSocket, data, offset, length);
} catch (Exception ex) {
handleException(ex, webSocket, webSocketHandler);
}
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new ByteArrayInputStream(data, offset, length));
return;
}
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent<byte[]>(data, MESSAGE, webSocket));
}
private void handleException(Exception ex, WebSocket webSocket, WebSocketHandler webSocketHandler) {
logger.error("", ex);
AtmosphereResource r = webSocket.resource();
webSocketHandler.onError(webSocket, new WebSocketException(ex,
new AtmosphereResponse.Builder()
.request(r != null ? AtmosphereResourceImpl.class.cast(r).getRequest(false) : null)
.status(500)
.statusMessage("Server Error").build()));
}
@Override
public void invokeWebSocketProtocol(WebSocket webSocket, InputStream stream) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
try {
if (webSocketHandler == null) {
if (WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = WebSocketProtocolStream.class.cast(webSocketProtocol).onBinaryStream(webSocket, stream);
dispatch(webSocket, list);
} else {
dispatchStream(webSocket, stream);
return;
}
} else {
if (WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
WebSocketStreamingHandler.class.cast(webSocketHandler).onBinaryStream(webSocket, stream);
} else {
dispatchStream(webSocket, stream);
return;
}
}
} catch (Exception ex) {
handleException(ex, webSocket, webSocketHandler);
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent<InputStream>(stream, MESSAGE, webSocket));
}
@Override
public void invokeWebSocketProtocol(WebSocket webSocket, Reader reader) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
try {
if (webSocketHandler == null) {
if (WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = WebSocketProtocolStream.class.cast(webSocketProtocol).onTextStream(webSocket, reader);
dispatch(webSocket, list);
} else {
dispatchReader(webSocket, reader);
return;
}
} else {
if (WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
WebSocketStreamingHandler.class.cast(webSocketHandler).onTextStream(webSocket, reader);
} else {
dispatchReader(webSocket, reader);
return;
}
}
} catch (Exception ex) {
handleException(ex, webSocket, webSocketHandler);
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent<Reader>(reader, MESSAGE, webSocket));
}
/**
* Dispatch to request/response to the {@link org.atmosphere.cpr.AsyncSupport} implementation as it was a normal HTTP request.
*
* @param request a {@link AtmosphereRequest}
* @param r a {@link AtmosphereResponse}
*/
public final void dispatch(WebSocket webSocket, final AtmosphereRequest request, final AtmosphereResponse r) {
if (request == null) return;
try {
framework.doCometSupport(request, r);
} catch (Throwable e) {
logger.warn("Failed invoking AtmosphereFramework.doCometSupport()", e);
webSocketProtocol.onError(webSocket, new WebSocketException(e,
new AtmosphereResponse.Builder()
.request(request)
.status(500)
.statusMessage("Server Error").build()));
return;
}
if (r.getStatus() >= 400) {
webSocketProtocol.onError(webSocket, new WebSocketException("Status code higher or equal than 400", r));
}
}
@Override
public void close(WebSocket webSocket, int closeCode) {
logger.trace("WebSocket closed with {}", closeCode);
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
// A message might be in the process of being processed and the websocket gets closed. In that corner
// case the webSocket.resource will be set to false and that might cause NPE in some WebSocketProcol implementation
// We could potentially synchronize on webSocket but since it is a rare case, it is better to not synchronize.
// synchronized (webSocket) {
closeCode = closeCode(closeCode);
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent(closeCode, CLOSE, webSocket));
AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
if (resource == null) {
logger.warn("Unable to retrieve AtmosphereResource for {}", webSocket);
} else {
AtmosphereRequest r = resource.getRequest(false);
AtmosphereResponse s = resource.getResponse(false);
try {
webSocketProtocol.onClose(webSocket);
if (resource != null && resource.isInScope()) {
if (webSocketHandler != null) {
webSocketHandler.onClose(webSocket);
}
- AsynchronousProcessor.AsynchronousProcessorHook h = (AsynchronousProcessor.AsynchronousProcessorHook)
- r.getAttribute(ASYNCHRONOUS_HOOK);
- if (!resource.isCancelled() && h != null) {
- if (closeCode == 1005) {
- h.closed();
- } else {
- h.timedOut();
- }
+ Object o = r.getAttribute(ASYNCHRONOUS_HOOK);
+ AsynchronousProcessor.AsynchronousProcessorHook h;
+ if (o != null && AsynchronousProcessor.class.isAssignableFrom(o.getClass())) {
+ h = (AsynchronousProcessor.AsynchronousProcessorHook)
+ r.getAttribute(ASYNCHRONOUS_HOOK);
+ if (!resource.isCancelled()) {
+ if (closeCode == 1005) {
+ h.closed();
+ } else {
+ h.timedOut();
+ }
- resource.setIsInScope(false);
- try {
- resource.cancel();
- } catch (IOException e) {
- logger.trace("", e);
+ resource.setIsInScope(false);
+ try {
+ resource.cancel();
+ } catch (IOException e) {
+ logger.trace("", e);
+ }
}
+ AtmosphereResourceImpl.class.cast(resource)._destroy();
}
- AtmosphereResourceImpl.class.cast(resource)._destroy();
}
} finally {
if (r != null) {
r.destroy(true);
}
if (s != null) {
s.destroy(true);
}
if (webSocket != null) {
try {
webSocket.resource(null).close(s);
} catch (IOException e) {
logger.trace("", e);
}
}
}
}
}
@Override
public void destroy() {
boolean shared = framework.isShareExecutorServices();
if (asyncExecutor != null && !shared) {
asyncExecutor.shutdown();
}
if (scheduler != null && !shared) {
scheduler.shutdown();
}
}
private int closeCode(int closeCode) {
// Tomcat and Jetty differ, same with browser
if (closeCode == 1000 && framework.getAsyncSupport().getContainerName().contains("Tomcat")) {
closeCode = 1005;
}
return closeCode;
}
@Override
public void notifyListener(WebSocket webSocket, WebSocketEventListener.WebSocketEvent event) {
AtmosphereResource resource = webSocket.resource();
if (resource == null) return;
AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(resource);
for (AtmosphereResourceEventListener l : r.atmosphereResourceEventListener()) {
if (WebSocketEventListener.class.isAssignableFrom(l.getClass())) {
try {
switch (event.type()) {
case CONNECT:
WebSocketEventListener.class.cast(l).onConnect(event);
break;
case DISCONNECT:
WebSocketEventListener.class.cast(l).onDisconnect(event);
break;
case CONTROL:
WebSocketEventListener.class.cast(l).onControl(event);
break;
case MESSAGE:
WebSocketEventListener.class.cast(l).onMessage(event);
break;
case HANDSHAKE:
WebSocketEventListener.class.cast(l).onHandshake(event);
break;
case CLOSE:
boolean isClosedByClient = r.getAtmosphereResourceEvent().isClosedByClient();
l.onDisconnect(new AtmosphereResourceEventImpl(r, !isClosedByClient, false, isClosedByClient, null));
WebSocketEventListener.class.cast(l).onDisconnect(event);
WebSocketEventListener.class.cast(l).onClose(event);
break;
}
} catch (Throwable t) {
logger.debug("Listener error {}", t);
try {
WebSocketEventListener.class.cast(l).onThrowable(new AtmosphereResourceEventImpl(r, false, false, t));
} catch (Throwable t2) {
logger.warn("Listener error {}", t2);
}
}
}
}
}
public static final Map<String, String> configureHeader(AtmosphereRequest request) {
Map<String, String> headers = new HashMap<String, String>();
Enumeration<String> e = request.getParameterNames();
String s;
while (e.hasMoreElements()) {
s = e.nextElement();
headers.put(s, request.getParameter(s));
}
headers.put(HeaderConfig.X_ATMOSPHERE_TRANSPORT, HeaderConfig.WEBSOCKET_TRANSPORT);
return headers;
}
protected void dispatchStream(WebSocket webSocket, InputStream is) throws IOException {
int read = 0;
ByteBuffer bb = webSocket.bb;
while (read > -1) {
bb.position(bb.position() + read);
if (bb.remaining() == 0) {
resizeByteBuffer(webSocket);
}
read = is.read(bb.array(), bb.position(), bb.remaining());
}
bb.flip();
try {
invokeWebSocketProtocol(webSocket, bb.array(), 0, bb.limit());
} finally {
bb.clear();
}
}
protected void dispatchReader(WebSocket webSocket, Reader r) throws IOException {
int read = 0;
CharBuffer cb = webSocket.cb;
while (read > -1) {
cb.position(cb.position() + read);
if (cb.remaining() == 0) {
resizeCharBuffer(webSocket);
}
read = r.read(cb.array(), cb.position(), cb.remaining());
}
cb.flip();
try {
invokeWebSocketProtocol(webSocket, cb.toString());
} finally {
cb.clear();
}
}
private void resizeByteBuffer(WebSocket webSocket) throws IOException {
int maxSize = getByteBufferMaxSize();
ByteBuffer bb = webSocket.bb;
if (bb.limit() >= maxSize) {
throw new IOException("Message Buffer too small");
}
long newSize = bb.limit() * 2;
if (newSize > maxSize) {
newSize = maxSize;
}
// Cast is safe. newSize < maxSize and maxSize is an int
ByteBuffer newBuffer = ByteBuffer.allocate((int) newSize);
bb.rewind();
newBuffer.put(bb);
webSocket.bb = newBuffer;
}
private void resizeCharBuffer(WebSocket webSocket) throws IOException {
int maxSize = getCharBufferMaxSize();
CharBuffer cb = webSocket.cb;
if (cb.limit() >= maxSize) {
throw new IOException("Message Buffer too small");
}
long newSize = cb.limit() * 2;
if (newSize > maxSize) {
newSize = maxSize;
}
// Cast is safe. newSize < maxSize and maxSize is an int
CharBuffer newBuffer = CharBuffer.allocate((int) newSize);
cb.rewind();
newBuffer.put(cb);
webSocket.cb = newBuffer;
}
/**
* Obtain the current maximum size (in bytes) of the buffer used for binary
* messages.
*/
public final int getByteBufferMaxSize() {
return byteBufferMaxSize;
}
/**
* Set the maximum size (in bytes) of the buffer used for binary messages.
*/
public final void setByteBufferMaxSize(int byteBufferMaxSize) {
this.byteBufferMaxSize = byteBufferMaxSize;
}
/**
* Obtain the current maximum size (in characters) of the buffer used for
* binary messages.
*/
public final int getCharBufferMaxSize() {
return charBufferMaxSize;
}
/**
* Set the maximum size (in characters) of the buffer used for textual
* messages.
*/
public final void setCharBufferMaxSize(int charBufferMaxSize) {
this.charBufferMaxSize = charBufferMaxSize;
}
protected void optimizeMapping() {
for (String w : framework.getAtmosphereConfig().handlers().keySet()) {
if (w.contains("{") && w.contains("}")) {
wildcardMapping = true;
}
}
}
public boolean wildcardMapping() {
return wildcardMapping;
}
}
| false | true | public void close(WebSocket webSocket, int closeCode) {
logger.trace("WebSocket closed with {}", closeCode);
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
// A message might be in the process of being processed and the websocket gets closed. In that corner
// case the webSocket.resource will be set to false and that might cause NPE in some WebSocketProcol implementation
// We could potentially synchronize on webSocket but since it is a rare case, it is better to not synchronize.
// synchronized (webSocket) {
closeCode = closeCode(closeCode);
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent(closeCode, CLOSE, webSocket));
AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
if (resource == null) {
logger.warn("Unable to retrieve AtmosphereResource for {}", webSocket);
} else {
AtmosphereRequest r = resource.getRequest(false);
AtmosphereResponse s = resource.getResponse(false);
try {
webSocketProtocol.onClose(webSocket);
if (resource != null && resource.isInScope()) {
if (webSocketHandler != null) {
webSocketHandler.onClose(webSocket);
}
AsynchronousProcessor.AsynchronousProcessorHook h = (AsynchronousProcessor.AsynchronousProcessorHook)
r.getAttribute(ASYNCHRONOUS_HOOK);
if (!resource.isCancelled() && h != null) {
if (closeCode == 1005) {
h.closed();
} else {
h.timedOut();
}
resource.setIsInScope(false);
try {
resource.cancel();
} catch (IOException e) {
logger.trace("", e);
}
}
AtmosphereResourceImpl.class.cast(resource)._destroy();
}
} finally {
if (r != null) {
r.destroy(true);
}
if (s != null) {
s.destroy(true);
}
if (webSocket != null) {
try {
webSocket.resource(null).close(s);
} catch (IOException e) {
logger.trace("", e);
}
}
}
}
}
| public void close(WebSocket webSocket, int closeCode) {
logger.trace("WebSocket closed with {}", closeCode);
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
// A message might be in the process of being processed and the websocket gets closed. In that corner
// case the webSocket.resource will be set to false and that might cause NPE in some WebSocketProcol implementation
// We could potentially synchronize on webSocket but since it is a rare case, it is better to not synchronize.
// synchronized (webSocket) {
closeCode = closeCode(closeCode);
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent(closeCode, CLOSE, webSocket));
AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
if (resource == null) {
logger.warn("Unable to retrieve AtmosphereResource for {}", webSocket);
} else {
AtmosphereRequest r = resource.getRequest(false);
AtmosphereResponse s = resource.getResponse(false);
try {
webSocketProtocol.onClose(webSocket);
if (resource != null && resource.isInScope()) {
if (webSocketHandler != null) {
webSocketHandler.onClose(webSocket);
}
Object o = r.getAttribute(ASYNCHRONOUS_HOOK);
AsynchronousProcessor.AsynchronousProcessorHook h;
if (o != null && AsynchronousProcessor.class.isAssignableFrom(o.getClass())) {
h = (AsynchronousProcessor.AsynchronousProcessorHook)
r.getAttribute(ASYNCHRONOUS_HOOK);
if (!resource.isCancelled()) {
if (closeCode == 1005) {
h.closed();
} else {
h.timedOut();
}
resource.setIsInScope(false);
try {
resource.cancel();
} catch (IOException e) {
logger.trace("", e);
}
}
AtmosphereResourceImpl.class.cast(resource)._destroy();
}
}
} finally {
if (r != null) {
r.destroy(true);
}
if (s != null) {
s.destroy(true);
}
if (webSocket != null) {
try {
webSocket.resource(null).close(s);
} catch (IOException e) {
logger.trace("", e);
}
}
}
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/CheckboxMultiSelectAttributeEditor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/CheckboxMultiSelectAttributeEditor.java
index b42792bb8..fad9c2a27 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/CheckboxMultiSelectAttributeEditor.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/CheckboxMultiSelectAttributeEditor.java
@@ -1,189 +1,197 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
* Pawel Niewiadomski - fix for bug 287832
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.editors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.provisional.commons.ui.WorkbenchUtil;
import org.eclipse.mylyn.internal.provisional.commons.ui.dialogs.IInPlaceDialogCloseListener;
import org.eclipse.mylyn.internal.provisional.commons.ui.dialogs.InPlaceCheckBoxTreeDialog;
import org.eclipse.mylyn.internal.provisional.commons.ui.dialogs.InPlaceDialogCloseEvent;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
import org.eclipse.mylyn.tasks.ui.editors.AbstractAttributeEditor;
import org.eclipse.mylyn.tasks.ui.editors.LayoutHint;
import org.eclipse.mylyn.tasks.ui.editors.LayoutHint.ColumnSpan;
import org.eclipse.mylyn.tasks.ui.editors.LayoutHint.RowSpan;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.SharedScrolledComposite;
/**
* @author Shawn Minto
*/
public class CheckboxMultiSelectAttributeEditor extends AbstractAttributeEditor {
private Text valueText;
private Composite parent;
public CheckboxMultiSelectAttributeEditor(TaskDataModel manager, TaskAttribute taskAttribute) {
super(manager, taskAttribute);
setLayoutHint(new LayoutHint(RowSpan.SINGLE, ColumnSpan.MULTIPLE));
}
@Override
public void createControl(Composite parent, FormToolkit toolkit) {
this.parent = parent;
Composite composite = toolkit.createComposite(parent);
+ composite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
GridLayout layout = new GridLayout(2, false);
- layout.marginWidth = 1;
+ layout.marginWidth = 0;
+ layout.marginBottom = 0;
+ layout.marginLeft = 0;
+ layout.marginRight = 0;
+ layout.marginTop = 0;
+ layout.marginHeight = 0;
composite.setLayout(layout);
valueText = toolkit.createText(composite, "", SWT.FLAT | SWT.WRAP); //$NON-NLS-1$
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(valueText);
valueText.setFont(EditorUtil.TEXT_FONT);
valueText.setEditable(false);
final ToolBar toolBar = new ToolBar(composite, SWT.FLAT);
ToolItem item = new ToolItem(toolBar, SWT.FLAT);
item.setImage(CommonImages.getImage(CommonImages.EDIT_SMALL));
+ item.setToolTipText(Messages.CheckboxMultiSelectAttributeEditor_Edit);
+ GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.BOTTOM).applyTo(toolBar);
item.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final List<String> values = getValues();
Map<String, String> validValues = getAttributeMapper().getOptions(getTaskAttribute());
final InPlaceCheckBoxTreeDialog selectionDialog = new InPlaceCheckBoxTreeDialog(
WorkbenchUtil.getShell(), toolBar, values, validValues, NLS.bind(
Messages.CheckboxMultiSelectAttributeEditor_Select_X, getLabel()));
selectionDialog.addCloseListener(new IInPlaceDialogCloseListener() {
public void dialogClosing(InPlaceDialogCloseEvent event) {
if (event.getReturnCode() == Window.OK) {
Set<String> newValues = selectionDialog.getSelectedValues();
if (!new HashSet<String>(values).equals(newValues)) {
setValues(new ArrayList<String>(newValues));
attributeChanged();
updateText();
}
}
}
});
selectionDialog.open();
}
});
toolkit.adapt(valueText, false, false);
updateText();
setControl(composite);
}
private void updateText() {
if (valueText != null && !valueText.isDisposed()) {
StringBuilder valueString = new StringBuilder();
List<String> values = getValuesLabels();
Collections.sort(values);
for (int i = 0; i < values.size(); i++) {
valueString.append(values.get(i));
if (i != values.size() - 1) {
valueString.append(", "); //$NON-NLS-1$
}
}
valueText.setText(valueString.toString());
if (valueText != null && parent != null && parent.getParent() != null
&& parent.getParent().getParent() != null) {
Point size = valueText.getSize();
// subtract 1 from size for border
Point newSize = valueText.computeSize(size.x - 1, SWT.DEFAULT);
if (newSize.y != size.y) {
reflow();
}
}
}
}
/**
* Update scroll bars of the enclosing form.
*
* @see Section#reflow()
*/
private void reflow() {
Composite c = parent;
while (c != null) {
c.setRedraw(false);
c = c.getParent();
if (c instanceof SharedScrolledComposite || c instanceof Shell) {
break;
}
}
c = parent;
while (c != null) {
c.layout(true);
c = c.getParent();
if (c instanceof SharedScrolledComposite) {
((SharedScrolledComposite) c).reflow(true);
break;
}
}
c = parent;
while (c != null) {
c.setRedraw(true);
c = c.getParent();
if (c instanceof SharedScrolledComposite || c instanceof Shell) {
break;
}
}
}
public List<String> getValues() {
return getAttributeMapper().getValues(getTaskAttribute());
}
public List<String> getValuesLabels() {
return getAttributeMapper().getValueLabels(getTaskAttribute());
}
public void setValues(List<String> newValues) {
getAttributeMapper().setValues(getTaskAttribute(), newValues);
attributeChanged();
}
@Override
protected void decorateIncoming(Color color) {
if (valueText != null && !valueText.isDisposed()) {
valueText.setBackground(color);
}
}
}
| false | true | public void createControl(Composite parent, FormToolkit toolkit) {
this.parent = parent;
Composite composite = toolkit.createComposite(parent);
GridLayout layout = new GridLayout(2, false);
layout.marginWidth = 1;
composite.setLayout(layout);
valueText = toolkit.createText(composite, "", SWT.FLAT | SWT.WRAP); //$NON-NLS-1$
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(valueText);
valueText.setFont(EditorUtil.TEXT_FONT);
valueText.setEditable(false);
final ToolBar toolBar = new ToolBar(composite, SWT.FLAT);
ToolItem item = new ToolItem(toolBar, SWT.FLAT);
item.setImage(CommonImages.getImage(CommonImages.EDIT_SMALL));
item.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final List<String> values = getValues();
Map<String, String> validValues = getAttributeMapper().getOptions(getTaskAttribute());
final InPlaceCheckBoxTreeDialog selectionDialog = new InPlaceCheckBoxTreeDialog(
WorkbenchUtil.getShell(), toolBar, values, validValues, NLS.bind(
Messages.CheckboxMultiSelectAttributeEditor_Select_X, getLabel()));
selectionDialog.addCloseListener(new IInPlaceDialogCloseListener() {
public void dialogClosing(InPlaceDialogCloseEvent event) {
if (event.getReturnCode() == Window.OK) {
Set<String> newValues = selectionDialog.getSelectedValues();
if (!new HashSet<String>(values).equals(newValues)) {
setValues(new ArrayList<String>(newValues));
attributeChanged();
updateText();
}
}
}
});
selectionDialog.open();
}
});
toolkit.adapt(valueText, false, false);
updateText();
setControl(composite);
}
| public void createControl(Composite parent, FormToolkit toolkit) {
this.parent = parent;
Composite composite = toolkit.createComposite(parent);
composite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
GridLayout layout = new GridLayout(2, false);
layout.marginWidth = 0;
layout.marginBottom = 0;
layout.marginLeft = 0;
layout.marginRight = 0;
layout.marginTop = 0;
layout.marginHeight = 0;
composite.setLayout(layout);
valueText = toolkit.createText(composite, "", SWT.FLAT | SWT.WRAP); //$NON-NLS-1$
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(valueText);
valueText.setFont(EditorUtil.TEXT_FONT);
valueText.setEditable(false);
final ToolBar toolBar = new ToolBar(composite, SWT.FLAT);
ToolItem item = new ToolItem(toolBar, SWT.FLAT);
item.setImage(CommonImages.getImage(CommonImages.EDIT_SMALL));
item.setToolTipText(Messages.CheckboxMultiSelectAttributeEditor_Edit);
GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.BOTTOM).applyTo(toolBar);
item.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final List<String> values = getValues();
Map<String, String> validValues = getAttributeMapper().getOptions(getTaskAttribute());
final InPlaceCheckBoxTreeDialog selectionDialog = new InPlaceCheckBoxTreeDialog(
WorkbenchUtil.getShell(), toolBar, values, validValues, NLS.bind(
Messages.CheckboxMultiSelectAttributeEditor_Select_X, getLabel()));
selectionDialog.addCloseListener(new IInPlaceDialogCloseListener() {
public void dialogClosing(InPlaceDialogCloseEvent event) {
if (event.getReturnCode() == Window.OK) {
Set<String> newValues = selectionDialog.getSelectedValues();
if (!new HashSet<String>(values).equals(newValues)) {
setValues(new ArrayList<String>(newValues));
attributeChanged();
updateText();
}
}
}
});
selectionDialog.open();
}
});
toolkit.adapt(valueText, false, false);
updateText();
setControl(composite);
}
|
diff --git a/src/main/java/net/pms/encoders/MEncoderVideo.java b/src/main/java/net/pms/encoders/MEncoderVideo.java
index 43ce4d236..9478395c6 100644
--- a/src/main/java/net/pms/encoders/MEncoderVideo.java
+++ b/src/main/java/net/pms/encoders/MEncoderVideo.java
@@ -1,2578 +1,2578 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.encoders;
import bsh.EvalError;
import bsh.Interpreter;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.sun.jna.Platform;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.List;
import javax.swing.*;
import net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.FormatConfiguration;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.dlna.*;
import net.pms.formats.Format;
import static net.pms.formats.v2.AudioUtils.getLPCMChannelMappingForMencoder;
import net.pms.formats.v2.SubtitleType;
import net.pms.formats.v2.SubtitleUtils;
import net.pms.io.*;
import net.pms.network.HTTPResource;
import net.pms.newgui.CustomJButton;
import net.pms.newgui.FontFileFilter;
import net.pms.newgui.MyComboBoxModel;
import net.pms.util.CodecUtil;
import net.pms.util.FileUtil;
import net.pms.util.FormLayoutUtil;
import net.pms.util.ProcessUtil;
import org.apache.commons.configuration.event.ConfigurationEvent;
import org.apache.commons.configuration.event.ConfigurationListener;
import static org.apache.commons.lang.BooleanUtils.isTrue;
import static org.apache.commons.lang.StringUtils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MEncoderVideo extends Player {
private static final Logger LOGGER = LoggerFactory.getLogger(MEncoderVideo.class);
private static final String COL_SPEC = "left:pref, 3dlu, p:grow, 3dlu, right:p:grow, 3dlu, p:grow, 3dlu, right:p:grow,3dlu, p:grow, 3dlu, right:p:grow,3dlu, pref:grow";
private static final String ROW_SPEC = "p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu,p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p , 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p";
private static final String REMOVE_OPTION = "---REMOVE-ME---"; // use an out-of-band option that can't be confused with a real option
private JTextField mencoder_ass_scale;
private JTextField mencoder_ass_margin;
private JTextField mencoder_ass_outline;
private JTextField mencoder_ass_shadow;
private JTextField mencoder_noass_scale;
private JTextField mencoder_noass_subpos;
private JTextField mencoder_noass_blur;
private JTextField mencoder_noass_outline;
private JTextField mencoder_custom_options;
private JTextField defaultaudiosubs;
private JTextField defaultfont;
private JComboBox subtitleCodePage;
private JTextField subq;
private JCheckBox forcefps;
private JCheckBox yadif;
private JCheckBox scaler;
private JTextField scaleX;
private JTextField scaleY;
private JCheckBox assdefaultstyle;
private JCheckBox fc;
private JCheckBox ass;
private JCheckBox checkBox;
private JCheckBox mencodermt;
private JCheckBox noskip;
private JCheckBox intelligentsync;
private JButton subColor;
private JButton fontselect;
private JTextField ocw;
private JTextField och;
private JCheckBox fribidi;
private final PmsConfiguration configuration;
private static final String[] INVALID_CUSTOM_OPTIONS = {
"-of",
"-oac",
"-ovc",
"-mpegopts"
};
private static final String INVALID_CUSTOM_OPTIONS_LIST = Arrays.toString(INVALID_CUSTOM_OPTIONS);
public static final int MENCODER_MAX_THREADS = 8;
public static final String ID = "mencoder";
// TODO (breaking change): most (probably all) of these
// protected fields should be private. And at least two
// shouldn't be fields
@Deprecated
protected boolean dvd;
@Deprecated
protected String overriddenMainArgs[];
protected boolean dtsRemux;
protected boolean pcm;
protected boolean ovccopy;
protected boolean ac3Remux;
protected boolean mpegts;
protected boolean wmv;
public static final String DEFAULT_CODEC_CONF_SCRIPT =
Messages.getString("MEncoderVideo.68")
+ Messages.getString("MEncoderVideo.69")
+ Messages.getString("MEncoderVideo.70")
+ Messages.getString("MEncoderVideo.71")
+ Messages.getString("MEncoderVideo.72")
+ Messages.getString("MEncoderVideo.73")
+ Messages.getString("MEncoderVideo.75")
+ Messages.getString("MEncoderVideo.76")
+ Messages.getString("MEncoderVideo.77")
+ Messages.getString("MEncoderVideo.78")
+ Messages.getString("MEncoderVideo.79")
+ "#\n"
+ Messages.getString("MEncoderVideo.80")
+ "container == iso :: -nosync\n"
+ "(container == avi || container == matroska) && vcodec == mpeg4 && acodec == mp3 :: -mc 0.1\n"
+ "container == flv :: -mc 0.1\n"
+ "container == mov :: -mc 0.1\n"
+ "container == rm :: -mc 0.1\n"
+ "container == matroska && framerate == 29.97 :: -nomux -mc 0\n"
+ "container == mp4 && vcodec == h264 :: -mc 0.1\n"
+ "\n"
+ Messages.getString("MEncoderVideo.87")
+ Messages.getString("MEncoderVideo.88")
+ Messages.getString("MEncoderVideo.89")
+ Messages.getString("MEncoderVideo.91");
public JCheckBox getCheckBox() {
return checkBox;
}
public JCheckBox getNoskip() {
return noskip;
}
public MEncoderVideo(PmsConfiguration configuration) {
this.configuration = configuration;
}
@Override
public JComponent config() {
// Apply the orientation for the locale
Locale locale = new Locale(configuration.getLanguage());
ComponentOrientation orientation = ComponentOrientation.getOrientation(locale);
String colSpec = FormLayoutUtil.getColSpec(COL_SPEC, orientation);
FormLayout layout = new FormLayout(colSpec, ROW_SPEC);
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
checkBox = new JCheckBox(Messages.getString("MEncoderVideo.0"));
checkBox.setContentAreaFilled(false);
if (configuration.getSkipLoopFilterEnabled()) {
checkBox.setSelected(true);
}
checkBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setSkipLoopFilterEnabled((e.getStateChange() == ItemEvent.SELECTED));
}
});
JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), FormLayoutUtil.flip(cc.xyw(1, 1, 15), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
mencodermt = new JCheckBox(Messages.getString("MEncoderVideo.35"));
mencodermt.setContentAreaFilled(false);
if (configuration.getMencoderMT()) {
mencodermt.setSelected(true);
}
mencodermt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setMencoderMT(mencodermt.isSelected());
}
});
mencodermt.setEnabled(Platform.isWindows() || Platform.isMac());
builder.add(mencodermt, FormLayoutUtil.flip(cc.xy(1, 3), colSpec, orientation));
builder.add(checkBox, FormLayoutUtil.flip(cc.xyw(3, 3, 12), colSpec, orientation));
noskip = new JCheckBox(Messages.getString("MEncoderVideo.2"));
noskip.setContentAreaFilled(false);
if (configuration.isMencoderNoOutOfSync()) {
noskip.setSelected(true);
}
noskip.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderNoOutOfSync((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(noskip, FormLayoutUtil.flip(cc.xy(1, 5), colSpec, orientation));
CustomJButton button = new CustomJButton(Messages.getString("MEncoderVideo.29"));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel codecPanel = new JPanel(new BorderLayout());
final JTextArea textArea = new JTextArea();
textArea.setText(configuration.getCodecSpecificConfig());
textArea.setFont(new Font("Courier", Font.PLAIN, 12));
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new java.awt.Dimension(900, 100));
final JTextArea textAreaDefault = new JTextArea();
textAreaDefault.setText(DEFAULT_CODEC_CONF_SCRIPT);
textAreaDefault.setBackground(Color.WHITE);
textAreaDefault.setFont(new Font("Courier", Font.PLAIN, 12));
textAreaDefault.setEditable(false);
textAreaDefault.setEnabled(configuration.isMencoderIntelligentSync());
JScrollPane scrollPaneDefault = new JScrollPane(textAreaDefault);
scrollPaneDefault.setPreferredSize(new java.awt.Dimension(900, 450));
JPanel customPanel = new JPanel(new BorderLayout());
intelligentsync = new JCheckBox(Messages.getString("MEncoderVideo.3"));
intelligentsync.setContentAreaFilled(false);
if (configuration.isMencoderIntelligentSync()) {
intelligentsync.setSelected(true);
}
intelligentsync.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderIntelligentSync((e.getStateChange() == ItemEvent.SELECTED));
textAreaDefault.setEnabled(configuration.isMencoderIntelligentSync());
}
});
JLabel label = new JLabel(Messages.getString("MEncoderVideo.33"));
customPanel.add(label, BorderLayout.NORTH);
customPanel.add(scrollPane, BorderLayout.SOUTH);
codecPanel.add(intelligentsync, BorderLayout.NORTH);
codecPanel.add(scrollPaneDefault, BorderLayout.CENTER);
codecPanel.add(customPanel, BorderLayout.SOUTH);
while (JOptionPane.showOptionDialog(SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame()),
codecPanel, Messages.getString("MEncoderVideo.34"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION) {
String newCodecparam = textArea.getText();
DLNAMediaInfo fakemedia = new DLNAMediaInfo();
DLNAMediaAudio audio = new DLNAMediaAudio();
audio.setCodecA("ac3");
fakemedia.setCodecV("mpeg4");
fakemedia.setContainer("matroska");
fakemedia.setDuration(45d*60);
audio.getAudioProperties().setNumberOfChannels(2);
fakemedia.setWidth(1280);
fakemedia.setHeight(720);
audio.setSampleFrequency("48000");
fakemedia.setFrameRate("23.976");
fakemedia.getAudioTracksList().add(audio);
String result[] = getSpecificCodecOptions(newCodecparam, fakemedia, new OutputParams(configuration), "dummy.mpg", "dummy.srt", false, true);
if (result.length > 0 && result[0].startsWith("@@")) {
String errorMessage = result[0].substring(2);
JOptionPane.showMessageDialog(
SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame()),
errorMessage,
Messages.getString("Dialog.Error"),
JOptionPane.ERROR_MESSAGE
);
} else {
configuration.setCodecSpecificConfig(newCodecparam);
break;
}
}
}
});
builder.add(button, FormLayoutUtil.flip(cc.xyw(1, 11, 2), colSpec, orientation));
forcefps = new JCheckBox(Messages.getString("MEncoderVideo.4"));
forcefps.setContentAreaFilled(false);
if (configuration.isMencoderForceFps()) {
forcefps.setSelected(true);
}
forcefps.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderForceFps(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(forcefps, FormLayoutUtil.flip(cc.xyw(1, 7, 2), colSpec, orientation));
yadif = new JCheckBox(Messages.getString("MEncoderVideo.26"));
yadif.setContentAreaFilled(false);
if (configuration.isMencoderYadif()) {
yadif.setSelected(true);
}
yadif.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderYadif(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(yadif, FormLayoutUtil.flip(cc.xyw(3, 7, 7), colSpec, orientation));
scaler = new JCheckBox(Messages.getString("MEncoderVideo.27"));
scaler.setContentAreaFilled(false);
scaler.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderScaler(e.getStateChange() == ItemEvent.SELECTED);
scaleX.setEnabled(configuration.isMencoderScaler());
scaleY.setEnabled(configuration.isMencoderScaler());
}
});
builder.add(scaler, FormLayoutUtil.flip(cc.xyw(3, 5, 7), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.28"), FormLayoutUtil.flip(cc.xyw(10, 5, 3, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
scaleX = new JTextField("" + configuration.getMencoderScaleX());
scaleX.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
try {
configuration.setMencoderScaleX(Integer.parseInt(scaleX.getText()));
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse scaleX from \"" + scaleX.getText() + "\"");
}
}
});
builder.add(scaleX, FormLayoutUtil.flip(cc.xyw(13, 5, 3), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.30"), FormLayoutUtil.flip(cc.xyw(10, 7, 3, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
scaleY = new JTextField("" + configuration.getMencoderScaleY());
scaleY.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
try {
configuration.setMencoderScaleY(Integer.parseInt(scaleY.getText()));
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse scaleY from \"" + scaleY.getText() + "\"");
}
}
});
builder.add(scaleY, FormLayoutUtil.flip(cc.xyw(13, 7, 3), colSpec, orientation));
if (configuration.isMencoderScaler()) {
scaler.setSelected(true);
} else {
scaleX.setEnabled(false);
scaleY.setEnabled(false);
}
cmp = builder.addSeparator(Messages.getString("MEncoderVideo.5"), FormLayoutUtil.flip(cc.xyw(1, 19, 15), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("MEncoderVideo.6"), FormLayoutUtil.flip(cc.xy(1, 21), colSpec, orientation));
mencoder_custom_options = new JTextField(configuration.getMencoderCustomOptions());
mencoder_custom_options.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderCustomOptions(mencoder_custom_options.getText());
}
});
builder.add(mencoder_custom_options, FormLayoutUtil.flip(cc.xyw(3, 21, 13), colSpec, orientation));
cmp = builder.addSeparator(Messages.getString("MEncoderVideo.8"), FormLayoutUtil.flip(cc.xyw(1, 25, 15), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("MEncoderVideo.10"), FormLayoutUtil.flip(cc.xy(1, 29), colSpec, orientation));
defaultaudiosubs = new JTextField(configuration.getAudioSubLanguages());
defaultaudiosubs.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAudioSubLanguages(defaultaudiosubs.getText());
}
});
builder.add(defaultaudiosubs, FormLayoutUtil.flip(cc.xyw(3, 29, 8), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.11"), FormLayoutUtil.flip(cc.xy(1, 31), colSpec, orientation));
Object data[] = new Object[]{
configuration.getMencoderSubCp(),
Messages.getString("MEncoderVideo.129"),
Messages.getString("MEncoderVideo.130"),
Messages.getString("MEncoderVideo.131"),
Messages.getString("MEncoderVideo.132"),
Messages.getString("MEncoderVideo.96"),
Messages.getString("MEncoderVideo.97"),
Messages.getString("MEncoderVideo.98"),
Messages.getString("MEncoderVideo.99"),
Messages.getString("MEncoderVideo.100"),
Messages.getString("MEncoderVideo.101"),
Messages.getString("MEncoderVideo.102"),
Messages.getString("MEncoderVideo.103"),
Messages.getString("MEncoderVideo.104"),
Messages.getString("MEncoderVideo.105"),
Messages.getString("MEncoderVideo.106"),
Messages.getString("MEncoderVideo.107"),
Messages.getString("MEncoderVideo.108"),
Messages.getString("MEncoderVideo.109"),
Messages.getString("MEncoderVideo.110"),
Messages.getString("MEncoderVideo.111"),
Messages.getString("MEncoderVideo.112"),
Messages.getString("MEncoderVideo.113"),
Messages.getString("MEncoderVideo.114"),
Messages.getString("MEncoderVideo.115"),
Messages.getString("MEncoderVideo.116"),
Messages.getString("MEncoderVideo.117"),
Messages.getString("MEncoderVideo.118"),
Messages.getString("MEncoderVideo.119"),
Messages.getString("MEncoderVideo.120"),
Messages.getString("MEncoderVideo.121"),
Messages.getString("MEncoderVideo.122"),
Messages.getString("MEncoderVideo.123"),
Messages.getString("MEncoderVideo.124")
};
MyComboBoxModel cbm = new MyComboBoxModel(data);
subtitleCodePage = new JComboBox(cbm);
subtitleCodePage.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String s = (String) e.getItem();
int offset = s.indexOf("/*");
if (offset > -1) {
s = s.substring(0, offset).trim();
}
configuration.setMencoderSubCp(s);
}
}
});
subtitleCodePage.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
subtitleCodePage.getItemListeners()[0].itemStateChanged(new ItemEvent(subtitleCodePage, 0, subtitleCodePage.getEditor().getItem(), ItemEvent.SELECTED));
}
});
subtitleCodePage.setEditable(true);
builder.add(subtitleCodePage, FormLayoutUtil.flip(cc.xyw(3, 31, 7), colSpec, orientation));
fribidi = new JCheckBox(Messages.getString("MEncoderVideo.23"));
fribidi.setContentAreaFilled(false);
if (configuration.isMencoderSubFribidi()) {
fribidi.setSelected(true);
}
fribidi.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderSubFribidi(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(fribidi, FormLayoutUtil.flip(cc.xyw(11, 31, 4), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.24"), FormLayoutUtil.flip(cc.xy(1, 33), colSpec, orientation));
defaultfont = new JTextField(configuration.getMencoderFont());
defaultfont.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderFont(defaultfont.getText());
}
});
builder.add(defaultfont, FormLayoutUtil.flip(cc.xyw(3, 33, 8), colSpec, orientation));
fontselect = new CustomJButton("...");
fontselect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FontFileFilter());
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("MEncoderVideo.25"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
defaultfont.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.setMencoderFont(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(fontselect, FormLayoutUtil.flip(cc.xyw(11, 33, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.12"), FormLayoutUtil.flip(cc.xy(1, 39, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
mencoder_ass_scale = new JTextField(configuration.getMencoderAssScale());
mencoder_ass_scale.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssScale(mencoder_ass_scale.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.13"), FormLayoutUtil.flip(cc.xy(5, 39), colSpec, orientation));
mencoder_ass_outline = new JTextField(configuration.getMencoderAssOutline());
mencoder_ass_outline.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssOutline(mencoder_ass_outline.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.14"), FormLayoutUtil.flip(cc.xy(9, 39), colSpec, orientation));
mencoder_ass_shadow = new JTextField(configuration.getMencoderAssShadow());
mencoder_ass_shadow.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssShadow(mencoder_ass_shadow.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.15"), FormLayoutUtil.flip(cc.xy(13, 39), colSpec, orientation));
mencoder_ass_margin = new JTextField(configuration.getMencoderAssMargin());
mencoder_ass_margin.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderAssMargin(mencoder_ass_margin.getText());
}
});
builder.add(mencoder_ass_scale, FormLayoutUtil.flip(cc.xy(3, 39), colSpec, orientation));
builder.add(mencoder_ass_outline, FormLayoutUtil.flip(cc.xy(7, 39), colSpec, orientation));
builder.add(mencoder_ass_shadow, FormLayoutUtil.flip(cc.xy(11, 39), colSpec, orientation));
builder.add(mencoder_ass_margin, FormLayoutUtil.flip(cc.xy(15, 39), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.16"), FormLayoutUtil.flip(cc.xy(1, 41, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
mencoder_noass_scale = new JTextField(configuration.getMencoderNoAssScale());
mencoder_noass_scale.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssScale(mencoder_noass_scale.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.17"), FormLayoutUtil.flip(cc.xy(5, 41), colSpec, orientation));
mencoder_noass_outline = new JTextField(configuration.getMencoderNoAssOutline());
mencoder_noass_outline.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssOutline(mencoder_noass_outline.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.18"), FormLayoutUtil.flip(cc.xy(9, 41), colSpec, orientation));
mencoder_noass_blur = new JTextField(configuration.getMencoderNoAssBlur());
mencoder_noass_blur.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssBlur(mencoder_noass_blur.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.19"), FormLayoutUtil.flip(cc.xy(13, 41), colSpec, orientation));
mencoder_noass_subpos = new JTextField(configuration.getMencoderNoAssSubPos());
mencoder_noass_subpos.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderNoAssSubPos(mencoder_noass_subpos.getText());
}
});
builder.add(mencoder_noass_scale, FormLayoutUtil.flip(cc.xy(3, 41), colSpec, orientation));
builder.add(mencoder_noass_outline, FormLayoutUtil.flip(cc.xy(7, 41), colSpec, orientation));
builder.add(mencoder_noass_blur, FormLayoutUtil.flip(cc.xy(11, 41), colSpec, orientation));
builder.add(mencoder_noass_subpos, FormLayoutUtil.flip(cc.xy(15, 41), colSpec, orientation));
ass = new JCheckBox(Messages.getString("MEncoderVideo.20"));
ass.setContentAreaFilled(false);
ass.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e != null) {
configuration.setMencoderAss(e.getStateChange() == ItemEvent.SELECTED);
}
}
});
builder.add(ass, FormLayoutUtil.flip(cc.xy(1, 37), colSpec, orientation));
ass.setSelected(configuration.isMencoderAss());
ass.getItemListeners()[0].itemStateChanged(null);
fc = new JCheckBox(Messages.getString("MEncoderVideo.21"));
fc.setContentAreaFilled(false);
fc.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderFontConfig(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(fc, FormLayoutUtil.flip(cc.xyw(3, 37, 5), colSpec, orientation));
fc.setSelected(configuration.isMencoderFontConfig());
assdefaultstyle = new JCheckBox(Messages.getString("MEncoderVideo.36"));
assdefaultstyle.setContentAreaFilled(false);
assdefaultstyle.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderAssDefaultStyle(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(assdefaultstyle, FormLayoutUtil.flip(cc.xyw(8, 37, 4), colSpec, orientation));
assdefaultstyle.setSelected(configuration.isMencoderAssDefaultStyle());
builder.addLabel(Messages.getString("MEncoderVideo.92"), FormLayoutUtil.flip(cc.xy(1, 45), colSpec, orientation));
subq = new JTextField(configuration.getMencoderVobsubSubtitleQuality());
subq.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderVobsubSubtitleQuality(subq.getText());
}
});
builder.add(subq, FormLayoutUtil.flip(cc.xyw(3, 45, 1), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.93"), FormLayoutUtil.flip(cc.xyw(1, 47, 6), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.28") + "% ", FormLayoutUtil.flip(cc.xy(1, 49, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
ocw = new JTextField(configuration.getMencoderOverscanCompensationWidth());
ocw.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderOverscanCompensationWidth(ocw.getText());
}
});
builder.add(ocw, FormLayoutUtil.flip(cc.xyw(3, 49, 1), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.30") + "% ", FormLayoutUtil.flip(cc.xy(5, 49), colSpec, orientation));
och = new JTextField(configuration.getMencoderOverscanCompensationHeight());
och.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setMencoderOverscanCompensationHeight(och.getText());
}
});
builder.add(och, FormLayoutUtil.flip(cc.xyw(7, 49, 1), colSpec, orientation));
subColor = new JButton();
subColor.setText(Messages.getString("MEncoderVideo.31"));
subColor.setBackground(new Color(configuration.getSubsColor()));
subColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color newColor = JColorChooser.showDialog(
SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame()),
Messages.getString("MEncoderVideo.125"),
subColor.getBackground()
);
if (newColor != null) {
subColor.setBackground(newColor);
configuration.setSubsColor(newColor.getRGB());
}
}
});
builder.add(subColor, FormLayoutUtil.flip(cc.xyw(12, 37, 4), colSpec, orientation));
configuration.addConfigurationListener(new ConfigurationListener() {
@Override
public void configurationChanged(ConfigurationEvent event) {
if (event.getPropertyName() == null ) {
return;
}
if ((!event.isBeforeUpdate()) && event.getPropertyName().equals(PmsConfiguration.KEY_DISABLE_SUBTITLES)) {
boolean enabled = !configuration.isDisableSubtitles();
subq.setEnabled(enabled);
subtitleCodePage.setEnabled(enabled);
ass.setEnabled(enabled);
assdefaultstyle.setEnabled(enabled);
fribidi.setEnabled(enabled);
fc.setEnabled(enabled);
mencoder_ass_scale.setEnabled(enabled);
mencoder_ass_outline.setEnabled(enabled);
mencoder_ass_shadow.setEnabled(enabled);
mencoder_ass_margin.setEnabled(enabled);
mencoder_noass_scale.setEnabled(enabled);
mencoder_noass_outline.setEnabled(enabled);
mencoder_noass_blur.setEnabled(enabled);
mencoder_noass_subpos.setEnabled(enabled);
defaultaudiosubs.setEnabled(enabled);
defaultfont.setEnabled(enabled);
subColor.setEnabled(enabled);
fontselect.setEnabled(enabled);
ocw.setEnabled(enabled);
och.setEnabled(enabled);
if (enabled) {
ass.getItemListeners()[0].itemStateChanged(null);
}
}
}
});
JPanel panel = builder.getPanel();
// Apply the orientation to the panel and all components in it
panel.applyComponentOrientation(orientation);
return panel;
}
@Override
public int purpose() {
return VIDEO_SIMPLEFILE_PLAYER;
}
@Override
public String id() {
return ID;
}
@Override
public boolean avisynth() {
return false;
}
@Override
public boolean isTimeSeekable() {
return true;
}
protected String[] getDefaultArgs() {
List<String> defaultArgsList = new ArrayList<String>();
defaultArgsList.add("-msglevel");
defaultArgsList.add("statusline=2");
defaultArgsList.add("-oac");
defaultArgsList.add((ac3Remux || dtsRemux) ? "copy" : (pcm ? "pcm" : "lavc"));
defaultArgsList.add("-of");
defaultArgsList.add((wmv || mpegts) ? "lavf" : ((pcm && avisynth()) ? "avi" : ((pcm || dtsRemux) ? "rawvideo" : "mpeg")));
if (wmv) {
defaultArgsList.add("-lavfopts");
defaultArgsList.add("format=asf");
} else if (mpegts) {
defaultArgsList.add("-lavfopts");
defaultArgsList.add("format=mpegts");
}
defaultArgsList.add("-mpegopts");
defaultArgsList.add("format=mpeg2:muxrate=500000:vbuf_size=1194:abuf_size=64");
defaultArgsList.add("-ovc");
defaultArgsList.add(ovccopy ? "copy" : "lavc");
String[] defaultArgsArray = new String[defaultArgsList.size()];
defaultArgsList.toArray(defaultArgsArray);
return defaultArgsArray;
}
private String[] sanitizeArgs(String[] args) {
List<String> sanitized = new ArrayList<String>();
int i = 0;
while (i < args.length) {
String name = args[i];
String value = null;
for (String option : INVALID_CUSTOM_OPTIONS) {
if (option.equals(name)) {
if ((i + 1) < args.length) {
value = " " + args[i + 1];
++i;
} else {
value = "";
}
LOGGER.warn(
"Ignoring custom MEncoder option: {}{}; the following options cannot be changed: " + INVALID_CUSTOM_OPTIONS_LIST,
name,
value
);
break;
}
}
if (value == null) {
sanitized.add(args[i]);
}
++i;
}
return sanitized.toArray(new String[sanitized.size()]);
}
@Override
public String[] args() {
String args[];
String defaultArgs[] = getDefaultArgs();
if (overriddenMainArgs != null) {
// add the sanitized custom MEncoder options.
// not cached because they may be changed on the fly in the GUI
// TODO if/when we upgrade to org.apache.commons.lang3:
// args = ArrayUtils.addAll(defaultArgs, sanitizeArgs(overriddenMainArgs))
String[] sanitizedCustomArgs = sanitizeArgs(overriddenMainArgs);
args = new String[defaultArgs.length + sanitizedCustomArgs.length];
System.arraycopy(defaultArgs, 0, args, 0, defaultArgs.length);
System.arraycopy(sanitizedCustomArgs, 0, args, defaultArgs.length, sanitizedCustomArgs.length);
} else {
args = defaultArgs;
}
return args;
}
@Override
public String executable() {
return configuration.getMencoderPath();
}
private int[] getVideoBitrateConfig(String bitrate) {
int bitrates[] = new int[2];
if (bitrate.contains("(") && bitrate.contains(")")) {
bitrates[1] = Integer.parseInt(bitrate.substring(bitrate.indexOf("(") + 1, bitrate.indexOf(")")));
}
if (bitrate.contains("(")) {
bitrate = bitrate.substring(0, bitrate.indexOf("(")).trim();
}
if (isBlank(bitrate)) {
bitrate = "0";
}
bitrates[0] = (int) Double.parseDouble(bitrate);
return bitrates;
}
/**
* Note: This is not exact. The bitrate can go above this but it is generally pretty good.
* @return The maximum bitrate the video should be along with the buffer size using MEncoder vars
*/
private String addMaximumBitrateConstraints(String encodeSettings, DLNAMediaInfo media, String quality, RendererConfiguration mediaRenderer, String audioType) {
int defaultMaxBitrates[] = getVideoBitrateConfig(configuration.getMaximumBitrate());
int rendererMaxBitrates[] = new int[2];
if (mediaRenderer.getMaxVideoBitrate() != null) {
rendererMaxBitrates = getVideoBitrateConfig(mediaRenderer.getMaxVideoBitrate());
}
if ((rendererMaxBitrates[0] > 0) && ((defaultMaxBitrates[0] == 0) || (rendererMaxBitrates[0] < defaultMaxBitrates[0]))) {
defaultMaxBitrates = rendererMaxBitrates;
}
if (mediaRenderer.getCBRVideoBitrate() == 0 && defaultMaxBitrates[0] > 0 && !quality.contains("vrc_buf_size") && !quality.contains("vrc_maxrate") && !quality.contains("vbitrate")) {
// Convert value from Mb to Kb
defaultMaxBitrates[0] = 1000 * defaultMaxBitrates[0];
// Halve it since it seems to send up to 1 second of video in advance
defaultMaxBitrates[0] = defaultMaxBitrates[0] / 2;
int bufSize = 1835;
if (media.isHDVideo()) {
bufSize = defaultMaxBitrates[0] / 3;
}
if (bufSize > 7000) {
bufSize = 7000;
}
if (defaultMaxBitrates[1] > 0) {
bufSize = defaultMaxBitrates[1];
}
if (mediaRenderer.isDefaultVBVSize() && rendererMaxBitrates[1] == 0) {
bufSize = 1835;
}
// Make room for audio
// If audio is PCM, subtract 4600kb/s
if ("pcm".equals(audioType)) {
defaultMaxBitrates[0] = defaultMaxBitrates[0] - 4600;
}
// If audio is DTS, subtract 1510kb/s
else if ("dts".equals(audioType)) {
defaultMaxBitrates[0] = defaultMaxBitrates[0] - 1510;
}
// If audio is AC3, subtract the configured amount (usually 640)
else if ("ac3".equals(audioType)) {
defaultMaxBitrates[0] = defaultMaxBitrates[0] - configuration.getAudioBitrate();
}
// Round down to the nearest Mb
defaultMaxBitrates[0] = defaultMaxBitrates[0] / 1000 * 1000;
encodeSettings += ":vrc_maxrate=" + defaultMaxBitrates[0] + ":vrc_buf_size=" + bufSize;
}
return encodeSettings;
}
/*
* Collapse the multiple internal ways of saying "subtitles are disabled" into a single method
* which returns true if any of the following are true:
*
* 1) configuration.isMencoderDisableSubs()
* 2) params.sid == null
* 3) avisynth()
*/
private boolean isDisableSubtitles(OutputParams params) {
return configuration.isDisableSubtitles() || (params.sid == null) || avisynth();
}
@Override
public ProcessWrapper launchTranscode(
String fileName,
DLNAResource dlna,
DLNAMediaInfo media,
OutputParams params
) throws IOException {
params.manageFastStart();
boolean avisynth = avisynth();
setAudioAndSubs(fileName, media, params, configuration);
String externalSubtitlesFileName = null;
if (params.sid != null && params.sid.isExternal()) {
if (params.sid.isExternalFileUtf16()) {
// convert UTF-16 -> UTF-8
File convertedSubtitles = new File(configuration.getTempFolder(), "utf8_" + params.sid.getExternalFile().getName());
FileUtil.convertFileFromUtf16ToUtf8(params.sid.getExternalFile(), convertedSubtitles);
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(convertedSubtitles.getAbsolutePath());
} else {
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(params.sid.getExternalFile().getAbsolutePath());
}
}
InputFile newInput = new InputFile();
newInput.setFilename(fileName);
newInput.setPush(params.stdin);
dvd = false;
if (media != null && media.getDvdtrack() > 0) {
dvd = true;
}
// Don't honour "Remux videos with tsMuxeR..." if the resource is being streamed via a MEncoder entry in
// the #--TRANSCODE--# folder, or it is a file that tsMuxeR does not support.
boolean forceMencoder = false;
if (
!configuration.getHideTranscodeEnabled() &&
dlna.isNoName() && // XXX remove this? http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12149
(
dlna.getParent() instanceof FileTranscodeVirtualFolder
)
) {
forceMencoder = true;
}
ovccopy = false;
pcm = false;
ac3Remux = false;
dtsRemux = false;
wmv = false;
int intOCW = 0;
int intOCH = 0;
try {
intOCW = Integer.parseInt(configuration.getMencoderOverscanCompensationWidth());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation width: \"{}\"", configuration.getMencoderOverscanCompensationWidth());
}
try {
intOCH = Integer.parseInt(configuration.getMencoderOverscanCompensationHeight());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation height: \"{}\"", configuration.getMencoderOverscanCompensationHeight());
}
/*
* Check if the video track and the container report different aspect ratios
*/
boolean aspectRatiosMatch = true;
if (
media.getAspectRatioContainer() != null &&
media.getAspectRatioVideoTrack() != null &&
!media.getAspectRatioContainer().equals(media.getAspectRatioVideoTrack())
) {
aspectRatiosMatch = false;
}
/**
* Do not use tsMuxeR if:
* - The resource is being streamed via a MEncoder entry in the transcode folder
* - There is a subtitle that matches the user preferences
* - The resource is a DVD
* - We are using AviSynth (TODO: do we still need this check?)
* - The resource is incompatible with tsMuxeR
* - The user has left the "switch to tsMuxeR" option enabled
* - The user has not specified overscan correction
* - The filename does not specify the resource as WEB-DL
* - The aspect ratio of the video needs to be changed
*/
if (
!forceMencoder &&
params.sid == null &&
!dvd &&
!avisynth() &&
media != null &&
(
media.isVideoWithinH264LevelLimits(newInput, params.mediaRenderer) ||
!params.mediaRenderer.isH264Level41Limited()
) &&
media.isMuxable(params.mediaRenderer) &&
configuration.isMencoderMuxWhenCompatible() &&
params.mediaRenderer.isMuxH264MpegTS() &&
(
intOCW == 0 &&
intOCH == 0
) &&
!fileName.contains("WEB-DL") &&
aspectRatiosMatch
) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
TsMuxeRVideo tv = new TsMuxeRVideo(configuration);
params.forceFps = media.getValidFps(false);
if (media.getCodecV() != null) {
if (media.getCodecV().equals("h264")) {
params.forceType = "V_MPEG4/ISO/AVC";
} else if (media.getCodecV().startsWith("mpeg2")) {
params.forceType = "V_MPEG-2";
} else if (media.getCodecV().equals("vc1")) {
params.forceType = "V_MS/VFW/WVC1";
}
}
return tv.launchTranscode(fileName, dlna, media, params);
}
} else if (params.sid == null && dvd && configuration.isMencoderRemuxMPEG2() && params.mediaRenderer.isMpeg2Supported()) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
ovccopy = true;
}
}
String vcodec = "mpeg2video";
if (params.mediaRenderer.isTranscodeToWMV()) {
wmv = true;
vcodec = "wmv2"; // http://wiki.megaframe.org/wiki/Ubuntu_XBOX_360#MEncoder not usable in streaming
}
mpegts = params.mediaRenderer.isTranscodeToMPEGTSAC3();
/**
* Disable AC3 remux for stereo tracks with 384 kbits bitrate and PS3 renderer (PS3 FW bug?)
*
* Commented out until we can find a way to detect when a video has an audio track that switches from 2 to 6 channels
* because MEncoder can't handle those files, which are very common these days.
boolean ps3_and_stereo_and_384_kbits = params.aid != null &&
(params.mediaRenderer.isPS3() && params.aid.getAudioProperties().getNumberOfChannels() == 2) &&
(params.aid.getBitRate() > 370000 && params.aid.getBitRate() < 400000);
*/
final boolean isTsMuxeRVideoEngineEnabled = configuration.getEnginesAsList(PMS.get().getRegistry()).contains(TsMuxeRVideo.ID);
final boolean mencoderAC3RemuxAudioDelayBug = (params.aid != null) && (params.aid.getAudioProperties().getAudioDelay() != 0) && (params.timeseek == 0);
if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) {
// AC-3 remux takes priority
ac3Remux = true;
} else {
// Now check for DTS remux and LPCM streaming
dtsRemux = isTsMuxeRVideoEngineEnabled &&
configuration.isDTSEmbedInPCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
) && params.aid != null &&
params.aid.isDTS() &&
!avisynth() &&
params.mediaRenderer.isDTSPlayable();
pcm = isTsMuxeRVideoEngineEnabled &&
configuration.isUsePCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
)
// Disable LPCM transcoding for MP4 container with non-H.264 video as workaround for MEncoder's A/V sync bug
&& !(media.getContainer().equals("mp4") && !media.getCodecV().equals("h264"))
&& params.aid != null &&
(
(params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || // disable 7.1 DTS-HD => LPCM because of channels mapping bug
params.aid.isLossless() ||
params.aid.isTrueHD() ||
(
!configuration.isMencoderUsePcmForHQAudioOnly() &&
(
params.aid.isAC3() ||
params.aid.isMP3() ||
params.aid.isAAC() ||
params.aid.isVorbis() ||
// Disable WMA to LPCM transcoding because of mencoder's channel mapping bug
// (see CodecUtil.getMixerOutput)
// params.aid.isWMA() ||
params.aid.isMpegAudio()
)
)
) && params.mediaRenderer.isLPCMPlayable();
}
if (dtsRemux || pcm) {
params.losslessaudio = true;
params.forceFps = media.getValidFps(false);
}
// MPEG-2 remux still buggy with MEncoder
// TODO when we can still use it?
ovccopy = false;
if (pcm && avisynth()) {
params.avidemux = true;
}
int channels;
if (ac3Remux) {
channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux
} else if (dtsRemux || wmv) {
channels = 2;
} else if (pcm) {
channels = params.aid.getAudioProperties().getNumberOfChannels();
} else {
channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding
}
LOGGER.trace("channels=" + channels);
String add = "";
String rendererMencoderOptions = params.mediaRenderer.getCustomMencoderOptions(); // default: empty string
String globalMencoderOptions = configuration.getMencoderCustomOptions(); // default: empty string
if (params.mediaRenderer.isKeepAspectRatio()) {
- rendererMencoderOptions += " -vf softskip,expand=::::1:16/9:4";
+ rendererMencoderOptions += " -vf expand=::::0:16/9:4,softskip";
}
String combinedCustomOptions = defaultString(globalMencoderOptions) +
" " +
defaultString(rendererMencoderOptions);
if (!combinedCustomOptions.contains("-lavdopts")) {
add = " -lavdopts debug=0";
}
if (isNotBlank(rendererMencoderOptions)) {
/**
* Ignore the renderer's custom MEncoder options if a) we're streaming a DVD (i.e. via dvd://)
* or b) the renderer's MEncoder options contain overscan settings (those are handled
* separately)
*/
// XXX we should weed out the unused/unwanted settings and keep the rest
// (see sanitizeArgs()) rather than ignoring the options entirely
if (rendererMencoderOptions.contains("expand=") && dvd) {
rendererMencoderOptions = null;
}
}
StringTokenizer st = new StringTokenizer(
"-channels " + channels +
(isNotBlank(globalMencoderOptions) ? " " + globalMencoderOptions : "") +
(isNotBlank(rendererMencoderOptions) ? " " + rendererMencoderOptions : "") +
add,
" "
);
// XXX why does this field (which is used to populate the array returned by args(),
// called below) store the renderer-specific (i.e. not global) MEncoder options?
overriddenMainArgs = new String[st.countTokens()];
{
int nThreads = (dvd || fileName.toLowerCase().endsWith("dvr-ms")) ?
1 :
configuration.getMencoderMaxThreads();
// MEncoder loses audio/video sync if more than 4 decoder (lavdopts) threads are used.
// Multithreading for decoding offers little performance gain anyway so it's not a big deal.
if (nThreads > 4) {
nThreads = 4;
}
boolean handleToken = false;
int i = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (handleToken) {
token += ":threads=" + nThreads;
if (configuration.getSkipLoopFilterEnabled() && !avisynth()) {
token += ":skiploopfilter=all";
}
handleToken = false;
}
if (token.toLowerCase().contains("lavdopts")) {
handleToken = true;
}
overriddenMainArgs[i++] = token;
}
}
if (configuration.getMPEG2MainSettings() != null) {
String mainConfig = configuration.getMPEG2MainSettings();
String customSettings = params.mediaRenderer.getCustomMencoderQualitySettings();
// Custom settings in PMS may override the settings of the saved configuration
if (isNotBlank(customSettings)) {
mainConfig = customSettings;
}
if (mainConfig.contains("/*")) {
mainConfig = mainConfig.substring(mainConfig.indexOf("/*"));
}
// Ditlew - WDTV Live (+ other byte asking clients), CBR. This probably ought to be placed in addMaximumBitrateConstraints(..)
int cbr_bitrate = params.mediaRenderer.getCBRVideoBitrate();
String cbr_settings = (cbr_bitrate > 0) ?
":vrc_buf_size=5000:vrc_minrate=" + cbr_bitrate + ":vrc_maxrate=" + cbr_bitrate + ":vbitrate=" + ((cbr_bitrate > 16000) ? cbr_bitrate * 1000 : cbr_bitrate) :
"";
String encodeSettings = "-lavcopts autoaspect=1:vcodec=" + vcodec +
(wmv ? ":acodec=wmav2:abitrate=448" : (cbr_settings + ":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid))) +
":threads=" + (wmv ? 1 : configuration.getMencoderMaxThreads()) +
("".equals(mainConfig) ? "" : ":" + mainConfig);
String audioType = "ac3";
if (dtsRemux) {
audioType = "dts";
} else if (pcm) {
audioType = "pcm";
}
encodeSettings = addMaximumBitrateConstraints(encodeSettings, media, mainConfig, params.mediaRenderer, audioType);
st = new StringTokenizer(encodeSettings, " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
while (st.hasMoreTokens()) {
overriddenMainArgs[i++] = st.nextToken();
}
}
}
boolean foundNoassParam = false;
if (media != null) {
String expertOptions [] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
for (String s : expertOptions) {
if (s.equals("-noass")) {
foundNoassParam = true;
}
}
}
StringBuilder sb = new StringBuilder();
// Set subtitles options
if (!isDisableSubtitles(params)) {
int subtitleMargin = 0;
int userMargin = 0;
// Use ASS flag (and therefore ASS font styles) for all subtitled files except vobsub, PGS (blu-ray) and DVD
boolean apply_ass_styling = params.sid.getType() != SubtitleType.VOBSUB &&
params.sid.getType() != SubtitleType.PGS &&
configuration.isMencoderAss() && // GUI: enable subtitles formating
!foundNoassParam && // GUI: codec specific options
!dvd;
if (apply_ass_styling) {
sb.append("-ass ");
// GUI: Override ASS subtitles style if requested (always for SRT and TX3G subtitles)
boolean override_ass_style = !configuration.isMencoderAssDefaultStyle() ||
params.sid.getType() == SubtitleType.SUBRIP ||
params.sid.getType() == SubtitleType.TX3G;
if (override_ass_style) {
String assSubColor = "ffffff00";
if (configuration.getSubsColor() != 0) {
assSubColor = Integer.toHexString(configuration.getSubsColor());
if (assSubColor.length() > 2) {
assSubColor = assSubColor.substring(2) + "00";
}
}
sb.append("-ass-color ").append(assSubColor).append(" -ass-border-color 00000000 -ass-font-scale ").append(configuration.getMencoderAssScale());
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
/* Set font with -font option, workaround for the bug:
* https://github.com/Happy-Neko/ps3mediaserver/commit/52e62203ea12c40628de1869882994ce1065446a#commitcomment-990156
*/
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
sb.append(" -ass-force-style FontName=").append(configuration.getMencoderFont()).append(",");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
/*
* Variable "font" contains a font path instead of a font name.
* Does "-ass-force-style" support font paths? In tests on OS X
* the font path is ignored (Outline, Shadow and MarginV are
* used, though) and the "-font" definition is used instead.
* See: https://github.com/ps3mediaserver/ps3mediaserver/pull/14
*/
sb.append(" -font ").append(font).append(" ");
sb.append(" -ass-force-style FontName=").append(font).append(",");
} else {
sb.append(" -font Arial ");
sb.append(" -ass-force-style FontName=Arial,");
}
}
/*
* Add to the subtitle margin if overscan compensation is being used
* This keeps the subtitle text inside the frame instead of in the border
*/
if (intOCH > 0) {
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
}
sb.append("Outline=").append(configuration.getMencoderAssOutline()).append(",Shadow=").append(configuration.getMencoderAssShadow());
try {
userMargin = Integer.parseInt(configuration.getMencoderAssMargin());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse SSA margin from \"" + configuration.getMencoderAssMargin() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(",MarginV=").append(subtitleMargin).append(" ");
} else if (intOCH > 0) {
/*
* Add to the subtitle margin
* This keeps the subtitle text inside the frame instead of in the border
*/
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
sb.append("-ass-force-style MarginV=").append(subtitleMargin).append(" ");
}
// MEncoder is not compiled with fontconfig on Mac OS X, therefore
// use of the "-ass" option also requires the "-font" option.
if (Platform.isMac() && sb.toString().indexOf(" -font ") < 0) {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append("-font ").append(font).append(" ");
}
}
// Workaround for MPlayer #2041, remove when that bug is fixed
if (!params.sid.isEmbedded()) {
sb.append("-noflip-hebrew ");
}
// Use PLAINTEXT formatting
} else {
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append(" -font ").append(font).append(" ");
}
}
sb.append(" -subfont-text-scale ").append(configuration.getMencoderNoAssScale());
sb.append(" -subfont-outline ").append(configuration.getMencoderNoAssOutline());
sb.append(" -subfont-blur ").append(configuration.getMencoderNoAssBlur());
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = intOCH;
}
try {
userMargin = Integer.parseInt(configuration.getMencoderNoAssSubPos());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse subpos from \"" + configuration.getMencoderNoAssSubPos() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(" -subpos ").append(100 - subtitleMargin).append(" ");
}
// Common subtitle options
// MEncoder on Mac OS X is compiled without fontconfig support.
// Appending the flag will break execution, so skip it on Mac OS X.
if (!Platform.isMac()) {
// Use fontconfig if enabled
sb.append("-").append(configuration.isMencoderFontConfig() ? "" : "no").append("fontconfig ");
}
// Apply DVD/VOBsub subtitle quality
if (params.sid.getType() == SubtitleType.VOBSUB && configuration.getMencoderVobsubSubtitleQuality() != null) {
String subtitleQuality = configuration.getMencoderVobsubSubtitleQuality();
sb.append("-spuaa ").append(subtitleQuality).append(" ");
}
// External subtitles file
if (params.sid.isExternal()) {
if (!params.sid.isExternalFileUtf()) {
String subcp = null;
// Append -subcp option for non UTF external subtitles
if (isNotBlank(configuration.getMencoderSubCp())) {
// Manual setting
subcp = configuration.getMencoderSubCp();
} else if (isNotBlank(SubtitleUtils.getSubCpOptionForMencoder(params.sid))) {
// Autodetect charset (blank mencoder_subcp config option)
subcp = SubtitleUtils.getSubCpOptionForMencoder(params.sid);
}
if (isNotBlank(subcp)) {
sb.append("-subcp ").append(subcp).append(" ");
if (configuration.isMencoderSubFribidi()) {
sb.append("-fribidi-charset ").append(subcp).append(" ");
}
}
}
}
}
st = new StringTokenizer(sb.toString(), " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
boolean handleToken = false;
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (handleToken) {
s = "-quiet";
handleToken = false;
}
if ((!configuration.isMencoderAss() || dvd) && s.contains("-ass")) {
s = "-quiet";
handleToken = true;
}
overriddenMainArgs[i++] = s;
}
}
List<String> cmdList = new ArrayList<String>();
cmdList.add(executable());
// Choose which time to seek to
cmdList.add("-ss");
cmdList.add((params.timeseek > 0) ? "" + params.timeseek : "0");
if (dvd) {
cmdList.add("-dvd-device");
}
String frameRateRatio = null;
String frameRateNumber = null;
if (media != null) {
frameRateRatio = media.getValidFps(true);
frameRateNumber = media.getValidFps(false);
}
// Input filename
if (avisynth && !fileName.toLowerCase().endsWith(".iso")) {
File avsFile = AviSynthMEncoder.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame, frameRateRatio, frameRateNumber);
cmdList.add(ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath()));
} else {
if (params.stdin != null) {
cmdList.add("-");
} else {
if (dvd) {
String dvdFileName = fileName.replace("\\VIDEO_TS", "");
cmdList.add(dvdFileName);
} else {
cmdList.add(fileName);
}
}
}
if (dvd) {
cmdList.add("dvd://" + media.getDvdtrack());
}
for (String arg : args()) {
if (arg.contains("format=mpeg2") && media.getAspect() != null && media.getValidAspect(true) != null) {
cmdList.add(arg + ":vaspect=" + media.getValidAspect(true));
} else {
cmdList.add(arg);
}
}
if (!dtsRemux && !pcm && !avisynth() && params.aid != null && media.getAudioTracksList().size() > 1) {
cmdList.add("-aid");
boolean lavf = false; // TODO Need to add support for LAVF demuxing
cmdList.add("" + (lavf ? params.aid.getId() + 1 : params.aid.getId()));
}
/*
* Handle subtitles
*
* Try to reconcile the fact that the handling of "Definitely disable subtitles" is spread out
* over net.pms.encoders.Player.setAudioAndSubs and here by setting both of MEncoder's "disable
* subs" options if any of the internal conditions for disabling subtitles are met.
*/
if (isDisableSubtitles(params)) {
// Ensure that internal subtitles are not automatically loaded
cmdList.add("-nosub");
// Ensure that external subtitles are not automatically loaded
cmdList.add("-noautosub");
} else {
// Note: isEmbedded() and isExternal() are mutually exclusive
if (params.sid.isEmbedded()) { // internal (embedded) subs
// Ensure that external subtitles are not automatically loaded
cmdList.add("-noautosub");
// Specify which internal subtitle we want
cmdList.add("-sid");
cmdList.add("" + params.sid.getId());
} else { // external subtitles
assert params.sid.isExternal(); // confirm the mutual exclusion
// Ensure that internal subtitles are not automatically loaded
cmdList.add("-nosub");
if (params.sid.getType() == SubtitleType.VOBSUB) {
cmdList.add("-vobsub");
cmdList.add(externalSubtitlesFileName.substring(0, externalSubtitlesFileName.length() - 4));
cmdList.add("-slang");
cmdList.add("" + params.sid.getLang());
} else {
cmdList.add("-sub");
cmdList.add(externalSubtitlesFileName.replace(",", "\\,")); // Commas in MEncoder separate multiple subtitle files
if (params.sid.isExternalFileUtf()) {
// Append -utf8 option for UTF-8 external subtitles
cmdList.add("-utf8");
}
}
}
}
// -ofps
String framerate = (frameRateRatio != null) ? frameRateRatio : "24000/1001"; // where a framerate is required, use the input framerate or 24000/1001
String ofps = framerate;
// Optional -fps or -mc
if (configuration.isMencoderForceFps()) {
if (!configuration.isFix25FPSAvMismatch()) {
cmdList.add("-fps");
cmdList.add(framerate);
} else if (frameRateRatio != null) { // XXX not sure why this "fix" requires the input to have a valid framerate, but that's the logic in the old (cmdArray) code
cmdList.add("-mc");
cmdList.add("0.005");
ofps = "25";
}
}
// Make MEncoder output framerate correspond to InterFrame
if (avisynth() && configuration.getAvisynthInterFrame() && !"60000/1001".equals(frameRateRatio) && !"50".equals(frameRateRatio) && !"60".equals(frameRateRatio)) {
if ("25".equals(frameRateRatio)) {
ofps = "50";
} else if ("30".equals(frameRateRatio)) {
ofps = "60";
} else {
ofps = "60000/1001";
}
}
cmdList.add("-ofps");
cmdList.add(ofps);
if (fileName.toLowerCase().endsWith(".evo")) {
cmdList.add("-psprobe");
cmdList.add("10000");
}
boolean deinterlace = configuration.isMencoderYadif();
// Check if the media renderer supports this resolution
boolean isResolutionTooHighForRenderer = params.mediaRenderer.isVideoRescale()
&& media != null
&& (
(media.getWidth() > params.mediaRenderer.getMaxVideoWidth())
||
(media.getHeight() > params.mediaRenderer.getMaxVideoHeight())
);
// Video scaler and overscan compensation
boolean scaleBool = isResolutionTooHighForRenderer
|| (configuration.isMencoderScaler() && (configuration.getMencoderScaleX() != 0 || configuration.getMencoderScaleY() != 0))
|| (intOCW > 0 || intOCH > 0);
if ((deinterlace || scaleBool) && !avisynth()) {
StringBuilder vfValueOverscanPrepend = new StringBuilder();
StringBuilder vfValueOverscanMiddle = new StringBuilder();
StringBuilder vfValueVS = new StringBuilder();
StringBuilder vfValueComplete = new StringBuilder();
String deinterlaceComma = "";
int scaleWidth = 0;
int scaleHeight = 0;
double rendererAspectRatio;
// Set defaults
if (media != null && media.getWidth() > 0 && media.getHeight() > 0) {
scaleWidth = media.getWidth();
scaleHeight = media.getHeight();
}
/*
* Implement overscan compensation settings
*
* This feature takes into account aspect ratio,
* making it less blunt than the Video Scaler option
*/
if (intOCW > 0 || intOCH > 0) {
int intOCWPixels = (media.getWidth() / 100) * intOCW;
int intOCHPixels = (media.getHeight() / 100) * intOCH;
scaleWidth = scaleWidth + intOCWPixels;
scaleHeight = scaleHeight + intOCHPixels;
// See if the video needs to be scaled down
if (
params.mediaRenderer.isVideoRescale() &&
(
(scaleWidth > params.mediaRenderer.getMaxVideoWidth()) ||
(scaleHeight > params.mediaRenderer.getMaxVideoHeight())
)
) {
double overscannedAspectRatio = scaleWidth / scaleHeight;
rendererAspectRatio = params.mediaRenderer.getMaxVideoWidth() / params.mediaRenderer.getMaxVideoHeight();
if (overscannedAspectRatio > rendererAspectRatio) {
// Limit video by width
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / overscannedAspectRatio);
} else {
// Limit video by height
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * overscannedAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
vfValueOverscanPrepend.append("softskip,expand=-").append(intOCWPixels).append(":-").append(intOCHPixels);
vfValueOverscanMiddle.append(",scale=").append(scaleWidth).append(":").append(scaleHeight);
}
/*
* Video Scaler and renderer-specific resolution-limiter
*/
if (configuration.isMencoderScaler()) {
// Use the manual, user-controlled scaler
if (configuration.getMencoderScaleX() != 0) {
if (configuration.getMencoderScaleX() <= params.mediaRenderer.getMaxVideoWidth()) {
scaleWidth = configuration.getMencoderScaleX();
} else {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
}
}
if (configuration.getMencoderScaleY() != 0) {
if (configuration.getMencoderScaleY() <= params.mediaRenderer.getMaxVideoHeight()) {
scaleHeight = configuration.getMencoderScaleY();
} else {
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", your Video Scaler setting");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
/*
* The video resolution is too big for the renderer so we need to scale it down
*/
} else if (
media != null &&
media.getWidth() > 0 &&
media.getHeight() > 0 &&
(
media.getWidth() > params.mediaRenderer.getMaxVideoWidth() ||
media.getHeight() > params.mediaRenderer.getMaxVideoHeight()
)
) {
double videoAspectRatio = (double) media.getWidth() / (double) media.getHeight();
rendererAspectRatio = (double) params.mediaRenderer.getMaxVideoWidth() / (double) params.mediaRenderer.getMaxVideoHeight();
/*
* First we deal with some exceptions, then if they are not matched we will
* let the renderer limits work.
*
* This is so, for example, we can still define a maximum resolution of
* 1920x1080 in the renderer config file but still support 1920x1088 when
* it's needed, otherwise we would either resize 1088 to 1080, meaning the
* ugly (unused) bottom 8 pixels would be displayed, or we would limit all
* videos to 1088 causing the bottom 8 meaningful pixels to be cut off.
*/
if (media.getWidth() == 3840 && media.getHeight() <= 1080) {
// Full-SBS
scaleWidth = 1920;
scaleHeight = media.getHeight();
} else if (media.getWidth() == 1920 && media.getHeight() == 2160) {
// Full-OU
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 1088) {
// SAT capture
scaleWidth = 1920;
scaleHeight = 1088;
} else {
// Passed the exceptions, now we allow the renderer to define the limits
if (videoAspectRatio > rendererAspectRatio) {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / videoAspectRatio);
} else {
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * videoAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", the maximum your renderer supports");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
}
// Put the string together taking into account overscan compensation and video scaler
if (intOCW > 0 || intOCH > 0) {
vfValueComplete.append(vfValueOverscanPrepend).append(vfValueOverscanMiddle).append(",harddup");
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", to fit your overscan compensation");
} else {
vfValueComplete.append(vfValueVS);
}
if (deinterlace) {
deinterlaceComma = ",";
}
String vfValue = (deinterlace ? "yadif" : "") + (scaleBool ? deinterlaceComma + vfValueComplete : "");
if (isNotBlank(vfValue)) {
cmdList.add("-vf");
cmdList.add(vfValue);
}
}
/*
* The PS3 and possibly other renderers display videos incorrectly
* if the dimensions aren't divisible by 4, so if that is the
* case we add borders until it is divisible by 4.
* This fixes the long-time bug of videos displaying in black and
* white with diagonal strips of colour, weird one.
*
* TODO: Integrate this with the other stuff so that "expand" only
* ever appears once in the MEncoder CMD.
*/
if (media != null && (media.getWidth() % 4 != 0) || media.getHeight() % 4 != 0) {
int expandBorderWidth;
int expandBorderHeight;
expandBorderWidth = media.getWidth() % 4;
expandBorderHeight = media.getHeight() % 4;
cmdList.add("-vf");
cmdList.add("softskip,expand=-" + expandBorderWidth + ":-" + expandBorderHeight);
}
if (configuration.getMencoderMT() && !avisynth && !dvd && !(media.getCodecV() != null && (media.getCodecV().startsWith("mpeg2")))) {
cmdList.add("-lavdopts");
cmdList.add("fast");
}
boolean disableMc0AndNoskip = false;
// Process the options for this file in Transcoding Settings -> Mencoder -> Expert Settings: Codec-specific parameters
// TODO this is better handled by a plugin with scripting support and will be removed
if (media != null) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
// the parameters (expertOptions) are processed in 3 passes
// 1) process expertOptions
// 2) process cmdList
// 3) append expertOptions to cmdList
if (expertOptions != null && expertOptions.length > 0) {
// remove this option (key) from the cmdList in pass 2.
// if the boolean value is true, also remove the option's corresponding value
Map<String, Boolean> removeCmdListOption = new HashMap<String, Boolean>();
// if this option (key) is defined in cmdList, merge this string value into the
// option's value in pass 2. the value is a string format template into which the
// cmdList option value is injected
Map<String, String> mergeCmdListOption = new HashMap<String, String>();
// merges that are performed in pass 2 are logged in this map; the key (string) is
// the option name and the value is a boolean indicating whether the option was merged
// or not. the map is populated after pass 1 with the options from mergeCmdListOption
// and all values initialised to false. if an option was merged, it is not appended
// to cmdList
Map<String, Boolean> mergedCmdListOption = new HashMap<String, Boolean>();
// pass 1: process expertOptions
for (int i = 0; i < expertOptions.length; ++i) {
if (expertOptions[i].equals("-noass")) {
// remove -ass from cmdList in pass 2.
// -ass won't have been added in this method (getSpecificCodecOptions
// has been called multiple times above to check for -noass and -nomux)
// but it may have been added via the renderer or global MEncoder options.
// XXX: there are currently 10 other -ass options (-ass-color, -ass-border-color &c.).
// technically, they should all be removed...
removeCmdListOption.put("-ass", false); // false: option does not have a corresponding value
// remove -noass from expertOptions in pass 3
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-nomux")) {
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mt")) {
// not an MEncoder option so remove it from exportOptions.
// multi-threaded MEncoder is used by default, so this is obsolete (TODO: Remove it from the description)
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-ofps")) {
// replace the cmdList version with the expertOptions version i.e. remove the former
removeCmdListOption.put("-ofps", true);
// skip (i.e. leave unchanged) the exportOptions value
++i;
} else if (expertOptions[i].equals("-fps")) {
removeCmdListOption.put("-fps", true);
++i;
} else if (expertOptions[i].equals("-ovc")) {
removeCmdListOption.put("-ovc", true);
++i;
} else if (expertOptions[i].equals("-channels")) {
removeCmdListOption.put("-channels", true);
++i;
} else if (expertOptions[i].equals("-oac")) {
removeCmdListOption.put("-oac", true);
++i;
} else if (expertOptions[i].equals("-quality")) {
// XXX like the old (cmdArray) code, this clobbers the old -lavcopts value
String lavcopts = String.format(
"autoaspect=1:vcodec=%s:acodec=%s:abitrate=%s:threads=%d:%s",
vcodec,
(configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3"),
CodecUtil.getAC3Bitrate(configuration, params.aid),
configuration.getMencoderMaxThreads(),
expertOptions[i + 1]
);
// append bitrate-limiting options if configured
lavcopts = addMaximumBitrateConstraints(
lavcopts,
media,
lavcopts,
params.mediaRenderer,
""
);
// a string format with no placeholders, so the cmdList option value is ignored.
// note: we protect "%" from being interpreted as a format by converting it to "%%",
// which is then turned back into "%" when the format is processed
mergeCmdListOption.put("-lavcopts", lavcopts.replace("%", "%%"));
// remove -quality <value>
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-mpegopts")) {
mergeCmdListOption.put("-mpegopts", "%s:" + expertOptions[i + 1].replace("%", "%%"));
// merge if cmdList already contains -mpegopts, but don't append if it doesn't (parity with the old (cmdArray) version)
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-vf")) {
mergeCmdListOption.put("-vf", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-af")) {
mergeCmdListOption.put("-af", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-nosync")) {
disableMc0AndNoskip = true;
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mc")) {
disableMc0AndNoskip = true;
}
}
for (String key : mergeCmdListOption.keySet()) {
mergedCmdListOption.put(key, false);
}
// pass 2: process cmdList
List<String> transformedCmdList = new ArrayList<String>();
for (int i = 0; i < cmdList.size(); ++i) {
String option = cmdList.get(i);
// we remove an option by *not* adding it to transformedCmdList
if (removeCmdListOption.containsKey(option)) {
if (isTrue(removeCmdListOption.get(option))) { // true: remove (i.e. don't add) the corresponding value
++i;
}
} else {
transformedCmdList.add(option);
if (mergeCmdListOption.containsKey(option)) {
String format = mergeCmdListOption.get(option);
String value = String.format(format, cmdList.get(i + 1));
// record the fact that an expertOption value has been merged into this cmdList value
mergedCmdListOption.put(option, true);
transformedCmdList.add(value);
++i;
}
}
}
cmdList = transformedCmdList;
// pass 3: append expertOptions to cmdList
for (int i = 0; i < expertOptions.length; ++i) {
String option = expertOptions[i];
if (!option.equals(REMOVE_OPTION)) {
if (isTrue(mergedCmdListOption.get(option))) { // true: this option and its value have already been merged into existing cmdList options
++i; // skip the value
} else {
cmdList.add(option);
}
}
}
}
}
if ((pcm || dtsRemux || ac3Remux) || (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip)) {
if (configuration.isFix25FPSAvMismatch()) {
cmdList.add("-mc");
cmdList.add("0.005");
} else if (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip) {
cmdList.add("-mc");
cmdList.add("0");
cmdList.add("-noskip");
}
}
if (params.timeend > 0) {
cmdList.add("-endpos");
cmdList.add("" + params.timeend);
}
String rate = "48000";
if (params.mediaRenderer.isXBOX()) {
rate = "44100";
}
// Force srate because MEncoder doesn't like anything other than 48khz for AC-3
if (media != null && !pcm && !dtsRemux && !ac3Remux) {
cmdList.add("-af");
cmdList.add("lavcresample=" + rate);
cmdList.add("-srate");
cmdList.add(rate);
}
// Add a -cache option for piped media (e.g. rar/zip file entries):
// https://code.google.com/p/ps3mediaserver/issues/detail?id=911
if (params.stdin != null) {
cmdList.add("-cache");
cmdList.add("8192");
}
PipeProcess pipe = null;
ProcessWrapperImpl pw;
if (pcm || dtsRemux) {
// Transcode video, demux audio, remux with tsMuxeR
boolean channels_filter_present = false;
for (String s : cmdList) {
if (isNotBlank(s) && s.startsWith("channels")) {
channels_filter_present = true;
break;
}
}
if (params.avidemux) {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux || ac3Remux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
if (pcm && !channels_filter_present && params.aid != null) {
String mixer = getLPCMChannelMappingForMencoder(params.aid);
if (isNotBlank(mixer)) {
cmdList.add("-af");
cmdList.add(mixer);
}
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
pw = new ProcessWrapperImpl(cmdArray, params);
PipeProcess videoPipe = new PipeProcess("videoPipe" + System.currentTimeMillis(), "out", "reconnect");
PipeProcess audioPipe = new PipeProcess("audioPipe" + System.currentTimeMillis(), "out", "reconnect");
ProcessWrapper videoPipeProcess = videoPipe.getPipeProcess();
ProcessWrapper audioPipeProcess = audioPipe.getPipeProcess();
params.output_pipes[0] = videoPipe;
params.output_pipes[1] = audioPipe;
pw.attachProcess(videoPipeProcess);
pw.attachProcess(audioPipeProcess);
videoPipeProcess.runInNewThread();
audioPipeProcess.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) { }
videoPipe.deleteLater();
audioPipe.deleteLater();
} else {
// remove the -oac switch, otherwise the "too many video packets" errors appear again
for (ListIterator<String> it = cmdList.listIterator(); it.hasNext();) {
String option = it.next();
if (option.equals("-oac")) {
it.set("-nosound");
if (it.hasNext()) {
it.next();
it.remove();
}
break;
}
}
pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts");
TsMuxeRVideo ts = new TsMuxeRVideo(configuration);
File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta");
String cmd[] = new String[]{ ts.executable(), f.getAbsolutePath(), pipe.getInputPipe() };
pw = new ProcessWrapperImpl(cmd, params);
PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true);
cmdList.add("-o");
cmdList.add(ffVideoPipe.getInputPipe());
OutputParams ffparams = new OutputParams(configuration);
ffparams.maxBufferSize = 1;
ffparams.stdin = params.stdin;
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArray, ffparams);
ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess();
pw.attachProcess(ff_video_pipe_process);
ff_video_pipe_process.runInNewThread();
ffVideoPipe.deleteLater();
pw.attachProcess(ffVideo);
ffVideo.runInNewThread();
String aid = null;
if (media != null && media.getAudioTracksList().size() > 1 && params.aid != null) {
if (media.getContainer() != null && (media.getContainer().equals(FormatConfiguration.AVI) || media.getContainer().equals(FormatConfiguration.FLV))) {
// TODO confirm (MP4s, OGMs and MOVs already tested: first aid is 0; AVIs: first aid is 1)
// For AVIs, FLVs and MOVs MEncoder starts audio tracks numbering from 1
aid = "" + (params.aid.getId() + 1);
} else {
// Everything else from 0
aid = "" + params.aid.getId();
}
}
PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true);
StreamModifier sm = new StreamModifier();
sm.setPcm(pcm);
sm.setDtsEmbed(dtsRemux);
sm.setSampleFrequency(48000);
sm.setBitsPerSample(16);
String mixer = null;
if (pcm && !dtsRemux) {
mixer = getLPCMChannelMappingForMencoder(params.aid); // LPCM always outputs 5.1/7.1 for multichannel tracks. Downmix with player if needed!
}
sm.setNbChannels(channels);
// It seems that -really-quiet prevents MEncoder from stopping the pipe output after some time
// -mc 0.1 makes the DTS-HD extraction work better with latest MEncoder builds, and has no impact on the regular DTS one
// TODO: See if these notes are still true, and if so leave specific revisions/release names of the latest version tested.
String ffmpegLPCMextract[] = new String[]{
executable(),
"-ss", "0",
fileName,
"-really-quiet",
"-msglevel", "statusline=2",
"-channels", "" + channels,
"-ovc", "copy",
"-of", "rawaudio",
"-mc", dtsRemux ? "0.1" : "0",
"-noskip",
(aid == null) ? "-quiet" : "-aid", (aid == null) ? "-quiet" : aid,
"-oac", (ac3Remux || dtsRemux) ? "copy" : "pcm",
(isNotBlank(mixer) && !channels_filter_present) ? "-af" : "-quiet", (isNotBlank(mixer) && !channels_filter_present) ? mixer : "-quiet",
"-srate", "48000",
"-o", ffAudioPipe.getInputPipe()
};
if (!params.mediaRenderer.isMuxDTSToMpeg()) { // No need to use the PCM trick when media renderer supports DTS
ffAudioPipe.setModifier(sm);
}
if (media != null && media.getDvdtrack() > 0) {
ffmpegLPCMextract[3] = "-dvd-device";
ffmpegLPCMextract[4] = fileName;
ffmpegLPCMextract[5] = "dvd://" + media.getDvdtrack();
} else if (params.stdin != null) {
ffmpegLPCMextract[3] = "-";
}
if (fileName.toLowerCase().endsWith(".evo")) {
ffmpegLPCMextract[4] = "-psprobe";
ffmpegLPCMextract[5] = "1000000";
}
if (params.timeseek > 0) {
ffmpegLPCMextract[2] = "" + params.timeseek;
}
OutputParams ffaudioparams = new OutputParams(configuration);
ffaudioparams.maxBufferSize = 1;
ffaudioparams.stdin = params.stdin;
ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams);
params.stdin = null;
PrintWriter pwMux = new PrintWriter(f);
pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500");
String videoType = "V_MPEG-2";
if (params.no_videoencode && params.forceType != null) {
videoType = params.forceType;
}
String fps = "";
if (params.forceFps != null) {
fps = "fps=" + params.forceFps + ", ";
}
String audioType;
if (ac3Remux) {
audioType = "A_AC3";
} else if (dtsRemux) {
if (params.mediaRenderer.isMuxDTSToMpeg()) {
// Renderer can play proper DTS track
audioType = "A_DTS";
} else {
// DTS padded in LPCM trick
audioType = "A_LPCM";
}
} else {
// PCM
audioType = "A_LPCM";
}
/*
* MEncoder bug (confirmed with MEncoder r35003 + FFmpeg 0.11.1)
* Audio delay is ignored when playing from file start (-ss 0)
* Override with tsmuxer.meta setting
*/
String timeshift = "";
if (mencoderAC3RemuxAudioDelayBug) {
timeshift = "timeshift=" + params.aid.getAudioProperties().getAudioDelay() + "ms, ";
}
pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1");
pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", " + timeshift + "track=2");
pwMux.close();
ProcessWrapper pipe_process = pipe.getPipeProcess();
pw.attachProcess(pipe_process);
pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
params.input_pipes[0] = pipe;
ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess();
pw.attachProcess(ff_pipe_process);
ff_pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
ffAudioPipe.deleteLater();
pw.attachProcess(ffAudio);
ffAudio.runInNewThread();
}
} else {
boolean directpipe = Platform.isMac() || Platform.isFreeBSD();
if (directpipe) {
cmdList.add("-o");
cmdList.add("-");
cmdList.add("-really-quiet");
cmdList.add("-msglevel");
cmdList.add("statusline=2");
params.input_pipes = new PipeProcess[2];
} else {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
cmdArray = finalizeTranscoderArgs(
fileName,
dlna,
media,
params,
cmdArray
);
pw = new ProcessWrapperImpl(cmdArray, params);
if (!directpipe) {
ProcessWrapper mkfifo_process = pipe.getPipeProcess();
pw.attachProcess(mkfifo_process);
mkfifo_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
}
}
pw.runInNewThread();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
return pw;
}
@Override
public String mimeType() {
return HTTPResource.VIDEO_TRANSCODE;
}
@Override
public String name() {
return "MEncoder";
}
@Override
public int type() {
return Format.VIDEO;
}
private String[] getSpecificCodecOptions(
String codecParam,
DLNAMediaInfo media,
OutputParams params,
String filename,
String externalSubtitlesFileName,
boolean enable,
boolean verifyOnly
) {
StringBuilder sb = new StringBuilder();
String codecs = enable ? DEFAULT_CODEC_CONF_SCRIPT : "";
codecs += "\n" + codecParam;
StringTokenizer stLines = new StringTokenizer(codecs, "\n");
try {
Interpreter interpreter = new Interpreter();
interpreter.setStrictJava(true);
ArrayList<String> types = CodecUtil.getPossibleCodecs();
int rank = 1;
if (types != null) {
for (String type : types) {
int r = rank++;
interpreter.set("" + type, r);
String secondaryType = "dummy";
if ("matroska".equals(type)) {
secondaryType = "mkv";
interpreter.set(secondaryType, r);
} else if ("rm".equals(type)) {
secondaryType = "rmvb";
interpreter.set(secondaryType, r);
} else if ("mpeg2".startsWith(type)) {
secondaryType = "mpeg2";
interpreter.set(secondaryType, r);
} else if ("mpeg1video".equals(type)) {
secondaryType = "mpeg1";
interpreter.set(secondaryType, r);
}
if (media.getContainer() != null && (media.getContainer().equals(type) || media.getContainer().equals(secondaryType))) {
interpreter.set("container", r);
} else if (media.getCodecV() != null && (media.getCodecV().equals(type) || media.getCodecV().equals(secondaryType))) {
interpreter.set("vcodec", r);
} else if (params.aid != null && params.aid.getCodecA() != null && params.aid.getCodecA().equals(type)) {
interpreter.set("acodec", r);
}
}
} else {
return null;
}
interpreter.set("filename", filename);
interpreter.set("audio", params.aid != null);
interpreter.set("subtitles", params.sid != null);
interpreter.set("srtfile", externalSubtitlesFileName);
if (params.aid != null) {
interpreter.set("samplerate", params.aid.getSampleRate());
}
String frameRateNumber = null;
if (media != null) {
frameRateNumber = media.getValidFps(false);
}
try {
if (frameRateNumber != null) {
interpreter.set("framerate", Double.parseDouble(frameRateNumber));
}
} catch (NumberFormatException e) {
LOGGER.debug("Could not parse framerate from \"" + frameRateNumber + "\"");
}
interpreter.set("duration", media.getDurationInSeconds());
if (params.aid != null) {
interpreter.set("channels", params.aid.getAudioProperties().getNumberOfChannels());
}
interpreter.set("height", media.getHeight());
interpreter.set("width", media.getWidth());
while (stLines.hasMoreTokens()) {
String line = stLines.nextToken();
if (!line.startsWith("#") && line.trim().length() > 0) {
int separator = line.indexOf("::");
if (separator > -1) {
String key = null;
try {
key = line.substring(0, separator).trim();
String value = line.substring(separator + 2).trim();
if (value.length() > 0) {
if (key.length() == 0) {
key = "1 == 1";
}
Object result = interpreter.eval(key);
if (result != null && result instanceof Boolean && (Boolean) result) {
sb.append(" ");
sb.append(value);
}
}
} catch (Throwable e) {
LOGGER.debug("Error while executing: " + key + " : " + e.getMessage());
if (verifyOnly) {
return new String[]{"@@Error while parsing: " + e.getMessage()};
}
}
} else if (verifyOnly) {
return new String[]{"@@Malformatted line: " + line};
}
}
}
} catch (EvalError e) {
LOGGER.debug("BeanShell error: " + e.getMessage());
}
String completeLine = sb.toString();
ArrayList<String> args = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(completeLine, " ");
while (st.hasMoreTokens()) {
String arg = st.nextToken().trim();
if (arg.length() > 0) {
args.add(arg);
}
}
String definitiveArgs[] = new String[args.size()];
args.toArray(definitiveArgs);
return definitiveArgs;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCompatible(DLNAResource resource) {
if (resource == null || resource.getFormat().getType() != Format.VIDEO) {
return false;
}
Format format = resource.getFormat();
if (format != null) {
Format.Identifier id = format.getIdentifier();
if (id.equals(Format.Identifier.ISO)
|| id.equals(Format.Identifier.MKV)
|| id.equals(Format.Identifier.MPG)) {
return true;
}
}
return false;
}
}
| true | true | public ProcessWrapper launchTranscode(
String fileName,
DLNAResource dlna,
DLNAMediaInfo media,
OutputParams params
) throws IOException {
params.manageFastStart();
boolean avisynth = avisynth();
setAudioAndSubs(fileName, media, params, configuration);
String externalSubtitlesFileName = null;
if (params.sid != null && params.sid.isExternal()) {
if (params.sid.isExternalFileUtf16()) {
// convert UTF-16 -> UTF-8
File convertedSubtitles = new File(configuration.getTempFolder(), "utf8_" + params.sid.getExternalFile().getName());
FileUtil.convertFileFromUtf16ToUtf8(params.sid.getExternalFile(), convertedSubtitles);
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(convertedSubtitles.getAbsolutePath());
} else {
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(params.sid.getExternalFile().getAbsolutePath());
}
}
InputFile newInput = new InputFile();
newInput.setFilename(fileName);
newInput.setPush(params.stdin);
dvd = false;
if (media != null && media.getDvdtrack() > 0) {
dvd = true;
}
// Don't honour "Remux videos with tsMuxeR..." if the resource is being streamed via a MEncoder entry in
// the #--TRANSCODE--# folder, or it is a file that tsMuxeR does not support.
boolean forceMencoder = false;
if (
!configuration.getHideTranscodeEnabled() &&
dlna.isNoName() && // XXX remove this? http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12149
(
dlna.getParent() instanceof FileTranscodeVirtualFolder
)
) {
forceMencoder = true;
}
ovccopy = false;
pcm = false;
ac3Remux = false;
dtsRemux = false;
wmv = false;
int intOCW = 0;
int intOCH = 0;
try {
intOCW = Integer.parseInt(configuration.getMencoderOverscanCompensationWidth());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation width: \"{}\"", configuration.getMencoderOverscanCompensationWidth());
}
try {
intOCH = Integer.parseInt(configuration.getMencoderOverscanCompensationHeight());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation height: \"{}\"", configuration.getMencoderOverscanCompensationHeight());
}
/*
* Check if the video track and the container report different aspect ratios
*/
boolean aspectRatiosMatch = true;
if (
media.getAspectRatioContainer() != null &&
media.getAspectRatioVideoTrack() != null &&
!media.getAspectRatioContainer().equals(media.getAspectRatioVideoTrack())
) {
aspectRatiosMatch = false;
}
/**
* Do not use tsMuxeR if:
* - The resource is being streamed via a MEncoder entry in the transcode folder
* - There is a subtitle that matches the user preferences
* - The resource is a DVD
* - We are using AviSynth (TODO: do we still need this check?)
* - The resource is incompatible with tsMuxeR
* - The user has left the "switch to tsMuxeR" option enabled
* - The user has not specified overscan correction
* - The filename does not specify the resource as WEB-DL
* - The aspect ratio of the video needs to be changed
*/
if (
!forceMencoder &&
params.sid == null &&
!dvd &&
!avisynth() &&
media != null &&
(
media.isVideoWithinH264LevelLimits(newInput, params.mediaRenderer) ||
!params.mediaRenderer.isH264Level41Limited()
) &&
media.isMuxable(params.mediaRenderer) &&
configuration.isMencoderMuxWhenCompatible() &&
params.mediaRenderer.isMuxH264MpegTS() &&
(
intOCW == 0 &&
intOCH == 0
) &&
!fileName.contains("WEB-DL") &&
aspectRatiosMatch
) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
TsMuxeRVideo tv = new TsMuxeRVideo(configuration);
params.forceFps = media.getValidFps(false);
if (media.getCodecV() != null) {
if (media.getCodecV().equals("h264")) {
params.forceType = "V_MPEG4/ISO/AVC";
} else if (media.getCodecV().startsWith("mpeg2")) {
params.forceType = "V_MPEG-2";
} else if (media.getCodecV().equals("vc1")) {
params.forceType = "V_MS/VFW/WVC1";
}
}
return tv.launchTranscode(fileName, dlna, media, params);
}
} else if (params.sid == null && dvd && configuration.isMencoderRemuxMPEG2() && params.mediaRenderer.isMpeg2Supported()) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
ovccopy = true;
}
}
String vcodec = "mpeg2video";
if (params.mediaRenderer.isTranscodeToWMV()) {
wmv = true;
vcodec = "wmv2"; // http://wiki.megaframe.org/wiki/Ubuntu_XBOX_360#MEncoder not usable in streaming
}
mpegts = params.mediaRenderer.isTranscodeToMPEGTSAC3();
/**
* Disable AC3 remux for stereo tracks with 384 kbits bitrate and PS3 renderer (PS3 FW bug?)
*
* Commented out until we can find a way to detect when a video has an audio track that switches from 2 to 6 channels
* because MEncoder can't handle those files, which are very common these days.
boolean ps3_and_stereo_and_384_kbits = params.aid != null &&
(params.mediaRenderer.isPS3() && params.aid.getAudioProperties().getNumberOfChannels() == 2) &&
(params.aid.getBitRate() > 370000 && params.aid.getBitRate() < 400000);
*/
final boolean isTsMuxeRVideoEngineEnabled = configuration.getEnginesAsList(PMS.get().getRegistry()).contains(TsMuxeRVideo.ID);
final boolean mencoderAC3RemuxAudioDelayBug = (params.aid != null) && (params.aid.getAudioProperties().getAudioDelay() != 0) && (params.timeseek == 0);
if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) {
// AC-3 remux takes priority
ac3Remux = true;
} else {
// Now check for DTS remux and LPCM streaming
dtsRemux = isTsMuxeRVideoEngineEnabled &&
configuration.isDTSEmbedInPCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
) && params.aid != null &&
params.aid.isDTS() &&
!avisynth() &&
params.mediaRenderer.isDTSPlayable();
pcm = isTsMuxeRVideoEngineEnabled &&
configuration.isUsePCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
)
// Disable LPCM transcoding for MP4 container with non-H.264 video as workaround for MEncoder's A/V sync bug
&& !(media.getContainer().equals("mp4") && !media.getCodecV().equals("h264"))
&& params.aid != null &&
(
(params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || // disable 7.1 DTS-HD => LPCM because of channels mapping bug
params.aid.isLossless() ||
params.aid.isTrueHD() ||
(
!configuration.isMencoderUsePcmForHQAudioOnly() &&
(
params.aid.isAC3() ||
params.aid.isMP3() ||
params.aid.isAAC() ||
params.aid.isVorbis() ||
// Disable WMA to LPCM transcoding because of mencoder's channel mapping bug
// (see CodecUtil.getMixerOutput)
// params.aid.isWMA() ||
params.aid.isMpegAudio()
)
)
) && params.mediaRenderer.isLPCMPlayable();
}
if (dtsRemux || pcm) {
params.losslessaudio = true;
params.forceFps = media.getValidFps(false);
}
// MPEG-2 remux still buggy with MEncoder
// TODO when we can still use it?
ovccopy = false;
if (pcm && avisynth()) {
params.avidemux = true;
}
int channels;
if (ac3Remux) {
channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux
} else if (dtsRemux || wmv) {
channels = 2;
} else if (pcm) {
channels = params.aid.getAudioProperties().getNumberOfChannels();
} else {
channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding
}
LOGGER.trace("channels=" + channels);
String add = "";
String rendererMencoderOptions = params.mediaRenderer.getCustomMencoderOptions(); // default: empty string
String globalMencoderOptions = configuration.getMencoderCustomOptions(); // default: empty string
if (params.mediaRenderer.isKeepAspectRatio()) {
rendererMencoderOptions += " -vf softskip,expand=::::1:16/9:4";
}
String combinedCustomOptions = defaultString(globalMencoderOptions) +
" " +
defaultString(rendererMencoderOptions);
if (!combinedCustomOptions.contains("-lavdopts")) {
add = " -lavdopts debug=0";
}
if (isNotBlank(rendererMencoderOptions)) {
/**
* Ignore the renderer's custom MEncoder options if a) we're streaming a DVD (i.e. via dvd://)
* or b) the renderer's MEncoder options contain overscan settings (those are handled
* separately)
*/
// XXX we should weed out the unused/unwanted settings and keep the rest
// (see sanitizeArgs()) rather than ignoring the options entirely
if (rendererMencoderOptions.contains("expand=") && dvd) {
rendererMencoderOptions = null;
}
}
StringTokenizer st = new StringTokenizer(
"-channels " + channels +
(isNotBlank(globalMencoderOptions) ? " " + globalMencoderOptions : "") +
(isNotBlank(rendererMencoderOptions) ? " " + rendererMencoderOptions : "") +
add,
" "
);
// XXX why does this field (which is used to populate the array returned by args(),
// called below) store the renderer-specific (i.e. not global) MEncoder options?
overriddenMainArgs = new String[st.countTokens()];
{
int nThreads = (dvd || fileName.toLowerCase().endsWith("dvr-ms")) ?
1 :
configuration.getMencoderMaxThreads();
// MEncoder loses audio/video sync if more than 4 decoder (lavdopts) threads are used.
// Multithreading for decoding offers little performance gain anyway so it's not a big deal.
if (nThreads > 4) {
nThreads = 4;
}
boolean handleToken = false;
int i = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (handleToken) {
token += ":threads=" + nThreads;
if (configuration.getSkipLoopFilterEnabled() && !avisynth()) {
token += ":skiploopfilter=all";
}
handleToken = false;
}
if (token.toLowerCase().contains("lavdopts")) {
handleToken = true;
}
overriddenMainArgs[i++] = token;
}
}
if (configuration.getMPEG2MainSettings() != null) {
String mainConfig = configuration.getMPEG2MainSettings();
String customSettings = params.mediaRenderer.getCustomMencoderQualitySettings();
// Custom settings in PMS may override the settings of the saved configuration
if (isNotBlank(customSettings)) {
mainConfig = customSettings;
}
if (mainConfig.contains("/*")) {
mainConfig = mainConfig.substring(mainConfig.indexOf("/*"));
}
// Ditlew - WDTV Live (+ other byte asking clients), CBR. This probably ought to be placed in addMaximumBitrateConstraints(..)
int cbr_bitrate = params.mediaRenderer.getCBRVideoBitrate();
String cbr_settings = (cbr_bitrate > 0) ?
":vrc_buf_size=5000:vrc_minrate=" + cbr_bitrate + ":vrc_maxrate=" + cbr_bitrate + ":vbitrate=" + ((cbr_bitrate > 16000) ? cbr_bitrate * 1000 : cbr_bitrate) :
"";
String encodeSettings = "-lavcopts autoaspect=1:vcodec=" + vcodec +
(wmv ? ":acodec=wmav2:abitrate=448" : (cbr_settings + ":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid))) +
":threads=" + (wmv ? 1 : configuration.getMencoderMaxThreads()) +
("".equals(mainConfig) ? "" : ":" + mainConfig);
String audioType = "ac3";
if (dtsRemux) {
audioType = "dts";
} else if (pcm) {
audioType = "pcm";
}
encodeSettings = addMaximumBitrateConstraints(encodeSettings, media, mainConfig, params.mediaRenderer, audioType);
st = new StringTokenizer(encodeSettings, " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
while (st.hasMoreTokens()) {
overriddenMainArgs[i++] = st.nextToken();
}
}
}
boolean foundNoassParam = false;
if (media != null) {
String expertOptions [] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
for (String s : expertOptions) {
if (s.equals("-noass")) {
foundNoassParam = true;
}
}
}
StringBuilder sb = new StringBuilder();
// Set subtitles options
if (!isDisableSubtitles(params)) {
int subtitleMargin = 0;
int userMargin = 0;
// Use ASS flag (and therefore ASS font styles) for all subtitled files except vobsub, PGS (blu-ray) and DVD
boolean apply_ass_styling = params.sid.getType() != SubtitleType.VOBSUB &&
params.sid.getType() != SubtitleType.PGS &&
configuration.isMencoderAss() && // GUI: enable subtitles formating
!foundNoassParam && // GUI: codec specific options
!dvd;
if (apply_ass_styling) {
sb.append("-ass ");
// GUI: Override ASS subtitles style if requested (always for SRT and TX3G subtitles)
boolean override_ass_style = !configuration.isMencoderAssDefaultStyle() ||
params.sid.getType() == SubtitleType.SUBRIP ||
params.sid.getType() == SubtitleType.TX3G;
if (override_ass_style) {
String assSubColor = "ffffff00";
if (configuration.getSubsColor() != 0) {
assSubColor = Integer.toHexString(configuration.getSubsColor());
if (assSubColor.length() > 2) {
assSubColor = assSubColor.substring(2) + "00";
}
}
sb.append("-ass-color ").append(assSubColor).append(" -ass-border-color 00000000 -ass-font-scale ").append(configuration.getMencoderAssScale());
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
/* Set font with -font option, workaround for the bug:
* https://github.com/Happy-Neko/ps3mediaserver/commit/52e62203ea12c40628de1869882994ce1065446a#commitcomment-990156
*/
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
sb.append(" -ass-force-style FontName=").append(configuration.getMencoderFont()).append(",");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
/*
* Variable "font" contains a font path instead of a font name.
* Does "-ass-force-style" support font paths? In tests on OS X
* the font path is ignored (Outline, Shadow and MarginV are
* used, though) and the "-font" definition is used instead.
* See: https://github.com/ps3mediaserver/ps3mediaserver/pull/14
*/
sb.append(" -font ").append(font).append(" ");
sb.append(" -ass-force-style FontName=").append(font).append(",");
} else {
sb.append(" -font Arial ");
sb.append(" -ass-force-style FontName=Arial,");
}
}
/*
* Add to the subtitle margin if overscan compensation is being used
* This keeps the subtitle text inside the frame instead of in the border
*/
if (intOCH > 0) {
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
}
sb.append("Outline=").append(configuration.getMencoderAssOutline()).append(",Shadow=").append(configuration.getMencoderAssShadow());
try {
userMargin = Integer.parseInt(configuration.getMencoderAssMargin());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse SSA margin from \"" + configuration.getMencoderAssMargin() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(",MarginV=").append(subtitleMargin).append(" ");
} else if (intOCH > 0) {
/*
* Add to the subtitle margin
* This keeps the subtitle text inside the frame instead of in the border
*/
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
sb.append("-ass-force-style MarginV=").append(subtitleMargin).append(" ");
}
// MEncoder is not compiled with fontconfig on Mac OS X, therefore
// use of the "-ass" option also requires the "-font" option.
if (Platform.isMac() && sb.toString().indexOf(" -font ") < 0) {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append("-font ").append(font).append(" ");
}
}
// Workaround for MPlayer #2041, remove when that bug is fixed
if (!params.sid.isEmbedded()) {
sb.append("-noflip-hebrew ");
}
// Use PLAINTEXT formatting
} else {
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append(" -font ").append(font).append(" ");
}
}
sb.append(" -subfont-text-scale ").append(configuration.getMencoderNoAssScale());
sb.append(" -subfont-outline ").append(configuration.getMencoderNoAssOutline());
sb.append(" -subfont-blur ").append(configuration.getMencoderNoAssBlur());
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = intOCH;
}
try {
userMargin = Integer.parseInt(configuration.getMencoderNoAssSubPos());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse subpos from \"" + configuration.getMencoderNoAssSubPos() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(" -subpos ").append(100 - subtitleMargin).append(" ");
}
// Common subtitle options
// MEncoder on Mac OS X is compiled without fontconfig support.
// Appending the flag will break execution, so skip it on Mac OS X.
if (!Platform.isMac()) {
// Use fontconfig if enabled
sb.append("-").append(configuration.isMencoderFontConfig() ? "" : "no").append("fontconfig ");
}
// Apply DVD/VOBsub subtitle quality
if (params.sid.getType() == SubtitleType.VOBSUB && configuration.getMencoderVobsubSubtitleQuality() != null) {
String subtitleQuality = configuration.getMencoderVobsubSubtitleQuality();
sb.append("-spuaa ").append(subtitleQuality).append(" ");
}
// External subtitles file
if (params.sid.isExternal()) {
if (!params.sid.isExternalFileUtf()) {
String subcp = null;
// Append -subcp option for non UTF external subtitles
if (isNotBlank(configuration.getMencoderSubCp())) {
// Manual setting
subcp = configuration.getMencoderSubCp();
} else if (isNotBlank(SubtitleUtils.getSubCpOptionForMencoder(params.sid))) {
// Autodetect charset (blank mencoder_subcp config option)
subcp = SubtitleUtils.getSubCpOptionForMencoder(params.sid);
}
if (isNotBlank(subcp)) {
sb.append("-subcp ").append(subcp).append(" ");
if (configuration.isMencoderSubFribidi()) {
sb.append("-fribidi-charset ").append(subcp).append(" ");
}
}
}
}
}
st = new StringTokenizer(sb.toString(), " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
boolean handleToken = false;
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (handleToken) {
s = "-quiet";
handleToken = false;
}
if ((!configuration.isMencoderAss() || dvd) && s.contains("-ass")) {
s = "-quiet";
handleToken = true;
}
overriddenMainArgs[i++] = s;
}
}
List<String> cmdList = new ArrayList<String>();
cmdList.add(executable());
// Choose which time to seek to
cmdList.add("-ss");
cmdList.add((params.timeseek > 0) ? "" + params.timeseek : "0");
if (dvd) {
cmdList.add("-dvd-device");
}
String frameRateRatio = null;
String frameRateNumber = null;
if (media != null) {
frameRateRatio = media.getValidFps(true);
frameRateNumber = media.getValidFps(false);
}
// Input filename
if (avisynth && !fileName.toLowerCase().endsWith(".iso")) {
File avsFile = AviSynthMEncoder.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame, frameRateRatio, frameRateNumber);
cmdList.add(ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath()));
} else {
if (params.stdin != null) {
cmdList.add("-");
} else {
if (dvd) {
String dvdFileName = fileName.replace("\\VIDEO_TS", "");
cmdList.add(dvdFileName);
} else {
cmdList.add(fileName);
}
}
}
if (dvd) {
cmdList.add("dvd://" + media.getDvdtrack());
}
for (String arg : args()) {
if (arg.contains("format=mpeg2") && media.getAspect() != null && media.getValidAspect(true) != null) {
cmdList.add(arg + ":vaspect=" + media.getValidAspect(true));
} else {
cmdList.add(arg);
}
}
if (!dtsRemux && !pcm && !avisynth() && params.aid != null && media.getAudioTracksList().size() > 1) {
cmdList.add("-aid");
boolean lavf = false; // TODO Need to add support for LAVF demuxing
cmdList.add("" + (lavf ? params.aid.getId() + 1 : params.aid.getId()));
}
/*
* Handle subtitles
*
* Try to reconcile the fact that the handling of "Definitely disable subtitles" is spread out
* over net.pms.encoders.Player.setAudioAndSubs and here by setting both of MEncoder's "disable
* subs" options if any of the internal conditions for disabling subtitles are met.
*/
if (isDisableSubtitles(params)) {
// Ensure that internal subtitles are not automatically loaded
cmdList.add("-nosub");
// Ensure that external subtitles are not automatically loaded
cmdList.add("-noautosub");
} else {
// Note: isEmbedded() and isExternal() are mutually exclusive
if (params.sid.isEmbedded()) { // internal (embedded) subs
// Ensure that external subtitles are not automatically loaded
cmdList.add("-noautosub");
// Specify which internal subtitle we want
cmdList.add("-sid");
cmdList.add("" + params.sid.getId());
} else { // external subtitles
assert params.sid.isExternal(); // confirm the mutual exclusion
// Ensure that internal subtitles are not automatically loaded
cmdList.add("-nosub");
if (params.sid.getType() == SubtitleType.VOBSUB) {
cmdList.add("-vobsub");
cmdList.add(externalSubtitlesFileName.substring(0, externalSubtitlesFileName.length() - 4));
cmdList.add("-slang");
cmdList.add("" + params.sid.getLang());
} else {
cmdList.add("-sub");
cmdList.add(externalSubtitlesFileName.replace(",", "\\,")); // Commas in MEncoder separate multiple subtitle files
if (params.sid.isExternalFileUtf()) {
// Append -utf8 option for UTF-8 external subtitles
cmdList.add("-utf8");
}
}
}
}
// -ofps
String framerate = (frameRateRatio != null) ? frameRateRatio : "24000/1001"; // where a framerate is required, use the input framerate or 24000/1001
String ofps = framerate;
// Optional -fps or -mc
if (configuration.isMencoderForceFps()) {
if (!configuration.isFix25FPSAvMismatch()) {
cmdList.add("-fps");
cmdList.add(framerate);
} else if (frameRateRatio != null) { // XXX not sure why this "fix" requires the input to have a valid framerate, but that's the logic in the old (cmdArray) code
cmdList.add("-mc");
cmdList.add("0.005");
ofps = "25";
}
}
// Make MEncoder output framerate correspond to InterFrame
if (avisynth() && configuration.getAvisynthInterFrame() && !"60000/1001".equals(frameRateRatio) && !"50".equals(frameRateRatio) && !"60".equals(frameRateRatio)) {
if ("25".equals(frameRateRatio)) {
ofps = "50";
} else if ("30".equals(frameRateRatio)) {
ofps = "60";
} else {
ofps = "60000/1001";
}
}
cmdList.add("-ofps");
cmdList.add(ofps);
if (fileName.toLowerCase().endsWith(".evo")) {
cmdList.add("-psprobe");
cmdList.add("10000");
}
boolean deinterlace = configuration.isMencoderYadif();
// Check if the media renderer supports this resolution
boolean isResolutionTooHighForRenderer = params.mediaRenderer.isVideoRescale()
&& media != null
&& (
(media.getWidth() > params.mediaRenderer.getMaxVideoWidth())
||
(media.getHeight() > params.mediaRenderer.getMaxVideoHeight())
);
// Video scaler and overscan compensation
boolean scaleBool = isResolutionTooHighForRenderer
|| (configuration.isMencoderScaler() && (configuration.getMencoderScaleX() != 0 || configuration.getMencoderScaleY() != 0))
|| (intOCW > 0 || intOCH > 0);
if ((deinterlace || scaleBool) && !avisynth()) {
StringBuilder vfValueOverscanPrepend = new StringBuilder();
StringBuilder vfValueOverscanMiddle = new StringBuilder();
StringBuilder vfValueVS = new StringBuilder();
StringBuilder vfValueComplete = new StringBuilder();
String deinterlaceComma = "";
int scaleWidth = 0;
int scaleHeight = 0;
double rendererAspectRatio;
// Set defaults
if (media != null && media.getWidth() > 0 && media.getHeight() > 0) {
scaleWidth = media.getWidth();
scaleHeight = media.getHeight();
}
/*
* Implement overscan compensation settings
*
* This feature takes into account aspect ratio,
* making it less blunt than the Video Scaler option
*/
if (intOCW > 0 || intOCH > 0) {
int intOCWPixels = (media.getWidth() / 100) * intOCW;
int intOCHPixels = (media.getHeight() / 100) * intOCH;
scaleWidth = scaleWidth + intOCWPixels;
scaleHeight = scaleHeight + intOCHPixels;
// See if the video needs to be scaled down
if (
params.mediaRenderer.isVideoRescale() &&
(
(scaleWidth > params.mediaRenderer.getMaxVideoWidth()) ||
(scaleHeight > params.mediaRenderer.getMaxVideoHeight())
)
) {
double overscannedAspectRatio = scaleWidth / scaleHeight;
rendererAspectRatio = params.mediaRenderer.getMaxVideoWidth() / params.mediaRenderer.getMaxVideoHeight();
if (overscannedAspectRatio > rendererAspectRatio) {
// Limit video by width
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / overscannedAspectRatio);
} else {
// Limit video by height
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * overscannedAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
vfValueOverscanPrepend.append("softskip,expand=-").append(intOCWPixels).append(":-").append(intOCHPixels);
vfValueOverscanMiddle.append(",scale=").append(scaleWidth).append(":").append(scaleHeight);
}
/*
* Video Scaler and renderer-specific resolution-limiter
*/
if (configuration.isMencoderScaler()) {
// Use the manual, user-controlled scaler
if (configuration.getMencoderScaleX() != 0) {
if (configuration.getMencoderScaleX() <= params.mediaRenderer.getMaxVideoWidth()) {
scaleWidth = configuration.getMencoderScaleX();
} else {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
}
}
if (configuration.getMencoderScaleY() != 0) {
if (configuration.getMencoderScaleY() <= params.mediaRenderer.getMaxVideoHeight()) {
scaleHeight = configuration.getMencoderScaleY();
} else {
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", your Video Scaler setting");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
/*
* The video resolution is too big for the renderer so we need to scale it down
*/
} else if (
media != null &&
media.getWidth() > 0 &&
media.getHeight() > 0 &&
(
media.getWidth() > params.mediaRenderer.getMaxVideoWidth() ||
media.getHeight() > params.mediaRenderer.getMaxVideoHeight()
)
) {
double videoAspectRatio = (double) media.getWidth() / (double) media.getHeight();
rendererAspectRatio = (double) params.mediaRenderer.getMaxVideoWidth() / (double) params.mediaRenderer.getMaxVideoHeight();
/*
* First we deal with some exceptions, then if they are not matched we will
* let the renderer limits work.
*
* This is so, for example, we can still define a maximum resolution of
* 1920x1080 in the renderer config file but still support 1920x1088 when
* it's needed, otherwise we would either resize 1088 to 1080, meaning the
* ugly (unused) bottom 8 pixels would be displayed, or we would limit all
* videos to 1088 causing the bottom 8 meaningful pixels to be cut off.
*/
if (media.getWidth() == 3840 && media.getHeight() <= 1080) {
// Full-SBS
scaleWidth = 1920;
scaleHeight = media.getHeight();
} else if (media.getWidth() == 1920 && media.getHeight() == 2160) {
// Full-OU
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 1088) {
// SAT capture
scaleWidth = 1920;
scaleHeight = 1088;
} else {
// Passed the exceptions, now we allow the renderer to define the limits
if (videoAspectRatio > rendererAspectRatio) {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / videoAspectRatio);
} else {
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * videoAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", the maximum your renderer supports");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
}
// Put the string together taking into account overscan compensation and video scaler
if (intOCW > 0 || intOCH > 0) {
vfValueComplete.append(vfValueOverscanPrepend).append(vfValueOverscanMiddle).append(",harddup");
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", to fit your overscan compensation");
} else {
vfValueComplete.append(vfValueVS);
}
if (deinterlace) {
deinterlaceComma = ",";
}
String vfValue = (deinterlace ? "yadif" : "") + (scaleBool ? deinterlaceComma + vfValueComplete : "");
if (isNotBlank(vfValue)) {
cmdList.add("-vf");
cmdList.add(vfValue);
}
}
/*
* The PS3 and possibly other renderers display videos incorrectly
* if the dimensions aren't divisible by 4, so if that is the
* case we add borders until it is divisible by 4.
* This fixes the long-time bug of videos displaying in black and
* white with diagonal strips of colour, weird one.
*
* TODO: Integrate this with the other stuff so that "expand" only
* ever appears once in the MEncoder CMD.
*/
if (media != null && (media.getWidth() % 4 != 0) || media.getHeight() % 4 != 0) {
int expandBorderWidth;
int expandBorderHeight;
expandBorderWidth = media.getWidth() % 4;
expandBorderHeight = media.getHeight() % 4;
cmdList.add("-vf");
cmdList.add("softskip,expand=-" + expandBorderWidth + ":-" + expandBorderHeight);
}
if (configuration.getMencoderMT() && !avisynth && !dvd && !(media.getCodecV() != null && (media.getCodecV().startsWith("mpeg2")))) {
cmdList.add("-lavdopts");
cmdList.add("fast");
}
boolean disableMc0AndNoskip = false;
// Process the options for this file in Transcoding Settings -> Mencoder -> Expert Settings: Codec-specific parameters
// TODO this is better handled by a plugin with scripting support and will be removed
if (media != null) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
// the parameters (expertOptions) are processed in 3 passes
// 1) process expertOptions
// 2) process cmdList
// 3) append expertOptions to cmdList
if (expertOptions != null && expertOptions.length > 0) {
// remove this option (key) from the cmdList in pass 2.
// if the boolean value is true, also remove the option's corresponding value
Map<String, Boolean> removeCmdListOption = new HashMap<String, Boolean>();
// if this option (key) is defined in cmdList, merge this string value into the
// option's value in pass 2. the value is a string format template into which the
// cmdList option value is injected
Map<String, String> mergeCmdListOption = new HashMap<String, String>();
// merges that are performed in pass 2 are logged in this map; the key (string) is
// the option name and the value is a boolean indicating whether the option was merged
// or not. the map is populated after pass 1 with the options from mergeCmdListOption
// and all values initialised to false. if an option was merged, it is not appended
// to cmdList
Map<String, Boolean> mergedCmdListOption = new HashMap<String, Boolean>();
// pass 1: process expertOptions
for (int i = 0; i < expertOptions.length; ++i) {
if (expertOptions[i].equals("-noass")) {
// remove -ass from cmdList in pass 2.
// -ass won't have been added in this method (getSpecificCodecOptions
// has been called multiple times above to check for -noass and -nomux)
// but it may have been added via the renderer or global MEncoder options.
// XXX: there are currently 10 other -ass options (-ass-color, -ass-border-color &c.).
// technically, they should all be removed...
removeCmdListOption.put("-ass", false); // false: option does not have a corresponding value
// remove -noass from expertOptions in pass 3
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-nomux")) {
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mt")) {
// not an MEncoder option so remove it from exportOptions.
// multi-threaded MEncoder is used by default, so this is obsolete (TODO: Remove it from the description)
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-ofps")) {
// replace the cmdList version with the expertOptions version i.e. remove the former
removeCmdListOption.put("-ofps", true);
// skip (i.e. leave unchanged) the exportOptions value
++i;
} else if (expertOptions[i].equals("-fps")) {
removeCmdListOption.put("-fps", true);
++i;
} else if (expertOptions[i].equals("-ovc")) {
removeCmdListOption.put("-ovc", true);
++i;
} else if (expertOptions[i].equals("-channels")) {
removeCmdListOption.put("-channels", true);
++i;
} else if (expertOptions[i].equals("-oac")) {
removeCmdListOption.put("-oac", true);
++i;
} else if (expertOptions[i].equals("-quality")) {
// XXX like the old (cmdArray) code, this clobbers the old -lavcopts value
String lavcopts = String.format(
"autoaspect=1:vcodec=%s:acodec=%s:abitrate=%s:threads=%d:%s",
vcodec,
(configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3"),
CodecUtil.getAC3Bitrate(configuration, params.aid),
configuration.getMencoderMaxThreads(),
expertOptions[i + 1]
);
// append bitrate-limiting options if configured
lavcopts = addMaximumBitrateConstraints(
lavcopts,
media,
lavcopts,
params.mediaRenderer,
""
);
// a string format with no placeholders, so the cmdList option value is ignored.
// note: we protect "%" from being interpreted as a format by converting it to "%%",
// which is then turned back into "%" when the format is processed
mergeCmdListOption.put("-lavcopts", lavcopts.replace("%", "%%"));
// remove -quality <value>
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-mpegopts")) {
mergeCmdListOption.put("-mpegopts", "%s:" + expertOptions[i + 1].replace("%", "%%"));
// merge if cmdList already contains -mpegopts, but don't append if it doesn't (parity with the old (cmdArray) version)
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-vf")) {
mergeCmdListOption.put("-vf", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-af")) {
mergeCmdListOption.put("-af", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-nosync")) {
disableMc0AndNoskip = true;
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mc")) {
disableMc0AndNoskip = true;
}
}
for (String key : mergeCmdListOption.keySet()) {
mergedCmdListOption.put(key, false);
}
// pass 2: process cmdList
List<String> transformedCmdList = new ArrayList<String>();
for (int i = 0; i < cmdList.size(); ++i) {
String option = cmdList.get(i);
// we remove an option by *not* adding it to transformedCmdList
if (removeCmdListOption.containsKey(option)) {
if (isTrue(removeCmdListOption.get(option))) { // true: remove (i.e. don't add) the corresponding value
++i;
}
} else {
transformedCmdList.add(option);
if (mergeCmdListOption.containsKey(option)) {
String format = mergeCmdListOption.get(option);
String value = String.format(format, cmdList.get(i + 1));
// record the fact that an expertOption value has been merged into this cmdList value
mergedCmdListOption.put(option, true);
transformedCmdList.add(value);
++i;
}
}
}
cmdList = transformedCmdList;
// pass 3: append expertOptions to cmdList
for (int i = 0; i < expertOptions.length; ++i) {
String option = expertOptions[i];
if (!option.equals(REMOVE_OPTION)) {
if (isTrue(mergedCmdListOption.get(option))) { // true: this option and its value have already been merged into existing cmdList options
++i; // skip the value
} else {
cmdList.add(option);
}
}
}
}
}
if ((pcm || dtsRemux || ac3Remux) || (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip)) {
if (configuration.isFix25FPSAvMismatch()) {
cmdList.add("-mc");
cmdList.add("0.005");
} else if (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip) {
cmdList.add("-mc");
cmdList.add("0");
cmdList.add("-noskip");
}
}
if (params.timeend > 0) {
cmdList.add("-endpos");
cmdList.add("" + params.timeend);
}
String rate = "48000";
if (params.mediaRenderer.isXBOX()) {
rate = "44100";
}
// Force srate because MEncoder doesn't like anything other than 48khz for AC-3
if (media != null && !pcm && !dtsRemux && !ac3Remux) {
cmdList.add("-af");
cmdList.add("lavcresample=" + rate);
cmdList.add("-srate");
cmdList.add(rate);
}
// Add a -cache option for piped media (e.g. rar/zip file entries):
// https://code.google.com/p/ps3mediaserver/issues/detail?id=911
if (params.stdin != null) {
cmdList.add("-cache");
cmdList.add("8192");
}
PipeProcess pipe = null;
ProcessWrapperImpl pw;
if (pcm || dtsRemux) {
// Transcode video, demux audio, remux with tsMuxeR
boolean channels_filter_present = false;
for (String s : cmdList) {
if (isNotBlank(s) && s.startsWith("channels")) {
channels_filter_present = true;
break;
}
}
if (params.avidemux) {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux || ac3Remux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
if (pcm && !channels_filter_present && params.aid != null) {
String mixer = getLPCMChannelMappingForMencoder(params.aid);
if (isNotBlank(mixer)) {
cmdList.add("-af");
cmdList.add(mixer);
}
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
pw = new ProcessWrapperImpl(cmdArray, params);
PipeProcess videoPipe = new PipeProcess("videoPipe" + System.currentTimeMillis(), "out", "reconnect");
PipeProcess audioPipe = new PipeProcess("audioPipe" + System.currentTimeMillis(), "out", "reconnect");
ProcessWrapper videoPipeProcess = videoPipe.getPipeProcess();
ProcessWrapper audioPipeProcess = audioPipe.getPipeProcess();
params.output_pipes[0] = videoPipe;
params.output_pipes[1] = audioPipe;
pw.attachProcess(videoPipeProcess);
pw.attachProcess(audioPipeProcess);
videoPipeProcess.runInNewThread();
audioPipeProcess.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) { }
videoPipe.deleteLater();
audioPipe.deleteLater();
} else {
// remove the -oac switch, otherwise the "too many video packets" errors appear again
for (ListIterator<String> it = cmdList.listIterator(); it.hasNext();) {
String option = it.next();
if (option.equals("-oac")) {
it.set("-nosound");
if (it.hasNext()) {
it.next();
it.remove();
}
break;
}
}
pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts");
TsMuxeRVideo ts = new TsMuxeRVideo(configuration);
File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta");
String cmd[] = new String[]{ ts.executable(), f.getAbsolutePath(), pipe.getInputPipe() };
pw = new ProcessWrapperImpl(cmd, params);
PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true);
cmdList.add("-o");
cmdList.add(ffVideoPipe.getInputPipe());
OutputParams ffparams = new OutputParams(configuration);
ffparams.maxBufferSize = 1;
ffparams.stdin = params.stdin;
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArray, ffparams);
ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess();
pw.attachProcess(ff_video_pipe_process);
ff_video_pipe_process.runInNewThread();
ffVideoPipe.deleteLater();
pw.attachProcess(ffVideo);
ffVideo.runInNewThread();
String aid = null;
if (media != null && media.getAudioTracksList().size() > 1 && params.aid != null) {
if (media.getContainer() != null && (media.getContainer().equals(FormatConfiguration.AVI) || media.getContainer().equals(FormatConfiguration.FLV))) {
// TODO confirm (MP4s, OGMs and MOVs already tested: first aid is 0; AVIs: first aid is 1)
// For AVIs, FLVs and MOVs MEncoder starts audio tracks numbering from 1
aid = "" + (params.aid.getId() + 1);
} else {
// Everything else from 0
aid = "" + params.aid.getId();
}
}
PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true);
StreamModifier sm = new StreamModifier();
sm.setPcm(pcm);
sm.setDtsEmbed(dtsRemux);
sm.setSampleFrequency(48000);
sm.setBitsPerSample(16);
String mixer = null;
if (pcm && !dtsRemux) {
mixer = getLPCMChannelMappingForMencoder(params.aid); // LPCM always outputs 5.1/7.1 for multichannel tracks. Downmix with player if needed!
}
sm.setNbChannels(channels);
// It seems that -really-quiet prevents MEncoder from stopping the pipe output after some time
// -mc 0.1 makes the DTS-HD extraction work better with latest MEncoder builds, and has no impact on the regular DTS one
// TODO: See if these notes are still true, and if so leave specific revisions/release names of the latest version tested.
String ffmpegLPCMextract[] = new String[]{
executable(),
"-ss", "0",
fileName,
"-really-quiet",
"-msglevel", "statusline=2",
"-channels", "" + channels,
"-ovc", "copy",
"-of", "rawaudio",
"-mc", dtsRemux ? "0.1" : "0",
"-noskip",
(aid == null) ? "-quiet" : "-aid", (aid == null) ? "-quiet" : aid,
"-oac", (ac3Remux || dtsRemux) ? "copy" : "pcm",
(isNotBlank(mixer) && !channels_filter_present) ? "-af" : "-quiet", (isNotBlank(mixer) && !channels_filter_present) ? mixer : "-quiet",
"-srate", "48000",
"-o", ffAudioPipe.getInputPipe()
};
if (!params.mediaRenderer.isMuxDTSToMpeg()) { // No need to use the PCM trick when media renderer supports DTS
ffAudioPipe.setModifier(sm);
}
if (media != null && media.getDvdtrack() > 0) {
ffmpegLPCMextract[3] = "-dvd-device";
ffmpegLPCMextract[4] = fileName;
ffmpegLPCMextract[5] = "dvd://" + media.getDvdtrack();
} else if (params.stdin != null) {
ffmpegLPCMextract[3] = "-";
}
if (fileName.toLowerCase().endsWith(".evo")) {
ffmpegLPCMextract[4] = "-psprobe";
ffmpegLPCMextract[5] = "1000000";
}
if (params.timeseek > 0) {
ffmpegLPCMextract[2] = "" + params.timeseek;
}
OutputParams ffaudioparams = new OutputParams(configuration);
ffaudioparams.maxBufferSize = 1;
ffaudioparams.stdin = params.stdin;
ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams);
params.stdin = null;
PrintWriter pwMux = new PrintWriter(f);
pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500");
String videoType = "V_MPEG-2";
if (params.no_videoencode && params.forceType != null) {
videoType = params.forceType;
}
String fps = "";
if (params.forceFps != null) {
fps = "fps=" + params.forceFps + ", ";
}
String audioType;
if (ac3Remux) {
audioType = "A_AC3";
} else if (dtsRemux) {
if (params.mediaRenderer.isMuxDTSToMpeg()) {
// Renderer can play proper DTS track
audioType = "A_DTS";
} else {
// DTS padded in LPCM trick
audioType = "A_LPCM";
}
} else {
// PCM
audioType = "A_LPCM";
}
/*
* MEncoder bug (confirmed with MEncoder r35003 + FFmpeg 0.11.1)
* Audio delay is ignored when playing from file start (-ss 0)
* Override with tsmuxer.meta setting
*/
String timeshift = "";
if (mencoderAC3RemuxAudioDelayBug) {
timeshift = "timeshift=" + params.aid.getAudioProperties().getAudioDelay() + "ms, ";
}
pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1");
pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", " + timeshift + "track=2");
pwMux.close();
ProcessWrapper pipe_process = pipe.getPipeProcess();
pw.attachProcess(pipe_process);
pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
params.input_pipes[0] = pipe;
ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess();
pw.attachProcess(ff_pipe_process);
ff_pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
ffAudioPipe.deleteLater();
pw.attachProcess(ffAudio);
ffAudio.runInNewThread();
}
} else {
boolean directpipe = Platform.isMac() || Platform.isFreeBSD();
if (directpipe) {
cmdList.add("-o");
cmdList.add("-");
cmdList.add("-really-quiet");
cmdList.add("-msglevel");
cmdList.add("statusline=2");
params.input_pipes = new PipeProcess[2];
} else {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
cmdArray = finalizeTranscoderArgs(
fileName,
dlna,
media,
params,
cmdArray
);
pw = new ProcessWrapperImpl(cmdArray, params);
if (!directpipe) {
ProcessWrapper mkfifo_process = pipe.getPipeProcess();
pw.attachProcess(mkfifo_process);
mkfifo_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
}
}
pw.runInNewThread();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
return pw;
}
| public ProcessWrapper launchTranscode(
String fileName,
DLNAResource dlna,
DLNAMediaInfo media,
OutputParams params
) throws IOException {
params.manageFastStart();
boolean avisynth = avisynth();
setAudioAndSubs(fileName, media, params, configuration);
String externalSubtitlesFileName = null;
if (params.sid != null && params.sid.isExternal()) {
if (params.sid.isExternalFileUtf16()) {
// convert UTF-16 -> UTF-8
File convertedSubtitles = new File(configuration.getTempFolder(), "utf8_" + params.sid.getExternalFile().getName());
FileUtil.convertFileFromUtf16ToUtf8(params.sid.getExternalFile(), convertedSubtitles);
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(convertedSubtitles.getAbsolutePath());
} else {
externalSubtitlesFileName = ProcessUtil.getShortFileNameIfWideChars(params.sid.getExternalFile().getAbsolutePath());
}
}
InputFile newInput = new InputFile();
newInput.setFilename(fileName);
newInput.setPush(params.stdin);
dvd = false;
if (media != null && media.getDvdtrack() > 0) {
dvd = true;
}
// Don't honour "Remux videos with tsMuxeR..." if the resource is being streamed via a MEncoder entry in
// the #--TRANSCODE--# folder, or it is a file that tsMuxeR does not support.
boolean forceMencoder = false;
if (
!configuration.getHideTranscodeEnabled() &&
dlna.isNoName() && // XXX remove this? http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12149
(
dlna.getParent() instanceof FileTranscodeVirtualFolder
)
) {
forceMencoder = true;
}
ovccopy = false;
pcm = false;
ac3Remux = false;
dtsRemux = false;
wmv = false;
int intOCW = 0;
int intOCH = 0;
try {
intOCW = Integer.parseInt(configuration.getMencoderOverscanCompensationWidth());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation width: \"{}\"", configuration.getMencoderOverscanCompensationWidth());
}
try {
intOCH = Integer.parseInt(configuration.getMencoderOverscanCompensationHeight());
} catch (NumberFormatException e) {
LOGGER.error("Cannot parse configured MEncoder overscan compensation height: \"{}\"", configuration.getMencoderOverscanCompensationHeight());
}
/*
* Check if the video track and the container report different aspect ratios
*/
boolean aspectRatiosMatch = true;
if (
media.getAspectRatioContainer() != null &&
media.getAspectRatioVideoTrack() != null &&
!media.getAspectRatioContainer().equals(media.getAspectRatioVideoTrack())
) {
aspectRatiosMatch = false;
}
/**
* Do not use tsMuxeR if:
* - The resource is being streamed via a MEncoder entry in the transcode folder
* - There is a subtitle that matches the user preferences
* - The resource is a DVD
* - We are using AviSynth (TODO: do we still need this check?)
* - The resource is incompatible with tsMuxeR
* - The user has left the "switch to tsMuxeR" option enabled
* - The user has not specified overscan correction
* - The filename does not specify the resource as WEB-DL
* - The aspect ratio of the video needs to be changed
*/
if (
!forceMencoder &&
params.sid == null &&
!dvd &&
!avisynth() &&
media != null &&
(
media.isVideoWithinH264LevelLimits(newInput, params.mediaRenderer) ||
!params.mediaRenderer.isH264Level41Limited()
) &&
media.isMuxable(params.mediaRenderer) &&
configuration.isMencoderMuxWhenCompatible() &&
params.mediaRenderer.isMuxH264MpegTS() &&
(
intOCW == 0 &&
intOCH == 0
) &&
!fileName.contains("WEB-DL") &&
aspectRatiosMatch
) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
TsMuxeRVideo tv = new TsMuxeRVideo(configuration);
params.forceFps = media.getValidFps(false);
if (media.getCodecV() != null) {
if (media.getCodecV().equals("h264")) {
params.forceType = "V_MPEG4/ISO/AVC";
} else if (media.getCodecV().startsWith("mpeg2")) {
params.forceType = "V_MPEG-2";
} else if (media.getCodecV().equals("vc1")) {
params.forceType = "V_MS/VFW/WVC1";
}
}
return tv.launchTranscode(fileName, dlna, media, params);
}
} else if (params.sid == null && dvd && configuration.isMencoderRemuxMPEG2() && params.mediaRenderer.isMpeg2Supported()) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
boolean nomux = false;
for (String s : expertOptions) {
if (s.equals("-nomux")) {
nomux = true;
}
}
if (!nomux) {
ovccopy = true;
}
}
String vcodec = "mpeg2video";
if (params.mediaRenderer.isTranscodeToWMV()) {
wmv = true;
vcodec = "wmv2"; // http://wiki.megaframe.org/wiki/Ubuntu_XBOX_360#MEncoder not usable in streaming
}
mpegts = params.mediaRenderer.isTranscodeToMPEGTSAC3();
/**
* Disable AC3 remux for stereo tracks with 384 kbits bitrate and PS3 renderer (PS3 FW bug?)
*
* Commented out until we can find a way to detect when a video has an audio track that switches from 2 to 6 channels
* because MEncoder can't handle those files, which are very common these days.
boolean ps3_and_stereo_and_384_kbits = params.aid != null &&
(params.mediaRenderer.isPS3() && params.aid.getAudioProperties().getNumberOfChannels() == 2) &&
(params.aid.getBitRate() > 370000 && params.aid.getBitRate() < 400000);
*/
final boolean isTsMuxeRVideoEngineEnabled = configuration.getEnginesAsList(PMS.get().getRegistry()).contains(TsMuxeRVideo.ID);
final boolean mencoderAC3RemuxAudioDelayBug = (params.aid != null) && (params.aid.getAudioProperties().getAudioDelay() != 0) && (params.timeseek == 0);
if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) {
// AC-3 remux takes priority
ac3Remux = true;
} else {
// Now check for DTS remux and LPCM streaming
dtsRemux = isTsMuxeRVideoEngineEnabled &&
configuration.isDTSEmbedInPCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
) && params.aid != null &&
params.aid.isDTS() &&
!avisynth() &&
params.mediaRenderer.isDTSPlayable();
pcm = isTsMuxeRVideoEngineEnabled &&
configuration.isUsePCM() &&
(
!dvd ||
configuration.isMencoderRemuxMPEG2()
)
// Disable LPCM transcoding for MP4 container with non-H.264 video as workaround for MEncoder's A/V sync bug
&& !(media.getContainer().equals("mp4") && !media.getCodecV().equals("h264"))
&& params.aid != null &&
(
(params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || // disable 7.1 DTS-HD => LPCM because of channels mapping bug
params.aid.isLossless() ||
params.aid.isTrueHD() ||
(
!configuration.isMencoderUsePcmForHQAudioOnly() &&
(
params.aid.isAC3() ||
params.aid.isMP3() ||
params.aid.isAAC() ||
params.aid.isVorbis() ||
// Disable WMA to LPCM transcoding because of mencoder's channel mapping bug
// (see CodecUtil.getMixerOutput)
// params.aid.isWMA() ||
params.aid.isMpegAudio()
)
)
) && params.mediaRenderer.isLPCMPlayable();
}
if (dtsRemux || pcm) {
params.losslessaudio = true;
params.forceFps = media.getValidFps(false);
}
// MPEG-2 remux still buggy with MEncoder
// TODO when we can still use it?
ovccopy = false;
if (pcm && avisynth()) {
params.avidemux = true;
}
int channels;
if (ac3Remux) {
channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux
} else if (dtsRemux || wmv) {
channels = 2;
} else if (pcm) {
channels = params.aid.getAudioProperties().getNumberOfChannels();
} else {
channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding
}
LOGGER.trace("channels=" + channels);
String add = "";
String rendererMencoderOptions = params.mediaRenderer.getCustomMencoderOptions(); // default: empty string
String globalMencoderOptions = configuration.getMencoderCustomOptions(); // default: empty string
if (params.mediaRenderer.isKeepAspectRatio()) {
rendererMencoderOptions += " -vf expand=::::0:16/9:4,softskip";
}
String combinedCustomOptions = defaultString(globalMencoderOptions) +
" " +
defaultString(rendererMencoderOptions);
if (!combinedCustomOptions.contains("-lavdopts")) {
add = " -lavdopts debug=0";
}
if (isNotBlank(rendererMencoderOptions)) {
/**
* Ignore the renderer's custom MEncoder options if a) we're streaming a DVD (i.e. via dvd://)
* or b) the renderer's MEncoder options contain overscan settings (those are handled
* separately)
*/
// XXX we should weed out the unused/unwanted settings and keep the rest
// (see sanitizeArgs()) rather than ignoring the options entirely
if (rendererMencoderOptions.contains("expand=") && dvd) {
rendererMencoderOptions = null;
}
}
StringTokenizer st = new StringTokenizer(
"-channels " + channels +
(isNotBlank(globalMencoderOptions) ? " " + globalMencoderOptions : "") +
(isNotBlank(rendererMencoderOptions) ? " " + rendererMencoderOptions : "") +
add,
" "
);
// XXX why does this field (which is used to populate the array returned by args(),
// called below) store the renderer-specific (i.e. not global) MEncoder options?
overriddenMainArgs = new String[st.countTokens()];
{
int nThreads = (dvd || fileName.toLowerCase().endsWith("dvr-ms")) ?
1 :
configuration.getMencoderMaxThreads();
// MEncoder loses audio/video sync if more than 4 decoder (lavdopts) threads are used.
// Multithreading for decoding offers little performance gain anyway so it's not a big deal.
if (nThreads > 4) {
nThreads = 4;
}
boolean handleToken = false;
int i = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (handleToken) {
token += ":threads=" + nThreads;
if (configuration.getSkipLoopFilterEnabled() && !avisynth()) {
token += ":skiploopfilter=all";
}
handleToken = false;
}
if (token.toLowerCase().contains("lavdopts")) {
handleToken = true;
}
overriddenMainArgs[i++] = token;
}
}
if (configuration.getMPEG2MainSettings() != null) {
String mainConfig = configuration.getMPEG2MainSettings();
String customSettings = params.mediaRenderer.getCustomMencoderQualitySettings();
// Custom settings in PMS may override the settings of the saved configuration
if (isNotBlank(customSettings)) {
mainConfig = customSettings;
}
if (mainConfig.contains("/*")) {
mainConfig = mainConfig.substring(mainConfig.indexOf("/*"));
}
// Ditlew - WDTV Live (+ other byte asking clients), CBR. This probably ought to be placed in addMaximumBitrateConstraints(..)
int cbr_bitrate = params.mediaRenderer.getCBRVideoBitrate();
String cbr_settings = (cbr_bitrate > 0) ?
":vrc_buf_size=5000:vrc_minrate=" + cbr_bitrate + ":vrc_maxrate=" + cbr_bitrate + ":vbitrate=" + ((cbr_bitrate > 16000) ? cbr_bitrate * 1000 : cbr_bitrate) :
"";
String encodeSettings = "-lavcopts autoaspect=1:vcodec=" + vcodec +
(wmv ? ":acodec=wmav2:abitrate=448" : (cbr_settings + ":acodec=" + (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3") +
":abitrate=" + CodecUtil.getAC3Bitrate(configuration, params.aid))) +
":threads=" + (wmv ? 1 : configuration.getMencoderMaxThreads()) +
("".equals(mainConfig) ? "" : ":" + mainConfig);
String audioType = "ac3";
if (dtsRemux) {
audioType = "dts";
} else if (pcm) {
audioType = "pcm";
}
encodeSettings = addMaximumBitrateConstraints(encodeSettings, media, mainConfig, params.mediaRenderer, audioType);
st = new StringTokenizer(encodeSettings, " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
while (st.hasMoreTokens()) {
overriddenMainArgs[i++] = st.nextToken();
}
}
}
boolean foundNoassParam = false;
if (media != null) {
String expertOptions [] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
for (String s : expertOptions) {
if (s.equals("-noass")) {
foundNoassParam = true;
}
}
}
StringBuilder sb = new StringBuilder();
// Set subtitles options
if (!isDisableSubtitles(params)) {
int subtitleMargin = 0;
int userMargin = 0;
// Use ASS flag (and therefore ASS font styles) for all subtitled files except vobsub, PGS (blu-ray) and DVD
boolean apply_ass_styling = params.sid.getType() != SubtitleType.VOBSUB &&
params.sid.getType() != SubtitleType.PGS &&
configuration.isMencoderAss() && // GUI: enable subtitles formating
!foundNoassParam && // GUI: codec specific options
!dvd;
if (apply_ass_styling) {
sb.append("-ass ");
// GUI: Override ASS subtitles style if requested (always for SRT and TX3G subtitles)
boolean override_ass_style = !configuration.isMencoderAssDefaultStyle() ||
params.sid.getType() == SubtitleType.SUBRIP ||
params.sid.getType() == SubtitleType.TX3G;
if (override_ass_style) {
String assSubColor = "ffffff00";
if (configuration.getSubsColor() != 0) {
assSubColor = Integer.toHexString(configuration.getSubsColor());
if (assSubColor.length() > 2) {
assSubColor = assSubColor.substring(2) + "00";
}
}
sb.append("-ass-color ").append(assSubColor).append(" -ass-border-color 00000000 -ass-font-scale ").append(configuration.getMencoderAssScale());
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
/* Set font with -font option, workaround for the bug:
* https://github.com/Happy-Neko/ps3mediaserver/commit/52e62203ea12c40628de1869882994ce1065446a#commitcomment-990156
*/
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
sb.append(" -ass-force-style FontName=").append(configuration.getMencoderFont()).append(",");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
/*
* Variable "font" contains a font path instead of a font name.
* Does "-ass-force-style" support font paths? In tests on OS X
* the font path is ignored (Outline, Shadow and MarginV are
* used, though) and the "-font" definition is used instead.
* See: https://github.com/ps3mediaserver/ps3mediaserver/pull/14
*/
sb.append(" -font ").append(font).append(" ");
sb.append(" -ass-force-style FontName=").append(font).append(",");
} else {
sb.append(" -font Arial ");
sb.append(" -ass-force-style FontName=Arial,");
}
}
/*
* Add to the subtitle margin if overscan compensation is being used
* This keeps the subtitle text inside the frame instead of in the border
*/
if (intOCH > 0) {
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
}
sb.append("Outline=").append(configuration.getMencoderAssOutline()).append(",Shadow=").append(configuration.getMencoderAssShadow());
try {
userMargin = Integer.parseInt(configuration.getMencoderAssMargin());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse SSA margin from \"" + configuration.getMencoderAssMargin() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(",MarginV=").append(subtitleMargin).append(" ");
} else if (intOCH > 0) {
/*
* Add to the subtitle margin
* This keeps the subtitle text inside the frame instead of in the border
*/
subtitleMargin = (media.getHeight() / 100) * intOCH;
subtitleMargin = subtitleMargin / 2;
sb.append("-ass-force-style MarginV=").append(subtitleMargin).append(" ");
}
// MEncoder is not compiled with fontconfig on Mac OS X, therefore
// use of the "-ass" option also requires the "-font" option.
if (Platform.isMac() && sb.toString().indexOf(" -font ") < 0) {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append("-font ").append(font).append(" ");
}
}
// Workaround for MPlayer #2041, remove when that bug is fixed
if (!params.sid.isEmbedded()) {
sb.append("-noflip-hebrew ");
}
// Use PLAINTEXT formatting
} else {
// Set subtitles font
if (configuration.getMencoderFont() != null && configuration.getMencoderFont().length() > 0) {
sb.append(" -font ").append(configuration.getMencoderFont()).append(" ");
} else {
String font = CodecUtil.getDefaultFontPath();
if (isNotBlank(font)) {
sb.append(" -font ").append(font).append(" ");
}
}
sb.append(" -subfont-text-scale ").append(configuration.getMencoderNoAssScale());
sb.append(" -subfont-outline ").append(configuration.getMencoderNoAssOutline());
sb.append(" -subfont-blur ").append(configuration.getMencoderNoAssBlur());
// Add to the subtitle margin if overscan compensation is being used
// This keeps the subtitle text inside the frame instead of in the border
if (intOCH > 0) {
subtitleMargin = intOCH;
}
try {
userMargin = Integer.parseInt(configuration.getMencoderNoAssSubPos());
} catch (NumberFormatException n) {
LOGGER.debug("Could not parse subpos from \"" + configuration.getMencoderNoAssSubPos() + "\"");
}
subtitleMargin = subtitleMargin + userMargin;
sb.append(" -subpos ").append(100 - subtitleMargin).append(" ");
}
// Common subtitle options
// MEncoder on Mac OS X is compiled without fontconfig support.
// Appending the flag will break execution, so skip it on Mac OS X.
if (!Platform.isMac()) {
// Use fontconfig if enabled
sb.append("-").append(configuration.isMencoderFontConfig() ? "" : "no").append("fontconfig ");
}
// Apply DVD/VOBsub subtitle quality
if (params.sid.getType() == SubtitleType.VOBSUB && configuration.getMencoderVobsubSubtitleQuality() != null) {
String subtitleQuality = configuration.getMencoderVobsubSubtitleQuality();
sb.append("-spuaa ").append(subtitleQuality).append(" ");
}
// External subtitles file
if (params.sid.isExternal()) {
if (!params.sid.isExternalFileUtf()) {
String subcp = null;
// Append -subcp option for non UTF external subtitles
if (isNotBlank(configuration.getMencoderSubCp())) {
// Manual setting
subcp = configuration.getMencoderSubCp();
} else if (isNotBlank(SubtitleUtils.getSubCpOptionForMencoder(params.sid))) {
// Autodetect charset (blank mencoder_subcp config option)
subcp = SubtitleUtils.getSubCpOptionForMencoder(params.sid);
}
if (isNotBlank(subcp)) {
sb.append("-subcp ").append(subcp).append(" ");
if (configuration.isMencoderSubFribidi()) {
sb.append("-fribidi-charset ").append(subcp).append(" ");
}
}
}
}
}
st = new StringTokenizer(sb.toString(), " ");
{
int i = overriddenMainArgs.length; // Old length
overriddenMainArgs = Arrays.copyOf(overriddenMainArgs, overriddenMainArgs.length + st.countTokens());
boolean handleToken = false;
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (handleToken) {
s = "-quiet";
handleToken = false;
}
if ((!configuration.isMencoderAss() || dvd) && s.contains("-ass")) {
s = "-quiet";
handleToken = true;
}
overriddenMainArgs[i++] = s;
}
}
List<String> cmdList = new ArrayList<String>();
cmdList.add(executable());
// Choose which time to seek to
cmdList.add("-ss");
cmdList.add((params.timeseek > 0) ? "" + params.timeseek : "0");
if (dvd) {
cmdList.add("-dvd-device");
}
String frameRateRatio = null;
String frameRateNumber = null;
if (media != null) {
frameRateRatio = media.getValidFps(true);
frameRateNumber = media.getValidFps(false);
}
// Input filename
if (avisynth && !fileName.toLowerCase().endsWith(".iso")) {
File avsFile = AviSynthMEncoder.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame, frameRateRatio, frameRateNumber);
cmdList.add(ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath()));
} else {
if (params.stdin != null) {
cmdList.add("-");
} else {
if (dvd) {
String dvdFileName = fileName.replace("\\VIDEO_TS", "");
cmdList.add(dvdFileName);
} else {
cmdList.add(fileName);
}
}
}
if (dvd) {
cmdList.add("dvd://" + media.getDvdtrack());
}
for (String arg : args()) {
if (arg.contains("format=mpeg2") && media.getAspect() != null && media.getValidAspect(true) != null) {
cmdList.add(arg + ":vaspect=" + media.getValidAspect(true));
} else {
cmdList.add(arg);
}
}
if (!dtsRemux && !pcm && !avisynth() && params.aid != null && media.getAudioTracksList().size() > 1) {
cmdList.add("-aid");
boolean lavf = false; // TODO Need to add support for LAVF demuxing
cmdList.add("" + (lavf ? params.aid.getId() + 1 : params.aid.getId()));
}
/*
* Handle subtitles
*
* Try to reconcile the fact that the handling of "Definitely disable subtitles" is spread out
* over net.pms.encoders.Player.setAudioAndSubs and here by setting both of MEncoder's "disable
* subs" options if any of the internal conditions for disabling subtitles are met.
*/
if (isDisableSubtitles(params)) {
// Ensure that internal subtitles are not automatically loaded
cmdList.add("-nosub");
// Ensure that external subtitles are not automatically loaded
cmdList.add("-noautosub");
} else {
// Note: isEmbedded() and isExternal() are mutually exclusive
if (params.sid.isEmbedded()) { // internal (embedded) subs
// Ensure that external subtitles are not automatically loaded
cmdList.add("-noautosub");
// Specify which internal subtitle we want
cmdList.add("-sid");
cmdList.add("" + params.sid.getId());
} else { // external subtitles
assert params.sid.isExternal(); // confirm the mutual exclusion
// Ensure that internal subtitles are not automatically loaded
cmdList.add("-nosub");
if (params.sid.getType() == SubtitleType.VOBSUB) {
cmdList.add("-vobsub");
cmdList.add(externalSubtitlesFileName.substring(0, externalSubtitlesFileName.length() - 4));
cmdList.add("-slang");
cmdList.add("" + params.sid.getLang());
} else {
cmdList.add("-sub");
cmdList.add(externalSubtitlesFileName.replace(",", "\\,")); // Commas in MEncoder separate multiple subtitle files
if (params.sid.isExternalFileUtf()) {
// Append -utf8 option for UTF-8 external subtitles
cmdList.add("-utf8");
}
}
}
}
// -ofps
String framerate = (frameRateRatio != null) ? frameRateRatio : "24000/1001"; // where a framerate is required, use the input framerate or 24000/1001
String ofps = framerate;
// Optional -fps or -mc
if (configuration.isMencoderForceFps()) {
if (!configuration.isFix25FPSAvMismatch()) {
cmdList.add("-fps");
cmdList.add(framerate);
} else if (frameRateRatio != null) { // XXX not sure why this "fix" requires the input to have a valid framerate, but that's the logic in the old (cmdArray) code
cmdList.add("-mc");
cmdList.add("0.005");
ofps = "25";
}
}
// Make MEncoder output framerate correspond to InterFrame
if (avisynth() && configuration.getAvisynthInterFrame() && !"60000/1001".equals(frameRateRatio) && !"50".equals(frameRateRatio) && !"60".equals(frameRateRatio)) {
if ("25".equals(frameRateRatio)) {
ofps = "50";
} else if ("30".equals(frameRateRatio)) {
ofps = "60";
} else {
ofps = "60000/1001";
}
}
cmdList.add("-ofps");
cmdList.add(ofps);
if (fileName.toLowerCase().endsWith(".evo")) {
cmdList.add("-psprobe");
cmdList.add("10000");
}
boolean deinterlace = configuration.isMencoderYadif();
// Check if the media renderer supports this resolution
boolean isResolutionTooHighForRenderer = params.mediaRenderer.isVideoRescale()
&& media != null
&& (
(media.getWidth() > params.mediaRenderer.getMaxVideoWidth())
||
(media.getHeight() > params.mediaRenderer.getMaxVideoHeight())
);
// Video scaler and overscan compensation
boolean scaleBool = isResolutionTooHighForRenderer
|| (configuration.isMencoderScaler() && (configuration.getMencoderScaleX() != 0 || configuration.getMencoderScaleY() != 0))
|| (intOCW > 0 || intOCH > 0);
if ((deinterlace || scaleBool) && !avisynth()) {
StringBuilder vfValueOverscanPrepend = new StringBuilder();
StringBuilder vfValueOverscanMiddle = new StringBuilder();
StringBuilder vfValueVS = new StringBuilder();
StringBuilder vfValueComplete = new StringBuilder();
String deinterlaceComma = "";
int scaleWidth = 0;
int scaleHeight = 0;
double rendererAspectRatio;
// Set defaults
if (media != null && media.getWidth() > 0 && media.getHeight() > 0) {
scaleWidth = media.getWidth();
scaleHeight = media.getHeight();
}
/*
* Implement overscan compensation settings
*
* This feature takes into account aspect ratio,
* making it less blunt than the Video Scaler option
*/
if (intOCW > 0 || intOCH > 0) {
int intOCWPixels = (media.getWidth() / 100) * intOCW;
int intOCHPixels = (media.getHeight() / 100) * intOCH;
scaleWidth = scaleWidth + intOCWPixels;
scaleHeight = scaleHeight + intOCHPixels;
// See if the video needs to be scaled down
if (
params.mediaRenderer.isVideoRescale() &&
(
(scaleWidth > params.mediaRenderer.getMaxVideoWidth()) ||
(scaleHeight > params.mediaRenderer.getMaxVideoHeight())
)
) {
double overscannedAspectRatio = scaleWidth / scaleHeight;
rendererAspectRatio = params.mediaRenderer.getMaxVideoWidth() / params.mediaRenderer.getMaxVideoHeight();
if (overscannedAspectRatio > rendererAspectRatio) {
// Limit video by width
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / overscannedAspectRatio);
} else {
// Limit video by height
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * overscannedAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
vfValueOverscanPrepend.append("softskip,expand=-").append(intOCWPixels).append(":-").append(intOCHPixels);
vfValueOverscanMiddle.append(",scale=").append(scaleWidth).append(":").append(scaleHeight);
}
/*
* Video Scaler and renderer-specific resolution-limiter
*/
if (configuration.isMencoderScaler()) {
// Use the manual, user-controlled scaler
if (configuration.getMencoderScaleX() != 0) {
if (configuration.getMencoderScaleX() <= params.mediaRenderer.getMaxVideoWidth()) {
scaleWidth = configuration.getMencoderScaleX();
} else {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
}
}
if (configuration.getMencoderScaleY() != 0) {
if (configuration.getMencoderScaleY() <= params.mediaRenderer.getMaxVideoHeight()) {
scaleHeight = configuration.getMencoderScaleY();
} else {
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", your Video Scaler setting");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
/*
* The video resolution is too big for the renderer so we need to scale it down
*/
} else if (
media != null &&
media.getWidth() > 0 &&
media.getHeight() > 0 &&
(
media.getWidth() > params.mediaRenderer.getMaxVideoWidth() ||
media.getHeight() > params.mediaRenderer.getMaxVideoHeight()
)
) {
double videoAspectRatio = (double) media.getWidth() / (double) media.getHeight();
rendererAspectRatio = (double) params.mediaRenderer.getMaxVideoWidth() / (double) params.mediaRenderer.getMaxVideoHeight();
/*
* First we deal with some exceptions, then if they are not matched we will
* let the renderer limits work.
*
* This is so, for example, we can still define a maximum resolution of
* 1920x1080 in the renderer config file but still support 1920x1088 when
* it's needed, otherwise we would either resize 1088 to 1080, meaning the
* ugly (unused) bottom 8 pixels would be displayed, or we would limit all
* videos to 1088 causing the bottom 8 meaningful pixels to be cut off.
*/
if (media.getWidth() == 3840 && media.getHeight() <= 1080) {
// Full-SBS
scaleWidth = 1920;
scaleHeight = media.getHeight();
} else if (media.getWidth() == 1920 && media.getHeight() == 2160) {
// Full-OU
scaleWidth = 1920;
scaleHeight = 1080;
} else if (media.getWidth() == 1920 && media.getHeight() == 1088) {
// SAT capture
scaleWidth = 1920;
scaleHeight = 1088;
} else {
// Passed the exceptions, now we allow the renderer to define the limits
if (videoAspectRatio > rendererAspectRatio) {
scaleWidth = params.mediaRenderer.getMaxVideoWidth();
scaleHeight = (int) Math.round(params.mediaRenderer.getMaxVideoWidth() / videoAspectRatio);
} else {
scaleWidth = (int) Math.round(params.mediaRenderer.getMaxVideoHeight() * videoAspectRatio);
scaleHeight = params.mediaRenderer.getMaxVideoHeight();
}
}
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", the maximum your renderer supports");
vfValueVS.append("scale=").append(scaleWidth).append(":").append(scaleHeight);
}
// Put the string together taking into account overscan compensation and video scaler
if (intOCW > 0 || intOCH > 0) {
vfValueComplete.append(vfValueOverscanPrepend).append(vfValueOverscanMiddle).append(",harddup");
LOGGER.info("Setting video resolution to: " + scaleWidth + "x" + scaleHeight + ", to fit your overscan compensation");
} else {
vfValueComplete.append(vfValueVS);
}
if (deinterlace) {
deinterlaceComma = ",";
}
String vfValue = (deinterlace ? "yadif" : "") + (scaleBool ? deinterlaceComma + vfValueComplete : "");
if (isNotBlank(vfValue)) {
cmdList.add("-vf");
cmdList.add(vfValue);
}
}
/*
* The PS3 and possibly other renderers display videos incorrectly
* if the dimensions aren't divisible by 4, so if that is the
* case we add borders until it is divisible by 4.
* This fixes the long-time bug of videos displaying in black and
* white with diagonal strips of colour, weird one.
*
* TODO: Integrate this with the other stuff so that "expand" only
* ever appears once in the MEncoder CMD.
*/
if (media != null && (media.getWidth() % 4 != 0) || media.getHeight() % 4 != 0) {
int expandBorderWidth;
int expandBorderHeight;
expandBorderWidth = media.getWidth() % 4;
expandBorderHeight = media.getHeight() % 4;
cmdList.add("-vf");
cmdList.add("softskip,expand=-" + expandBorderWidth + ":-" + expandBorderHeight);
}
if (configuration.getMencoderMT() && !avisynth && !dvd && !(media.getCodecV() != null && (media.getCodecV().startsWith("mpeg2")))) {
cmdList.add("-lavdopts");
cmdList.add("fast");
}
boolean disableMc0AndNoskip = false;
// Process the options for this file in Transcoding Settings -> Mencoder -> Expert Settings: Codec-specific parameters
// TODO this is better handled by a plugin with scripting support and will be removed
if (media != null) {
String expertOptions[] = getSpecificCodecOptions(
configuration.getCodecSpecificConfig(),
media,
params,
fileName,
externalSubtitlesFileName,
configuration.isMencoderIntelligentSync(),
false
);
// the parameters (expertOptions) are processed in 3 passes
// 1) process expertOptions
// 2) process cmdList
// 3) append expertOptions to cmdList
if (expertOptions != null && expertOptions.length > 0) {
// remove this option (key) from the cmdList in pass 2.
// if the boolean value is true, also remove the option's corresponding value
Map<String, Boolean> removeCmdListOption = new HashMap<String, Boolean>();
// if this option (key) is defined in cmdList, merge this string value into the
// option's value in pass 2. the value is a string format template into which the
// cmdList option value is injected
Map<String, String> mergeCmdListOption = new HashMap<String, String>();
// merges that are performed in pass 2 are logged in this map; the key (string) is
// the option name and the value is a boolean indicating whether the option was merged
// or not. the map is populated after pass 1 with the options from mergeCmdListOption
// and all values initialised to false. if an option was merged, it is not appended
// to cmdList
Map<String, Boolean> mergedCmdListOption = new HashMap<String, Boolean>();
// pass 1: process expertOptions
for (int i = 0; i < expertOptions.length; ++i) {
if (expertOptions[i].equals("-noass")) {
// remove -ass from cmdList in pass 2.
// -ass won't have been added in this method (getSpecificCodecOptions
// has been called multiple times above to check for -noass and -nomux)
// but it may have been added via the renderer or global MEncoder options.
// XXX: there are currently 10 other -ass options (-ass-color, -ass-border-color &c.).
// technically, they should all be removed...
removeCmdListOption.put("-ass", false); // false: option does not have a corresponding value
// remove -noass from expertOptions in pass 3
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-nomux")) {
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mt")) {
// not an MEncoder option so remove it from exportOptions.
// multi-threaded MEncoder is used by default, so this is obsolete (TODO: Remove it from the description)
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-ofps")) {
// replace the cmdList version with the expertOptions version i.e. remove the former
removeCmdListOption.put("-ofps", true);
// skip (i.e. leave unchanged) the exportOptions value
++i;
} else if (expertOptions[i].equals("-fps")) {
removeCmdListOption.put("-fps", true);
++i;
} else if (expertOptions[i].equals("-ovc")) {
removeCmdListOption.put("-ovc", true);
++i;
} else if (expertOptions[i].equals("-channels")) {
removeCmdListOption.put("-channels", true);
++i;
} else if (expertOptions[i].equals("-oac")) {
removeCmdListOption.put("-oac", true);
++i;
} else if (expertOptions[i].equals("-quality")) {
// XXX like the old (cmdArray) code, this clobbers the old -lavcopts value
String lavcopts = String.format(
"autoaspect=1:vcodec=%s:acodec=%s:abitrate=%s:threads=%d:%s",
vcodec,
(configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3"),
CodecUtil.getAC3Bitrate(configuration, params.aid),
configuration.getMencoderMaxThreads(),
expertOptions[i + 1]
);
// append bitrate-limiting options if configured
lavcopts = addMaximumBitrateConstraints(
lavcopts,
media,
lavcopts,
params.mediaRenderer,
""
);
// a string format with no placeholders, so the cmdList option value is ignored.
// note: we protect "%" from being interpreted as a format by converting it to "%%",
// which is then turned back into "%" when the format is processed
mergeCmdListOption.put("-lavcopts", lavcopts.replace("%", "%%"));
// remove -quality <value>
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-mpegopts")) {
mergeCmdListOption.put("-mpegopts", "%s:" + expertOptions[i + 1].replace("%", "%%"));
// merge if cmdList already contains -mpegopts, but don't append if it doesn't (parity with the old (cmdArray) version)
expertOptions[i] = expertOptions[i + 1] = REMOVE_OPTION;
++i;
} else if (expertOptions[i].equals("-vf")) {
mergeCmdListOption.put("-vf", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-af")) {
mergeCmdListOption.put("-af", "%s," + expertOptions[i + 1].replace("%", "%%"));
++i;
} else if (expertOptions[i].equals("-nosync")) {
disableMc0AndNoskip = true;
expertOptions[i] = REMOVE_OPTION;
} else if (expertOptions[i].equals("-mc")) {
disableMc0AndNoskip = true;
}
}
for (String key : mergeCmdListOption.keySet()) {
mergedCmdListOption.put(key, false);
}
// pass 2: process cmdList
List<String> transformedCmdList = new ArrayList<String>();
for (int i = 0; i < cmdList.size(); ++i) {
String option = cmdList.get(i);
// we remove an option by *not* adding it to transformedCmdList
if (removeCmdListOption.containsKey(option)) {
if (isTrue(removeCmdListOption.get(option))) { // true: remove (i.e. don't add) the corresponding value
++i;
}
} else {
transformedCmdList.add(option);
if (mergeCmdListOption.containsKey(option)) {
String format = mergeCmdListOption.get(option);
String value = String.format(format, cmdList.get(i + 1));
// record the fact that an expertOption value has been merged into this cmdList value
mergedCmdListOption.put(option, true);
transformedCmdList.add(value);
++i;
}
}
}
cmdList = transformedCmdList;
// pass 3: append expertOptions to cmdList
for (int i = 0; i < expertOptions.length; ++i) {
String option = expertOptions[i];
if (!option.equals(REMOVE_OPTION)) {
if (isTrue(mergedCmdListOption.get(option))) { // true: this option and its value have already been merged into existing cmdList options
++i; // skip the value
} else {
cmdList.add(option);
}
}
}
}
}
if ((pcm || dtsRemux || ac3Remux) || (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip)) {
if (configuration.isFix25FPSAvMismatch()) {
cmdList.add("-mc");
cmdList.add("0.005");
} else if (configuration.isMencoderNoOutOfSync() && !disableMc0AndNoskip) {
cmdList.add("-mc");
cmdList.add("0");
cmdList.add("-noskip");
}
}
if (params.timeend > 0) {
cmdList.add("-endpos");
cmdList.add("" + params.timeend);
}
String rate = "48000";
if (params.mediaRenderer.isXBOX()) {
rate = "44100";
}
// Force srate because MEncoder doesn't like anything other than 48khz for AC-3
if (media != null && !pcm && !dtsRemux && !ac3Remux) {
cmdList.add("-af");
cmdList.add("lavcresample=" + rate);
cmdList.add("-srate");
cmdList.add(rate);
}
// Add a -cache option for piped media (e.g. rar/zip file entries):
// https://code.google.com/p/ps3mediaserver/issues/detail?id=911
if (params.stdin != null) {
cmdList.add("-cache");
cmdList.add("8192");
}
PipeProcess pipe = null;
ProcessWrapperImpl pw;
if (pcm || dtsRemux) {
// Transcode video, demux audio, remux with tsMuxeR
boolean channels_filter_present = false;
for (String s : cmdList) {
if (isNotBlank(s) && s.startsWith("channels")) {
channels_filter_present = true;
break;
}
}
if (params.avidemux) {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux || ac3Remux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
if (pcm && !channels_filter_present && params.aid != null) {
String mixer = getLPCMChannelMappingForMencoder(params.aid);
if (isNotBlank(mixer)) {
cmdList.add("-af");
cmdList.add(mixer);
}
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
pw = new ProcessWrapperImpl(cmdArray, params);
PipeProcess videoPipe = new PipeProcess("videoPipe" + System.currentTimeMillis(), "out", "reconnect");
PipeProcess audioPipe = new PipeProcess("audioPipe" + System.currentTimeMillis(), "out", "reconnect");
ProcessWrapper videoPipeProcess = videoPipe.getPipeProcess();
ProcessWrapper audioPipeProcess = audioPipe.getPipeProcess();
params.output_pipes[0] = videoPipe;
params.output_pipes[1] = audioPipe;
pw.attachProcess(videoPipeProcess);
pw.attachProcess(audioPipeProcess);
videoPipeProcess.runInNewThread();
audioPipeProcess.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) { }
videoPipe.deleteLater();
audioPipe.deleteLater();
} else {
// remove the -oac switch, otherwise the "too many video packets" errors appear again
for (ListIterator<String> it = cmdList.listIterator(); it.hasNext();) {
String option = it.next();
if (option.equals("-oac")) {
it.set("-nosound");
if (it.hasNext()) {
it.next();
it.remove();
}
break;
}
}
pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts");
TsMuxeRVideo ts = new TsMuxeRVideo(configuration);
File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta");
String cmd[] = new String[]{ ts.executable(), f.getAbsolutePath(), pipe.getInputPipe() };
pw = new ProcessWrapperImpl(cmd, params);
PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true);
cmdList.add("-o");
cmdList.add(ffVideoPipe.getInputPipe());
OutputParams ffparams = new OutputParams(configuration);
ffparams.maxBufferSize = 1;
ffparams.stdin = params.stdin;
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArray, ffparams);
ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess();
pw.attachProcess(ff_video_pipe_process);
ff_video_pipe_process.runInNewThread();
ffVideoPipe.deleteLater();
pw.attachProcess(ffVideo);
ffVideo.runInNewThread();
String aid = null;
if (media != null && media.getAudioTracksList().size() > 1 && params.aid != null) {
if (media.getContainer() != null && (media.getContainer().equals(FormatConfiguration.AVI) || media.getContainer().equals(FormatConfiguration.FLV))) {
// TODO confirm (MP4s, OGMs and MOVs already tested: first aid is 0; AVIs: first aid is 1)
// For AVIs, FLVs and MOVs MEncoder starts audio tracks numbering from 1
aid = "" + (params.aid.getId() + 1);
} else {
// Everything else from 0
aid = "" + params.aid.getId();
}
}
PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true);
StreamModifier sm = new StreamModifier();
sm.setPcm(pcm);
sm.setDtsEmbed(dtsRemux);
sm.setSampleFrequency(48000);
sm.setBitsPerSample(16);
String mixer = null;
if (pcm && !dtsRemux) {
mixer = getLPCMChannelMappingForMencoder(params.aid); // LPCM always outputs 5.1/7.1 for multichannel tracks. Downmix with player if needed!
}
sm.setNbChannels(channels);
// It seems that -really-quiet prevents MEncoder from stopping the pipe output after some time
// -mc 0.1 makes the DTS-HD extraction work better with latest MEncoder builds, and has no impact on the regular DTS one
// TODO: See if these notes are still true, and if so leave specific revisions/release names of the latest version tested.
String ffmpegLPCMextract[] = new String[]{
executable(),
"-ss", "0",
fileName,
"-really-quiet",
"-msglevel", "statusline=2",
"-channels", "" + channels,
"-ovc", "copy",
"-of", "rawaudio",
"-mc", dtsRemux ? "0.1" : "0",
"-noskip",
(aid == null) ? "-quiet" : "-aid", (aid == null) ? "-quiet" : aid,
"-oac", (ac3Remux || dtsRemux) ? "copy" : "pcm",
(isNotBlank(mixer) && !channels_filter_present) ? "-af" : "-quiet", (isNotBlank(mixer) && !channels_filter_present) ? mixer : "-quiet",
"-srate", "48000",
"-o", ffAudioPipe.getInputPipe()
};
if (!params.mediaRenderer.isMuxDTSToMpeg()) { // No need to use the PCM trick when media renderer supports DTS
ffAudioPipe.setModifier(sm);
}
if (media != null && media.getDvdtrack() > 0) {
ffmpegLPCMextract[3] = "-dvd-device";
ffmpegLPCMextract[4] = fileName;
ffmpegLPCMextract[5] = "dvd://" + media.getDvdtrack();
} else if (params.stdin != null) {
ffmpegLPCMextract[3] = "-";
}
if (fileName.toLowerCase().endsWith(".evo")) {
ffmpegLPCMextract[4] = "-psprobe";
ffmpegLPCMextract[5] = "1000000";
}
if (params.timeseek > 0) {
ffmpegLPCMextract[2] = "" + params.timeseek;
}
OutputParams ffaudioparams = new OutputParams(configuration);
ffaudioparams.maxBufferSize = 1;
ffaudioparams.stdin = params.stdin;
ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams);
params.stdin = null;
PrintWriter pwMux = new PrintWriter(f);
pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500");
String videoType = "V_MPEG-2";
if (params.no_videoencode && params.forceType != null) {
videoType = params.forceType;
}
String fps = "";
if (params.forceFps != null) {
fps = "fps=" + params.forceFps + ", ";
}
String audioType;
if (ac3Remux) {
audioType = "A_AC3";
} else if (dtsRemux) {
if (params.mediaRenderer.isMuxDTSToMpeg()) {
// Renderer can play proper DTS track
audioType = "A_DTS";
} else {
// DTS padded in LPCM trick
audioType = "A_LPCM";
}
} else {
// PCM
audioType = "A_LPCM";
}
/*
* MEncoder bug (confirmed with MEncoder r35003 + FFmpeg 0.11.1)
* Audio delay is ignored when playing from file start (-ss 0)
* Override with tsmuxer.meta setting
*/
String timeshift = "";
if (mencoderAC3RemuxAudioDelayBug) {
timeshift = "timeshift=" + params.aid.getAudioProperties().getAudioDelay() + "ms, ";
}
pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1");
pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", " + timeshift + "track=2");
pwMux.close();
ProcessWrapper pipe_process = pipe.getPipeProcess();
pw.attachProcess(pipe_process);
pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
params.input_pipes[0] = pipe;
ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess();
pw.attachProcess(ff_pipe_process);
ff_pipe_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
ffAudioPipe.deleteLater();
pw.attachProcess(ffAudio);
ffAudio.runInNewThread();
}
} else {
boolean directpipe = Platform.isMac() || Platform.isFreeBSD();
if (directpipe) {
cmdList.add("-o");
cmdList.add("-");
cmdList.add("-really-quiet");
cmdList.add("-msglevel");
cmdList.add("statusline=2");
params.input_pipes = new PipeProcess[2];
} else {
pipe = new PipeProcess("mencoder" + System.currentTimeMillis(), (pcm || dtsRemux) ? null : params);
params.input_pipes[0] = pipe;
cmdList.add("-o");
cmdList.add(pipe.getInputPipe());
}
String[] cmdArray = new String[cmdList.size()];
cmdList.toArray(cmdArray);
cmdArray = finalizeTranscoderArgs(
fileName,
dlna,
media,
params,
cmdArray
);
pw = new ProcessWrapperImpl(cmdArray, params);
if (!directpipe) {
ProcessWrapper mkfifo_process = pipe.getPipeProcess();
pw.attachProcess(mkfifo_process);
mkfifo_process.runInNewThread();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
pipe.deleteLater();
}
}
pw.runInNewThread();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
return pw;
}
|
diff --git a/astCreatorPlugin/src/main/java/org/overture/tools/maven/astcreator/GenerateTree.java b/astCreatorPlugin/src/main/java/org/overture/tools/maven/astcreator/GenerateTree.java
index 390f9dc..b7fc798 100644
--- a/astCreatorPlugin/src/main/java/org/overture/tools/maven/astcreator/GenerateTree.java
+++ b/astCreatorPlugin/src/main/java/org/overture/tools/maven/astcreator/GenerateTree.java
@@ -1,469 +1,469 @@
package org.overture.tools.maven.astcreator;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.overture.tools.astcreator.Main;
import org.overture.tools.astcreator.env.Environment;
import org.overture.tools.maven.astcreator.util.Util;
/**
* Generate Tree
*
* @goal generate
* @phase generate-sources
* @requiresDependencyResolution compile
*/
public class GenerateTree extends AstCreatorBaseMojo
{
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
getLog().info("Preparing for tree generation...");
// Let's make sure that maven knows to look in the output directory
project.addCompileSourceRoot(outputDirectory.getPath());
// Base tree
File baseAstFile = new File(getResourcesDir(), ast);
File baseAsttoStringFile = new File(baseAstFile.getAbsolutePath()
+ Main.TO_STRING_FILE_NAME_EXT);
// Extended tree
File extendedAstFile = (extendedAst == null ? null
: new File(getResourcesDir(), extendedAst));
File extendedAstToStringFile = (extendedAstFile == null ? null
: new File(extendedAstFile.getAbsolutePath()
+ Main.TO_STRING_FILE_NAME_EXT));
if (extendedAstFile != null)
{
getLog().info("Configuring extension");
if (this.extendedAstGroupId == null
|| this.extendedAstArtifactId == null)
{
getLog().error("\tExtension base dependency not configures with groupId and artifactId");
}
getLog().info("\tExtension base dependency is: \""
+ this.extendedAstGroupId + ":"
+ this.extendedAstArtifactId + "\"");
getLog().info("\tSearching for base dependency artifact");
if (extendedAstFile != null)
{
DefaultArtifact baseArtifact = null;
for (Object a : this.project.getDependencyArtifacts())
{
if (a instanceof DefaultArtifact)
{
DefaultArtifact artifact = (DefaultArtifact) a;
if (artifact.getGroupId().equals(this.extendedAstGroupId)
&& artifact.getArtifactId().equals(this.extendedAstArtifactId))
{
baseArtifact = artifact;
break;
}
}
}
getLog().info("\tExtension base artifact found - exstracting base tree definition files");
File baseJar = baseArtifact.getFile();
preparebase(baseJar, ast);
getLog().info("\tSetting base definition files to:");
baseAstFile = new File(getProjectOutputDirectory(), ast);
baseAsttoStringFile = new File(baseAstFile.getAbsolutePath()
+ Main.TO_STRING_FILE_NAME_EXT);
getLog().info("\t\tbase: " + baseAstFile);
getLog().info("\t\tbase tostring: " + baseAsttoStringFile);
getLog().info("\tExtension base artifact configured.");
}
}
getLog().info("Checking if generation required.");
if (isCrcEqual(baseAstFile) && isCrcEqual(baseAsttoStringFile)
&& isVersionEqual(getDeclaredPluginVersion()))
{
if (extendedAst != null && !extendedAst.isEmpty())
{
if (isCrcEqual(new File(getResourcesDir(), extendedAst))
&& isCrcEqual(new File(getResourcesDir(), extendedAst))
- && isVersionEqual(project.getVersion()))
+ && isVersionEqual(getDeclaredPluginVersion()))
{
getLog().info("Extended AST unchanged");
getLog().info("Nothing to generate, source already up-to-date");
return;
}
getLog().info("Extended AST generation needed");
} else
{
getLog().info("All up to date");
return;
}
} else
{
getLog().info("Full AST generation needed");
}
getLog().info("Generating...");
if (deletePackageOnGenerate != null)
{
for (String relativePath : deletePackageOnGenerate)
{
relativePath = relativePath.replace('.', File.separatorChar);
getLog().info("Deleting folder: " + relativePath);
File f = new File(getGeneratedFolder(), relativePath.replace('/', File.separatorChar));
if (f.exists())
{
deleteDir(f);
} else
{
getLog().warn("Folder not found and delete skipped: "
+ relativePath);
}
}
}
if (baseAstFile.exists())
{
File generated = getGeneratedFolder();
getLog().info("Generator starting with input: " + baseAstFile);
Environment env1 = null;
if (extendedName == null && extendedAst != null)
{
getLog().error("Missing extendedName for AST extension of: "
+ extendedAst);
} else if (extendedAst == null)
{
generateSingleAst(baseAstFile, baseAsttoStringFile, generated, env1);
} else
{
generateExtendedAst(baseAstFile, extendedAstFile, baseAsttoStringFile, extendedAstToStringFile, generated);
}
} else
{
getLog().error("Cannot find input file: "
+ baseAstFile.getAbsolutePath());
}
}
private void preparebase(File baseJar, String ast)
throws MojoExecutionException, MojoFailureException
{
if (baseJar.isFile())
{
preparebaseJar(baseJar, ast);
} else
{
preparebaseDirectory(baseJar, ast);
}
}
private void preparebaseDirectory(File baseJar, String ast)
throws MojoExecutionException
{
File astDefinition = new File(baseJar, ast);
File astDefinitionToString = new File(baseJar, ast
+ Main.TO_STRING_FILE_NAME_EXT);
try
{
Util.copyFile(astDefinition, new File(getProjectOutputDirectory(), astDefinition.getName()));
} catch (IOException e)
{
throw new MojoExecutionException("Failed to copy AST defintion file from source: "
+ astDefinition);
}
try
{
Util.copyFile(astDefinitionToString, new File(getProjectOutputDirectory(), astDefinitionToString.getName()));
} catch (IOException e)
{
}
}
private void preparebaseJar(File baseJar, String ast)
throws MojoExecutionException, MojoFailureException
{
// assuming you already have an InputStream to the jar file..
JarInputStream jis = null;
boolean astDefinitionPrepared = false;
try
{
jis = new JarInputStream(new FileInputStream(baseJar));
// get the first entry
ZipEntry entry = jis.getNextEntry();
// we will loop through all the entries in the jar file
while (entry != null)
{
// test the entry.getName() against whatever you are looking for, etc
if (entry.getName().equalsIgnoreCase(ast)
|| entry.getName().equalsIgnoreCase(ast
+ Main.TO_STRING_FILE_NAME_EXT))
{
// read from the JarInputStream until the read method returns -1
// ...
// do what ever you want with the read output
// ...
// if you only care about one file, break here
OutputStream resStreamOut = null;
int readBytes;
byte[] buffer = new byte[4096];
boolean copyContentSuccess = false;
try
{
resStreamOut = new FileOutputStream(new File(getProjectOutputDirectory(), entry.getName()));
while ((readBytes = jis.read(buffer)) > 0)
{
resStreamOut.write(buffer, 0, readBytes);
copyContentSuccess = true;
}
} catch (IOException e1)
{
copyContentSuccess = false;
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
resStreamOut.close();
}
if (entry.getName().equalsIgnoreCase(ast)
&& copyContentSuccess)
{
astDefinitionPrepared = true;
}
}
// get the next entry
entry = jis.getNextEntry();
}
jis.close();
} catch (FileNotFoundException e)
{
getLog().error("Failed to find file for base artifact: " + baseJar);
throw new MojoExecutionException("Unable to find base artifact jar: "
+ baseJar, e);
} catch (IOException e)
{
getLog().error("Failed to while reading from base artifact: "
+ baseJar);
throw new MojoExecutionException("Unable to read from base artifact jar: "
+ baseJar, e);
} finally
{
try
{
if (jis != null)
{
jis.close();
}
} catch (IOException e)
{
}
}
if (!astDefinitionPrepared)
{
throw new MojoFailureException("Failed to prepare base AST definition, from source: "
+ baseJar);
}
}
public boolean generateVdm()
{
return generateVdm != null && generateVdm;
}
public File getGeneratedFolder()
{
return outputDirectory;
}
private String getDeclaredPluginVersion()
{
for (Object o : project.getModel().getBuild().getPlugins())
{
if (o instanceof Plugin)
{
Plugin p = (Plugin) o;
if (p.getGroupId().equals(PLUGIN_GROUPID)
&& p.getArtifactId().equals(PLUGIN_ARTIFACTID))
{
return p.getVersion();
}
}
}
return "";
}
public void generateSingleAst(File treeName, File toStringAstFile,
File generated, Environment env1)
{
try
{
FileInputStream toStringFileStream = new FileInputStream(toStringAstFile);
env1 = Main.create(toStringFileStream, new FileInputStream(treeName.getAbsolutePath()), generated, true, generateVdm());
setCrc(treeName);
setCrc(toStringAstFile);
setVersion(getDeclaredPluginVersion());
} catch (Exception e)
{
getLog().error(e);
}
if (env1 != null)
{
getLog().info("Generator completed with "
+ env1.getAllDefinitions().size() + " generated files.\n\n");
}
}
public void generateExtendedAst(File baseAstFile, File extendedAstFile,
File baseAstToStringAstFile, File extendedAstToStringFile,
File generated)
{
getLog().info("Generator starting with extension input: "
+ extendedAstFile);
if (!extendedAstFile.exists())
{
getLog().equals("Extended AST file does not exist: "
+ extendedAstFile.getAbsolutePath());
return;
}
FileInputStream toStringAstFileStream = null;
FileInputStream toStringExtendedFileInputStream = null;
try
{
if (baseAstToStringAstFile.canRead())
toStringAstFileStream = new FileInputStream(baseAstToStringAstFile);
if (extendedAstToStringFile.canRead())
toStringExtendedFileInputStream = new FileInputStream(extendedAstToStringFile);
} catch (FileNotFoundException e)
{
}
try
{
Main.create(toStringAstFileStream, toStringExtendedFileInputStream, new FileInputStream(baseAstFile), new FileInputStream(extendedAstFile), generated, extendedName, generateVdm(), extendedTreeOnly);
setCrc(baseAstFile);
setCrc(baseAstToStringAstFile);
setCrc(extendedAstFile);
setCrc(extendedAstToStringFile);
setVersion(getDeclaredPluginVersion());
} catch (Exception e)
{
getLog().error(e);
}
}
public static boolean deleteDir(File dir)
{
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
boolean success = deleteDir(new File(dir, children[i]));
if (!success)
{
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
public boolean isCrcEqual(File file)
{
if (file == null)
{
return false;
}
String name = file.getName();
long sourceCrc = Util.getCheckSum(file.getAbsolutePath());
File crcFile = new File(getProjectOutputDirectory(), name + ".crc");
if (!crcFile.exists())
{
return false;
}
String crcString;
try
{
crcString = Util.readFile(crcFile);
} catch (IOException e)
{
e.printStackTrace();
return false;
}
long destinationCrc = Long.valueOf(crcString);
return destinationCrc == sourceCrc;
}
public void setCrc(File astFile) throws IOException
{
String name = astFile.getName();
Long sourceCrc = Util.getCheckSum(astFile.getAbsolutePath());
File crcFile = new File(getProjectOutputDirectory(), name + ".crc");
Util.writeFile(crcFile, sourceCrc.toString());
}
public boolean isVersionEqual(String version)
{
File crcFile = new File(getProjectOutputDirectory(), "version.crc");
if (!crcFile.exists())
{
return false;
}
String crcString;
try
{
crcString = Util.readFile(crcFile);
} catch (IOException e)
{
e.printStackTrace();
return false;
}
return version.equals(crcString);
}
public void setVersion(String version) throws IOException
{
File crcFile = new File(getProjectOutputDirectory(), "version.crc");
Util.writeFile(crcFile, version);
}
}
| true | true | public void execute() throws MojoExecutionException, MojoFailureException
{
getLog().info("Preparing for tree generation...");
// Let's make sure that maven knows to look in the output directory
project.addCompileSourceRoot(outputDirectory.getPath());
// Base tree
File baseAstFile = new File(getResourcesDir(), ast);
File baseAsttoStringFile = new File(baseAstFile.getAbsolutePath()
+ Main.TO_STRING_FILE_NAME_EXT);
// Extended tree
File extendedAstFile = (extendedAst == null ? null
: new File(getResourcesDir(), extendedAst));
File extendedAstToStringFile = (extendedAstFile == null ? null
: new File(extendedAstFile.getAbsolutePath()
+ Main.TO_STRING_FILE_NAME_EXT));
if (extendedAstFile != null)
{
getLog().info("Configuring extension");
if (this.extendedAstGroupId == null
|| this.extendedAstArtifactId == null)
{
getLog().error("\tExtension base dependency not configures with groupId and artifactId");
}
getLog().info("\tExtension base dependency is: \""
+ this.extendedAstGroupId + ":"
+ this.extendedAstArtifactId + "\"");
getLog().info("\tSearching for base dependency artifact");
if (extendedAstFile != null)
{
DefaultArtifact baseArtifact = null;
for (Object a : this.project.getDependencyArtifacts())
{
if (a instanceof DefaultArtifact)
{
DefaultArtifact artifact = (DefaultArtifact) a;
if (artifact.getGroupId().equals(this.extendedAstGroupId)
&& artifact.getArtifactId().equals(this.extendedAstArtifactId))
{
baseArtifact = artifact;
break;
}
}
}
getLog().info("\tExtension base artifact found - exstracting base tree definition files");
File baseJar = baseArtifact.getFile();
preparebase(baseJar, ast);
getLog().info("\tSetting base definition files to:");
baseAstFile = new File(getProjectOutputDirectory(), ast);
baseAsttoStringFile = new File(baseAstFile.getAbsolutePath()
+ Main.TO_STRING_FILE_NAME_EXT);
getLog().info("\t\tbase: " + baseAstFile);
getLog().info("\t\tbase tostring: " + baseAsttoStringFile);
getLog().info("\tExtension base artifact configured.");
}
}
getLog().info("Checking if generation required.");
if (isCrcEqual(baseAstFile) && isCrcEqual(baseAsttoStringFile)
&& isVersionEqual(getDeclaredPluginVersion()))
{
if (extendedAst != null && !extendedAst.isEmpty())
{
if (isCrcEqual(new File(getResourcesDir(), extendedAst))
&& isCrcEqual(new File(getResourcesDir(), extendedAst))
&& isVersionEqual(project.getVersion()))
{
getLog().info("Extended AST unchanged");
getLog().info("Nothing to generate, source already up-to-date");
return;
}
getLog().info("Extended AST generation needed");
} else
{
getLog().info("All up to date");
return;
}
} else
{
getLog().info("Full AST generation needed");
}
getLog().info("Generating...");
if (deletePackageOnGenerate != null)
{
for (String relativePath : deletePackageOnGenerate)
{
relativePath = relativePath.replace('.', File.separatorChar);
getLog().info("Deleting folder: " + relativePath);
File f = new File(getGeneratedFolder(), relativePath.replace('/', File.separatorChar));
if (f.exists())
{
deleteDir(f);
} else
{
getLog().warn("Folder not found and delete skipped: "
+ relativePath);
}
}
}
if (baseAstFile.exists())
{
File generated = getGeneratedFolder();
getLog().info("Generator starting with input: " + baseAstFile);
Environment env1 = null;
if (extendedName == null && extendedAst != null)
{
getLog().error("Missing extendedName for AST extension of: "
+ extendedAst);
} else if (extendedAst == null)
{
generateSingleAst(baseAstFile, baseAsttoStringFile, generated, env1);
} else
{
generateExtendedAst(baseAstFile, extendedAstFile, baseAsttoStringFile, extendedAstToStringFile, generated);
}
} else
{
getLog().error("Cannot find input file: "
+ baseAstFile.getAbsolutePath());
}
}
| public void execute() throws MojoExecutionException, MojoFailureException
{
getLog().info("Preparing for tree generation...");
// Let's make sure that maven knows to look in the output directory
project.addCompileSourceRoot(outputDirectory.getPath());
// Base tree
File baseAstFile = new File(getResourcesDir(), ast);
File baseAsttoStringFile = new File(baseAstFile.getAbsolutePath()
+ Main.TO_STRING_FILE_NAME_EXT);
// Extended tree
File extendedAstFile = (extendedAst == null ? null
: new File(getResourcesDir(), extendedAst));
File extendedAstToStringFile = (extendedAstFile == null ? null
: new File(extendedAstFile.getAbsolutePath()
+ Main.TO_STRING_FILE_NAME_EXT));
if (extendedAstFile != null)
{
getLog().info("Configuring extension");
if (this.extendedAstGroupId == null
|| this.extendedAstArtifactId == null)
{
getLog().error("\tExtension base dependency not configures with groupId and artifactId");
}
getLog().info("\tExtension base dependency is: \""
+ this.extendedAstGroupId + ":"
+ this.extendedAstArtifactId + "\"");
getLog().info("\tSearching for base dependency artifact");
if (extendedAstFile != null)
{
DefaultArtifact baseArtifact = null;
for (Object a : this.project.getDependencyArtifacts())
{
if (a instanceof DefaultArtifact)
{
DefaultArtifact artifact = (DefaultArtifact) a;
if (artifact.getGroupId().equals(this.extendedAstGroupId)
&& artifact.getArtifactId().equals(this.extendedAstArtifactId))
{
baseArtifact = artifact;
break;
}
}
}
getLog().info("\tExtension base artifact found - exstracting base tree definition files");
File baseJar = baseArtifact.getFile();
preparebase(baseJar, ast);
getLog().info("\tSetting base definition files to:");
baseAstFile = new File(getProjectOutputDirectory(), ast);
baseAsttoStringFile = new File(baseAstFile.getAbsolutePath()
+ Main.TO_STRING_FILE_NAME_EXT);
getLog().info("\t\tbase: " + baseAstFile);
getLog().info("\t\tbase tostring: " + baseAsttoStringFile);
getLog().info("\tExtension base artifact configured.");
}
}
getLog().info("Checking if generation required.");
if (isCrcEqual(baseAstFile) && isCrcEqual(baseAsttoStringFile)
&& isVersionEqual(getDeclaredPluginVersion()))
{
if (extendedAst != null && !extendedAst.isEmpty())
{
if (isCrcEqual(new File(getResourcesDir(), extendedAst))
&& isCrcEqual(new File(getResourcesDir(), extendedAst))
&& isVersionEqual(getDeclaredPluginVersion()))
{
getLog().info("Extended AST unchanged");
getLog().info("Nothing to generate, source already up-to-date");
return;
}
getLog().info("Extended AST generation needed");
} else
{
getLog().info("All up to date");
return;
}
} else
{
getLog().info("Full AST generation needed");
}
getLog().info("Generating...");
if (deletePackageOnGenerate != null)
{
for (String relativePath : deletePackageOnGenerate)
{
relativePath = relativePath.replace('.', File.separatorChar);
getLog().info("Deleting folder: " + relativePath);
File f = new File(getGeneratedFolder(), relativePath.replace('/', File.separatorChar));
if (f.exists())
{
deleteDir(f);
} else
{
getLog().warn("Folder not found and delete skipped: "
+ relativePath);
}
}
}
if (baseAstFile.exists())
{
File generated = getGeneratedFolder();
getLog().info("Generator starting with input: " + baseAstFile);
Environment env1 = null;
if (extendedName == null && extendedAst != null)
{
getLog().error("Missing extendedName for AST extension of: "
+ extendedAst);
} else if (extendedAst == null)
{
generateSingleAst(baseAstFile, baseAsttoStringFile, generated, env1);
} else
{
generateExtendedAst(baseAstFile, extendedAstFile, baseAsttoStringFile, extendedAstToStringFile, generated);
}
} else
{
getLog().error("Cannot find input file: "
+ baseAstFile.getAbsolutePath());
}
}
|
diff --git a/clients/android/NewsBlur/src/com/newsblur/network/LikeCommentTask.java b/clients/android/NewsBlur/src/com/newsblur/network/LikeCommentTask.java
index f0308692d..044b47026 100644
--- a/clients/android/NewsBlur/src/com/newsblur/network/LikeCommentTask.java
+++ b/clients/android/NewsBlur/src/com/newsblur/network/LikeCommentTask.java
@@ -1,75 +1,77 @@
package com.newsblur.network;
import java.lang.ref.WeakReference;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.Toast;
import com.newsblur.R;
import com.newsblur.domain.Comment;
import com.newsblur.domain.UserDetails;
import com.newsblur.util.PrefsUtils;
import com.newsblur.util.UIUtils;
import com.newsblur.view.FlowLayout;
public class LikeCommentTask extends AsyncTask<Void, Void, Boolean>{
final WeakReference<ImageView> favouriteIconViewHolder;
private final APIManager apiManager;
private final String storyId;
private final Comment comment;
private final String feedId;
private final Context context;
private final String userId;
private Bitmap userImage;
private WeakReference<FlowLayout> favouriteAvatarHolder;
private UserDetails user;
public LikeCommentTask(final Context context, final APIManager apiManager, final ImageView favouriteIcon, final FlowLayout favouriteAvatarLayout, final String storyId, final Comment comment, final String feedId, final String userId) {
this.apiManager = apiManager;
this.storyId = storyId;
this.comment = comment;
this.feedId = feedId;
this.context = context;
this.userId = userId;
favouriteAvatarHolder = new WeakReference<FlowLayout>(favouriteAvatarLayout);
favouriteIconViewHolder = new WeakReference<ImageView>(favouriteIcon);
userImage = PrefsUtils.getUserImage(context);
user = PrefsUtils.getUserDetails(context);
}
@Override
protected Boolean doInBackground(Void... params) {
return apiManager.favouriteComment(storyId, comment.userId, feedId);
}
@Override
protected void onPostExecute(Boolean result) {
if (favouriteIconViewHolder.get() != null) {
if (result.booleanValue()) {
favouriteIconViewHolder.get().setImageResource(R.drawable.have_favourite);
- ImageView favouriteImage = new ImageView(context);
- favouriteImage.setTag(user.id);
- userImage = UIUtils.roundCorners(userImage, 10f);
- favouriteImage.setImageBitmap(userImage);
- favouriteAvatarHolder.get().addView(favouriteImage);
+ if (userImage != null) {
+ ImageView favouriteImage = new ImageView(context);
+ favouriteImage.setTag(user.id);
+ userImage = UIUtils.roundCorners(userImage, 10f);
+ favouriteImage.setImageBitmap(userImage);
+ favouriteAvatarHolder.get().addView(favouriteImage);
+ }
String[] newArray = new String[comment.likingUsers.length + 1];
System.arraycopy(comment.likingUsers, 0, newArray, 0, comment.likingUsers.length);
newArray[newArray.length - 1] = userId;
comment.likingUsers = newArray;
Toast.makeText(context, R.string.comment_favourited, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, R.string.error_liking_comment, Toast.LENGTH_SHORT).show();
}
}
}
}
| true | true | protected void onPostExecute(Boolean result) {
if (favouriteIconViewHolder.get() != null) {
if (result.booleanValue()) {
favouriteIconViewHolder.get().setImageResource(R.drawable.have_favourite);
ImageView favouriteImage = new ImageView(context);
favouriteImage.setTag(user.id);
userImage = UIUtils.roundCorners(userImage, 10f);
favouriteImage.setImageBitmap(userImage);
favouriteAvatarHolder.get().addView(favouriteImage);
String[] newArray = new String[comment.likingUsers.length + 1];
System.arraycopy(comment.likingUsers, 0, newArray, 0, comment.likingUsers.length);
newArray[newArray.length - 1] = userId;
comment.likingUsers = newArray;
Toast.makeText(context, R.string.comment_favourited, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, R.string.error_liking_comment, Toast.LENGTH_SHORT).show();
}
}
}
| protected void onPostExecute(Boolean result) {
if (favouriteIconViewHolder.get() != null) {
if (result.booleanValue()) {
favouriteIconViewHolder.get().setImageResource(R.drawable.have_favourite);
if (userImage != null) {
ImageView favouriteImage = new ImageView(context);
favouriteImage.setTag(user.id);
userImage = UIUtils.roundCorners(userImage, 10f);
favouriteImage.setImageBitmap(userImage);
favouriteAvatarHolder.get().addView(favouriteImage);
}
String[] newArray = new String[comment.likingUsers.length + 1];
System.arraycopy(comment.likingUsers, 0, newArray, 0, comment.likingUsers.length);
newArray[newArray.length - 1] = userId;
comment.likingUsers = newArray;
Toast.makeText(context, R.string.comment_favourited, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, R.string.error_liking_comment, Toast.LENGTH_SHORT).show();
}
}
}
|
diff --git a/src/main/java/com/blackboard/HorizontalLine.java b/src/main/java/com/blackboard/HorizontalLine.java
index c8dd469..5a33af3 100644
--- a/src/main/java/com/blackboard/HorizontalLine.java
+++ b/src/main/java/com/blackboard/HorizontalLine.java
@@ -1,66 +1,66 @@
package com.blackboard;
public class HorizontalLine implements Line {
private int length;
private int segments = 1;
public void setLength(int length) {
this.length = length;
}
public String toString() {
StringBuilder sb = new StringBuilder();
int splitBoundry = length / segments;
int extras = length % segments;
int segmentsPrinted = 0;
for (int i = 0; i < length; i++) {
if ((i + 1) % splitBoundry == 0) {
// If we reach the end of the "normal", non-leftover segments then
// append a character without a trailing space and break out of the loop
// so that we can print the leftovers at the end
if (segments == segmentsPrinted + 1) {
sb.append("=");
break;
}
- // If we reach the end of the string then don't print a trailling space
+ // If we reach the end of the string then don't print a trailing space
if (i + 1 == length) {
sb.append("="); // Avoid spurious whitespace
segmentsPrinted += 1;
} else {
sb.append("= "); //Add space char for split
segmentsPrinted += 1;
}
} else {
// Only print if we have not yet reached the end of
- // "normal" non-lefover segments
+ // "normal" non-leftover segments
if (segments != segmentsPrinted) {
sb.append("=");
}
}
}
// If we have leftovers then pop them on the end
// I decided to do this instead of redistribute among the pieces
// as that re-arranges things and, if used on a non-uniform string, would
// corrupt it.
if (extras > 0) {
for(int curExtra = 0; curExtra < extras; curExtra++) {
sb.append("=");
}
}
return sb.toString();
}
public void split(int segments) {
if (segments > length) {
throw new IllegalArgumentException("Cannot split a string in more pieces than its constituent parts");
}
if (length == 0) {
throw new IllegalArgumentException("Can't split zero length string");
}
if (segments == 0) {
throw new IllegalArgumentException("Can't split a string into zero pieces");
}
this.segments = segments;
}
}
| false | true | public String toString() {
StringBuilder sb = new StringBuilder();
int splitBoundry = length / segments;
int extras = length % segments;
int segmentsPrinted = 0;
for (int i = 0; i < length; i++) {
if ((i + 1) % splitBoundry == 0) {
// If we reach the end of the "normal", non-leftover segments then
// append a character without a trailing space and break out of the loop
// so that we can print the leftovers at the end
if (segments == segmentsPrinted + 1) {
sb.append("=");
break;
}
// If we reach the end of the string then don't print a trailling space
if (i + 1 == length) {
sb.append("="); // Avoid spurious whitespace
segmentsPrinted += 1;
} else {
sb.append("= "); //Add space char for split
segmentsPrinted += 1;
}
} else {
// Only print if we have not yet reached the end of
// "normal" non-lefover segments
if (segments != segmentsPrinted) {
sb.append("=");
}
}
}
// If we have leftovers then pop them on the end
// I decided to do this instead of redistribute among the pieces
// as that re-arranges things and, if used on a non-uniform string, would
// corrupt it.
if (extras > 0) {
for(int curExtra = 0; curExtra < extras; curExtra++) {
sb.append("=");
}
}
return sb.toString();
}
| public String toString() {
StringBuilder sb = new StringBuilder();
int splitBoundry = length / segments;
int extras = length % segments;
int segmentsPrinted = 0;
for (int i = 0; i < length; i++) {
if ((i + 1) % splitBoundry == 0) {
// If we reach the end of the "normal", non-leftover segments then
// append a character without a trailing space and break out of the loop
// so that we can print the leftovers at the end
if (segments == segmentsPrinted + 1) {
sb.append("=");
break;
}
// If we reach the end of the string then don't print a trailing space
if (i + 1 == length) {
sb.append("="); // Avoid spurious whitespace
segmentsPrinted += 1;
} else {
sb.append("= "); //Add space char for split
segmentsPrinted += 1;
}
} else {
// Only print if we have not yet reached the end of
// "normal" non-leftover segments
if (segments != segmentsPrinted) {
sb.append("=");
}
}
}
// If we have leftovers then pop them on the end
// I decided to do this instead of redistribute among the pieces
// as that re-arranges things and, if used on a non-uniform string, would
// corrupt it.
if (extras > 0) {
for(int curExtra = 0; curExtra < extras; curExtra++) {
sb.append("=");
}
}
return sb.toString();
}
|
diff --git a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
index d7e465f..541ce73 100644
--- a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
+++ b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java
@@ -1,425 +1,426 @@
/*
* Created on Jul 27, 2005
*/
package uk.org.ponder.rsf.renderer.html;
import java.io.InputStream;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import uk.org.ponder.rsf.components.ParameterList;
import uk.org.ponder.rsf.components.UIAnchor;
import uk.org.ponder.rsf.components.UIBound;
import uk.org.ponder.rsf.components.UIBoundBoolean;
import uk.org.ponder.rsf.components.UIBoundList;
import uk.org.ponder.rsf.components.UIBoundString;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIComponent;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInput;
import uk.org.ponder.rsf.components.UILink;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UIOutputMultiline;
import uk.org.ponder.rsf.components.UIParameter;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UIVerbatim;
import uk.org.ponder.rsf.renderer.ComponentRenderer;
import uk.org.ponder.rsf.renderer.RenderSystem;
import uk.org.ponder.rsf.renderer.RenderUtil;
import uk.org.ponder.rsf.renderer.StaticComponentRenderer;
import uk.org.ponder.rsf.renderer.StaticRendererCollection;
import uk.org.ponder.rsf.request.FossilizedConverter;
import uk.org.ponder.rsf.request.SubmittedValueEntry;
import uk.org.ponder.rsf.template.XMLLump;
import uk.org.ponder.rsf.template.XMLLumpList;
import uk.org.ponder.rsf.uitype.UITypes;
import uk.org.ponder.rsf.viewstate.ViewParamUtil;
import uk.org.ponder.streamutil.StreamCopyUtil;
import uk.org.ponder.streamutil.write.PrintOutputStream;
import uk.org.ponder.stringutil.StringList;
import uk.org.ponder.stringutil.StringSet;
import uk.org.ponder.stringutil.URLUtil;
import uk.org.ponder.util.Logger;
import uk.org.ponder.xml.XMLUtil;
import uk.org.ponder.xml.XMLWriter;
/**
* The implementation of the standard XHTML rendering System. This class is due
* for basic refactoring since it contains logic that belongs in a) a "base
* System-independent" lookup bean, and b) in a number of individual
* ComponentRenderer objects.
*
* @author Antranig Basman ([email protected])
*
*/
public class BasicHTMLRenderSystem implements RenderSystem {
private StaticRendererCollection scrc;
public void setStaticRenderers(StaticRendererCollection scrc) {
this.scrc = scrc;
}
// two methods for the RenderSystemDecoder interface
public void normalizeRequestMap(Map requestparams) {
String key = RenderUtil.findCommandParams(requestparams);
if (key != null) {
String params = key.substring(FossilizedConverter.COMMAND_LINK_PARAMETERS
.length());
RenderUtil.unpackCommandLink(params, requestparams);
requestparams.remove(key);
}
}
public void fixupUIType(SubmittedValueEntry sve) {
if (sve.oldvalue instanceof Boolean) {
if (sve.newvalue == null)
sve.newvalue = Boolean.FALSE;
}
else if (sve.oldvalue instanceof String[]) {
if (sve.newvalue == null)
sve.newvalue = new String[] {};
}
}
private void closeTag(PrintOutputStream pos, XMLLump uselump) {
pos.print("</");
pos.write(uselump.buffer, uselump.start + 1, uselump.length - 2);
pos.print(">");
}
private void dumpBoundFields(UIBound torender, XMLWriter xmlw) {
if (torender != null) {
if (torender.fossilizedbinding != null) {
RenderUtil.dumpHiddenField(torender.fossilizedbinding.name,
torender.fossilizedbinding.value, xmlw);
}
if (torender.fossilizedshaper != null) {
RenderUtil.dumpHiddenField(torender.fossilizedshaper.name,
torender.fossilizedshaper.value, xmlw);
}
}
}
// No, this method will not stay like this forever! We plan on an architecture
// with renderer-per-component "class" as before, plus interceptors.
// Although a lot of the parameterisation now lies in the allowable tag
// set at target.
public int renderComponent(UIComponent torendero, XMLLump[] lumps,
int lumpindex, PrintOutputStream pos) {
XMLWriter xmlw = new XMLWriter(pos);
XMLLump lump = lumps[lumpindex];
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap
.headsForID(XMLLump.PAYLOAD_COMPONENT)
: null;
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr != null) {
int tagtype = scr.render(lumps, lumpindex, xmlw);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
}
if (lump.textEquals("<form ")) {
Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID
+ " and all children at " + lump.toDebugString()
+ " since no peer component");
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos);
lumpindex = payload.lumpindex;
}
String fullID = torendero.getFullID();
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
attrcopy.put("id", fullID);
attrcopy.remove(XMLLump.ID_ATTRIBUTE);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
pos.write(uselump.buffer, uselump.start, uselump.length);
// TODO: Note that these are actually BOUND now. Create some kind of
// defaultBoundRenderer.
if (torendero instanceof UIBound) {
UIBound torender = (UIBound) torendero;
if (!torender.willinput) {
if (torendero.getClass() == UIOutput.class) {
String value = ((UIOutput) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
xmlw.write(value);
closeTag(pos, uselump);
}
}
else if (torendero.getClass() == UIOutputMultiline.class) {
StringList value = ((UIOutputMultiline) torendero).getValue();
if (value == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
for (int i = 0; i < value.size(); ++i) {
if (i != 0) {
pos.print("<br/>");
}
xmlw.write(value.stringAt(i));
}
closeTag(pos, uselump);
}
}
else if (torender.getClass() == UIAnchor.class) {
String value = ((UIAnchor) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
attrcopy.put("name", value);
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (endopen.lumpindex == close.lumpindex) {
pos.print("/>");
}
else {
pos.print(">");
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
}
}
}
// factor out component-invariant processing of UIBound.
else { // Bound with willinput = true
attrcopy.put("name", fullID);
// attrcopy.put("id", fullID);
String value = "";
String body = null;
if (torendero instanceof UIInput) {
value = ((UIInput) torender).getValue();
if (uselump.textEquals("<textarea ")) {
body = value;
}
else {
attrcopy.put("value", value);
}
}
else if (torendero instanceof UIBoundBoolean) {
if (((UIBoundBoolean) torender).getValue()) {
attrcopy.put("checked", "yes");
// this "value" is thrown away for checkboxes.
value = "true";
}
else {
+ attrcopy.remove("checked");
value = "false";
}
// eh? What is the "value" attribute for one of these?
attrcopy.put("value", "true");
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
if (body != null) {
xmlw.write(body);
pos.write(close.buffer, close.start, close.length);
}
else {
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
// unify hidden field processing? ANY parameter children found must
// be dumped as hidden fields.
}
// dump any fossilized binding for this component.
dumpBoundFields(torender, xmlw);
} // end if UIBound
else if (torendero instanceof UISelect) {
UISelect select = (UISelect) torendero;
// The HTML submitted value from a <select> actually corresponds
// with the selection member, not the top-level component.
attrcopy.put("name", select.selection.getFullID());
attrcopy.put("id", select.selection.getFullID());
StringSet selected = new StringSet();
if (select.selection instanceof UIBoundList) {
selected.addAll(((UIBoundList) select.selection).getValue());
attrcopy.put("multiple", "true");
}
else if (select.selection instanceof UIBoundString) {
selected.add(((UIBoundString) select.selection).getValue());
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
String[] values = select.optionlist.getValue();
String[] names = select.optionnames == null ? values
: select.optionnames.getValue();
for (int i = 0; i < names.length; ++i) {
pos.print("<option value=\"");
xmlw.write(values[i]);
if (selected.contains(values[i])) {
pos.print("\" selected=\"true");
}
pos.print("\">");
xmlw.write(names[i]);
pos.print("</option>\n");
}
closeTag(pos, uselump);
dumpBoundFields(select.selection, xmlw);
dumpBoundFields(select.optionlist, xmlw);
dumpBoundFields(select.optionnames, xmlw);
}
else if (torendero instanceof UILink) {
UILink torender = (UILink) torendero;
String attrname = URLRewriteSCR.getLinkAttribute(uselump);
if (attrname != null) {
attrcopy.put(attrname, torender.target.getValue());
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
String value = torender.linktext == null ? null
: torender.linktext.getValue();
if (value != null && !UITypes.isPlaceholder(value)) {
xmlw.write(value);
closeTag(pos, uselump);
}
else {
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
}
else if (torendero instanceof UICommand) {
UICommand torender = (UICommand) torendero;
String value = RenderUtil.makeURLAttributes(torender.parameters);
// any desired "attributes" decoded for JUST THIS ACTION must be
// secretly
// bundled as this special attribute.
attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS
+ value);
if (lump.textEquals("<input ") && torender.commandtext != null) {
attrcopy.put("value", torender.commandtext);
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (endopen.lumpindex == close.lumpindex) {
pos.print("/>");
}
else {
pos.print(">");
if (torender.commandtext != null && lump.textEquals("<button ")) {
xmlw.write(torender.commandtext);
closeTag(pos, uselump);
}
else {
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
}
// RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD,
// torender.actionhandler, pos);
}
// Forms behave slightly oddly in the hierarchy - by the time they reach
// the renderer, they have been "shunted out" of line with their children,
// i.e. any "submitting" controls, if indeed they ever were there.
else if (torendero instanceof UIForm) {
UIForm torender = (UIForm) torendero;
int qpos = torender.postURL.indexOf('?');
// Ensure that any attributes on this postURL
if (qpos == -1) {
attrcopy.put("action", torender.postURL);
}
else {
attrcopy.put("action", torender.postURL.substring(0, qpos));
String attrs = torender.postURL.substring(qpos + 1);
Map attrmap = URLUtil.paramsToMap(attrs, new HashMap());
ParameterList urlparams = ViewParamUtil.mapToParamList(attrmap);
torender.parameters.addAll(urlparams);
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.println(">");
for (int i = 0; i < torender.parameters.size(); ++i) {
UIParameter param = torender.parameters.parameterAt(i);
RenderUtil.dumpHiddenField(param.name, param.value, xmlw);
}
// override "nextpos" - form is expected to contain numerous nested
// Components.
// this is the only ANOMALY!! Forms together with payload cannot work.
// the fact we are at the wrong recursion level will "come out in the
// wash"
// since we must return to the base recursion level before we exit this
// domain.
// Assuming there are no paths *IN* through forms that do not also lead
// *OUT* there will be no problem. Check what this *MEANS* tomorrow.
nextpos = endopen.lumpindex + 1;
}
else if (torendero instanceof UIVerbatim) {
UIVerbatim torender = (UIVerbatim) torendero;
String rendered = null;
// inefficient implementation for now, upgrade when we write bulk POS
// utils.
if (torender.markup instanceof InputStream) {
rendered = StreamCopyUtil
.streamToString((InputStream) torender.markup);
}
else if (torender.markup instanceof Reader) {
rendered = StreamCopyUtil.readerToString((Reader) torender.markup);
}
else if (torender.markup != null) {
rendered = torender.markup.toString();
}
if (rendered == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1, close.lumpindex + 1,
pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
pos.print(rendered);
closeTag(pos, uselump);
}
}
// if there is a payload, dump the postamble.
if (payload != null) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, pos);
}
}
return nextpos;
}
}
| true | true | public int renderComponent(UIComponent torendero, XMLLump[] lumps,
int lumpindex, PrintOutputStream pos) {
XMLWriter xmlw = new XMLWriter(pos);
XMLLump lump = lumps[lumpindex];
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap
.headsForID(XMLLump.PAYLOAD_COMPONENT)
: null;
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr != null) {
int tagtype = scr.render(lumps, lumpindex, xmlw);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
}
if (lump.textEquals("<form ")) {
Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID
+ " and all children at " + lump.toDebugString()
+ " since no peer component");
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos);
lumpindex = payload.lumpindex;
}
String fullID = torendero.getFullID();
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
attrcopy.put("id", fullID);
attrcopy.remove(XMLLump.ID_ATTRIBUTE);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
pos.write(uselump.buffer, uselump.start, uselump.length);
// TODO: Note that these are actually BOUND now. Create some kind of
// defaultBoundRenderer.
if (torendero instanceof UIBound) {
UIBound torender = (UIBound) torendero;
if (!torender.willinput) {
if (torendero.getClass() == UIOutput.class) {
String value = ((UIOutput) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
xmlw.write(value);
closeTag(pos, uselump);
}
}
else if (torendero.getClass() == UIOutputMultiline.class) {
StringList value = ((UIOutputMultiline) torendero).getValue();
if (value == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
for (int i = 0; i < value.size(); ++i) {
if (i != 0) {
pos.print("<br/>");
}
xmlw.write(value.stringAt(i));
}
closeTag(pos, uselump);
}
}
else if (torender.getClass() == UIAnchor.class) {
String value = ((UIAnchor) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
attrcopy.put("name", value);
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (endopen.lumpindex == close.lumpindex) {
pos.print("/>");
}
else {
pos.print(">");
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
}
}
}
// factor out component-invariant processing of UIBound.
else { // Bound with willinput = true
attrcopy.put("name", fullID);
// attrcopy.put("id", fullID);
String value = "";
String body = null;
if (torendero instanceof UIInput) {
value = ((UIInput) torender).getValue();
if (uselump.textEquals("<textarea ")) {
body = value;
}
else {
attrcopy.put("value", value);
}
}
else if (torendero instanceof UIBoundBoolean) {
if (((UIBoundBoolean) torender).getValue()) {
attrcopy.put("checked", "yes");
// this "value" is thrown away for checkboxes.
value = "true";
}
else {
value = "false";
}
// eh? What is the "value" attribute for one of these?
attrcopy.put("value", "true");
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
if (body != null) {
xmlw.write(body);
pos.write(close.buffer, close.start, close.length);
}
else {
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
// unify hidden field processing? ANY parameter children found must
// be dumped as hidden fields.
}
// dump any fossilized binding for this component.
dumpBoundFields(torender, xmlw);
} // end if UIBound
else if (torendero instanceof UISelect) {
UISelect select = (UISelect) torendero;
// The HTML submitted value from a <select> actually corresponds
// with the selection member, not the top-level component.
attrcopy.put("name", select.selection.getFullID());
attrcopy.put("id", select.selection.getFullID());
StringSet selected = new StringSet();
if (select.selection instanceof UIBoundList) {
selected.addAll(((UIBoundList) select.selection).getValue());
attrcopy.put("multiple", "true");
}
else if (select.selection instanceof UIBoundString) {
selected.add(((UIBoundString) select.selection).getValue());
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
String[] values = select.optionlist.getValue();
String[] names = select.optionnames == null ? values
: select.optionnames.getValue();
for (int i = 0; i < names.length; ++i) {
pos.print("<option value=\"");
xmlw.write(values[i]);
if (selected.contains(values[i])) {
pos.print("\" selected=\"true");
}
pos.print("\">");
xmlw.write(names[i]);
pos.print("</option>\n");
}
closeTag(pos, uselump);
dumpBoundFields(select.selection, xmlw);
dumpBoundFields(select.optionlist, xmlw);
dumpBoundFields(select.optionnames, xmlw);
}
else if (torendero instanceof UILink) {
UILink torender = (UILink) torendero;
String attrname = URLRewriteSCR.getLinkAttribute(uselump);
if (attrname != null) {
attrcopy.put(attrname, torender.target.getValue());
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
String value = torender.linktext == null ? null
: torender.linktext.getValue();
if (value != null && !UITypes.isPlaceholder(value)) {
xmlw.write(value);
closeTag(pos, uselump);
}
else {
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
}
else if (torendero instanceof UICommand) {
UICommand torender = (UICommand) torendero;
String value = RenderUtil.makeURLAttributes(torender.parameters);
// any desired "attributes" decoded for JUST THIS ACTION must be
// secretly
// bundled as this special attribute.
attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS
+ value);
if (lump.textEquals("<input ") && torender.commandtext != null) {
attrcopy.put("value", torender.commandtext);
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (endopen.lumpindex == close.lumpindex) {
pos.print("/>");
}
else {
pos.print(">");
if (torender.commandtext != null && lump.textEquals("<button ")) {
xmlw.write(torender.commandtext);
closeTag(pos, uselump);
}
else {
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
}
// RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD,
// torender.actionhandler, pos);
}
// Forms behave slightly oddly in the hierarchy - by the time they reach
// the renderer, they have been "shunted out" of line with their children,
// i.e. any "submitting" controls, if indeed they ever were there.
else if (torendero instanceof UIForm) {
UIForm torender = (UIForm) torendero;
int qpos = torender.postURL.indexOf('?');
// Ensure that any attributes on this postURL
if (qpos == -1) {
attrcopy.put("action", torender.postURL);
}
else {
attrcopy.put("action", torender.postURL.substring(0, qpos));
String attrs = torender.postURL.substring(qpos + 1);
Map attrmap = URLUtil.paramsToMap(attrs, new HashMap());
ParameterList urlparams = ViewParamUtil.mapToParamList(attrmap);
torender.parameters.addAll(urlparams);
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.println(">");
for (int i = 0; i < torender.parameters.size(); ++i) {
UIParameter param = torender.parameters.parameterAt(i);
RenderUtil.dumpHiddenField(param.name, param.value, xmlw);
}
// override "nextpos" - form is expected to contain numerous nested
// Components.
// this is the only ANOMALY!! Forms together with payload cannot work.
// the fact we are at the wrong recursion level will "come out in the
// wash"
// since we must return to the base recursion level before we exit this
// domain.
// Assuming there are no paths *IN* through forms that do not also lead
// *OUT* there will be no problem. Check what this *MEANS* tomorrow.
nextpos = endopen.lumpindex + 1;
}
else if (torendero instanceof UIVerbatim) {
UIVerbatim torender = (UIVerbatim) torendero;
String rendered = null;
// inefficient implementation for now, upgrade when we write bulk POS
// utils.
if (torender.markup instanceof InputStream) {
rendered = StreamCopyUtil
.streamToString((InputStream) torender.markup);
}
else if (torender.markup instanceof Reader) {
rendered = StreamCopyUtil.readerToString((Reader) torender.markup);
}
else if (torender.markup != null) {
rendered = torender.markup.toString();
}
if (rendered == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1, close.lumpindex + 1,
pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
pos.print(rendered);
closeTag(pos, uselump);
}
}
// if there is a payload, dump the postamble.
if (payload != null) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, pos);
}
}
return nextpos;
}
| public int renderComponent(UIComponent torendero, XMLLump[] lumps,
int lumpindex, PrintOutputStream pos) {
XMLWriter xmlw = new XMLWriter(pos);
XMLLump lump = lumps[lumpindex];
int nextpos = -1;
XMLLump outerendopen = lump.open_end;
XMLLump outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
XMLLumpList payloadlist = lump.downmap == null ? null
: lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap
.headsForID(XMLLump.PAYLOAD_COMPONENT)
: null;
XMLLump payload = payloadlist == null ? null
: payloadlist.lumpAt(0);
// if there is no peer component, it might still be a static resource holder
// that needs URLs rewriting.
// we assume there is no payload component here, since there is no producer
// ID that might govern selection. So we use "outer" indices.
if (torendero == null) {
if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) {
String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length());
StaticComponentRenderer scr = scrc.getSCR(scrname);
if (scr != null) {
int tagtype = scr.render(lumps, lumpindex, xmlw);
nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1
: outerendopen.lumpindex + 1;
}
}
if (lump.textEquals("<form ")) {
Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID
+ " and all children at " + lump.toDebugString()
+ " since no peer component");
}
}
else {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
XMLLump endopen = outerendopen;
XMLLump close = outerclose;
XMLLump uselump = lump;
if (payload != null) {
endopen = payload.open_end;
close = payload.close_tag;
uselump = payload;
RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos);
lumpindex = payload.lumpindex;
}
String fullID = torendero.getFullID();
HashMap attrcopy = new HashMap();
attrcopy.putAll(uselump.attributemap);
attrcopy.put("id", fullID);
attrcopy.remove(XMLLump.ID_ATTRIBUTE);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
pos.write(uselump.buffer, uselump.start, uselump.length);
// TODO: Note that these are actually BOUND now. Create some kind of
// defaultBoundRenderer.
if (torendero instanceof UIBound) {
UIBound torender = (UIBound) torendero;
if (!torender.willinput) {
if (torendero.getClass() == UIOutput.class) {
String value = ((UIOutput) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
xmlw.write(value);
closeTag(pos, uselump);
}
}
else if (torendero.getClass() == UIOutputMultiline.class) {
StringList value = ((UIOutputMultiline) torendero).getValue();
if (value == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
for (int i = 0; i < value.size(); ++i) {
if (i != 0) {
pos.print("<br/>");
}
xmlw.write(value.stringAt(i));
}
closeTag(pos, uselump);
}
}
else if (torender.getClass() == UIAnchor.class) {
String value = ((UIAnchor) torendero).getValue();
if (UITypes.isPlaceholder(value)) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1,
close.lumpindex + 1, pos);
}
else {
attrcopy.put("name", value);
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (endopen.lumpindex == close.lumpindex) {
pos.print("/>");
}
else {
pos.print(">");
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
}
}
}
// factor out component-invariant processing of UIBound.
else { // Bound with willinput = true
attrcopy.put("name", fullID);
// attrcopy.put("id", fullID);
String value = "";
String body = null;
if (torendero instanceof UIInput) {
value = ((UIInput) torender).getValue();
if (uselump.textEquals("<textarea ")) {
body = value;
}
else {
attrcopy.put("value", value);
}
}
else if (torendero instanceof UIBoundBoolean) {
if (((UIBoundBoolean) torender).getValue()) {
attrcopy.put("checked", "yes");
// this "value" is thrown away for checkboxes.
value = "true";
}
else {
attrcopy.remove("checked");
value = "false";
}
// eh? What is the "value" attribute for one of these?
attrcopy.put("value", "true");
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
if (body != null) {
xmlw.write(body);
pos.write(close.buffer, close.start, close.length);
}
else {
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
// unify hidden field processing? ANY parameter children found must
// be dumped as hidden fields.
}
// dump any fossilized binding for this component.
dumpBoundFields(torender, xmlw);
} // end if UIBound
else if (torendero instanceof UISelect) {
UISelect select = (UISelect) torendero;
// The HTML submitted value from a <select> actually corresponds
// with the selection member, not the top-level component.
attrcopy.put("name", select.selection.getFullID());
attrcopy.put("id", select.selection.getFullID());
StringSet selected = new StringSet();
if (select.selection instanceof UIBoundList) {
selected.addAll(((UIBoundList) select.selection).getValue());
attrcopy.put("multiple", "true");
}
else if (select.selection instanceof UIBoundString) {
selected.add(((UIBoundString) select.selection).getValue());
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
String[] values = select.optionlist.getValue();
String[] names = select.optionnames == null ? values
: select.optionnames.getValue();
for (int i = 0; i < names.length; ++i) {
pos.print("<option value=\"");
xmlw.write(values[i]);
if (selected.contains(values[i])) {
pos.print("\" selected=\"true");
}
pos.print("\">");
xmlw.write(names[i]);
pos.print("</option>\n");
}
closeTag(pos, uselump);
dumpBoundFields(select.selection, xmlw);
dumpBoundFields(select.optionlist, xmlw);
dumpBoundFields(select.optionnames, xmlw);
}
else if (torendero instanceof UILink) {
UILink torender = (UILink) torendero;
String attrname = URLRewriteSCR.getLinkAttribute(uselump);
if (attrname != null) {
attrcopy.put(attrname, torender.target.getValue());
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
String value = torender.linktext == null ? null
: torender.linktext.getValue();
if (value != null && !UITypes.isPlaceholder(value)) {
xmlw.write(value);
closeTag(pos, uselump);
}
else {
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
}
else if (torendero instanceof UICommand) {
UICommand torender = (UICommand) torendero;
String value = RenderUtil.makeURLAttributes(torender.parameters);
// any desired "attributes" decoded for JUST THIS ACTION must be
// secretly
// bundled as this special attribute.
attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS
+ value);
if (lump.textEquals("<input ") && torender.commandtext != null) {
attrcopy.put("value", torender.commandtext);
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
if (endopen.lumpindex == close.lumpindex) {
pos.print("/>");
}
else {
pos.print(">");
if (torender.commandtext != null && lump.textEquals("<button ")) {
xmlw.write(torender.commandtext);
closeTag(pos, uselump);
}
else {
RenderUtil.dumpTillLump(lumps, endopen.lumpindex + 1,
close.lumpindex + 1, pos);
}
}
// RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD,
// torender.actionhandler, pos);
}
// Forms behave slightly oddly in the hierarchy - by the time they reach
// the renderer, they have been "shunted out" of line with their children,
// i.e. any "submitting" controls, if indeed they ever were there.
else if (torendero instanceof UIForm) {
UIForm torender = (UIForm) torendero;
int qpos = torender.postURL.indexOf('?');
// Ensure that any attributes on this postURL
if (qpos == -1) {
attrcopy.put("action", torender.postURL);
}
else {
attrcopy.put("action", torender.postURL.substring(0, qpos));
String attrs = torender.postURL.substring(qpos + 1);
Map attrmap = URLUtil.paramsToMap(attrs, new HashMap());
ParameterList urlparams = ViewParamUtil.mapToParamList(attrmap);
torender.parameters.addAll(urlparams);
}
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.println(">");
for (int i = 0; i < torender.parameters.size(); ++i) {
UIParameter param = torender.parameters.parameterAt(i);
RenderUtil.dumpHiddenField(param.name, param.value, xmlw);
}
// override "nextpos" - form is expected to contain numerous nested
// Components.
// this is the only ANOMALY!! Forms together with payload cannot work.
// the fact we are at the wrong recursion level will "come out in the
// wash"
// since we must return to the base recursion level before we exit this
// domain.
// Assuming there are no paths *IN* through forms that do not also lead
// *OUT* there will be no problem. Check what this *MEANS* tomorrow.
nextpos = endopen.lumpindex + 1;
}
else if (torendero instanceof UIVerbatim) {
UIVerbatim torender = (UIVerbatim) torendero;
String rendered = null;
// inefficient implementation for now, upgrade when we write bulk POS
// utils.
if (torender.markup instanceof InputStream) {
rendered = StreamCopyUtil
.streamToString((InputStream) torender.markup);
}
else if (torender.markup instanceof Reader) {
rendered = StreamCopyUtil.readerToString((Reader) torender.markup);
}
else if (torender.markup != null) {
rendered = torender.markup.toString();
}
if (rendered == null) {
RenderUtil.dumpTillLump(lumps, lumpindex + 1, close.lumpindex + 1,
pos);
}
else {
XMLUtil.dumpAttributes(attrcopy, xmlw);
pos.print(">");
pos.print(rendered);
closeTag(pos, uselump);
}
}
// if there is a payload, dump the postamble.
if (payload != null) {
RenderUtil.dumpTillLump(lumps, close.lumpindex + 1,
outerclose.lumpindex + 1, pos);
}
}
return nextpos;
}
|
diff --git a/wikapidia-core/src/main/java/org/wikapidia/core/cmd/Env.java b/wikapidia-core/src/main/java/org/wikapidia/core/cmd/Env.java
index f6dc1d08..9e8d615e 100644
--- a/wikapidia-core/src/main/java/org/wikapidia/core/cmd/Env.java
+++ b/wikapidia-core/src/main/java/org/wikapidia/core/cmd/Env.java
@@ -1,114 +1,114 @@
package org.wikapidia.core.cmd;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.wikapidia.conf.Configuration;
import org.wikapidia.conf.ConfigurationException;
import org.wikapidia.conf.Configurator;
import org.wikapidia.conf.DefaultOptionBuilder;
import org.wikapidia.core.lang.LanguageSet;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* @author Shilad Sen
*/
public class Env {
private static final Logger LOG = Logger.getLogger(Env.class.getName());
private LanguageSet languages;
private Configuration configuration;
private Configurator configurator;
private int maxThreads = Runtime.getRuntime().availableProcessors();
/**
* Adds the standard command line options to an options argument.
* @param options
*/
public static void addStandardOptions(Options options) {
Option toAdd[] = new Option[] {
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("conf")
.withDescription("configuration file")
.create("c"),
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("threads")
.withDescription("the maximum number of threads that should be used")
.create("h"),
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("languages")
.withDescription("the set of languages to process, separated by commas")
.create("l")
};
for (Option o : toAdd) {
if (options.hasOption(o.getOpt())) {
throw new IllegalArgumentException("Standard command line option " + o.getOpt() + " reused");
}
options.addOption(o);
}
}
/**
* Parses standard command line arguments and builds the environment using them.
* @param cmd
* @throws ConfigurationException
*/
public Env(CommandLine cmd) throws ConfigurationException {
this(cmd, new HashMap<String, String>());
}
/**
* Parses standard command line arguments and builds the environment using them.
* @param cmd
* @throws ConfigurationException
*/
public Env(CommandLine cmd, Map<String, String> confOverrides) throws ConfigurationException {
// Override configuration parameters using system properties
for (String key : confOverrides.keySet()) {
System.setProperty(key, confOverrides.get(key));
}
// Load basic configuration
File pathConf = cmd.hasOption('c') ? new File(cmd.getOptionValue('c')) : null;
configuration = new Configuration(pathConf);
configurator = new Configurator(configuration);
// Load languages
if (cmd.hasOption("l")) {
languages = new LanguageSet(cmd.getOptionValue("l"));
} else {
- languages = new LanguageSet(configuration.get().getStringList("Languages"));
+ languages = new LanguageSet(configuration.get().getStringList("languages"));
}
// Load numThreads
if (cmd.hasOption("h")) {
maxThreads = new Integer(cmd.getOptionValue("h"));
}
LOG.info("using languages " + languages);
LOG.info("using maxThreads " + maxThreads);
}
public LanguageSet getLanguages() {
return languages;
}
public Configuration getConfiguration() {
return configuration;
}
public Configurator getConfigurator() {
return configurator;
}
public int getMaxThreads() {
return maxThreads;
}
}
| true | true | public Env(CommandLine cmd, Map<String, String> confOverrides) throws ConfigurationException {
// Override configuration parameters using system properties
for (String key : confOverrides.keySet()) {
System.setProperty(key, confOverrides.get(key));
}
// Load basic configuration
File pathConf = cmd.hasOption('c') ? new File(cmd.getOptionValue('c')) : null;
configuration = new Configuration(pathConf);
configurator = new Configurator(configuration);
// Load languages
if (cmd.hasOption("l")) {
languages = new LanguageSet(cmd.getOptionValue("l"));
} else {
languages = new LanguageSet(configuration.get().getStringList("Languages"));
}
// Load numThreads
if (cmd.hasOption("h")) {
maxThreads = new Integer(cmd.getOptionValue("h"));
}
LOG.info("using languages " + languages);
LOG.info("using maxThreads " + maxThreads);
}
| public Env(CommandLine cmd, Map<String, String> confOverrides) throws ConfigurationException {
// Override configuration parameters using system properties
for (String key : confOverrides.keySet()) {
System.setProperty(key, confOverrides.get(key));
}
// Load basic configuration
File pathConf = cmd.hasOption('c') ? new File(cmd.getOptionValue('c')) : null;
configuration = new Configuration(pathConf);
configurator = new Configurator(configuration);
// Load languages
if (cmd.hasOption("l")) {
languages = new LanguageSet(cmd.getOptionValue("l"));
} else {
languages = new LanguageSet(configuration.get().getStringList("languages"));
}
// Load numThreads
if (cmd.hasOption("h")) {
maxThreads = new Integer(cmd.getOptionValue("h"));
}
LOG.info("using languages " + languages);
LOG.info("using maxThreads " + maxThreads);
}
|
diff --git a/stripes/src/net/sourceforge/stripes/util/UrlBuilder.java b/stripes/src/net/sourceforge/stripes/util/UrlBuilder.java
index 48967e5..5ad409c 100644
--- a/stripes/src/net/sourceforge/stripes/util/UrlBuilder.java
+++ b/stripes/src/net/sourceforge/stripes/util/UrlBuilder.java
@@ -1,211 +1,211 @@
/* Copyright 2005-2006 Tim Fennell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.stripes.util;
import net.sourceforge.stripes.exception.StripesRuntimeException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Map;
/**
* <p>Simple class that encapsulates the process of building up a URL from a path fragment
* and a zero or more parameters. Parameters can be single valued, array valued or
* collection valued. In the case of arrays and collections, each value in the array or
* collection will be added as a separate URL parameter (with the same name). The assembled
* URL can then be retrieved by calling toString().</p>
*
* <p>While not immediately obvious, it is possible to add a single parameter with multiple
* values by invoking the addParameter() method that uses varargs, and supplying a Collection as
* the single parameter value to the method.</p>
*
* @author Tim Fennell
* @since Stripes 1.1.2
*/
public class UrlBuilder {
private StringBuilder url = new StringBuilder(256);
boolean seenQuestionMark = false;
private String parameterSeparator;
private String anchor;
/**
* Constructs a UrlBuilder with the path to a resource. Parameters can be added
* later using addParameter(). If the link is to be used in a page then the ampersand
* character usually used to separate parameters will be escaped using the XML entity
* for ampersand.
*
* @param url the path part of the URL
* @param isForPage true if the URL is to be embedded in a page (e.g. in an anchor of img
* tag), false if for some other purpose.
*/
public UrlBuilder(String url, boolean isForPage) {
if (url != null) {
// Check to see if there is an embedded anchor, and strip it out for later
int index = url.indexOf('#');
if (index != -1) {
this.anchor = url.substring(index+1);
url = url.substring(0, index);
}
this.url.append(url);
this.seenQuestionMark = this.url.indexOf("?") != -1;
}
if (isForPage) {
this.parameterSeparator = "&";
}
else {
this.parameterSeparator = "&";
}
}
/**
* Returns the string that will be used to separate parameters in the query string.
* Will usually be either '&' for query strings that will be embedded in HTML
* pages and '&' otherwise.
*/
public String getParameterSeparator() { return parameterSeparator; }
/**
* Sets the string that will be used to separate parameters. By default the values is a
* single ampersand character. If the URL is to be embedded in a page the value should be
* set to the XML ampersand entity.
*/
public void setParameterSeparator(String parameterSeparator) {
this.parameterSeparator = parameterSeparator;
}
/**
* <p>Appends one or more values of a parameter to the URL. Checks to see if each value is
* null, and if so generates a parameter with no value. URL Encodes the parameter values
* to make sure that it is safe to insert into the URL.</p>
*
* <p>If any parameter value passed is a Collection or an Array then this method is called
* recursively with the contents of the collection or array. As a result you can pass
* arbitrarily nested arrays and collections to this method and it will recurse through them
* adding all scalar values as parameters to the URL.</p.
*
* @param name the name of the request parameter being added
* @param values one or more values for the parameter supplied
*/
public void addParameter(String name, Object... values) {
try {
// If values is null or empty, then simply sub in a single empty string
if (values == null || values.length == 0) {
values = Literal.array("");
}
for (Object v : values) {
// Special case: recurse for nested collections and arrays!
if (v instanceof Collection) {
addParameter(name, ((Collection) v).toArray());
}
- else if (v.getClass().isArray()) {
+ else if (v != null && v.getClass().isArray()) {
addParameter(name, (Object[]) CollectionUtil.asObjectArray(v));
}
else {
// Figure out whether we already have params or not
if (!this.seenQuestionMark) {
this.url.append('?');
this.seenQuestionMark = true;
}
else {
this.url.append(this.parameterSeparator);
}
this.url.append(name);
this.url.append('=');
if (v != null) {
this.url.append( URLEncoder.encode(v.toString(), "UTF-8") );
}
}
}
}
catch (UnsupportedEncodingException uee) {
throw new StripesRuntimeException("Unsupported encoding? UTF-8? That's unpossible.");
}
}
/**
* Appends one or more parameters to the URL. Various assumptions are made about the Map
* parameter. Firstly, that the keys are all either Strings, or objects that can be safely
* toString()'d to yield parameter names. Secondly that the values either toString() to form
* a single parameter value, or are arrays or collections that contain toString()'able
* objects.
*
* @param parameters a non-null Map as described above
*/
public void addParameters(Map<? extends Object,? extends Object> parameters) {
for (Map.Entry<? extends Object,? extends Object> parameter : parameters.entrySet()) {
String name = parameter.getKey().toString();
Object valueOrValues = parameter.getValue();
if (valueOrValues == null) {
addParameter(name, (Object) null);
}
else if (valueOrValues.getClass().isArray()) {
Object[] values = (Object[]) valueOrValues;
addParameter(name, values);
}
else if (valueOrValues instanceof Collection) {
Collection values = (Collection) valueOrValues;
addParameter(name, values);
}
else {
addParameter(name, valueOrValues);
}
}
}
/**
* Gets the anchor, if any, that will be appended to the URL. E.g. if this method
* returns 'input' then the URL will be terminated with '#input' in order to instruct
* the browser to navigate to the HTML anchor callled 'input' when accessing the URL.
*
* @return the anchor (if any) without the leading pound sign, or null
*/
public String getAnchor() { return anchor; }
/**
* Sets the anchor, if any, that will be appended to the URL. E.g. if supplied with
* 'input' then the URL will be terminated with '#input' in order to instruct
* the browser to navigate to the HTML anchor callled 'input' when accessing the URL.
*
* @param anchor the anchor with or without the leading pound sign, or null to disable
*/
public void setAnchor(String anchor) {
if (anchor != null && anchor.startsWith("#") && anchor.length() > 1) {
this.anchor = anchor.substring(1);
}
else {
this.anchor = anchor;
}
}
/**
* Returns the URL composed thus far as a String. All paramter values will have been
* URL encoded and appended to the URL before returning it.
*/
@Override
public String toString() {
if (this.anchor != null && !"".equals(this.anchor)) {
return this.url.toString() + "#" + this.anchor;
}
else {
return this.url.toString();
}
}
}
| true | true | public void addParameter(String name, Object... values) {
try {
// If values is null or empty, then simply sub in a single empty string
if (values == null || values.length == 0) {
values = Literal.array("");
}
for (Object v : values) {
// Special case: recurse for nested collections and arrays!
if (v instanceof Collection) {
addParameter(name, ((Collection) v).toArray());
}
else if (v.getClass().isArray()) {
addParameter(name, (Object[]) CollectionUtil.asObjectArray(v));
}
else {
// Figure out whether we already have params or not
if (!this.seenQuestionMark) {
this.url.append('?');
this.seenQuestionMark = true;
}
else {
this.url.append(this.parameterSeparator);
}
this.url.append(name);
this.url.append('=');
if (v != null) {
this.url.append( URLEncoder.encode(v.toString(), "UTF-8") );
}
}
}
}
catch (UnsupportedEncodingException uee) {
throw new StripesRuntimeException("Unsupported encoding? UTF-8? That's unpossible.");
}
}
| public void addParameter(String name, Object... values) {
try {
// If values is null or empty, then simply sub in a single empty string
if (values == null || values.length == 0) {
values = Literal.array("");
}
for (Object v : values) {
// Special case: recurse for nested collections and arrays!
if (v instanceof Collection) {
addParameter(name, ((Collection) v).toArray());
}
else if (v != null && v.getClass().isArray()) {
addParameter(name, (Object[]) CollectionUtil.asObjectArray(v));
}
else {
// Figure out whether we already have params or not
if (!this.seenQuestionMark) {
this.url.append('?');
this.seenQuestionMark = true;
}
else {
this.url.append(this.parameterSeparator);
}
this.url.append(name);
this.url.append('=');
if (v != null) {
this.url.append( URLEncoder.encode(v.toString(), "UTF-8") );
}
}
}
}
catch (UnsupportedEncodingException uee) {
throw new StripesRuntimeException("Unsupported encoding? UTF-8? That's unpossible.");
}
}
|
diff --git a/src/controller/QuitAction.java b/src/controller/QuitAction.java
index af615ef..4c065b3 100644
--- a/src/controller/QuitAction.java
+++ b/src/controller/QuitAction.java
@@ -1,35 +1,35 @@
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.Environment;
public class QuitAction implements ActionListener {
private JFrame frame;
public QuitAction(JFrame f) {
frame = f;
}
public void actionPerformed(ActionEvent e) {
if (Environment.wrkman.unsavedProjects()) {
- int option = JOptionPane.showConfirmDialog(frame, "Istnieją niezapisane projekty. Czy chcesz je zapisać przed wyjściem?", "Zapisz zmiany",
+ int option = JOptionPane.showConfirmDialog(frame, "Istniej� niezapisane projekty. Czy chcesz je zapisa� przed wyj�ciem?", "Zapisz zmiany",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
switch (option) {
case JOptionPane.YES_OPTION:
Environment.wrkman.saveAllProjects();
frame.dispose();
break;
case JOptionPane.NO_OPTION:
frame.dispose();
break;
}
} else {
frame.dispose();
}
}
}
| true | true | public void actionPerformed(ActionEvent e) {
if (Environment.wrkman.unsavedProjects()) {
int option = JOptionPane.showConfirmDialog(frame, "Istnieją niezapisane projekty. Czy chcesz je zapisać przed wyjściem?", "Zapisz zmiany",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
switch (option) {
case JOptionPane.YES_OPTION:
Environment.wrkman.saveAllProjects();
frame.dispose();
break;
case JOptionPane.NO_OPTION:
frame.dispose();
break;
}
} else {
frame.dispose();
}
}
| public void actionPerformed(ActionEvent e) {
if (Environment.wrkman.unsavedProjects()) {
int option = JOptionPane.showConfirmDialog(frame, "Istniej� niezapisane projekty. Czy chcesz je zapisa� przed wyj�ciem?", "Zapisz zmiany",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
switch (option) {
case JOptionPane.YES_OPTION:
Environment.wrkman.saveAllProjects();
frame.dispose();
break;
case JOptionPane.NO_OPTION:
frame.dispose();
break;
}
} else {
frame.dispose();
}
}
|
diff --git a/src/main/java/org/apache/commons/digester3/RulesBinderImpl.java b/src/main/java/org/apache/commons/digester3/RulesBinderImpl.java
index 79d65cc9..8981a24a 100644
--- a/src/main/java/org/apache/commons/digester3/RulesBinderImpl.java
+++ b/src/main/java/org/apache/commons/digester3/RulesBinderImpl.java
@@ -1,480 +1,480 @@
/* $Id$
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.digester3;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.digester3.rulesbinder.BackToLinkedRuleBuilder;
import org.apache.commons.digester3.rulesbinder.BeanPropertySetterBuilder;
import org.apache.commons.digester3.rulesbinder.CallMethodBuilder;
import org.apache.commons.digester3.rulesbinder.CallParamBuilder;
import org.apache.commons.digester3.rulesbinder.ConverterBuilder;
import org.apache.commons.digester3.rulesbinder.FactoryCreateBuilder;
import org.apache.commons.digester3.rulesbinder.LinkedRuleBuilder;
import org.apache.commons.digester3.rulesbinder.NestedPropertiesBuilder;
import org.apache.commons.digester3.rulesbinder.ObjectCreateBuilder;
import org.apache.commons.digester3.rulesbinder.ObjectParamBuilder;
import org.apache.commons.digester3.rulesbinder.ParamTypeBuilder;
import org.apache.commons.digester3.rulesbinder.PathCallParamBuilder;
import org.apache.commons.digester3.rulesbinder.SetPropertiesBuilder;
import org.apache.commons.digester3.rulesbinder.SetPropertyBuilder;
import org.apache.commons.digester3.spi.RuleProvider;
/**
* The Digester EDSL implementation.
*/
final class RulesBinderImpl implements RulesBinder {
/**
* Errors that can occur during binding time or rules creation.
*/
private final List<ErrorMessage> errors = new ArrayList<ErrorMessage>();
/**
* {@inheritDoc}
*/
public void addError(String messagePattern, Object... arguments) {
this.addError(new ErrorMessage(messagePattern, arguments));
}
/**
* {@inheritDoc}
*/
public void addError(Throwable t) {
String message = "An exception was caught and reported. Message: " + t.getMessage();
this.addError(new ErrorMessage(message, t));
}
/**
*
*
* @param errorMessage
*/
private void addError(ErrorMessage errorMessage) {
this.errors.add(errorMessage);
}
/**
*
*
* @return
*/
public boolean containsErrors() {
return !this.errors.isEmpty();
}
/**
*
*
* @return
*/
public List<ErrorMessage> getErrors() {
return errors;
}
/**
* {@inheritDoc}
*/
public void install(RulesModule rulesModule) {
rulesModule.configure(this);
}
/**
* {@inheritDoc}
*/
public LinkedRuleBuilder forPattern(String pattern) {
final String keyPattern;
if (pattern == null || pattern.length() == 0) {
this.addError(new IllegalArgumentException("Null or empty pattern is not valid"));
keyPattern = null;
} else {
if (pattern.endsWith("/")) {
// to help users who accidently add '/' to the end of their patterns
keyPattern = pattern.substring(0, pattern.length() - 1);
} else {
keyPattern = pattern;
}
}
return new LinkedRuleBuilder() {
private final LinkedRuleBuilder mainBuilder = this;
private String namespaceURI;
public LinkedRuleBuilder withNamespaceURI(/* @Nullable */ String namespaceURI) {
this.namespaceURI = namespaceURI;
return this;
}
/**
*
*/
public ParamTypeBuilder<SetTopRule> setTop(final String methodName) {
if (methodName == null || methodName.length() == 0) {
addError("{forPattern(\"%s\").setTop(String)} empty 'methodName' not allowed", keyPattern);
}
return new AbstractParamTypeBuilder<SetTopRule>(keyPattern, methodName, RulesBinderImpl.this, this) {
@Override
protected String getCalledMethodName() {
return "setTop";
}
public SetTopRule get() {
return new SetTopRule(this.getMethodName(), this.getParamType(), this.isUseExactMatch());
}
};
}
/**
*
*/
public ParamTypeBuilder<SetRootRule> setRoot(final String methodName) {
if (methodName == null || methodName.length() == 0) {
addError("{forPattern(\"%s\").setRoot(String)} empty 'methodName' not allowed", keyPattern);
}
return new AbstractParamTypeBuilder<SetRootRule>(keyPattern, methodName, RulesBinderImpl.this, this) {
@Override
protected String getCalledMethodName() {
return "setRoot";
}
public SetRootRule get() {
return new SetRootRule(this.getMethodName(), this.getParamType(), this.isUseExactMatch());
}
};
}
public SetPropertyBuilder setProperty(String attributePropertyName) {
return null;
}
/**
*
*/
public SetPropertiesBuilder setProperties() {
return new SetPropertiesBuilder() {
private final Map<String, String> aliases = new HashMap<String, String>();
private boolean ignoreMissingProperty = true;
public SetPropertiesRule get() {
return new SetPropertiesRule(this.aliases, this.ignoreMissingProperty);
}
public LinkedRuleBuilder then() {
- return null;
+ return mainBuilder;
}
public SetPropertiesBuilder ignoreMissingProperty(boolean ignoreMissingProperty) {
this.ignoreMissingProperty = ignoreMissingProperty;
return this;
}
public SetPropertiesBuilder addAlias(String attributeName, /* @Nullable */String propertyName) {
if (attributeName == null) {
addError("{forPattern(\"%s\").setProperties().addAlias(String,String)} empty 'methodName' not allowed",
keyPattern);
} else {
this.aliases.put(attributeName, propertyName);
}
return this;
}
};
}
/**
*
*/
public ParamTypeBuilder<SetNextRule> setNext(final String methodName) {
if (methodName == null || methodName.length() == 0) {
addError("{forPattern(\"%s\").setNext(String)} empty 'methodName' not allowed", keyPattern);
}
return new AbstractParamTypeBuilder<SetNextRule>(keyPattern, methodName, RulesBinderImpl.this, this) {
@Override
protected String getCalledMethodName() {
return "setNext";
}
public SetNextRule get() {
return new SetNextRule(this.getMethodName(), this.getParamType(), this.isUseExactMatch());
}
};
}
/**
*
*/
public NestedPropertiesBuilder setNestedProperties() {
return new NestedPropertiesBuilder() {
private final Map<String, String> elementNames = new HashMap<String, String>();
private boolean trimData = true;
private boolean allowUnknownChildElements = false;
public SetNestedPropertiesRule get() {
return new SetNestedPropertiesRule(elementNames, trimData, allowUnknownChildElements);
}
public LinkedRuleBuilder then() {
return mainBuilder;
}
public NestedPropertiesBuilder trimData(boolean trimData) {
this.trimData = trimData;
return this;
}
public NestedPropertiesBuilder addAlias(String elementName, String propertyName) {
if (elementName == null) {
addError("{forPattern(\"%s\").setNestedProperties().addAlias(String,String)} empty 'methodName' not allowed",
keyPattern);
} else {
this.elementNames.put(elementName, propertyName);
}
return this;
}
};
}
/**
*
*/
public BeanPropertySetterBuilder setBeanProperty() {
return new BeanPropertySetterBuilder() {
private String propertyName;
public BeanPropertySetterRule get() {
return new BeanPropertySetterRule(this.propertyName);
}
public LinkedRuleBuilder then() {
return mainBuilder;
}
public BeanPropertySetterBuilder withName(String propertyName) {
this.propertyName = propertyName;
return this;
}
};
}
public <T> ObjectParamBuilder objectParam(T paramObj) {
return null;
}
public FactoryCreateBuilder factoryCreate() {
return null;
}
/**
*
*/
public ObjectCreateBuilder createObject() {
return new ObjectCreateBuilder() {
private String className;
private String attributeName;
public ObjectCreateRule get() {
if (this.className == null && this.attributeName == null) {
addError("{forPattern(\"%s\").createObject()} At least one between 'className' or 'attributeName' has to be specified",
keyPattern);
return null;
}
ObjectCreateRule rule = new ObjectCreateRule(this.className, this.attributeName);
rule.setNamespaceURI(namespaceURI);
return rule;
}
public LinkedRuleBuilder then() {
return mainBuilder;
}
public ObjectCreateBuilder ofTypeSpecifiedByAttribute(String attributeName) {
this.attributeName = attributeName;
return this;
}
public ObjectCreateBuilder ofType(Class<?> type) {
if (type == null) {
addError("{forPattern(\"%s\").createObject().ofType(Class<?>)} NULL Java type not allowed",
keyPattern);
return this;
}
return this.ofType(type.getName());
}
public ObjectCreateBuilder ofType(String className) {
this.className = className;
return this;
}
};
}
public PathCallParamBuilder callParamPath() {
return null;
}
public CallParamBuilder callParam() {
return null;
}
public CallMethodBuilder callMethod(String methodName) {
return null;
}
/**
*
*/
public <R extends Rule> BackToLinkedRuleBuilder<R> addRule(final R rule) {
if (rule == null) {
addError("{forPattern(\"%s\").addRule()} null rule not valid", keyPattern);
}
return this.addRuleCreatedBy(new RuleProvider<R>() {
public R get() {
return rule;
}
});
}
/**
*
*/
public <R extends Rule> BackToLinkedRuleBuilder<R> addRuleCreatedBy(final RuleProvider<R> provider) {
if (provider == null) {
addError("{forPattern(\"%s\").addRuleCreatedBy()} null rule not valid", keyPattern);
}
return new BackToLinkedRuleBuilder<R>() {
public LinkedRuleBuilder then() {
return mainBuilder;
}
public R get() {
R rule = provider.get();
rule.setNamespaceURI(namespaceURI);
return rule;
}
};
}
};
}
private static abstract class AbstractParamTypeBuilder<R extends Rule> implements ParamTypeBuilder<R> {
private final String keyPattern;
private final String methodName;
private final RulesBinder binder;
private final LinkedRuleBuilder mainLinkedBuilder;
private boolean useExactMatch = false;
private String paramType;
public AbstractParamTypeBuilder(String keyPattern,
String methodName,
RulesBinder binder,
LinkedRuleBuilder mainBuilder) {
this.keyPattern = keyPattern;
this.methodName = methodName;
this.binder = binder;
this.mainLinkedBuilder = mainBuilder;
}
public final LinkedRuleBuilder then() {
return this.mainLinkedBuilder;
}
public final ParamTypeBuilder<R> useExactMatch(boolean useExactMatch) {
this.useExactMatch = useExactMatch;
return this;
}
public final ParamTypeBuilder<R> withParameterType(Class<?> paramType) {
if (paramType == null) {
this.binder.addError("{forPattern(\"%s\").%s.withParameterType(Class<?>)} NULL Java type not allowed",
this.keyPattern,
this.getCalledMethodName());
return this;
}
return this.withParameterType(paramType.getName());
}
public ParamTypeBuilder<R> withParameterType(String paramType) {
this.paramType = paramType;
return this;
}
protected abstract String getCalledMethodName();
public String getMethodName() {
return methodName;
}
public String getParamType() {
return paramType;
}
public boolean isUseExactMatch() {
return useExactMatch;
}
}
/**
* {@inheritDoc}
*/
public <T> ConverterBuilder<T> convert(Class<T> type) {
return null;
}
}
| true | true | public LinkedRuleBuilder forPattern(String pattern) {
final String keyPattern;
if (pattern == null || pattern.length() == 0) {
this.addError(new IllegalArgumentException("Null or empty pattern is not valid"));
keyPattern = null;
} else {
if (pattern.endsWith("/")) {
// to help users who accidently add '/' to the end of their patterns
keyPattern = pattern.substring(0, pattern.length() - 1);
} else {
keyPattern = pattern;
}
}
return new LinkedRuleBuilder() {
private final LinkedRuleBuilder mainBuilder = this;
private String namespaceURI;
public LinkedRuleBuilder withNamespaceURI(/* @Nullable */ String namespaceURI) {
this.namespaceURI = namespaceURI;
return this;
}
/**
*
*/
public ParamTypeBuilder<SetTopRule> setTop(final String methodName) {
if (methodName == null || methodName.length() == 0) {
addError("{forPattern(\"%s\").setTop(String)} empty 'methodName' not allowed", keyPattern);
}
return new AbstractParamTypeBuilder<SetTopRule>(keyPattern, methodName, RulesBinderImpl.this, this) {
@Override
protected String getCalledMethodName() {
return "setTop";
}
public SetTopRule get() {
return new SetTopRule(this.getMethodName(), this.getParamType(), this.isUseExactMatch());
}
};
}
/**
*
*/
public ParamTypeBuilder<SetRootRule> setRoot(final String methodName) {
if (methodName == null || methodName.length() == 0) {
addError("{forPattern(\"%s\").setRoot(String)} empty 'methodName' not allowed", keyPattern);
}
return new AbstractParamTypeBuilder<SetRootRule>(keyPattern, methodName, RulesBinderImpl.this, this) {
@Override
protected String getCalledMethodName() {
return "setRoot";
}
public SetRootRule get() {
return new SetRootRule(this.getMethodName(), this.getParamType(), this.isUseExactMatch());
}
};
}
public SetPropertyBuilder setProperty(String attributePropertyName) {
return null;
}
/**
*
*/
public SetPropertiesBuilder setProperties() {
return new SetPropertiesBuilder() {
private final Map<String, String> aliases = new HashMap<String, String>();
private boolean ignoreMissingProperty = true;
public SetPropertiesRule get() {
return new SetPropertiesRule(this.aliases, this.ignoreMissingProperty);
}
public LinkedRuleBuilder then() {
return null;
}
public SetPropertiesBuilder ignoreMissingProperty(boolean ignoreMissingProperty) {
this.ignoreMissingProperty = ignoreMissingProperty;
return this;
}
public SetPropertiesBuilder addAlias(String attributeName, /* @Nullable */String propertyName) {
if (attributeName == null) {
addError("{forPattern(\"%s\").setProperties().addAlias(String,String)} empty 'methodName' not allowed",
keyPattern);
} else {
this.aliases.put(attributeName, propertyName);
}
return this;
}
};
}
/**
*
*/
public ParamTypeBuilder<SetNextRule> setNext(final String methodName) {
if (methodName == null || methodName.length() == 0) {
addError("{forPattern(\"%s\").setNext(String)} empty 'methodName' not allowed", keyPattern);
}
return new AbstractParamTypeBuilder<SetNextRule>(keyPattern, methodName, RulesBinderImpl.this, this) {
@Override
protected String getCalledMethodName() {
return "setNext";
}
public SetNextRule get() {
return new SetNextRule(this.getMethodName(), this.getParamType(), this.isUseExactMatch());
}
};
}
/**
*
*/
public NestedPropertiesBuilder setNestedProperties() {
return new NestedPropertiesBuilder() {
private final Map<String, String> elementNames = new HashMap<String, String>();
private boolean trimData = true;
private boolean allowUnknownChildElements = false;
public SetNestedPropertiesRule get() {
return new SetNestedPropertiesRule(elementNames, trimData, allowUnknownChildElements);
}
public LinkedRuleBuilder then() {
return mainBuilder;
}
public NestedPropertiesBuilder trimData(boolean trimData) {
this.trimData = trimData;
return this;
}
public NestedPropertiesBuilder addAlias(String elementName, String propertyName) {
if (elementName == null) {
addError("{forPattern(\"%s\").setNestedProperties().addAlias(String,String)} empty 'methodName' not allowed",
keyPattern);
} else {
this.elementNames.put(elementName, propertyName);
}
return this;
}
};
}
/**
*
*/
public BeanPropertySetterBuilder setBeanProperty() {
return new BeanPropertySetterBuilder() {
private String propertyName;
public BeanPropertySetterRule get() {
return new BeanPropertySetterRule(this.propertyName);
}
public LinkedRuleBuilder then() {
return mainBuilder;
}
public BeanPropertySetterBuilder withName(String propertyName) {
this.propertyName = propertyName;
return this;
}
};
}
public <T> ObjectParamBuilder objectParam(T paramObj) {
return null;
}
public FactoryCreateBuilder factoryCreate() {
return null;
}
/**
*
*/
public ObjectCreateBuilder createObject() {
return new ObjectCreateBuilder() {
private String className;
private String attributeName;
public ObjectCreateRule get() {
if (this.className == null && this.attributeName == null) {
addError("{forPattern(\"%s\").createObject()} At least one between 'className' or 'attributeName' has to be specified",
keyPattern);
return null;
}
ObjectCreateRule rule = new ObjectCreateRule(this.className, this.attributeName);
rule.setNamespaceURI(namespaceURI);
return rule;
}
public LinkedRuleBuilder then() {
return mainBuilder;
}
public ObjectCreateBuilder ofTypeSpecifiedByAttribute(String attributeName) {
this.attributeName = attributeName;
return this;
}
public ObjectCreateBuilder ofType(Class<?> type) {
if (type == null) {
addError("{forPattern(\"%s\").createObject().ofType(Class<?>)} NULL Java type not allowed",
keyPattern);
return this;
}
return this.ofType(type.getName());
}
public ObjectCreateBuilder ofType(String className) {
this.className = className;
return this;
}
};
}
public PathCallParamBuilder callParamPath() {
return null;
}
public CallParamBuilder callParam() {
return null;
}
public CallMethodBuilder callMethod(String methodName) {
return null;
}
/**
*
*/
public <R extends Rule> BackToLinkedRuleBuilder<R> addRule(final R rule) {
if (rule == null) {
addError("{forPattern(\"%s\").addRule()} null rule not valid", keyPattern);
}
return this.addRuleCreatedBy(new RuleProvider<R>() {
public R get() {
return rule;
}
});
}
/**
*
*/
public <R extends Rule> BackToLinkedRuleBuilder<R> addRuleCreatedBy(final RuleProvider<R> provider) {
if (provider == null) {
addError("{forPattern(\"%s\").addRuleCreatedBy()} null rule not valid", keyPattern);
}
return new BackToLinkedRuleBuilder<R>() {
public LinkedRuleBuilder then() {
return mainBuilder;
}
public R get() {
R rule = provider.get();
rule.setNamespaceURI(namespaceURI);
return rule;
}
};
}
};
}
| public LinkedRuleBuilder forPattern(String pattern) {
final String keyPattern;
if (pattern == null || pattern.length() == 0) {
this.addError(new IllegalArgumentException("Null or empty pattern is not valid"));
keyPattern = null;
} else {
if (pattern.endsWith("/")) {
// to help users who accidently add '/' to the end of their patterns
keyPattern = pattern.substring(0, pattern.length() - 1);
} else {
keyPattern = pattern;
}
}
return new LinkedRuleBuilder() {
private final LinkedRuleBuilder mainBuilder = this;
private String namespaceURI;
public LinkedRuleBuilder withNamespaceURI(/* @Nullable */ String namespaceURI) {
this.namespaceURI = namespaceURI;
return this;
}
/**
*
*/
public ParamTypeBuilder<SetTopRule> setTop(final String methodName) {
if (methodName == null || methodName.length() == 0) {
addError("{forPattern(\"%s\").setTop(String)} empty 'methodName' not allowed", keyPattern);
}
return new AbstractParamTypeBuilder<SetTopRule>(keyPattern, methodName, RulesBinderImpl.this, this) {
@Override
protected String getCalledMethodName() {
return "setTop";
}
public SetTopRule get() {
return new SetTopRule(this.getMethodName(), this.getParamType(), this.isUseExactMatch());
}
};
}
/**
*
*/
public ParamTypeBuilder<SetRootRule> setRoot(final String methodName) {
if (methodName == null || methodName.length() == 0) {
addError("{forPattern(\"%s\").setRoot(String)} empty 'methodName' not allowed", keyPattern);
}
return new AbstractParamTypeBuilder<SetRootRule>(keyPattern, methodName, RulesBinderImpl.this, this) {
@Override
protected String getCalledMethodName() {
return "setRoot";
}
public SetRootRule get() {
return new SetRootRule(this.getMethodName(), this.getParamType(), this.isUseExactMatch());
}
};
}
public SetPropertyBuilder setProperty(String attributePropertyName) {
return null;
}
/**
*
*/
public SetPropertiesBuilder setProperties() {
return new SetPropertiesBuilder() {
private final Map<String, String> aliases = new HashMap<String, String>();
private boolean ignoreMissingProperty = true;
public SetPropertiesRule get() {
return new SetPropertiesRule(this.aliases, this.ignoreMissingProperty);
}
public LinkedRuleBuilder then() {
return mainBuilder;
}
public SetPropertiesBuilder ignoreMissingProperty(boolean ignoreMissingProperty) {
this.ignoreMissingProperty = ignoreMissingProperty;
return this;
}
public SetPropertiesBuilder addAlias(String attributeName, /* @Nullable */String propertyName) {
if (attributeName == null) {
addError("{forPattern(\"%s\").setProperties().addAlias(String,String)} empty 'methodName' not allowed",
keyPattern);
} else {
this.aliases.put(attributeName, propertyName);
}
return this;
}
};
}
/**
*
*/
public ParamTypeBuilder<SetNextRule> setNext(final String methodName) {
if (methodName == null || methodName.length() == 0) {
addError("{forPattern(\"%s\").setNext(String)} empty 'methodName' not allowed", keyPattern);
}
return new AbstractParamTypeBuilder<SetNextRule>(keyPattern, methodName, RulesBinderImpl.this, this) {
@Override
protected String getCalledMethodName() {
return "setNext";
}
public SetNextRule get() {
return new SetNextRule(this.getMethodName(), this.getParamType(), this.isUseExactMatch());
}
};
}
/**
*
*/
public NestedPropertiesBuilder setNestedProperties() {
return new NestedPropertiesBuilder() {
private final Map<String, String> elementNames = new HashMap<String, String>();
private boolean trimData = true;
private boolean allowUnknownChildElements = false;
public SetNestedPropertiesRule get() {
return new SetNestedPropertiesRule(elementNames, trimData, allowUnknownChildElements);
}
public LinkedRuleBuilder then() {
return mainBuilder;
}
public NestedPropertiesBuilder trimData(boolean trimData) {
this.trimData = trimData;
return this;
}
public NestedPropertiesBuilder addAlias(String elementName, String propertyName) {
if (elementName == null) {
addError("{forPattern(\"%s\").setNestedProperties().addAlias(String,String)} empty 'methodName' not allowed",
keyPattern);
} else {
this.elementNames.put(elementName, propertyName);
}
return this;
}
};
}
/**
*
*/
public BeanPropertySetterBuilder setBeanProperty() {
return new BeanPropertySetterBuilder() {
private String propertyName;
public BeanPropertySetterRule get() {
return new BeanPropertySetterRule(this.propertyName);
}
public LinkedRuleBuilder then() {
return mainBuilder;
}
public BeanPropertySetterBuilder withName(String propertyName) {
this.propertyName = propertyName;
return this;
}
};
}
public <T> ObjectParamBuilder objectParam(T paramObj) {
return null;
}
public FactoryCreateBuilder factoryCreate() {
return null;
}
/**
*
*/
public ObjectCreateBuilder createObject() {
return new ObjectCreateBuilder() {
private String className;
private String attributeName;
public ObjectCreateRule get() {
if (this.className == null && this.attributeName == null) {
addError("{forPattern(\"%s\").createObject()} At least one between 'className' or 'attributeName' has to be specified",
keyPattern);
return null;
}
ObjectCreateRule rule = new ObjectCreateRule(this.className, this.attributeName);
rule.setNamespaceURI(namespaceURI);
return rule;
}
public LinkedRuleBuilder then() {
return mainBuilder;
}
public ObjectCreateBuilder ofTypeSpecifiedByAttribute(String attributeName) {
this.attributeName = attributeName;
return this;
}
public ObjectCreateBuilder ofType(Class<?> type) {
if (type == null) {
addError("{forPattern(\"%s\").createObject().ofType(Class<?>)} NULL Java type not allowed",
keyPattern);
return this;
}
return this.ofType(type.getName());
}
public ObjectCreateBuilder ofType(String className) {
this.className = className;
return this;
}
};
}
public PathCallParamBuilder callParamPath() {
return null;
}
public CallParamBuilder callParam() {
return null;
}
public CallMethodBuilder callMethod(String methodName) {
return null;
}
/**
*
*/
public <R extends Rule> BackToLinkedRuleBuilder<R> addRule(final R rule) {
if (rule == null) {
addError("{forPattern(\"%s\").addRule()} null rule not valid", keyPattern);
}
return this.addRuleCreatedBy(new RuleProvider<R>() {
public R get() {
return rule;
}
});
}
/**
*
*/
public <R extends Rule> BackToLinkedRuleBuilder<R> addRuleCreatedBy(final RuleProvider<R> provider) {
if (provider == null) {
addError("{forPattern(\"%s\").addRuleCreatedBy()} null rule not valid", keyPattern);
}
return new BackToLinkedRuleBuilder<R>() {
public LinkedRuleBuilder then() {
return mainBuilder;
}
public R get() {
R rule = provider.get();
rule.setNamespaceURI(namespaceURI);
return rule;
}
};
}
};
}
|
diff --git a/distributed1/serversrc/resImpl/Middleware.java b/distributed1/serversrc/resImpl/Middleware.java
index e36a616..4d60173 100644
--- a/distributed1/serversrc/resImpl/Middleware.java
+++ b/distributed1/serversrc/resImpl/Middleware.java
@@ -1,311 +1,312 @@
package serversrc.resImpl;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Enumeration;
import java.util.Vector;
import serversrc.resInterface.*;
public class Middleware implements ResourceManager {
RMCar rmCar;
RMFlight rmFlight;
RMHotel rmHotel;
RMCustomer rmCustomer;
public static void main(String args[]) {
// Figure out where server is running
String server = "localhost";
int port = 1099;
Registry registry;
if (args.length == 5) {
server = server + ":" + args[4];
port = Integer.parseInt(args[4]);
} else {
System.err.println ("Wrong usage");
System.out.println("Usage: java ResImpl.Middleware rmCar rmFlight rmHotel [port]");
System.exit(1);
}
try {
// create a new Server object
// dynamically generate the stub (client proxy)
Middleware obj = new Middleware();
ResourceManager rm = (ResourceManager) UnicastRemoteObject.exportObject(obj, 0);
// get a reference to the rmiregistry
registry = LocateRegistry.getRegistry(args[0], port);
// get the proxy and the remote reference by rmiregistry lookup
obj.rmCar = (RMCar) registry.lookup("Group2RMCar");
- registry = LocateRegistry.getRegistry(args[1], port);
+ registry = LocateRegistry.getRegistry(args[1], port);
obj.rmFlight = (RMFlight) registry.lookup("Group2RMFlight");
- registry = LocateRegistry.getRegistry(args[2], port);
+ registry = LocateRegistry.getRegistry(args[2], port);
obj.rmHotel = (RMHotel) registry.lookup("Group2RMHotel");
- registry = LocateRegistry.getRegistry(args[3], port);
+ registry = LocateRegistry.getRegistry(args[3], port);
obj.rmCustomer = (RMCustomer) registry.lookup("Group2RMCustomer");
if(obj.rmCar!=null && obj.rmFlight != null && obj.rmHotel!=null)
{
System.out.println("Successful");
System.out.println("Connected to RMs");
}
else
{
System.out.println("Unsuccessful");
}
// Bind the remote object's stub in the registry
registry = LocateRegistry.getRegistry(port);
+ registry = LocateRegistry.getRegistry(port);
registry.rebind("Group2Middleware", rm);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
// Create and install a security manager
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
}
@Override
public boolean addFlight(int id, int flightNum, int flightSeats,
int flightPrice) throws RemoteException {
return rmFlight.addFlight(id, flightNum, flightSeats, flightPrice);
}
@Override
public boolean addCars(int id, String location, int numCars, int price)
throws RemoteException {
return rmCar.addCars(id, location, numCars, price);
}
@Override
public boolean addRooms(int id, String location, int numRooms, int price)
throws RemoteException {
return rmHotel.addRooms(id, location, numRooms, price);
}
@Override
public int newCustomer(int id) throws RemoteException {
return rmCustomer.newCustomer(id);
}
@Override
public boolean newCustomer(int id, int cid) throws RemoteException {
return rmCustomer.newCustomer(id, cid);
}
@Override
public boolean deleteFlight(int id, int flightNum) throws RemoteException {
return rmFlight.deleteFlight(id, flightNum);
}
@Override
public boolean deleteCars(int id, String location) throws RemoteException {
return rmCar.deleteCars(id, location);
}
@Override
public boolean deleteRooms(int id, String location) throws RemoteException {
return rmHotel.deleteRooms(id, location);
}
@Override
public boolean deleteCustomer(int id, int customer) throws RemoteException {
RMHashtable reservationHT = rmCustomer.deleteCustomer(id, customer);
for (Enumeration e = reservationHT.keys(); e.hasMoreElements();) {
String reservedkey = (String) (e.nextElement());
ReservedItem reserveditem = (ReservedItem) reservationHT.get( reservedkey );
Trace.info("RM::deleteCustomer(" + id + ", " + customer + ") has reserved " + reserveditem.getKey() + " " + reserveditem.getCount() + " times" );
if (reserveditem.getrType() == ReservedItem.rType.FLIGHT)
rmFlight.unreserveItem(id, reserveditem);
else if (reserveditem.getrType() == ReservedItem.rType.CAR)
rmCar.unreserveItem(id, reserveditem);
else if (reserveditem.getrType() == ReservedItem.rType.ROOM)
rmHotel.unreserveItem(id, reserveditem);
}
return true;
}
@Override
public int queryFlight(int id, int flightNumber) throws RemoteException {
return rmFlight.queryFlight(id, flightNumber);
}
@Override
public int queryCars(int id, String location) throws RemoteException {
return rmCar.queryCars(id, location);
}
@Override
public int queryRooms(int id, String location) throws RemoteException {
return rmHotel.queryRooms(id, location);
}
@Override
public String queryCustomerInfo(int id, int customer)
throws RemoteException {
return rmCustomer.queryCustomerInfo(id, customer);
}
@Override
public int queryFlightPrice(int id, int flightNumber)
throws RemoteException {
return rmFlight.queryFlightPrice(id, flightNumber);
}
@Override
public int queryCarsPrice(int id, String location) throws RemoteException {
return rmCar.queryCarsPrice(id, location);
}
@Override
public int queryRoomsPrice(int id, String location) throws RemoteException {
return rmHotel.queryRoomsPrice(id, location);
}
@Override
public boolean reserveFlight(int id, int customer, int flightNum)
throws RemoteException {
return reserveItem(id, customer, Flight.getKey(flightNum), String.valueOf(flightNum), ReservedItem.rType.FLIGHT);
}
@Override
public boolean reserveCar(int id, int customer, String location)
throws RemoteException {
return reserveItem(id, customer, Car.getKey(location), location, ReservedItem.rType.CAR);
}
@Override
public boolean reserveRoom(int id, int customer, String location)
throws RemoteException {
return reserveItem(id, customer, Hotel.getKey(location), location, ReservedItem.rType.ROOM);
}
@Override
public boolean itinerary(int id, int customer, Vector flightNumbers,
String location, boolean Car, boolean Room) throws RemoteException {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + Car + ", " + Room + " ) called" );
// Read customer object if it exists (and read lock it)
Customer cust = rmCustomer.getCustomer(id, customer);
if ( cust == null ) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + Car + ", " + Room + " ) -- Customer non existent, adding it." );
rmCustomer.newCustomer(id, customer);
cust = rmCustomer.getCustomer(id, customer);
}
if (Car){
if (reserveCar(id, customer, location)) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + Car + ", " + Room + " ) -- Car could not have been reserved." );
return false;
}
}
if (Room){
if (reserveRoom(id, customer, location)) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + Car + ", " + Room + " ) -- Room could not have been reserved." );
return false;
}
}
for (Enumeration e = flightNumbers.elements(); e.hasMoreElements();) {
int flightnum = 0;
try {
flightnum = getInt(e.nextElement());
} catch(Exception ex) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + Car + ", " + Room + " ) -- Expected FlightNumber was not a valid integer. Exception "
+ ex + " cached");
return false;
}
if (reserveFlight(id, customer, flightnum)){
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightnum+ ", "+location+
", " + Car + ", " + Room + " ) -- flight could not have been reserved." );
return false;
}
}
return true;
}
/*Since the client sends a Vector of objects, we need this
* unsafe function that retrieves the int from the vector.
*
*/
public int getInt(Object temp) throws Exception {
try {
return (new Integer((String)temp)).intValue();
}
catch(Exception e) {
throw e;
}
}
/*
* Call RMCust to obtain customer, if it exists.
* Verify if item exists and is available. (Call RM*obj*)
* Reserve with RMCustomer
* Tell RM*obj* to reduce the number of available
*/
protected boolean reserveItem(int id, int customerID, String key, String location, ReservedItem.rType rtype)
throws RemoteException {
Trace.info("RM::reserveItem( " + id + ", customer=" + customerID + ", " +key+ ", "+location+" ) called" );
// Read customer object if it exists (and read lock it)
Customer cust = rmCustomer.getCustomer(id, customerID);
if ( cust == null ) {
Trace.warn("RM::reserveCar( " + id + ", " + customerID + ", " + key + ", "+location+") failed--customer doesn't exist" );
return false;
}
RMInteger price = null;
// check if the item is available
if (rtype == ReservedItem.rType.CAR)
price = rmCar.reserveItem(id, customerID, key, location);
else if (rtype == ReservedItem.rType.FLIGHT)
price = rmFlight.reserveItem(id, customerID, key, location);
else if (rtype == ReservedItem.rType.ROOM)
price = rmHotel.reserveItem(id, customerID, key, location);
if ( price == null ) {
Trace.warn("RM::reserveItem( " + id + ", " + customerID + ", " + key+", " +location+") failed-- Object RM returned false." );
return false;
} else {
cust.reserve( key, location, price.getValue(), rtype);
rmCustomer.reserve( id, cust);
Trace.info("RM::reserveItem( " + id + ", " + customerID + ", " + key + ", " +location+") succeeded" );
return true;
}
}
}
| false | true | public static void main(String args[]) {
// Figure out where server is running
String server = "localhost";
int port = 1099;
Registry registry;
if (args.length == 5) {
server = server + ":" + args[4];
port = Integer.parseInt(args[4]);
} else {
System.err.println ("Wrong usage");
System.out.println("Usage: java ResImpl.Middleware rmCar rmFlight rmHotel [port]");
System.exit(1);
}
try {
// create a new Server object
// dynamically generate the stub (client proxy)
Middleware obj = new Middleware();
ResourceManager rm = (ResourceManager) UnicastRemoteObject.exportObject(obj, 0);
// get a reference to the rmiregistry
registry = LocateRegistry.getRegistry(args[0], port);
// get the proxy and the remote reference by rmiregistry lookup
obj.rmCar = (RMCar) registry.lookup("Group2RMCar");
registry = LocateRegistry.getRegistry(args[1], port);
obj.rmFlight = (RMFlight) registry.lookup("Group2RMFlight");
registry = LocateRegistry.getRegistry(args[2], port);
obj.rmHotel = (RMHotel) registry.lookup("Group2RMHotel");
registry = LocateRegistry.getRegistry(args[3], port);
obj.rmCustomer = (RMCustomer) registry.lookup("Group2RMCustomer");
if(obj.rmCar!=null && obj.rmFlight != null && obj.rmHotel!=null)
{
System.out.println("Successful");
System.out.println("Connected to RMs");
}
else
{
System.out.println("Unsuccessful");
}
// Bind the remote object's stub in the registry
registry = LocateRegistry.getRegistry(port);
registry.rebind("Group2Middleware", rm);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
// Create and install a security manager
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
}
| public static void main(String args[]) {
// Figure out where server is running
String server = "localhost";
int port = 1099;
Registry registry;
if (args.length == 5) {
server = server + ":" + args[4];
port = Integer.parseInt(args[4]);
} else {
System.err.println ("Wrong usage");
System.out.println("Usage: java ResImpl.Middleware rmCar rmFlight rmHotel [port]");
System.exit(1);
}
try {
// create a new Server object
// dynamically generate the stub (client proxy)
Middleware obj = new Middleware();
ResourceManager rm = (ResourceManager) UnicastRemoteObject.exportObject(obj, 0);
// get a reference to the rmiregistry
registry = LocateRegistry.getRegistry(args[0], port);
// get the proxy and the remote reference by rmiregistry lookup
obj.rmCar = (RMCar) registry.lookup("Group2RMCar");
registry = LocateRegistry.getRegistry(args[1], port);
obj.rmFlight = (RMFlight) registry.lookup("Group2RMFlight");
registry = LocateRegistry.getRegistry(args[2], port);
obj.rmHotel = (RMHotel) registry.lookup("Group2RMHotel");
registry = LocateRegistry.getRegistry(args[3], port);
obj.rmCustomer = (RMCustomer) registry.lookup("Group2RMCustomer");
if(obj.rmCar!=null && obj.rmFlight != null && obj.rmHotel!=null)
{
System.out.println("Successful");
System.out.println("Connected to RMs");
}
else
{
System.out.println("Unsuccessful");
}
// Bind the remote object's stub in the registry
registry = LocateRegistry.getRegistry(port);
registry = LocateRegistry.getRegistry(port);
registry.rebind("Group2Middleware", rm);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
// Create and install a security manager
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
}
|
diff --git a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/AbstractReference.java b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/AbstractReference.java
index dee6f1a7..7689cf12 100644
--- a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/AbstractReference.java
+++ b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/AbstractReference.java
@@ -1,161 +1,161 @@
/*******************************************************************************
* Copyright (c) 2010 xored software, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* xored software, Inc. - initial API and Implementation (Alex Panchenko)
*******************************************************************************/
package org.eclipse.dltk.internal.javascript.ti;
import java.util.Collections;
import java.util.Set;
import org.eclipse.dltk.javascript.typeinference.IValueReference;
import org.eclipse.dltk.javascript.typeinference.ReferenceKind;
import org.eclipse.dltk.javascript.typeinference.ReferenceLocation;
import org.eclipse.dltk.javascript.typeinfo.model.Type;
public abstract class AbstractReference implements IValueReference,
IValueProvider {
public abstract IValue getValue();
public abstract IValue createValue();
public void setValue(IValueReference value) {
IValue val = createValue();
if (val != null) {
- val.clear();
if (value != null) {
IValue src = ((IValueProvider) value).getValue();
if (src == null)
return;
+ val.clear();
if (src instanceof Value
&& ((IValueProvider) value).isReference()) {
val.addReference(src);
} else {
val.addValue(src);
}
}
}
}
public void addValue(IValueReference value, boolean copy) {
if (value == null) {
return;
}
IValue val = createValue();
if (val != null) {
IValue src = ((IValueProvider) value).getValue();
if (src == null)
return;
if (!copy && src instanceof Value
&& ((IValueProvider) value).isReference()) {
val.addReference(src);
} else {
val.addValue(src);
}
}
}
public void clear() {
IValue value = getValue();
if (value != null) {
value.clear();
}
}
public boolean exists() {
return getValue() != null;
}
public final Object getAttribute(String key) {
return getAttribute(key, false);
}
public Object getAttribute(String key, boolean includeReferences) {
IValue value = getValue();
return value != null ? value.getAttribute(key, includeReferences)
: null;
}
public Type getDeclaredType() {
IValue value = getValue();
return value != null ? value.getDeclaredType() : null;
}
public Set<Type> getDeclaredTypes() {
IValue value = getValue();
return value != null ? value.getDeclaredTypes() : Collections
.<Type> emptySet();
}
public ReferenceKind getKind() {
IValue value = getValue();
return value != null ? value.getKind() : ReferenceKind.UNKNOWN;
}
public ReferenceLocation getLocation() {
IValue value = getValue();
return value != null ? value.getLocation() : ReferenceLocation.UNKNOWN;
}
public Set<Type> getTypes() {
IValue value = getValue();
return value != null ? value.getTypes() : Collections.<Type> emptySet();
}
public void setAttribute(String key, Object value) {
IValue val = createValue();
if (val != null) {
val.setAttribute(key, value);
}
}
public void setDeclaredType(Type type) {
IValue value = createValue();
if (value != null) {
value.setDeclaredType(type);
}
}
public void setKind(ReferenceKind kind) {
IValue value = createValue();
if (value != null) {
value.setKind(kind);
}
}
public void setLocation(ReferenceLocation location) {
IValue value = createValue();
if (value != null) {
value.setLocation(location);
}
}
public IValueReference getChild(String name) {
return new ChildReference(this, name);
}
public boolean hasChild(String name) {
IValue value = getValue();
return value != null && value.getChild(name, true) != null;
}
public Set<String> getDirectChildren() {
final IValue value = getValue();
return value != null ? value.getDirectChildren() : Collections
.<String> emptySet();
}
public Set<String> getDeletedChildren() {
final IValue value = getValue();
return value != null ? value.getDeletedChildren() : Collections
.<String> emptySet();
}
}
| false | true | public void setValue(IValueReference value) {
IValue val = createValue();
if (val != null) {
val.clear();
if (value != null) {
IValue src = ((IValueProvider) value).getValue();
if (src == null)
return;
if (src instanceof Value
&& ((IValueProvider) value).isReference()) {
val.addReference(src);
} else {
val.addValue(src);
}
}
}
}
| public void setValue(IValueReference value) {
IValue val = createValue();
if (val != null) {
if (value != null) {
IValue src = ((IValueProvider) value).getValue();
if (src == null)
return;
val.clear();
if (src instanceof Value
&& ((IValueProvider) value).isReference()) {
val.addReference(src);
} else {
val.addValue(src);
}
}
}
}
|
diff --git a/src/main/java/com/bigu/testing/DbController.java b/src/main/java/com/bigu/testing/DbController.java
index db42499..ac05dfe 100644
--- a/src/main/java/com/bigu/testing/DbController.java
+++ b/src/main/java/com/bigu/testing/DbController.java
@@ -1,74 +1,74 @@
package com.bigu.testing;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.stereotype.Controller;
@RequestMapping("/db")
@Controller
public class DbController {
private static final Logger logger = LoggerFactory.getLogger(DbController.class);
@RequestMapping(value = "", method = RequestMethod.GET)
public String db(Locale locale, Model model){
logger.info("db page");
return "db";
}
/*
@RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(HttpServletRequest request,Locale locale,Model model){
String test = "";
try{
test = ServletRequestUtils.getStringParameter(request, "test");
}
catch(ServletRequestBindingException e){
e.printStackTrace();
}
model.addAttribute("test",test);
logger.info("test page {}", test);
return "test";
}
*/
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String testConnection(Locale locale, Model model) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/contacts","root", "");
} catch (SQLException e) {
e.printStackTrace();
}
if (conn != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
logger.debug("inside index method");
- return "home";
+ return "test";
}
}
| true | true | public String testConnection(Locale locale, Model model) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/contacts","root", "");
} catch (SQLException e) {
e.printStackTrace();
}
if (conn != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
logger.debug("inside index method");
return "home";
}
| public String testConnection(Locale locale, Model model) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/contacts","root", "");
} catch (SQLException e) {
e.printStackTrace();
}
if (conn != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
logger.debug("inside index method");
return "test";
}
|
diff --git a/deegree-services/deegree-services-wms/src/main/java/org/deegree/services/wms/OldStyleMapService.java b/deegree-services/deegree-services-wms/src/main/java/org/deegree/services/wms/OldStyleMapService.java
index 8c4509eb01..a3094346a7 100644
--- a/deegree-services/deegree-services-wms/src/main/java/org/deegree/services/wms/OldStyleMapService.java
+++ b/deegree-services/deegree-services-wms/src/main/java/org/deegree/services/wms/OldStyleMapService.java
@@ -1,401 +1,400 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2012 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
and
- Occam Labs UG (haftungsbeschränkt) -
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
Occam Labs UG (haftungsbeschränkt)
Godesberger Allee 139, 53175 Bonn
Germany
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.services.wms;
import static org.deegree.commons.utils.CollectionUtils.AND;
import static org.deegree.commons.utils.CollectionUtils.addAllUncontained;
import static org.deegree.commons.utils.CollectionUtils.map;
import static org.deegree.commons.utils.CollectionUtils.reduce;
import static org.deegree.commons.utils.MapUtils.DEFAULT_PIXEL_SIZE;
import static org.deegree.rendering.r2d.RenderHelper.calcScaleWMS130;
import static org.deegree.rendering.r2d.context.Java2DHelper.applyHints;
import static org.deegree.services.wms.model.layers.Layer.render;
import static org.deegree.style.utils.ImageUtils.postprocessPng8bit;
import static org.slf4j.LoggerFactory.getLogger;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import org.deegree.commons.utils.CollectionUtils;
import org.deegree.commons.utils.CollectionUtils.Mapper;
import org.deegree.commons.utils.DoublePair;
import org.deegree.commons.utils.Pair;
import org.deegree.feature.Feature;
import org.deegree.feature.FeatureCollection;
import org.deegree.feature.Features;
import org.deegree.feature.GenericFeatureCollection;
import org.deegree.feature.persistence.FeatureStore;
import org.deegree.feature.persistence.FeatureStoreException;
import org.deegree.feature.persistence.query.Query;
import org.deegree.feature.stream.FeatureInputStream;
import org.deegree.feature.stream.ThreadedFeatureInputStream;
import org.deegree.feature.xpath.TypedObjectNodeXPathEvaluator;
import org.deegree.filter.FilterEvaluationException;
import org.deegree.filter.XPathEvaluator;
import org.deegree.protocol.wms.WMSException.InvalidDimensionValue;
import org.deegree.protocol.wms.WMSException.MissingDimensionValue;
import org.deegree.protocol.wms.filter.ScaleFunction;
import org.deegree.rendering.r2d.Java2DRenderer;
import org.deegree.rendering.r2d.Java2DTextRenderer;
import org.deegree.services.wms.controller.ops.GetFeatureInfo;
import org.deegree.services.wms.controller.ops.GetMap;
import org.deegree.services.wms.model.layers.FeatureLayer;
import org.deegree.services.wms.model.layers.Layer;
import org.deegree.style.se.unevaluated.Style;
import org.slf4j.Logger;
/**
* Factored out old style map service methods (using old configuration, old architecture).
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author: stranger $
*
* @version $Revision: $, $Date: $
*/
class OldStyleMapService {
private static final Logger LOG = getLogger( OldStyleMapService.class );
private MapService service;
OldStyleMapService( MapService service ) {
this.service = service;
}
/**
* @param gm
* @return a rendered image, containing the requested maps
* @throws InvalidDimensionValue
* @throws MissingDimensionValue
*/
Pair<BufferedImage, LinkedList<String>> getMapImage( GetMap gm )
throws MissingDimensionValue, InvalidDimensionValue {
LinkedList<String> warnings = new LinkedList<String>();
ScaleFunction.getCurrentScaleValue().set( gm.getScale() );
BufferedImage img = MapService.prepareImage( gm );
Graphics2D g = img.createGraphics();
paintMap( g, gm, warnings );
g.dispose();
// 8 bit png color map support copied from deegree 2, to be optimized
if ( gm.getFormat().equals( "image/png; mode=8bit" ) || gm.getFormat().equals( "image/png; subtype=8bit" )
|| gm.getFormat().equals( "image/gif" ) ) {
img = postprocessPng8bit( img );
}
ScaleFunction.getCurrentScaleValue().remove();
return new Pair<BufferedImage, LinkedList<String>>( img, warnings );
}
/**
* Paints the map on a graphics object.
*
* @param g
* @param gm
* @param warnings
* @throws InvalidDimensionValue
* @throws MissingDimensionValue
*/
private void paintMap( Graphics2D g, GetMap gm, LinkedList<String> warnings )
throws MissingDimensionValue, InvalidDimensionValue {
Iterator<Layer> layers = gm.getLayers().iterator();
Iterator<Style> styles = gm.getStyles().iterator();
if ( reduce( true, map( gm.getLayers(), CollectionUtils.<Layer> getInstanceofMapper( FeatureLayer.class ) ),
AND ) ) {
LinkedList<FeatureLayer> fls = new LinkedList<FeatureLayer>();
Map<FeatureStore, LinkedList<Query>> queries = new HashMap<FeatureStore, LinkedList<Query>>();
HashMap<QName, FeatureLayer> ftToLayer = new HashMap<QName, FeatureLayer>();
HashMap<QName, Style> ftToStyle = new HashMap<QName, Style>();
double scale = gm.getScale();
if ( reduce( true, map( gm.getLayers(), getFeatureLayerCollector( fls ) ), AND ) ) {
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
s = s.filter( scale );
DoublePair scales = l.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale || ( !s.isDefault() && s.getRules().isEmpty() ) ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.",
l.getName() == null ? l.getTitle() : l.getName() );
continue;
}
LinkedList<String> otherWarns = collectFeatureQueries( queries, (FeatureLayer) l, s, gm, ftToLayer,
ftToStyle );
if ( otherWarns == null ) {
queries.clear();
break;
}
warnings.addAll( otherWarns );
}
}
if ( queries.size() == 1 ) {
handleCollectedQueries( queries, ftToLayer, ftToStyle, gm, g );
return;
}
if ( queries.isEmpty() ) {
- LOG.debug( "No queries found when collecting, probably due to scale constraints in the layers/styles." );
- return;
+ LOG.debug( "No queries found when collecting, trying without collected queries." );
}
LOG.debug( "Not using collected queries." );
layers = gm.getLayers().iterator();
styles = gm.getStyles().iterator();
}
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
applyHints( l.getName(), g, service.layerOptions, service.defaultLayerOptions );
warnings.addAll( paintLayer( l, s, g, gm ) );
}
}
// must ensure that subtree consists of feature layers only
// returns null if not all styles contain distinct feature type names
private LinkedList<String> collectFeatureQueries( Map<FeatureStore, LinkedList<Query>> queries, FeatureLayer l,
Style style, GetMap gm, HashMap<QName, FeatureLayer> ftToLayer,
HashMap<QName, Style> ftToStyle )
throws MissingDimensionValue, InvalidDimensionValue {
if ( !l.getClass().equals( FeatureLayer.class ) ) {
return null;
}
LinkedList<String> warns = new LinkedList<String>();
LinkedList<Query> list = queries.get( l.getDataStore() );
if ( list == null ) {
list = new LinkedList<Query>();
queries.put( l.getDataStore(), list );
}
warns.addAll( l.collectQueries( style, gm, list ) );
QName name = style == null ? null : style.getFeatureType();
if ( name == null || ftToLayer.containsKey( name ) ) {
return null;
}
ftToLayer.put( name, l );
ftToStyle.put( name, style );
for ( Layer child : l.getChildren() ) {
LinkedList<String> otherWarns = collectFeatureQueries( queries,
(FeatureLayer) child,
service.registry.get( child.getInternalName(), null ),
gm, ftToLayer, ftToStyle );
if ( otherWarns == null ) {
return null;
}
warns.addAll( otherWarns );
}
return warns;
}
private void handleCollectedQueries( Map<FeatureStore, LinkedList<Query>> queries,
HashMap<QName, FeatureLayer> ftToLayer, HashMap<QName, Style> ftToStyle,
GetMap gm, Graphics2D g ) {
LOG.debug( "Using collected queries for better performance." );
Java2DRenderer renderer = new Java2DRenderer( g, gm.getWidth(), gm.getHeight(), gm.getBoundingBox(),
gm.getPixelSize() );
Java2DTextRenderer textRenderer = new Java2DTextRenderer( renderer );
// TODO
XPathEvaluator<?> evaluator = new TypedObjectNodeXPathEvaluator();
Collection<LinkedList<Query>> qs = queries.values();
FeatureInputStream rs = null;
try {
FeatureStore store = queries.keySet().iterator().next();
LinkedList<Query> queriesList = qs.iterator().next();
if ( !queriesList.isEmpty() ) {
rs = store.query( queriesList.toArray( new Query[queriesList.size()] ) );
// TODO Should this always be done on this level? What about min and maxFill values?
rs = new ThreadedFeatureInputStream( rs, 100, 20 );
for ( Feature f : rs ) {
QName name = f.getType().getName();
FeatureLayer l = ftToLayer.get( name );
applyHints( l.getName(), g, service.layerOptions, service.defaultLayerOptions );
render( f, (XPathEvaluator<Feature>) evaluator, ftToStyle.get( name ), renderer, textRenderer,
gm.getScale(), gm.getResolution() );
}
} else {
LOG.warn( "No queries were found for the requested layers." );
}
} catch ( FilterEvaluationException e ) {
LOG.error( "A filter could not be evaluated. The error was '{}'.", e.getLocalizedMessage() );
LOG.trace( "Stack trace:", e );
} catch ( FeatureStoreException e ) {
LOG.error( "Data could not be fetched from the feature store. The error was '{}'.", e.getLocalizedMessage() );
LOG.trace( "Stack trace:", e );
} finally {
if ( rs != null ) {
rs.close();
}
}
}
private static Mapper<Boolean, Layer> getFeatureLayerCollector( final LinkedList<FeatureLayer> list ) {
return new Mapper<Boolean, Layer>() {
@Override
public Boolean apply( Layer u ) {
return collectFeatureLayers( u, list );
}
};
}
/**
* @param l
* @param list
* @return true, if all sub layers were feature layers and its style had a distinct feature type name
*/
static boolean collectFeatureLayers( Layer l, final LinkedList<FeatureLayer> list ) {
if ( l instanceof FeatureLayer ) {
list.add( (FeatureLayer) l );
return reduce( true, map( l.getChildren(), getFeatureLayerCollector( list ) ), AND );
}
return false;
}
protected LinkedList<String> paintLayer( Layer l, Style s, Graphics2D g, GetMap gm )
throws MissingDimensionValue, InvalidDimensionValue {
LinkedList<String> warnings = new LinkedList<String>();
double scale = gm.getScale();
DoublePair scales = l.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.", l.getName() == null ? l.getTitle()
: l.getName() );
return warnings;
}
warnings.addAll( l.paintMap( g, gm, s ) );
for ( Layer child : l.getChildren() ) {
warnings.addAll( paintLayer( child, service.registry.get( child.getInternalName(), null ), g, gm ) );
}
return warnings;
}
/**
* @param fi
* @return a collection of feature values for the selected area, and warning headers
* @throws InvalidDimensionValue
* @throws MissingDimensionValue
*/
Pair<FeatureCollection, LinkedList<String>> getFeatures( GetFeatureInfo fi )
throws MissingDimensionValue, InvalidDimensionValue {
List<Feature> list = new LinkedList<Feature>();
LinkedList<String> warnings = new LinkedList<String>();
Iterator<Style> styles = fi.getStyles().iterator();
double scale = calcScaleWMS130( fi.getWidth(), fi.getHeight(), fi.getEnvelope(), fi.getCoordinateSystem(),
DEFAULT_PIXEL_SIZE );
for ( Layer layer : fi.getQueryLayers() ) {
DoublePair scales = layer.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.",
layer.getName() == null ? layer.getTitle() : layer.getName() );
continue;
}
warnings.addAll( getFeatures( list, layer, fi, styles.next() ) );
}
list = Features.clearDuplicates( list );
if ( list.size() > fi.getFeatureCount() ) {
list = list.subList( 0, fi.getFeatureCount() );
}
GenericFeatureCollection col = new GenericFeatureCollection();
col.addAll( list );
return new Pair<FeatureCollection, LinkedList<String>>( col, warnings );
}
private LinkedList<String> getFeatures( Collection<Feature> feats, Layer l, GetFeatureInfo fi, Style s )
throws MissingDimensionValue, InvalidDimensionValue {
LinkedList<String> warnings = new LinkedList<String>();
if ( l.isQueryable() ) {
Pair<FeatureCollection, LinkedList<String>> pair = l.getFeatures( fi, s );
if ( pair != null ) {
if ( pair.first != null ) {
addAllUncontained( feats, pair.first );
}
warnings.addAll( pair.second );
}
}
double scale = calcScaleWMS130( fi.getWidth(), fi.getHeight(), fi.getEnvelope(), fi.getCoordinateSystem(),
DEFAULT_PIXEL_SIZE );
for ( Layer c : l.getChildren() ) {
DoublePair scales = c.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.",
c.getName() == null ? c.getTitle() : c.getName() );
continue;
}
if ( c.getName() != null ) {
s = service.registry.get( c.getName(), null );
}
warnings.addAll( getFeatures( feats, c, fi, s ) );
}
return warnings;
}
}
| true | true | private void paintMap( Graphics2D g, GetMap gm, LinkedList<String> warnings )
throws MissingDimensionValue, InvalidDimensionValue {
Iterator<Layer> layers = gm.getLayers().iterator();
Iterator<Style> styles = gm.getStyles().iterator();
if ( reduce( true, map( gm.getLayers(), CollectionUtils.<Layer> getInstanceofMapper( FeatureLayer.class ) ),
AND ) ) {
LinkedList<FeatureLayer> fls = new LinkedList<FeatureLayer>();
Map<FeatureStore, LinkedList<Query>> queries = new HashMap<FeatureStore, LinkedList<Query>>();
HashMap<QName, FeatureLayer> ftToLayer = new HashMap<QName, FeatureLayer>();
HashMap<QName, Style> ftToStyle = new HashMap<QName, Style>();
double scale = gm.getScale();
if ( reduce( true, map( gm.getLayers(), getFeatureLayerCollector( fls ) ), AND ) ) {
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
s = s.filter( scale );
DoublePair scales = l.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale || ( !s.isDefault() && s.getRules().isEmpty() ) ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.",
l.getName() == null ? l.getTitle() : l.getName() );
continue;
}
LinkedList<String> otherWarns = collectFeatureQueries( queries, (FeatureLayer) l, s, gm, ftToLayer,
ftToStyle );
if ( otherWarns == null ) {
queries.clear();
break;
}
warnings.addAll( otherWarns );
}
}
if ( queries.size() == 1 ) {
handleCollectedQueries( queries, ftToLayer, ftToStyle, gm, g );
return;
}
if ( queries.isEmpty() ) {
LOG.debug( "No queries found when collecting, probably due to scale constraints in the layers/styles." );
return;
}
LOG.debug( "Not using collected queries." );
layers = gm.getLayers().iterator();
styles = gm.getStyles().iterator();
}
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
applyHints( l.getName(), g, service.layerOptions, service.defaultLayerOptions );
warnings.addAll( paintLayer( l, s, g, gm ) );
}
}
| private void paintMap( Graphics2D g, GetMap gm, LinkedList<String> warnings )
throws MissingDimensionValue, InvalidDimensionValue {
Iterator<Layer> layers = gm.getLayers().iterator();
Iterator<Style> styles = gm.getStyles().iterator();
if ( reduce( true, map( gm.getLayers(), CollectionUtils.<Layer> getInstanceofMapper( FeatureLayer.class ) ),
AND ) ) {
LinkedList<FeatureLayer> fls = new LinkedList<FeatureLayer>();
Map<FeatureStore, LinkedList<Query>> queries = new HashMap<FeatureStore, LinkedList<Query>>();
HashMap<QName, FeatureLayer> ftToLayer = new HashMap<QName, FeatureLayer>();
HashMap<QName, Style> ftToStyle = new HashMap<QName, Style>();
double scale = gm.getScale();
if ( reduce( true, map( gm.getLayers(), getFeatureLayerCollector( fls ) ), AND ) ) {
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
s = s.filter( scale );
DoublePair scales = l.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale || ( !s.isDefault() && s.getRules().isEmpty() ) ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.",
l.getName() == null ? l.getTitle() : l.getName() );
continue;
}
LinkedList<String> otherWarns = collectFeatureQueries( queries, (FeatureLayer) l, s, gm, ftToLayer,
ftToStyle );
if ( otherWarns == null ) {
queries.clear();
break;
}
warnings.addAll( otherWarns );
}
}
if ( queries.size() == 1 ) {
handleCollectedQueries( queries, ftToLayer, ftToStyle, gm, g );
return;
}
if ( queries.isEmpty() ) {
LOG.debug( "No queries found when collecting, trying without collected queries." );
}
LOG.debug( "Not using collected queries." );
layers = gm.getLayers().iterator();
styles = gm.getStyles().iterator();
}
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
applyHints( l.getName(), g, service.layerOptions, service.defaultLayerOptions );
warnings.addAll( paintLayer( l, s, g, gm ) );
}
}
|
diff --git a/src/main/ed/log/PrintStreamAppender.java b/src/main/ed/log/PrintStreamAppender.java
index 33c0a2fcd..92d4cef8f 100644
--- a/src/main/ed/log/PrintStreamAppender.java
+++ b/src/main/ed/log/PrintStreamAppender.java
@@ -1,50 +1,54 @@
// PrintStreamAppender.java
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ed.log;
import java.io.*;
import java.text.*;
public class PrintStreamAppender implements Appender {
public PrintStreamAppender( PrintStream out ){
this( out , new EventFormatter.DefaultEventFormatter() );
}
public PrintStreamAppender( PrintStream out , EventFormatter formatter ){
_out = out;
_formatter = formatter;
}
public void append( final Event e ){
String output = _formatter.format( e );
try {
_out.write( output.getBytes( "utf8" ) );
+ if ( e._throwable != null )
+ e._throwable.printStackTrace( _out );
}
catch ( IOException encodingBad ){
_out.print( output );
}
- if ( e._throwable != null )
- e._throwable.printStackTrace( _out );
+ catch ( Exception we ){
+ _out.print( output );
+ we.printStackTrace();
+ }
}
final PrintStream _out;
final EventFormatter _formatter;
}
| false | true | public void append( final Event e ){
String output = _formatter.format( e );
try {
_out.write( output.getBytes( "utf8" ) );
}
catch ( IOException encodingBad ){
_out.print( output );
}
if ( e._throwable != null )
e._throwable.printStackTrace( _out );
}
| public void append( final Event e ){
String output = _formatter.format( e );
try {
_out.write( output.getBytes( "utf8" ) );
if ( e._throwable != null )
e._throwable.printStackTrace( _out );
}
catch ( IOException encodingBad ){
_out.print( output );
}
catch ( Exception we ){
_out.print( output );
we.printStackTrace();
}
}
|
diff --git a/org.eclipse.riena.navigation/src/org/eclipse/riena/navigation/model/AbstractSimpleNavigationNodeProvider.java b/org.eclipse.riena.navigation/src/org/eclipse/riena/navigation/model/AbstractSimpleNavigationNodeProvider.java
index 4cfd21331..374c6cf2c 100644
--- a/org.eclipse.riena.navigation/src/org/eclipse/riena/navigation/model/AbstractSimpleNavigationNodeProvider.java
+++ b/org.eclipse.riena.navigation/src/org/eclipse/riena/navigation/model/AbstractSimpleNavigationNodeProvider.java
@@ -1,467 +1,469 @@
/*******************************************************************************
* Copyright (c) 2007, 2011 compeople AG and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* compeople AG - initial API and implementation
*******************************************************************************/
package org.eclipse.riena.navigation.model;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import org.osgi.service.log.LogService;
import org.eclipse.core.runtime.Assert;
import org.eclipse.equinox.log.Logger;
import org.eclipse.riena.core.Log4r;
import org.eclipse.riena.core.util.StringUtils;
import org.eclipse.riena.internal.navigation.Activator;
import org.eclipse.riena.navigation.IAssemblerProvider;
import org.eclipse.riena.navigation.IGenericNavigationAssembler;
import org.eclipse.riena.navigation.INavigationAssembler;
import org.eclipse.riena.navigation.INavigationNode;
import org.eclipse.riena.navigation.INavigationNodeProvider;
import org.eclipse.riena.navigation.NavigationArgument;
import org.eclipse.riena.navigation.NavigationNodeId;
import org.eclipse.riena.navigation.NodePositioner;
import org.eclipse.riena.navigation.StartupNodeInfo;
import org.eclipse.riena.navigation.StartupNodeInfo.Level;
import org.eclipse.riena.navigation.extension.ICommonNavigationAssemblyExtension;
import org.eclipse.riena.navigation.extension.INavigationAssembly2Extension;
import org.eclipse.riena.navigation.extension.INode2Extension;
import org.eclipse.riena.ui.core.uiprocess.UIExecutor;
/**
* This class provides navigation nodes that are defined by assemlies2
* extensions.
*/
public abstract class AbstractSimpleNavigationNodeProvider implements INavigationNodeProvider, IAssemblerProvider {
private final static Logger LOGGER = Log4r.getLogger(Activator.getDefault(),
AbstractSimpleNavigationNodeProvider.class);
private static Random random = null;
private final Map<String, INavigationAssembler> assemblyId2AssemblerCache = new HashMap<String, INavigationAssembler>();
/**
* {@inheritDoc}
*/
public List<StartupNodeInfo> getSortedStartupNodeInfos() {
final List<StartupNodeInfo> startups = new ArrayList<StartupNodeInfo>();
for (final INavigationAssembler assembler : getNavigationAssemblers()) {
if (assembler.getStartOrder() > 0) {
final StartupNodeInfo startupNodeInfo = createStartupSortable(assembler, assembler.getStartOrder());
if (startupNodeInfo != null) {
startups.add(startupNodeInfo);
}
}
}
Collections.sort(startups);
return startups;
}
private StartupNodeInfo createStartupSortable(final INavigationAssembler assembler, final Integer sequence) {
final INavigationAssembly2Extension assembly = assembler.getAssembly();
if (assembly == null) {
return null;
}
String id = getTypeId(assembly.getSubApplications());
if (id != null) {
return new StartupNodeInfo(Level.SUBAPPLICATION, sequence, id);
}
id = getTypeId(assembly.getModuleGroups());
if (id != null) {
return new StartupNodeInfo(Level.MODULEGROUP, sequence, id);
}
id = getTypeId(assembly.getModules());
if (id != null) {
return new StartupNodeInfo(Level.MODULE, sequence, id);
}
id = getTypeId(assembly.getSubModules());
if (id != null) {
return new StartupNodeInfo(Level.SUBMODULE, sequence, id);
}
id = assembler.getId();
Assert.isNotNull(assembly.getNavigationAssembler(), "Assembly '" + id //$NON-NLS-1$
+ "' must have an assembler specified since no immediate child has a typeId."); //$NON-NLS-1$
if (id != null) {
return new StartupNodeInfo(Level.CUSTOM, sequence, id);
}
return null;
}
private String getTypeId(final INode2Extension[] extensions) {
if ((extensions != null) && (extensions.length > 0)) {
return extensions[0].getNodeId();
} else {
return null;
}
}
/**
* {@inheritDoc}
*/
public INavigationNode<?> provideNode(final INavigationNode<?> sourceNode, final NavigationNodeId targetId,
final NavigationArgument argument) {
return provideNodeHook(sourceNode, targetId, argument);
}
/**
* Returns a navigationNode identified by the given navigationNodeId. The
* node is created if it not yet exists.
*
* @param sourceNode
* an existing node in the navigation model
* @param targetId
* the ID of the target node
* @param argument
* contains information passed used for providing the target node
* @param createNodeAsync
* @return target node
*/
@SuppressWarnings("rawtypes")
protected INavigationNode<?> provideNodeHook(final INavigationNode<?> sourceNode, final NavigationNodeId targetId,
final NavigationArgument argument) {
INavigationNode<?> targetNode = findNode(getRootNode(sourceNode), targetId);
if (targetNode == null) {
if (LOGGER.isLoggable(LogService.LOG_DEBUG)) {
LOGGER.log(LogService.LOG_DEBUG, "createNode: " + targetId); //$NON-NLS-1$
}
final INavigationAssembler assembler = getNavigationAssembler(targetId, argument);
if (assembler != null) {
final NavigationNodeId parentTypeId = getParentTypeId(argument, assembler);
// Call of findNode() on the result of method provideNodeHook() fixes problem for the case when the result
// is not the node with typeId parentTypeId but one of the nodes parents (i.e. when the nodes assembler also
// builds some of its parent nodes).
final INavigationNode parentNode = findNode(provideNodeHook(sourceNode, parentTypeId, null),
parentTypeId);
prepareNavigationAssembler(targetId, assembler, parentNode);
INavigationNode<?>[] targetNodes;
if ((null != argument && argument.isCreateNodesAsync()) || shouldRunAsync(assembler)) {
targetNodes = UIExecutor.executeLively(new Callable<INavigationNode<?>[]>() {
public INavigationNode<?>[] call() throws Exception {
return assembler.buildNode(targetId, argument);
}
});
} else {
targetNodes = assembler.buildNode(targetId, argument);
}
if ((targetNodes != null) && (targetNodes.length > 0)) {
prepareNodesAfterBuild(targetNodes, argument, parentNode, assembler, targetId, sourceNode);
targetNode = targetNodes[0];
}
} else {
- throw new ExtensionPointFailure("No assembler found for ID=" + targetId.getTypeId()); //$NON-NLS-1$
+ if (getRootNode(sourceNode).isActivated()) {
+ throw new ExtensionPointFailure("No assembler found for ID=" + targetId.getTypeId()); //$NON-NLS-1$
+ }
}
} else {
prepareExistingNode(sourceNode, targetNode, argument);
}
if (argument != null) {
if (argument.isPrepareAll()) {
prepareAll(targetNode);
}
}
// TODO: all targetNodes have to be returned, because overriding subclass may need it.
return targetNode;
}
/**
* @param assembler
* @return <code>true</code> if the given assembler has a {@link RunAsync}
* annotation, otherwise <code>false</code>
*/
private boolean shouldRunAsync(final INavigationAssembler assembler) {
return assembler.getClass().isAnnotationPresent(RunAsync.class);
}
// private void printNodeTree(final INavigationNode<?> root, final int depth) {
// final StringBuffer b = new StringBuffer();
// for (int i = 0; i < depth; i++) {
// b.append(" ");
// }
//
// System.err.println(b.toString() + root.getNodeId());
//
// for (final INavigationNode<?> c : root.getChildren()) {
// printNodeTree(c, depth + 1);
// }
// }
/**
* @since 3.0
*/
protected void prepareNodesAfterBuild(final INavigationNode<?>[] targetNodes, final NavigationArgument argument,
final INavigationNode<?> parentNode, final INavigationAssembler assembler, final NavigationNodeId targetId,
final INavigationNode<?> sourceNode) {
final NodePositioner nodePositioner = argument != null ? argument.getNodePositioner() : NodePositioner.ADD_END;
for (final INavigationNode<?> node : targetNodes) {
prepareNodeAfterBuild(node, argument, parentNode, assembler, targetId, nodePositioner);
}
}
/**
* @since 3.0
*/
protected void prepareNodeAfterBuild(final INavigationNode<?> node, final NavigationArgument argument,
final INavigationNode<?> parentNode, final INavigationAssembler assembler, final NavigationNodeId targetId,
final NodePositioner nodePositioner) {
storeNavigationArgument(node, argument);
nodePositioner.addChildToParent(parentNode, node);
if (node.getNodeId() == null && assembler.getId().equals(targetId.getTypeId())) {
node.setNodeId(targetId);
}
}
/**
* @since 3.0
*/
protected void prepareExistingNode(final INavigationNode<?> sourceNode, final INavigationNode<?> targetNode,
final NavigationArgument argument) {
storeNavigationArgument(targetNode, argument);
}
/**
* Stores the given argument in the context of the given node
*
* @param targetNode
* target node
* @param argument
* contains information passed used for providing the target node
*/
private void storeNavigationArgument(final INavigationNode<?> targetNode, final NavigationArgument argument) {
if (argument != null) {
targetNode.setContext(NavigationArgument.CONTEXTKEY_ARGUMENT, argument);
}
}
/**
* Creates the assembler ({@link INavigationAssembler}) for the given
* assembly and registers it.
*
* @param assembly
* assembly to register
*/
public void register(final INavigationAssembly2Extension assembly) {
String assemblyId = assembly.getId();
if (assemblyId == null) {
if (random == null) {
try {
random = SecureRandom.getInstance("SHA1PRNG"); //$NON-NLS-1$
} catch (final NoSuchAlgorithmException e) {
random = new Random(System.currentTimeMillis());
}
}
assemblyId = "Riena.random.assemblyid." + Long.valueOf(random.nextLong()).toString(); //$NON-NLS-1$
LOGGER.log(LogService.LOG_DEBUG, "Assembly has no id. Generated a random '" + assemblyId //$NON-NLS-1$
+ "'. For Assembler=" + assembly.getNavigationAssembler()); //$NON-NLS-1$
}
INavigationAssembler assembler = assembly.createNavigationAssembler();
if (assembler == null) {
assembler = createDefaultAssembler();
}
assembler.setId(assemblyId);
assembler.setParentNodeId(assembly.getParentNodeId());
assembler.setStartOrder(getStartOrder(assembly));
assembler.setAssembly(assembly);
registerNavigationAssembler(assemblyId, assembler);
}
private int getStartOrder(final ICommonNavigationAssemblyExtension assembly) {
try {
final INavigationAssembly2Extension assembly2 = (INavigationAssembly2Extension) assembly;
return assembly2.getStartOrder();
} catch (final NumberFormatException e) {
return -1;
}
}
/**
* Returns the root node in the navigation model tree for the given node.
*
* @param node
* child node
* @return root node
*/
protected INavigationNode<?> getRootNode(final INavigationNode<?> node) {
if (node.getParent() == null) {
return node;
}
return getRootNode(node.getParent());
}
/**
* Searches for a node that has the given ID and it's a child of the given
* node.
*
* @param node
* the node form that the search is started
* @param targetId
* ID of the node that should be found
* @return the found node or {@code null} if no matching node was found
*/
protected INavigationNode<?> findNode(final INavigationNode<?> node, final NavigationNodeId targetId) {
if (targetId == null) {
return null;
}
if (targetId.equals(node.getNodeId())) {
return node;
}
for (final INavigationNode<?> child : node.getChildren()) {
final INavigationNode<?> foundNode = findNode(child, targetId);
if (foundNode != null) {
return foundNode;
}
}
return null;
}
public INavigationAssembler getNavigationAssembler(final NavigationNodeId nodeId, final NavigationArgument argument) {
if (nodeId != null && nodeId.getTypeId() != null) {
for (final INavigationAssembler probe : getNavigationAssemblers()) {
if (probe.acceptsToBuildNode(nodeId, argument)) {
return probe;
}
}
}
return null;
}
/**
* Returns the ID of the parent node.
*
* @param argument
* contains information passed used for providing the target
* node. One information can be a parent node
* @param assembler
* navigation assembler. If the navigation argument has no parent
* node information the parent node ID of the assembler is
* returned.
* @return ID of the parent node
*/
private NavigationNodeId getParentTypeId(final NavigationArgument argument, final INavigationAssembler assembler) {
if (argument != null && argument.getParentNodeId() != null) {
return argument.getParentNodeId();
} else {
final String parentTypeId = assembler.getParentNodeId();
if (StringUtils.isEmpty(parentTypeId)) {
final String id = assembler.getId();
throw new ExtensionPointFailure("parentTypeId cannot be null or blank for assembly ID=" //$NON-NLS-1$
+ id);
}
return new NavigationNodeId(parentTypeId);
}
}
/**
* Prepares the given node and all its children.
*
* @param node
* navigation node to prepare.
*/
private void prepareAll(final INavigationNode<?> node) {
node.prepare();
for (final INavigationNode<?> child : node.getChildren()) {
prepareAll(child);
}
}
/**
* {@inheritDoc}
*/
public void cleanUp() {
assemblyId2AssemblerCache.clear();
}
/**
* {@inheritDoc}
*/
public INavigationAssembler getNavigationAssembler(final String assemblyId) {
return assemblyId2AssemblerCache.get(assemblyId);
}
/**
* Returns all registered assemblers.
*
* @return collection of all assemblers
*/
public Collection<INavigationAssembler> getNavigationAssemblers() {
return assemblyId2AssemblerCache.values();
}
/**
* Registers the given assembler and associates it with the given assembly
* ID.
* <p>
* If another assembler is already registered with the same ID an exception
* ({@link IllegalStateException}) is thrown.
*
* @param id
* ID of the assembly
* @param assembler
* assembler to register
*/
public void registerNavigationAssembler(final String id, final INavigationAssembler assembler) {
final INavigationAssembler oldAssembler = assemblyId2AssemblerCache.put(id, assembler);
if (oldAssembler != null) {
final String msg = String.format("There are two assembly extension definitions for '%s'.", id); //$NON-NLS-1$
final RuntimeException runtimeExc = new IllegalStateException(msg);
LOGGER.log(LogService.LOG_ERROR, msg, runtimeExc);
throw runtimeExc;
}
}
/**
* Used to prepare the assembler in a application specific way.
*
* @param targetId
* @param assembler
* @param parentNode
*/
protected void prepareNavigationAssembler(final NavigationNodeId targetId, final INavigationAssembler assembler,
final INavigationNode<?> parentNode) {
if (assembler instanceof IGenericNavigationAssembler) {
((IGenericNavigationAssembler) assembler).setAssemblerProvider(this);
}
}
/**
* Creates a generic assembler that is used if the assembly has no
* assembler.
*
* @return default assembler
*/
protected INavigationAssembler createDefaultAssembler() {
return new GenericNavigationAssembler();
}
}
| true | true | protected INavigationNode<?> provideNodeHook(final INavigationNode<?> sourceNode, final NavigationNodeId targetId,
final NavigationArgument argument) {
INavigationNode<?> targetNode = findNode(getRootNode(sourceNode), targetId);
if (targetNode == null) {
if (LOGGER.isLoggable(LogService.LOG_DEBUG)) {
LOGGER.log(LogService.LOG_DEBUG, "createNode: " + targetId); //$NON-NLS-1$
}
final INavigationAssembler assembler = getNavigationAssembler(targetId, argument);
if (assembler != null) {
final NavigationNodeId parentTypeId = getParentTypeId(argument, assembler);
// Call of findNode() on the result of method provideNodeHook() fixes problem for the case when the result
// is not the node with typeId parentTypeId but one of the nodes parents (i.e. when the nodes assembler also
// builds some of its parent nodes).
final INavigationNode parentNode = findNode(provideNodeHook(sourceNode, parentTypeId, null),
parentTypeId);
prepareNavigationAssembler(targetId, assembler, parentNode);
INavigationNode<?>[] targetNodes;
if ((null != argument && argument.isCreateNodesAsync()) || shouldRunAsync(assembler)) {
targetNodes = UIExecutor.executeLively(new Callable<INavigationNode<?>[]>() {
public INavigationNode<?>[] call() throws Exception {
return assembler.buildNode(targetId, argument);
}
});
} else {
targetNodes = assembler.buildNode(targetId, argument);
}
if ((targetNodes != null) && (targetNodes.length > 0)) {
prepareNodesAfterBuild(targetNodes, argument, parentNode, assembler, targetId, sourceNode);
targetNode = targetNodes[0];
}
} else {
throw new ExtensionPointFailure("No assembler found for ID=" + targetId.getTypeId()); //$NON-NLS-1$
}
} else {
prepareExistingNode(sourceNode, targetNode, argument);
}
if (argument != null) {
if (argument.isPrepareAll()) {
prepareAll(targetNode);
}
}
// TODO: all targetNodes have to be returned, because overriding subclass may need it.
return targetNode;
}
| protected INavigationNode<?> provideNodeHook(final INavigationNode<?> sourceNode, final NavigationNodeId targetId,
final NavigationArgument argument) {
INavigationNode<?> targetNode = findNode(getRootNode(sourceNode), targetId);
if (targetNode == null) {
if (LOGGER.isLoggable(LogService.LOG_DEBUG)) {
LOGGER.log(LogService.LOG_DEBUG, "createNode: " + targetId); //$NON-NLS-1$
}
final INavigationAssembler assembler = getNavigationAssembler(targetId, argument);
if (assembler != null) {
final NavigationNodeId parentTypeId = getParentTypeId(argument, assembler);
// Call of findNode() on the result of method provideNodeHook() fixes problem for the case when the result
// is not the node with typeId parentTypeId but one of the nodes parents (i.e. when the nodes assembler also
// builds some of its parent nodes).
final INavigationNode parentNode = findNode(provideNodeHook(sourceNode, parentTypeId, null),
parentTypeId);
prepareNavigationAssembler(targetId, assembler, parentNode);
INavigationNode<?>[] targetNodes;
if ((null != argument && argument.isCreateNodesAsync()) || shouldRunAsync(assembler)) {
targetNodes = UIExecutor.executeLively(new Callable<INavigationNode<?>[]>() {
public INavigationNode<?>[] call() throws Exception {
return assembler.buildNode(targetId, argument);
}
});
} else {
targetNodes = assembler.buildNode(targetId, argument);
}
if ((targetNodes != null) && (targetNodes.length > 0)) {
prepareNodesAfterBuild(targetNodes, argument, parentNode, assembler, targetId, sourceNode);
targetNode = targetNodes[0];
}
} else {
if (getRootNode(sourceNode).isActivated()) {
throw new ExtensionPointFailure("No assembler found for ID=" + targetId.getTypeId()); //$NON-NLS-1$
}
}
} else {
prepareExistingNode(sourceNode, targetNode, argument);
}
if (argument != null) {
if (argument.isPrepareAll()) {
prepareAll(targetNode);
}
}
// TODO: all targetNodes have to be returned, because overriding subclass may need it.
return targetNode;
}
|
diff --git a/de.gebit.integrity.runner/src/de/gebit/integrity/runner/providers/FilesystemTestResourceProvider.java b/de.gebit.integrity.runner/src/de/gebit/integrity/runner/providers/FilesystemTestResourceProvider.java
index 28c493c0..2347d421 100644
--- a/de.gebit.integrity.runner/src/de/gebit/integrity/runner/providers/FilesystemTestResourceProvider.java
+++ b/de.gebit.integrity.runner/src/de/gebit/integrity/runner/providers/FilesystemTestResourceProvider.java
@@ -1,82 +1,82 @@
package de.gebit.integrity.runner.providers;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* A resource provider which reads test files from the filesystem, either from one or more flat directories or
* optionally in a recursive way.
*
*
* @author Rene Schneider
*
*/
public class FilesystemTestResourceProvider implements TestResourceProvider {
private Set<String> resourceFiles = new HashSet<String>();
private ClassLoader classLoader = getClass().getClassLoader();
public FilesystemTestResourceProvider(Collection<? extends File> someResourceFiles) {
for (File tempFile : someResourceFiles) {
if (tempFile.exists() && tempFile.isFile()) {
resourceFiles.add(tempFile.getAbsolutePath());
}
}
}
public FilesystemTestResourceProvider(Collection<? extends File> someDirectories, boolean aSearchRecursivelyFlag) {
for (File tempDir : someDirectories) {
scanDirectory(tempDir, aSearchRecursivelyFlag);
}
}
protected void scanDirectory(File aDirectory, boolean aSearchRecursivelyFlag) {
if (!aDirectory.isDirectory()) {
return;
}
for (File tempFile : aDirectory.listFiles()) {
if (tempFile.isFile()) {
if (tempFile.getAbsolutePath().endsWith(".integrity")) {
resourceFiles.add(tempFile.getAbsolutePath());
- } else if (aSearchRecursivelyFlag && tempFile.isDirectory()) {
- scanDirectory(tempFile, aSearchRecursivelyFlag);
}
+ } else if (aSearchRecursivelyFlag && tempFile.isDirectory()) {
+ scanDirectory(tempFile, aSearchRecursivelyFlag);
}
}
}
@Override
public String[] getResourceNames() {
return resourceFiles.toArray(new String[0]);
}
@Override
public InputStream openResource(String aResourceName) {
if (resourceFiles.contains(aResourceName)) {
try {
return new FileInputStream(new File(aResourceName));
} catch (FileNotFoundException exc) {
exc.printStackTrace();
return null;
}
}
return null;
}
public void setClassLoader(ClassLoader aClassLoader) {
classLoader = aClassLoader;
}
@Override
public ClassLoader getClassLoader() {
return classLoader;
}
}
| false | true | protected void scanDirectory(File aDirectory, boolean aSearchRecursivelyFlag) {
if (!aDirectory.isDirectory()) {
return;
}
for (File tempFile : aDirectory.listFiles()) {
if (tempFile.isFile()) {
if (tempFile.getAbsolutePath().endsWith(".integrity")) {
resourceFiles.add(tempFile.getAbsolutePath());
} else if (aSearchRecursivelyFlag && tempFile.isDirectory()) {
scanDirectory(tempFile, aSearchRecursivelyFlag);
}
}
}
}
| protected void scanDirectory(File aDirectory, boolean aSearchRecursivelyFlag) {
if (!aDirectory.isDirectory()) {
return;
}
for (File tempFile : aDirectory.listFiles()) {
if (tempFile.isFile()) {
if (tempFile.getAbsolutePath().endsWith(".integrity")) {
resourceFiles.add(tempFile.getAbsolutePath());
}
} else if (aSearchRecursivelyFlag && tempFile.isDirectory()) {
scanDirectory(tempFile, aSearchRecursivelyFlag);
}
}
}
|
diff --git a/ModGod/src/com/github/CubieX/ModGod/ModGodCommandHandler.java b/ModGod/src/com/github/CubieX/ModGod/ModGodCommandHandler.java
index 266db9f..c423d78 100644
--- a/ModGod/src/com/github/CubieX/ModGod/ModGodCommandHandler.java
+++ b/ModGod/src/com/github/CubieX/ModGod/ModGodCommandHandler.java
@@ -1,64 +1,64 @@
package com.github.CubieX.ModGod;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ModGodCommandHandler implements CommandExecutor
{
private ModGod plugin = null;
private ModGodConfigHandler configHandler = null;
public ModGodCommandHandler(ModGod plugin, ModGodConfigHandler configHandler)
{
this.plugin = plugin;
this.configHandler = configHandler;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
Player player = null;
if (sender instanceof Player)
{
player = (Player) sender;
}
if(ModGod.debug){ModGod.log.info("onCommand");}
if (cmd.getName().equalsIgnoreCase("mg"))
{
if (args.length == 0)
{ //no arguments, so help will be displayed
return false;
}
if (args.length==1)
{
if (args[0].equalsIgnoreCase("version"))
{
sender.sendMessage(ChatColor.YELLOW + "This server is running ModGod version " + plugin.getDescription().getVersion());
return true;
}
if (args[0].equalsIgnoreCase("reload"))
{
- if(sender.hasPermission("modgod.reload"))
+ if(sender.hasPermission("modgod.admin"))
{
configHandler.reloadConfig(sender);
return true;
}
else
{
sender.sendMessage(ChatColor.RED + "You do not have sufficient permission to reload " + plugin.getDescription().getName() + "!");
}
}
}
else
{
sender.sendMessage(ChatColor.YELLOW + "Ungueltige Anzahl Argumente.");
}
}
return false; // if false is returned, the help for the command stated in the plugin.yml will be displayed to the player
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
Player player = null;
if (sender instanceof Player)
{
player = (Player) sender;
}
if(ModGod.debug){ModGod.log.info("onCommand");}
if (cmd.getName().equalsIgnoreCase("mg"))
{
if (args.length == 0)
{ //no arguments, so help will be displayed
return false;
}
if (args.length==1)
{
if (args[0].equalsIgnoreCase("version"))
{
sender.sendMessage(ChatColor.YELLOW + "This server is running ModGod version " + plugin.getDescription().getVersion());
return true;
}
if (args[0].equalsIgnoreCase("reload"))
{
if(sender.hasPermission("modgod.reload"))
{
configHandler.reloadConfig(sender);
return true;
}
else
{
sender.sendMessage(ChatColor.RED + "You do not have sufficient permission to reload " + plugin.getDescription().getName() + "!");
}
}
}
else
{
sender.sendMessage(ChatColor.YELLOW + "Ungueltige Anzahl Argumente.");
}
}
return false; // if false is returned, the help for the command stated in the plugin.yml will be displayed to the player
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
Player player = null;
if (sender instanceof Player)
{
player = (Player) sender;
}
if(ModGod.debug){ModGod.log.info("onCommand");}
if (cmd.getName().equalsIgnoreCase("mg"))
{
if (args.length == 0)
{ //no arguments, so help will be displayed
return false;
}
if (args.length==1)
{
if (args[0].equalsIgnoreCase("version"))
{
sender.sendMessage(ChatColor.YELLOW + "This server is running ModGod version " + plugin.getDescription().getVersion());
return true;
}
if (args[0].equalsIgnoreCase("reload"))
{
if(sender.hasPermission("modgod.admin"))
{
configHandler.reloadConfig(sender);
return true;
}
else
{
sender.sendMessage(ChatColor.RED + "You do not have sufficient permission to reload " + plugin.getDescription().getName() + "!");
}
}
}
else
{
sender.sendMessage(ChatColor.YELLOW + "Ungueltige Anzahl Argumente.");
}
}
return false; // if false is returned, the help for the command stated in the plugin.yml will be displayed to the player
}
|
diff --git a/src/multitallented/redcastlemedia/bukkit/herostronghold/listeners/RegionBlockListener.java b/src/multitallented/redcastlemedia/bukkit/herostronghold/listeners/RegionBlockListener.java
index 0a83abe..22bee35 100644
--- a/src/multitallented/redcastlemedia/bukkit/herostronghold/listeners/RegionBlockListener.java
+++ b/src/multitallented/redcastlemedia/bukkit/herostronghold/listeners/RegionBlockListener.java
@@ -1,288 +1,288 @@
package multitallented.redcastlemedia.bukkit.herostronghold.listeners;
import multitallented.redcastlemedia.bukkit.herostronghold.effect.Effect;
import multitallented.redcastlemedia.bukkit.herostronghold.HeroStronghold;
import multitallented.redcastlemedia.bukkit.herostronghold.region.Region;
import multitallented.redcastlemedia.bukkit.herostronghold.region.RegionManager;
import multitallented.redcastlemedia.bukkit.herostronghold.region.RegionType;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.inventory.ItemStack;
/**
*
* @author Multitallented
*/
public class RegionBlockListener extends BlockListener {
private final RegionManager regionManager;
private final HeroStronghold plugin;
public RegionBlockListener(HeroStronghold plugin) {
this.plugin = plugin;
this.regionManager = plugin.getRegionManager();
}
@Override
public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
Location currentLoc = null;
boolean delete = false;
double x1 = loc.getX();
for (Region r : regionManager.getSortedRegions()) {
currentLoc = r.getLocation();
if (currentLoc.getBlock().equals(loc.getBlock())) {
Region currentRegion = regionManager.getRegion(currentLoc);
RegionType currentRegionType = regionManager.getRegionType(currentRegion.getType());
Player player = event.getPlayer();
Effect effect = new Effect(plugin);
if ((player == null || (!currentRegion.isOwner(player.getName()) && !currentRegion.isMember(player.getName())))
&& effect.regionHasEffect(currentRegionType.getEffects(), "denyblockbreak") != 0 && effect.hasReagents(currentLoc)) {
event.setCancelled(true);
if (player != null)
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
return;
}
regionManager.destroyRegion(currentLoc);
delete=true;
break;
}
int radius = regionManager.getRegionType(r.getType()).getRadius();
Location l = r.getLocation();
if (l.getX() + radius < x1) {
return;
}
try {
if (!(l.getX() - radius > x1) && l.distanceSquared(loc) < radius) {
Region currentRegion = regionManager.getRegion(currentLoc);
RegionType currentRegionType = regionManager.getRegionType(currentRegion.getType());
Player player = event.getPlayer();
Effect effect = new Effect(plugin);
if ((player == null || (!currentRegion.isOwner(player.getName()) && !currentRegion.isMember(player.getName())))
&& effect.regionHasEffect(currentRegionType.getEffects(), "denyblockbreak") != 0 && effect.hasReagents(currentLoc)) {
event.setCancelled(true);
if (player != null)
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
return;
}
int amountRequired = 0;
int i = 0;
for (ItemStack currentStack : currentRegionType.getRequirements()) {
if (currentStack.getTypeId() == event.getBlock().getTypeId()) {
amountRequired = new Integer(currentStack.getAmount());
break;
}
}
if (amountRequired == 0)
return;
+ int radius1 = (int) Math.sqrt(radius);
- //TODO improve this
- for (int x= (int) (currentLoc.getX()-radius); x<radius + currentLoc.getX(); x++) {
- for (int y = currentLoc.getY()- radius > 1 ? (int) (currentLoc.getY() - radius) : 1; y< radius + currentLoc.getY() && y < 128; y++) {
- for (int z = (int) (currentLoc.getZ() - radius); z<radius + currentLoc.getZ(); z++) {
+ for (int x= (int) (currentLoc.getX()-radius1); x<radius1 + currentLoc.getX(); x++) {
+ for (int y = currentLoc.getY()- radius1 > 1 ? (int) (currentLoc.getY() - radius1) : 1; y< radius1 + currentLoc.getY() && y < 128; y++) {
+ for (int z = (int) (currentLoc.getZ() - radius1); z<radius1 + currentLoc.getZ(); z++) {
Block tempBlock = currentLoc.getWorld().getBlockAt(x, y, z);
if (tempBlock.getTypeId() == event.getBlock().getTypeId()) {
if (i >= amountRequired) {
return;
} else {
i++;
}
}
}
}
}
regionManager.destroyRegion(currentLoc);
delete = true;
break;
}
} catch (IllegalArgumentException iae) {
}
}
/*Set<Location> locations = regionManager.getRegionLocations();
outer: for (Iterator<Location> iter = locations.iterator(); iter.hasNext();) {
currentLoc = iter.next();
try {
if (currentLoc.getBlock().equals(loc.getBlock())) {
regionManager.destroyRegion(currentLoc);
break outer;
}
Region currentRegion = regionManager.getRegion(currentLoc);
RegionType currentRegionType = regionManager.getRegionType(currentRegion.getType());
int radius = currentRegionType.getRadius();
if (Math.sqrt(loc.distanceSquared(currentLoc)) < radius) {
Player player = event.getPlayer();
Effect effect = new Effect(plugin);
if ((player == null || (!currentRegion.isOwner(player.getName()) && !currentRegion.isMember(player.getName())))
&& effect.regionHasEffect(currentRegionType.getEffects(), "denyblockbreak") != 0 && effect.hasReagents(currentLoc)) {
event.setCancelled(true);
if (player != null)
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
}
int amountRequired = 0;
int i = 0;
for (ItemStack currentStack : currentRegionType.getRequirements()) {
if (currentStack.getTypeId() == event.getBlock().getTypeId()) {
amountRequired = currentStack.getAmount();
break;
}
}
if (amountRequired == 0)
return;
for (int x= (int) (currentLoc.getX()-radius); x<radius + currentLoc.getX(); x++) {
for (int y = currentLoc.getY()- radius > 1 ? (int) (currentLoc.getY() - radius) : 1; y< radius + currentLoc.getY() && y < 128; y++) {
for (int z = (int) (currentLoc.getZ() - radius); z<radius + currentLoc.getZ(); z++) {
Block tempBlock = currentLoc.getWorld().getBlockAt(x, y, z);
if (tempBlock.getTypeId() == event.getBlock().getTypeId()) {
if (i >= amountRequired) {
return;
} else {
i++;
}
}
}
}
}
regionManager.destroyRegion(currentLoc);
iter.remove();
delete = true;
break outer;
}
} catch (IllegalArgumentException iae) {
}
}*/
if (delete && currentLoc != null) {
regionManager.removeRegion(currentLoc);
}
}
@Override
public void onBlockPlace(BlockPlaceEvent event) {
if (event.isCancelled() || !regionManager.shouldTakeAction(event.getBlock().getLocation(), event.getPlayer(), 0, "denyblockbuild"))
return;
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
}
@Override
public void onBlockDamage(BlockDamageEvent event) {
if (event.isCancelled() || !event.getBlock().getType().equals(Material.CAKE_BLOCK))
return;
if (regionManager.shouldTakeAction(event.getBlock().getLocation(), event.getPlayer(), 0, "denyblockbreak")) {
event.getPlayer().sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
event.setCancelled(true);
return;
}
}
@Override
public void onBlockFromTo(BlockFromToEvent event) {
if (event.isCancelled() || !regionManager.shouldTakeAction(event.getToBlock().getLocation(), null, 0, "denyblockbreak"))
return;
Block blockFrom = event.getBlock();
// Check the fluid block (from) whether it is air.
if (blockFrom.getTypeId() == 0 || blockFrom.getTypeId() == 8 || blockFrom.getTypeId() == 9) {
event.setCancelled(true);
return;
}
if (blockFrom.getTypeId() == 10 || blockFrom.getTypeId() == 11) {
event.setCancelled(true);
return;
}
}
@Override
public void onBlockIgnite(BlockIgniteEvent event) {
if (event.isCancelled()) {
return;
}
IgniteCause cause = event.getCause();
if (cause == IgniteCause.LIGHTNING && regionManager.shouldTakeAction(event.getBlock().getLocation(), null, 0, "denyblockbreak")) {
event.setCancelled(true);
return;
}
if (cause == IgniteCause.LAVA && regionManager.shouldTakeAction(event.getBlock().getLocation(), null, 0, "denyblockbreak")) {
event.setCancelled(true);
return;
}
if (cause == IgniteCause.SPREAD && regionManager.shouldTakeAction(event.getBlock().getLocation(), null, 0, "denyblockbreak")) {
event.setCancelled(true);
return;
}
if (cause == IgniteCause.FLINT_AND_STEEL && regionManager.shouldTakeAction(event.getBlock().getLocation(), event.getPlayer(), 1, "denyblockbreak")) {
event.setCancelled(true);
if (event.getPlayer() != null)
event.getPlayer().sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
return;
}
}
@Override
public void onBlockBurn(BlockBurnEvent event) {
if (event.isCancelled() || !regionManager.shouldTakeAction(event.getBlock().getLocation(), null, 0, "denyblockbreak")) {
return;
}
event.setCancelled(true);
}
@Override
public void onSignChange(SignChangeEvent event) {
if (event.isCancelled() || !regionManager.shouldTakeAction(event.getBlock().getLocation(), event.getPlayer(), 0, "denyblockbreak"))
return;
event.setCancelled(true);
if (event.getPlayer() != null)
event.getPlayer().sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
}
@Override
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if (event.isCancelled()) {
return;
}
for (Block b : event.getBlocks()) {
if (regionManager.shouldTakeAction(b.getLocation(), null, 0, "denyblockbreak")) {
event.setCancelled(true);
return;
}
}
}
@Override
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if (event.isCancelled() || !event.isSticky() || !regionManager.shouldTakeAction(event.getBlock().getLocation(), null, 0, "denyblockbreak"))
return;
event.setCancelled(true);
}
}
| false | true | public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
Location currentLoc = null;
boolean delete = false;
double x1 = loc.getX();
for (Region r : regionManager.getSortedRegions()) {
currentLoc = r.getLocation();
if (currentLoc.getBlock().equals(loc.getBlock())) {
Region currentRegion = regionManager.getRegion(currentLoc);
RegionType currentRegionType = regionManager.getRegionType(currentRegion.getType());
Player player = event.getPlayer();
Effect effect = new Effect(plugin);
if ((player == null || (!currentRegion.isOwner(player.getName()) && !currentRegion.isMember(player.getName())))
&& effect.regionHasEffect(currentRegionType.getEffects(), "denyblockbreak") != 0 && effect.hasReagents(currentLoc)) {
event.setCancelled(true);
if (player != null)
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
return;
}
regionManager.destroyRegion(currentLoc);
delete=true;
break;
}
int radius = regionManager.getRegionType(r.getType()).getRadius();
Location l = r.getLocation();
if (l.getX() + radius < x1) {
return;
}
try {
if (!(l.getX() - radius > x1) && l.distanceSquared(loc) < radius) {
Region currentRegion = regionManager.getRegion(currentLoc);
RegionType currentRegionType = regionManager.getRegionType(currentRegion.getType());
Player player = event.getPlayer();
Effect effect = new Effect(plugin);
if ((player == null || (!currentRegion.isOwner(player.getName()) && !currentRegion.isMember(player.getName())))
&& effect.regionHasEffect(currentRegionType.getEffects(), "denyblockbreak") != 0 && effect.hasReagents(currentLoc)) {
event.setCancelled(true);
if (player != null)
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
return;
}
int amountRequired = 0;
int i = 0;
for (ItemStack currentStack : currentRegionType.getRequirements()) {
if (currentStack.getTypeId() == event.getBlock().getTypeId()) {
amountRequired = new Integer(currentStack.getAmount());
break;
}
}
if (amountRequired == 0)
return;
//TODO improve this
for (int x= (int) (currentLoc.getX()-radius); x<radius + currentLoc.getX(); x++) {
for (int y = currentLoc.getY()- radius > 1 ? (int) (currentLoc.getY() - radius) : 1; y< radius + currentLoc.getY() && y < 128; y++) {
for (int z = (int) (currentLoc.getZ() - radius); z<radius + currentLoc.getZ(); z++) {
Block tempBlock = currentLoc.getWorld().getBlockAt(x, y, z);
if (tempBlock.getTypeId() == event.getBlock().getTypeId()) {
if (i >= amountRequired) {
return;
} else {
i++;
}
}
}
}
}
regionManager.destroyRegion(currentLoc);
delete = true;
break;
}
} catch (IllegalArgumentException iae) {
}
}
/*Set<Location> locations = regionManager.getRegionLocations();
outer: for (Iterator<Location> iter = locations.iterator(); iter.hasNext();) {
currentLoc = iter.next();
try {
if (currentLoc.getBlock().equals(loc.getBlock())) {
regionManager.destroyRegion(currentLoc);
break outer;
}
Region currentRegion = regionManager.getRegion(currentLoc);
RegionType currentRegionType = regionManager.getRegionType(currentRegion.getType());
int radius = currentRegionType.getRadius();
if (Math.sqrt(loc.distanceSquared(currentLoc)) < radius) {
Player player = event.getPlayer();
Effect effect = new Effect(plugin);
if ((player == null || (!currentRegion.isOwner(player.getName()) && !currentRegion.isMember(player.getName())))
&& effect.regionHasEffect(currentRegionType.getEffects(), "denyblockbreak") != 0 && effect.hasReagents(currentLoc)) {
event.setCancelled(true);
if (player != null)
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
}
int amountRequired = 0;
int i = 0;
for (ItemStack currentStack : currentRegionType.getRequirements()) {
if (currentStack.getTypeId() == event.getBlock().getTypeId()) {
amountRequired = currentStack.getAmount();
break;
}
}
if (amountRequired == 0)
return;
for (int x= (int) (currentLoc.getX()-radius); x<radius + currentLoc.getX(); x++) {
for (int y = currentLoc.getY()- radius > 1 ? (int) (currentLoc.getY() - radius) : 1; y< radius + currentLoc.getY() && y < 128; y++) {
for (int z = (int) (currentLoc.getZ() - radius); z<radius + currentLoc.getZ(); z++) {
Block tempBlock = currentLoc.getWorld().getBlockAt(x, y, z);
if (tempBlock.getTypeId() == event.getBlock().getTypeId()) {
if (i >= amountRequired) {
return;
} else {
i++;
}
}
}
}
}
regionManager.destroyRegion(currentLoc);
iter.remove();
delete = true;
break outer;
}
} catch (IllegalArgumentException iae) {
}
}*/
if (delete && currentLoc != null) {
regionManager.removeRegion(currentLoc);
}
}
| public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
Location currentLoc = null;
boolean delete = false;
double x1 = loc.getX();
for (Region r : regionManager.getSortedRegions()) {
currentLoc = r.getLocation();
if (currentLoc.getBlock().equals(loc.getBlock())) {
Region currentRegion = regionManager.getRegion(currentLoc);
RegionType currentRegionType = regionManager.getRegionType(currentRegion.getType());
Player player = event.getPlayer();
Effect effect = new Effect(plugin);
if ((player == null || (!currentRegion.isOwner(player.getName()) && !currentRegion.isMember(player.getName())))
&& effect.regionHasEffect(currentRegionType.getEffects(), "denyblockbreak") != 0 && effect.hasReagents(currentLoc)) {
event.setCancelled(true);
if (player != null)
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
return;
}
regionManager.destroyRegion(currentLoc);
delete=true;
break;
}
int radius = regionManager.getRegionType(r.getType()).getRadius();
Location l = r.getLocation();
if (l.getX() + radius < x1) {
return;
}
try {
if (!(l.getX() - radius > x1) && l.distanceSquared(loc) < radius) {
Region currentRegion = regionManager.getRegion(currentLoc);
RegionType currentRegionType = regionManager.getRegionType(currentRegion.getType());
Player player = event.getPlayer();
Effect effect = new Effect(plugin);
if ((player == null || (!currentRegion.isOwner(player.getName()) && !currentRegion.isMember(player.getName())))
&& effect.regionHasEffect(currentRegionType.getEffects(), "denyblockbreak") != 0 && effect.hasReagents(currentLoc)) {
event.setCancelled(true);
if (player != null)
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
return;
}
int amountRequired = 0;
int i = 0;
for (ItemStack currentStack : currentRegionType.getRequirements()) {
if (currentStack.getTypeId() == event.getBlock().getTypeId()) {
amountRequired = new Integer(currentStack.getAmount());
break;
}
}
if (amountRequired == 0)
return;
int radius1 = (int) Math.sqrt(radius);
for (int x= (int) (currentLoc.getX()-radius1); x<radius1 + currentLoc.getX(); x++) {
for (int y = currentLoc.getY()- radius1 > 1 ? (int) (currentLoc.getY() - radius1) : 1; y< radius1 + currentLoc.getY() && y < 128; y++) {
for (int z = (int) (currentLoc.getZ() - radius1); z<radius1 + currentLoc.getZ(); z++) {
Block tempBlock = currentLoc.getWorld().getBlockAt(x, y, z);
if (tempBlock.getTypeId() == event.getBlock().getTypeId()) {
if (i >= amountRequired) {
return;
} else {
i++;
}
}
}
}
}
regionManager.destroyRegion(currentLoc);
delete = true;
break;
}
} catch (IllegalArgumentException iae) {
}
}
/*Set<Location> locations = regionManager.getRegionLocations();
outer: for (Iterator<Location> iter = locations.iterator(); iter.hasNext();) {
currentLoc = iter.next();
try {
if (currentLoc.getBlock().equals(loc.getBlock())) {
regionManager.destroyRegion(currentLoc);
break outer;
}
Region currentRegion = regionManager.getRegion(currentLoc);
RegionType currentRegionType = regionManager.getRegionType(currentRegion.getType());
int radius = currentRegionType.getRadius();
if (Math.sqrt(loc.distanceSquared(currentLoc)) < radius) {
Player player = event.getPlayer();
Effect effect = new Effect(plugin);
if ((player == null || (!currentRegion.isOwner(player.getName()) && !currentRegion.isMember(player.getName())))
&& effect.regionHasEffect(currentRegionType.getEffects(), "denyblockbreak") != 0 && effect.hasReagents(currentLoc)) {
event.setCancelled(true);
if (player != null)
player.sendMessage(ChatColor.GRAY + "[HeroStronghold] This region is protected");
}
int amountRequired = 0;
int i = 0;
for (ItemStack currentStack : currentRegionType.getRequirements()) {
if (currentStack.getTypeId() == event.getBlock().getTypeId()) {
amountRequired = currentStack.getAmount();
break;
}
}
if (amountRequired == 0)
return;
for (int x= (int) (currentLoc.getX()-radius); x<radius + currentLoc.getX(); x++) {
for (int y = currentLoc.getY()- radius > 1 ? (int) (currentLoc.getY() - radius) : 1; y< radius + currentLoc.getY() && y < 128; y++) {
for (int z = (int) (currentLoc.getZ() - radius); z<radius + currentLoc.getZ(); z++) {
Block tempBlock = currentLoc.getWorld().getBlockAt(x, y, z);
if (tempBlock.getTypeId() == event.getBlock().getTypeId()) {
if (i >= amountRequired) {
return;
} else {
i++;
}
}
}
}
}
regionManager.destroyRegion(currentLoc);
iter.remove();
delete = true;
break outer;
}
} catch (IllegalArgumentException iae) {
}
}*/
if (delete && currentLoc != null) {
regionManager.removeRegion(currentLoc);
}
}
|
diff --git a/CubicUnitExporter/src/main/java/org/cubictest/exporters/cubicunit/runner/converters/ElementConverter.java b/CubicUnitExporter/src/main/java/org/cubictest/exporters/cubicunit/runner/converters/ElementConverter.java
index de07e90b..fc8a0018 100644
--- a/CubicUnitExporter/src/main/java/org/cubictest/exporters/cubicunit/runner/converters/ElementConverter.java
+++ b/CubicUnitExporter/src/main/java/org/cubictest/exporters/cubicunit/runner/converters/ElementConverter.java
@@ -1,214 +1,214 @@
/*
* Created on 4.aug.2006
*
* This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE
* Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html
*
*/
package org.cubictest.exporters.cubicunit.runner.converters;
import java.util.Map;
import org.cubictest.common.utils.ErrorHandler;
import org.cubictest.export.converters.IPageElementConverter;
import org.cubictest.exporters.cubicunit.runner.holders.Holder;
import org.cubictest.model.FormElement;
import org.cubictest.model.Identifier;
import org.cubictest.model.IdentifierType;
import org.cubictest.model.Image;
import org.cubictest.model.Link;
import org.cubictest.model.PageElement;
import org.cubictest.model.TestPartStatus;
import org.cubictest.model.Text;
import org.cubictest.model.Title;
import org.cubictest.model.context.IContext;
import org.cubictest.model.formElement.Button;
import org.cubictest.model.formElement.Checkbox;
import org.cubictest.model.formElement.Password;
import org.cubictest.model.formElement.RadioButton;
import org.cubictest.model.formElement.Select;
import org.cubictest.model.formElement.TextArea;
import org.cubictest.model.formElement.TextField;
import org.cubicunit.Container;
import org.cubicunit.Document;
import org.cubicunit.Element;
import org.cubicunit.ElementTypes;
import org.cubicunit.internal.selenium.SeleniumAbstractElement;
import org.cubicunit.types.ElementType;
import org.cubicunit.types.ImageType;
import org.cubicunit.types.InputType;
import org.cubicunit.types.LinkType;
import org.cubicunit.types.SelectMenuType;
import org.cubicunit.types.SelectType;
import org.cubicunit.types.TextInputType;
public class ElementConverter implements IPageElementConverter<Holder> {
public void handlePageElement(Holder holder,PageElement pe) {
Container container = holder.getContainer();
boolean not = pe.isNot();
TestPartStatus status = TestPartStatus.FAIL;
try{
if (pe instanceof Text) {
String text = pe.getIdentifier(IdentifierType.LABEL).getValue();
if (not != container.containsText(text))
status = TestPartStatus.PASS;
else
status = TestPartStatus.FAIL;
}else if (pe instanceof Title){
String text = pe.getIdentifier(IdentifierType.LABEL).getValue();
Document doc = holder.getDocument();
String title = doc.getTitle();
if (not != title.equals(text))
status = (TestPartStatus.PASS);
else{
status = (TestPartStatus.FAIL);
//identifier.setActual(title);
}
}else{
ElementType<?> elementType = null;
if (pe instanceof Link) {
elementType = ElementTypes.LINK;
}else if (pe instanceof Image) {
elementType = ElementTypes.IMAGE;
}else if (pe instanceof FormElement){
if(pe instanceof TextArea)
elementType = ElementTypes.TEXT_AREA;
else if (pe instanceof Button)
elementType = ElementTypes.BUTTON;
else if (pe instanceof Select)
elementType = ElementTypes.SELECT_MENU;
else if (pe instanceof Checkbox)
elementType = ElementTypes.CHECKBOX;
else if (pe instanceof RadioButton)
elementType = ElementTypes.RADIO_BUTTON;
else if (pe instanceof Password)
elementType = ElementTypes.PASSWORD_FIELD;
else if (pe instanceof TextField)
elementType = ElementTypes.TEXT_FIELD;
else{
elementType = ElementTypes.ELEMENT;
ErrorHandler.logAndShowErrorDialog("Error could not convert: " + pe);
}
}else if (pe instanceof IContext){
throw new IllegalArgumentException();
}else{
elementType = ElementTypes.ELEMENT;
ErrorHandler.logAndShowErrorDialog("Error could not convert: " + pe);
}
for(Identifier id : pe.getIdentifiers()){
switch (id.getType()) {
case CHECKED:
elementType = ((SelectType<?>)elementType).
checked(id.getProbability(), Boolean.getBoolean(id.getValue()));
break;
case HREF:
elementType = ((LinkType)elementType).href(
id.getProbability(), id.getValue());
break;
case ID:
elementType = elementType.id(id.getProbability(), id.getValue());
break;
case INDEX:
// TODO
break;
case LABEL:
if(elementType instanceof LinkType)
elementType = ((LinkType)elementType).
text(id.getProbability(), id.getValue());
else if (elementType instanceof InputType<?>)
elementType = ((InputType<?>)elementType).
label(id.getProbability(), id.getValue());
break;
case MULTISELECT:
elementType = ((SelectMenuType)elementType).
multiSelect(id.getProbability(), Boolean.getBoolean(id.getValue()));
break;
case NAME:
elementType = ((InputType<?>)elementType).
name(id.getProbability(), id.getValue());
break;
case SRC:
elementType = ((ImageType)elementType).src(id.getProbability(), id.getValue());
break;
case TITLE:
elementType = elementType.title(id.getProbability(), id.getValue());
break;
case VALUE:
elementType = ((TextInputType<?>)elementType).value
(id.getProbability(), id.getValue());
break;
case XPATH:
//TODO
break;
case SELECTED:
elementType = ((SelectType<?>)elementType).
checked(id.getProbability(), Boolean.getBoolean(id.getValue()));
break;
case ELEMENT_NAME:
break;
}
}
Element element = container.get(elementType);
if(not)
if(element == null)
status = TestPartStatus.PASS;
else
status = TestPartStatus.FAIL;
else{
if(element == null)
status = TestPartStatus.FAIL;
else{
holder.put(pe,element);
status = TestPartStatus.PASS;
Map<String, Object> props =
((SeleniumAbstractElement)element).getProperties();
if(props != null){
for(String key: props.keySet()){
String actualValue = (String) props.get(key);
IdentifierType id = null;
- if("diffid".equals(key)){
+ if("diffId".equals(key)){
id = IdentifierType.ID;
}else if("diffName".equals(key)){
id = IdentifierType.NAME;
}else if("diffHref".equals(key)){
id = IdentifierType.HREF;
}else if("diffSrc".equals(key)){
id = IdentifierType.SRC;
}else if("diffIndex".equals(key)){
id = IdentifierType.INDEX;
}else if("diffValue".equals(key)){
id = IdentifierType.VALUE;
}else if("diffChecked".equals(key)){
id = IdentifierType.CHECKED;
}else if("diffLabel".equals(key)){
id = IdentifierType.LABEL;
}else if("diffMultiselect".equals(key)){
id = IdentifierType.MULTISELECT;
}else if("diffSelected".equals(key)){
id = IdentifierType.SELECTED;
}else
continue;
if(pe.getIdentifier(id) != null){
pe.getIdentifier(id).setActual(actualValue);
status = TestPartStatus.WARN;
}
}
}
}
}
}
}catch(RuntimeException e){
status = TestPartStatus.EXCEPTION;
throw e;
}
holder.addResult(pe, status);
}
}
| true | true | public void handlePageElement(Holder holder,PageElement pe) {
Container container = holder.getContainer();
boolean not = pe.isNot();
TestPartStatus status = TestPartStatus.FAIL;
try{
if (pe instanceof Text) {
String text = pe.getIdentifier(IdentifierType.LABEL).getValue();
if (not != container.containsText(text))
status = TestPartStatus.PASS;
else
status = TestPartStatus.FAIL;
}else if (pe instanceof Title){
String text = pe.getIdentifier(IdentifierType.LABEL).getValue();
Document doc = holder.getDocument();
String title = doc.getTitle();
if (not != title.equals(text))
status = (TestPartStatus.PASS);
else{
status = (TestPartStatus.FAIL);
//identifier.setActual(title);
}
}else{
ElementType<?> elementType = null;
if (pe instanceof Link) {
elementType = ElementTypes.LINK;
}else if (pe instanceof Image) {
elementType = ElementTypes.IMAGE;
}else if (pe instanceof FormElement){
if(pe instanceof TextArea)
elementType = ElementTypes.TEXT_AREA;
else if (pe instanceof Button)
elementType = ElementTypes.BUTTON;
else if (pe instanceof Select)
elementType = ElementTypes.SELECT_MENU;
else if (pe instanceof Checkbox)
elementType = ElementTypes.CHECKBOX;
else if (pe instanceof RadioButton)
elementType = ElementTypes.RADIO_BUTTON;
else if (pe instanceof Password)
elementType = ElementTypes.PASSWORD_FIELD;
else if (pe instanceof TextField)
elementType = ElementTypes.TEXT_FIELD;
else{
elementType = ElementTypes.ELEMENT;
ErrorHandler.logAndShowErrorDialog("Error could not convert: " + pe);
}
}else if (pe instanceof IContext){
throw new IllegalArgumentException();
}else{
elementType = ElementTypes.ELEMENT;
ErrorHandler.logAndShowErrorDialog("Error could not convert: " + pe);
}
for(Identifier id : pe.getIdentifiers()){
switch (id.getType()) {
case CHECKED:
elementType = ((SelectType<?>)elementType).
checked(id.getProbability(), Boolean.getBoolean(id.getValue()));
break;
case HREF:
elementType = ((LinkType)elementType).href(
id.getProbability(), id.getValue());
break;
case ID:
elementType = elementType.id(id.getProbability(), id.getValue());
break;
case INDEX:
// TODO
break;
case LABEL:
if(elementType instanceof LinkType)
elementType = ((LinkType)elementType).
text(id.getProbability(), id.getValue());
else if (elementType instanceof InputType<?>)
elementType = ((InputType<?>)elementType).
label(id.getProbability(), id.getValue());
break;
case MULTISELECT:
elementType = ((SelectMenuType)elementType).
multiSelect(id.getProbability(), Boolean.getBoolean(id.getValue()));
break;
case NAME:
elementType = ((InputType<?>)elementType).
name(id.getProbability(), id.getValue());
break;
case SRC:
elementType = ((ImageType)elementType).src(id.getProbability(), id.getValue());
break;
case TITLE:
elementType = elementType.title(id.getProbability(), id.getValue());
break;
case VALUE:
elementType = ((TextInputType<?>)elementType).value
(id.getProbability(), id.getValue());
break;
case XPATH:
//TODO
break;
case SELECTED:
elementType = ((SelectType<?>)elementType).
checked(id.getProbability(), Boolean.getBoolean(id.getValue()));
break;
case ELEMENT_NAME:
break;
}
}
Element element = container.get(elementType);
if(not)
if(element == null)
status = TestPartStatus.PASS;
else
status = TestPartStatus.FAIL;
else{
if(element == null)
status = TestPartStatus.FAIL;
else{
holder.put(pe,element);
status = TestPartStatus.PASS;
Map<String, Object> props =
((SeleniumAbstractElement)element).getProperties();
if(props != null){
for(String key: props.keySet()){
String actualValue = (String) props.get(key);
IdentifierType id = null;
if("diffid".equals(key)){
id = IdentifierType.ID;
}else if("diffName".equals(key)){
id = IdentifierType.NAME;
}else if("diffHref".equals(key)){
id = IdentifierType.HREF;
}else if("diffSrc".equals(key)){
id = IdentifierType.SRC;
}else if("diffIndex".equals(key)){
id = IdentifierType.INDEX;
}else if("diffValue".equals(key)){
id = IdentifierType.VALUE;
}else if("diffChecked".equals(key)){
id = IdentifierType.CHECKED;
}else if("diffLabel".equals(key)){
id = IdentifierType.LABEL;
}else if("diffMultiselect".equals(key)){
id = IdentifierType.MULTISELECT;
}else if("diffSelected".equals(key)){
id = IdentifierType.SELECTED;
}else
continue;
if(pe.getIdentifier(id) != null){
pe.getIdentifier(id).setActual(actualValue);
status = TestPartStatus.WARN;
}
}
}
}
}
}
}catch(RuntimeException e){
status = TestPartStatus.EXCEPTION;
throw e;
}
holder.addResult(pe, status);
}
| public void handlePageElement(Holder holder,PageElement pe) {
Container container = holder.getContainer();
boolean not = pe.isNot();
TestPartStatus status = TestPartStatus.FAIL;
try{
if (pe instanceof Text) {
String text = pe.getIdentifier(IdentifierType.LABEL).getValue();
if (not != container.containsText(text))
status = TestPartStatus.PASS;
else
status = TestPartStatus.FAIL;
}else if (pe instanceof Title){
String text = pe.getIdentifier(IdentifierType.LABEL).getValue();
Document doc = holder.getDocument();
String title = doc.getTitle();
if (not != title.equals(text))
status = (TestPartStatus.PASS);
else{
status = (TestPartStatus.FAIL);
//identifier.setActual(title);
}
}else{
ElementType<?> elementType = null;
if (pe instanceof Link) {
elementType = ElementTypes.LINK;
}else if (pe instanceof Image) {
elementType = ElementTypes.IMAGE;
}else if (pe instanceof FormElement){
if(pe instanceof TextArea)
elementType = ElementTypes.TEXT_AREA;
else if (pe instanceof Button)
elementType = ElementTypes.BUTTON;
else if (pe instanceof Select)
elementType = ElementTypes.SELECT_MENU;
else if (pe instanceof Checkbox)
elementType = ElementTypes.CHECKBOX;
else if (pe instanceof RadioButton)
elementType = ElementTypes.RADIO_BUTTON;
else if (pe instanceof Password)
elementType = ElementTypes.PASSWORD_FIELD;
else if (pe instanceof TextField)
elementType = ElementTypes.TEXT_FIELD;
else{
elementType = ElementTypes.ELEMENT;
ErrorHandler.logAndShowErrorDialog("Error could not convert: " + pe);
}
}else if (pe instanceof IContext){
throw new IllegalArgumentException();
}else{
elementType = ElementTypes.ELEMENT;
ErrorHandler.logAndShowErrorDialog("Error could not convert: " + pe);
}
for(Identifier id : pe.getIdentifiers()){
switch (id.getType()) {
case CHECKED:
elementType = ((SelectType<?>)elementType).
checked(id.getProbability(), Boolean.getBoolean(id.getValue()));
break;
case HREF:
elementType = ((LinkType)elementType).href(
id.getProbability(), id.getValue());
break;
case ID:
elementType = elementType.id(id.getProbability(), id.getValue());
break;
case INDEX:
// TODO
break;
case LABEL:
if(elementType instanceof LinkType)
elementType = ((LinkType)elementType).
text(id.getProbability(), id.getValue());
else if (elementType instanceof InputType<?>)
elementType = ((InputType<?>)elementType).
label(id.getProbability(), id.getValue());
break;
case MULTISELECT:
elementType = ((SelectMenuType)elementType).
multiSelect(id.getProbability(), Boolean.getBoolean(id.getValue()));
break;
case NAME:
elementType = ((InputType<?>)elementType).
name(id.getProbability(), id.getValue());
break;
case SRC:
elementType = ((ImageType)elementType).src(id.getProbability(), id.getValue());
break;
case TITLE:
elementType = elementType.title(id.getProbability(), id.getValue());
break;
case VALUE:
elementType = ((TextInputType<?>)elementType).value
(id.getProbability(), id.getValue());
break;
case XPATH:
//TODO
break;
case SELECTED:
elementType = ((SelectType<?>)elementType).
checked(id.getProbability(), Boolean.getBoolean(id.getValue()));
break;
case ELEMENT_NAME:
break;
}
}
Element element = container.get(elementType);
if(not)
if(element == null)
status = TestPartStatus.PASS;
else
status = TestPartStatus.FAIL;
else{
if(element == null)
status = TestPartStatus.FAIL;
else{
holder.put(pe,element);
status = TestPartStatus.PASS;
Map<String, Object> props =
((SeleniumAbstractElement)element).getProperties();
if(props != null){
for(String key: props.keySet()){
String actualValue = (String) props.get(key);
IdentifierType id = null;
if("diffId".equals(key)){
id = IdentifierType.ID;
}else if("diffName".equals(key)){
id = IdentifierType.NAME;
}else if("diffHref".equals(key)){
id = IdentifierType.HREF;
}else if("diffSrc".equals(key)){
id = IdentifierType.SRC;
}else if("diffIndex".equals(key)){
id = IdentifierType.INDEX;
}else if("diffValue".equals(key)){
id = IdentifierType.VALUE;
}else if("diffChecked".equals(key)){
id = IdentifierType.CHECKED;
}else if("diffLabel".equals(key)){
id = IdentifierType.LABEL;
}else if("diffMultiselect".equals(key)){
id = IdentifierType.MULTISELECT;
}else if("diffSelected".equals(key)){
id = IdentifierType.SELECTED;
}else
continue;
if(pe.getIdentifier(id) != null){
pe.getIdentifier(id).setActual(actualValue);
status = TestPartStatus.WARN;
}
}
}
}
}
}
}catch(RuntimeException e){
status = TestPartStatus.EXCEPTION;
throw e;
}
holder.addResult(pe, status);
}
|
diff --git a/org.amanzi.awe.render.network/src/org/amanzi/awe/render/network/NetworkRenderer.java b/org.amanzi.awe.render.network/src/org/amanzi/awe/render/network/NetworkRenderer.java
index b7ad1bd1a..dc92f3aa1 100644
--- a/org.amanzi.awe.render.network/src/org/amanzi/awe/render/network/NetworkRenderer.java
+++ b/org.amanzi.awe.render.network/src/org/amanzi/awe/render/network/NetworkRenderer.java
@@ -1,960 +1,960 @@
/* AWE - Amanzi Wireless Explorer
* http://awe.amanzi.org
* (C) 2008-2009, AmanziTel AB
*
* This library is provided under the terms of the Eclipse Public License
* as described at http://www.eclipse.org/legal/epl-v10.html. Any use,
* reproduction or distribution of the library constitutes recipient's
* acceptance of this agreement.
*
* This library is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.amanzi.awe.render.network;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.refractions.udig.catalog.IGeoResource;
import net.refractions.udig.core.Pair;
import net.refractions.udig.project.ILayer;
import net.refractions.udig.project.IStyleBlackboard;
import net.refractions.udig.project.internal.render.impl.RendererImpl;
import net.refractions.udig.project.render.RenderException;
import org.amanzi.awe.catalog.neo.GeoNeo;
import org.amanzi.awe.catalog.neo.GeoNeo.GeoNode;
import org.amanzi.awe.filters.AbstractFilter;
import org.amanzi.awe.filters.FilterUtil;
import org.amanzi.awe.neostyle.NeoStyle;
import org.amanzi.awe.neostyle.NeoStyleContent;
import org.amanzi.neo.core.INeoConstants;
import org.amanzi.neo.core.NeoCorePlugin;
import org.amanzi.neo.core.enums.GeoNeoRelationshipTypes;
import org.amanzi.neo.core.enums.GisTypes;
import org.amanzi.neo.core.enums.NetworkRelationshipTypes;
import org.amanzi.neo.core.enums.NetworkSiteType;
import org.amanzi.neo.core.service.NeoServiceProvider;
import org.amanzi.neo.core.utils.NeoUtils;
import org.amanzi.neo.loader.internal.NeoLoaderPlugin;
import org.amanzi.neo.preferences.DataLoadPreferences;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.ReturnableEvaluator;
import org.neo4j.graphdb.StopEvaluator;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.TraversalPosition;
import org.neo4j.graphdb.Traverser.Order;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
public class NetworkRenderer extends RendererImpl {
/** double CIRCLE_BEAMWIDTH field */
private static final double CIRCLE_BEAMWIDTH = 360.0;
private static final double DRFAULT_BEAMWIDTH = 10.0;
public static final String BLACKBOARD_NODE_LIST = "org.amanzi.awe.tool.star.StarTool.nodes";
public static final String BLACKBOARD_START_ANALYSER = "org.amanzi.awe.tool.star.StarTool.analyser";
private static final Color COLOR_SITE_SELECTED = Color.CYAN;
private static final Color COLOR_SECTOR_SELECTED = Color.CYAN;
private static final Color COLOR_SECTOR_STAR = Color.RED;
private AffineTransform base_transform = null; // save original graphics transform for repeated re-use
private Color drawColor = Color.DARK_GRAY;
private Color siteColor = new Color(128, 128, 128,(int)(0.6*255.0));
private Color fillColor = new Color(255, 255, 128,(int)(0.6*255.0));
private MathTransform transform_d2w;
private MathTransform transform_w2d;
private Color labelColor = Color.DARK_GRAY;
private Color surroundColor = Color.WHITE;
private Color lineColor;
private Node aggNode;
private String siteName;
private boolean normalSiteName;
private String sectorName;
private boolean sectorLabeling;
private boolean noSiteName;
private AbstractFilter filterSectors;
private AbstractFilter filterSites;
private void setCrsTransforms(CoordinateReferenceSystem dataCrs) throws FactoryException{
boolean lenient = true; // needs to be lenient to work on uDIG 1.1 (otherwise we get error: bursa wolf parameters required
CoordinateReferenceSystem worldCrs = context.getCRS();
this.transform_d2w = CRS.findMathTransform(dataCrs, worldCrs, lenient);
this.transform_w2d = CRS.findMathTransform(worldCrs, dataCrs, lenient); // could use transform_d2w.inverse() also
}
private Envelope getTransformedBounds() throws TransformException {
ReferencedEnvelope bounds = getRenderBounds();
if (bounds == null) {
bounds = this.context.getViewportModel().getBounds();
}
Envelope bounds_transformed = null;
if (bounds != null && transform_w2d != null) {
bounds_transformed = JTS.transform(bounds, transform_w2d);
}
return bounds_transformed;
}
/**
* This method is called to render what it can. It is passed a graphics context
* with which it can draw. The class already contains a reference to a RenderContext
* from which it can obtain the layer and the GeoResource to render.
* @see net.refractions.udig.project.internal.render.impl.RendererImpl#render(java.awt.Graphics2D, org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public void render( Graphics2D g, IProgressMonitor monitor ) throws RenderException {
ILayer layer = getContext().getLayer();
// Are there any resources in the layer that respond to the GeoNeo class (should be the case if we found a Neo4J database with GeoNeo data)
IGeoResource resource = layer.findGeoResource(GeoNeo.class);
//Lagutko, 22.10.2009, initialize BlackboardEntry for star, this is necessary to enable IMomento to save on app exit
layer.getMap().getBlackboard().get(BLACKBOARD_NODE_LIST);
if(resource != null){
renderGeoNeo(g,resource,monitor);
}
}
/**
* This method is called to render data from the Neo4j 'GeoNeo' Geo-Resource.
*/
private void renderGeoNeo( Graphics2D g, IGeoResource neoGeoResource, IProgressMonitor monitor ) throws RenderException {
if (monitor == null)
monitor = new NullProgressMonitor();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
monitor.beginTask("render network sites and sectors: "+neoGeoResource.getIdentifier(), IProgressMonitor.UNKNOWN); // TODO: Get size from info
GeoNeo geoNeo = null;
// Setup default drawing parameters and thresholds (to be modified by style if found)
int drawSize=15;
int alpha = (int)(0.6*255.0);
int maxSitesLabel = 30;
int maxSitesFull = 100;
int maxSitesLite = 1000;
int maxSymbolSize = 40;
Font font = g.getFont();
int fontSize = font.getSize();
int sectorFontSize = font.getSize();
boolean scaleSectors = true;
IStyleBlackboard style = getContext().getLayer().getStyleBlackboard();
NeoStyle neostyle = (NeoStyle)style.get(NeoStyleContent.ID );
siteName = NeoStyleContent.DEF_MAIN_PROPERTY;
sectorName = NeoStyleContent.DEF_SECONDARY_PROPERTY;
if (neostyle!=null){
try {
siteColor = neostyle.getSiteFill();
fillColor=neostyle.getFill();
drawColor=neostyle.getLine();
labelColor=neostyle.getLabel();
float colSum = 0.0f;
for(float comp: labelColor.getRGBColorComponents(null)){
colSum += comp;
}
if(colSum>2.0) {
surroundColor=Color.DARK_GRAY;
} else {
surroundColor=Color.WHITE;
}
drawSize = neostyle.getSymbolSize();
alpha = 255 - (int)((double)neostyle.getSymbolTransparency() / 100.0 * 255.0);
maxSitesLabel = neostyle.getLabeling();
maxSitesFull = neostyle.getSmallSymb();
maxSitesLite = neostyle.getSmallestSymb();
scaleSectors = !neostyle.isFixSymbolSize();
maxSymbolSize = neostyle.getMaximumSymbolSize();
fontSize = neostyle.getFontSize();
sectorFontSize = neostyle.getSecondaryFontSize();
siteName = neostyle.getMainProperty();
sectorName = neostyle.getSecondaryProperty();
} catch (Exception e) {
//TODO: we can get here if an old style exists, and we have added new fields
}
}
normalSiteName = NeoStyleContent.DEF_MAIN_PROPERTY.equals(siteName);
noSiteName = !normalSiteName && NeoStyleContent.DEF_SECONDARY_PROPERTY.equals(siteName);
sectorLabeling = !NeoStyleContent.DEF_SECONDARY_PROPERTY.equals(sectorName);
g.setFont(font.deriveFont((float)fontSize));
lineColor = new Color(drawColor.getRed(), drawColor.getGreen(), drawColor.getBlue(), alpha);
siteColor = new Color(siteColor.getRed(), siteColor.getGreen(), siteColor.getBlue(), alpha);
fillColor = new Color(fillColor.getRed(), fillColor.getGreen(), fillColor.getBlue(), alpha);
Map<Node, java.awt.Point> nodesMap = new HashMap<Node, java.awt.Point>();
Map<Node, java.awt.Point> sectorMap = new HashMap<Node, java.awt.Point>();
Map<Point, String> labelsMap = new HashMap<Point, String>();
GraphDatabaseService neo = NeoServiceProvider.getProvider().getService();
Transaction tx = neo.beginTx();
NeoUtils.addTransactionLog(tx, Thread.currentThread(), "render Network");
try {
monitor.subTask("connecting");
geoNeo = neoGeoResource.resolve(GeoNeo.class, new SubProgressMonitor(monitor, 10));
System.out.println("NetworkRenderer resolved geoNeo '"+geoNeo.getName()+"' from resource: "+neoGeoResource.getIdentifier());
filterSectors = FilterUtil.getFilterOfData(geoNeo.getMainGisNode(), neo);
filterSites = FilterUtil.getFilterOfData(geoNeo.getMainGisNode().getSingleRelationship(GeoNeoRelationshipTypes.NEXT, Direction.OUTGOING).getOtherNode(geoNeo.getMainGisNode()), neo);
String starProperty = getSelectProperty(geoNeo);
Pair<Point, Long> starPoint = getStarPoint();
Node starNode = null;
if(starPoint != null) {
System.out.println("Have star selection: "+starPoint);
}
ArrayList<Pair<String,Integer>> multiOmnis = new ArrayList<Pair<String,Integer>>();
aggNode = geoNeo.getAggrNode();
setCrsTransforms(neoGeoResource.getInfo(null).getCRS());
Envelope bounds_transformed = getTransformedBounds();
Envelope data_bounds = geoNeo.getBounds();
boolean drawFull = true;
boolean drawLite = true;
boolean drawLabels = true;
if (bounds_transformed == null) {
drawFull = false;
drawLite = false;
drawLabels = false;
}else if (data_bounds != null && data_bounds.getHeight()>0 && data_bounds.getWidth()>0) {
double dataScaled = (bounds_transformed.getHeight() * bounds_transformed.getWidth())
/ (data_bounds.getHeight() * data_bounds.getWidth());
long count = geoNeo.getCount();
if (NeoLoaderPlugin.getDefault().getPreferenceStore().getBoolean(DataLoadPreferences.NETWORK_COMBINED_CALCULATION)) {
count = getAverageCount(monitor);
}
double countScaled = dataScaled * count;
drawLabels = countScaled < maxSitesLabel;
drawFull = countScaled < maxSitesFull;
drawLite = countScaled < maxSitesLite;
if (drawFull && scaleSectors) {
drawSize *= Math.sqrt(maxSitesFull) / (3 * Math.sqrt(countScaled));
drawSize = Math.min(drawSize, maxSymbolSize);
}
// expand the boundary to include sites just out of view (so partial sectors can be see)
bounds_transformed.expandBy(0.75 * (bounds_transformed.getHeight() + bounds_transformed.getWidth()));
}
g.setColor(drawColor);
int count = 0;
monitor.subTask("drawing");
Coordinate world_location = new Coordinate(); // single object for re-use in transform below (minimize object creation)
// draw selection
java.awt.Point prev_p = null;
java.awt.Point prev_l_p = null;
ArrayList<Node> selectedPoints = new ArrayList<Node>();
final Set<Node> selectedNodes = new HashSet<Node>(geoNeo.getSelectedNodes());
final ReturnableEvaluator returnableEvaluator = new ReturnableEvaluator() {
@Override
public boolean isReturnableNode(TraversalPosition currentPos) {
final Object property = currentPos.currentNode().getProperty("type", "");
return "site".equals(property)||"probe".equals(property);
}
};
for (Node node : selectedNodes) {
final String nodeType = NeoUtils.getNodeType(node, "");
if ("network".equals(nodeType)) {
// Select all 'site' nodes in that file
for (Node rnode : node
.traverse(Order.DEPTH_FIRST, StopEvaluator.END_OF_GRAPH, returnableEvaluator, GeoNeoRelationshipTypes.NEXT, Direction.OUTGOING, NetworkRelationshipTypes.CHILD, Direction.OUTGOING)) {
selectedPoints.add(rnode);
}
} else if ("city".equals(nodeType) || "bsc".equals(nodeType)) {
for (Node rnode : node.traverse(Order.DEPTH_FIRST, StopEvaluator.END_OF_GRAPH,
returnableEvaluator, NetworkRelationshipTypes.CHILD, Direction.OUTGOING)) {
selectedPoints.add(rnode);
}
} else {
// Traverse backwards on CHILD relations to closest 'mp' Point
for (@SuppressWarnings("unused")
Node rnode : node.traverse(Order.DEPTH_FIRST, new StopEvaluator() {
@Override
public boolean isStopNode(TraversalPosition currentPos) {
return "site".equals(currentPos.currentNode().getProperty("type", ""));
}
}, new ReturnableEvaluator() {
@Override
public boolean isReturnableNode(TraversalPosition currentPos) {
return "site".equals(currentPos.currentNode().getProperty("type", ""));
}
}, NetworkRelationshipTypes.CHILD, Direction.INCOMING)) {
selectedPoints.add(rnode);
break;
}
}
}
// Now draw the selected points highlights
//TODO remove double selection?
for (Node rnode : selectedPoints) {
GeoNode node = new GeoNode(rnode);
Coordinate location = node.getCoordinate();
if (location == null) {
continue;
}
if (bounds_transformed != null && !bounds_transformed.contains(location)) {
continue; // Don't draw points outside viewport
}
if (filterSites != null) {
if (!filterSites.filterNode(node.getNode()).isValid()) {
continue;
}
}
try {
JTS.transform(location, world_location, transform_d2w);
} catch (Exception e) {
continue;
}
java.awt.Point p = getContext().worldToPixel(world_location);
if (prev_p != null && prev_p.x == p.x && prev_p.y == p.y) {
prev_p = p;
continue;
} else {
prev_p = p;
}
renderSelectionGlow(g, p, drawSize * 4);
}
g.setColor(drawColor);
long startTime = System.currentTimeMillis();
for(GeoNode node:geoNeo.getGeoNodes(bounds_transformed)) {
if (filterSites != null) {
if (!filterSites.filterNode(node.getNode()).isValid()) {
continue;
}
}
Coordinate location = node.getCoordinate();
if (bounds_transformed != null && !bounds_transformed.contains(location)) {
continue; // Don't draw points outside viewport
}
try {
JTS.transform(location, world_location, transform_d2w);
} catch (Exception e) {
//JTS.transform(location, world_location, transform_w2d.inverse());
}
java.awt.Point p = getContext().worldToPixel(world_location);
Color borderColor = g.getColor();
boolean selected = false;
if (geoNeo.getSelectedNodes().contains(node.getNode())) {
borderColor = COLOR_SITE_SELECTED;
// if selection exist - do not necessary to select node again
selected = false;
} else {
// if selection exist - do not necessary to select node again
selected = !selectedPoints.contains(node.getNode());
// this selection was already checked
// for (Node rnode:node.getNode().traverse(Traverser.Order.BREADTH_FIRST,
// StopEvaluator.DEPTH_ONE, ReturnableEvaluator.ALL_BUT_START_NODE,
// NetworkRelationshipTypes.CHILD, Direction.BOTH)){
// if (geoNeo.getSelectedNodes().contains(rnode)) {
// selected = true;
// break;
// }
// }
if (selected) {
selected = false;
DELTA_LOOP: for (Node rnode:node.getNode().traverse(Order.DEPTH_FIRST, StopEvaluator.DEPTH_ONE, ReturnableEvaluator.ALL_BUT_START_NODE, NetworkRelationshipTypes.MISSING, Direction.INCOMING, NetworkRelationshipTypes.DIFFERENT, Direction.INCOMING)){
if (geoNeo.getSelectedNodes().contains(rnode)) {
selected = true;
break;
} else {
for (Node xnode:rnode.traverse(Order.BREADTH_FIRST, new StopEvaluator(){
@Override
public boolean isStopNode(TraversalPosition currentPos) {
return "delta_report".equals(currentPos.currentNode().getProperty("type",""));
}}, ReturnableEvaluator.ALL_BUT_START_NODE, NetworkRelationshipTypes.CHILD, Direction.INCOMING)){
if (geoNeo.getSelectedNodes().contains(xnode)) {
selected = true;
break DELTA_LOOP;
}
}
}
}
}
}
renderSite(g, p, borderColor, siteColor, drawSize, drawFull, drawLite, selected);
nodesMap.put(node.getNode(), p);
if (drawFull) {
int countOmnis = 0;
double[] label_position_angles = new double[] {0, 90};
try {
int s = 0;
for (Relationship relationship : node.getNode().getRelationships(NetworkRelationshipTypes.CHILD, Direction.OUTGOING)) {
Node child = relationship.getEndNode();
if (child.hasProperty("type") && child.getProperty("type").toString().equals("sector")) {
- double azimuth = getDouble(child, "azimuth", Double.NaN);
- double beamwidth = Double.NaN;
- if (azimuth == Double.NaN) {
+ Double azimuth = getDouble(child, "azimuth", Double.NaN);
+ Double beamwidth = Double.NaN;
+ if (azimuth.equals(Double.NaN)) {
beamwidth = getDouble(child, "beamwidth", CIRCLE_BEAMWIDTH);
if(beamwidth<CIRCLE_BEAMWIDTH){
- azimuth = 0;
+ azimuth = 0.0;
System.err.println("Error in render GeoNeo: azimuth is defined, but beamwidth less than "+CIRCLE_BEAMWIDTH);
}
}else{
beamwidth = getDouble(child, "beamwidth", DRFAULT_BEAMWIDTH);
}
Color colorToFill = getSectorColor(child, fillColor);
borderColor = drawColor;
if (starPoint != null && starPoint.right().equals(child.getId())) {
borderColor = COLOR_SECTOR_STAR;
starNode = child;
} else
if (geoNeo.getSelectedNodes().contains(child)) {
borderColor = COLOR_SECTOR_SELECTED;
}
// put sector information in to blackboard
if (filterSectors != null) {
if (!filterSectors.filterNode(child).isValid()) {
continue;
}
}
Pair<Point, Point> centerPoint = renderSector(g, p, azimuth, beamwidth, colorToFill, borderColor, drawSize);
nodesMap.put(child, centerPoint.getLeft());
if (sectorLabeling){
sectorMap.put(child, centerPoint.getRight());
}
if (s < label_position_angles.length) {
label_position_angles[s] = azimuth;
}
// g.setColor(drawColor);
// g.rotate(-Math.toRadians(beamwidth/2));
// g.drawString(sector.getString("name"),drawSize,0);
if(beamwidth==CIRCLE_BEAMWIDTH) countOmnis++;
s++;
}
}
} finally {
if (base_transform != null) {
// recover the normal transform
g.setTransform(base_transform);
g.setColor(drawColor);
}
}
if (base_transform != null) {
g.setTransform(base_transform);
}
String drawString = getSiteName(node);
if (countOmnis>1) {
//System.err.println("Site "+node+" had "+countOmnis+" omni antennas");
multiOmnis.add(new Pair<String, Integer>(drawString, countOmnis));
}
if (drawLabels) {
labelsMap.put(p, drawString);
}
}
monitor.worked(1);
count++;
if (monitor.isCanceled())
break;
}
if (drawLabels && labelsMap.size() > 0) {
Set<Rectangle> labelRec = new HashSet<Rectangle>();
FontMetrics metrics = g.getFontMetrics(font);
// get the height of a line of text in this font and render context
int hgt = metrics.getHeight();
for(Point p: labelsMap.keySet()) {
String drawString = labelsMap.get(p);
int label_x = drawSize > 15 ? 15 : drawSize;
int label_y = hgt / 3;
p = new Point(p.x + label_x, p.y + label_y);
// get the advance of my text in this font and render context
int adv = metrics.stringWidth(drawString);
// calculate the size of a box to hold the text with some padding.
Rectangle rect = new Rectangle(p.x -1 , p.y - hgt + 1, adv + 2, hgt + 2);
boolean drawsLabel = findNonOverlapPosition(labelRec, hgt, p, rect);
if (drawsLabel && !drawString.isEmpty()) {
labelRec.add(rect);
drawLabel(g, p, drawString);
}
}
// draw sector name
if (sectorLabeling) {
Font fontOld = g.getFont();
Font fontSector = fontOld.deriveFont((float)sectorFontSize);
g.setFont(fontSector);
FontMetrics metric = g.getFontMetrics(fontSector);
hgt = metrics.getHeight();
int h = hgt / 3;
for (Node sector : nodesMap.keySet()) {
String name = getSectorName(sector);
if (name.isEmpty()) {
continue;
}
int w = metric.stringWidth(name);
Point pSector = nodesMap.get(sector);
Point endLine = sectorMap.get(sector);
// calculate p
int x = (endLine.x < pSector.x) ? endLine.x - w : endLine.x;
int y = (endLine.y < pSector.y) ? endLine.y - h : endLine.y;
Point p = new Point(x, y);
// get the advance of my text in this font and render context
int adv = metrics.stringWidth(name);
// calculate the size of a box to hold the text with some padding.
Rectangle rect = new Rectangle(p.x -1 , p.y - hgt + 1, adv + 2, hgt + 2);
boolean drawsLabel = findNonOverlapPosition(labelRec, hgt, p, rect);
if (drawsLabel) {
labelRec.add(rect);
drawLabel(g, p, name);
}
}
g.setFont(fontOld);
}
}
if(multiOmnis.size()>0){
//TODO: Move this to utility class
StringBuffer sb = new StringBuffer();
int llen=0;
for (Pair<String, Integer> pair : multiOmnis) {
if (sb.length() > 1)
sb.append(", ");
else
sb.append("\t");
if (sb.length() > 100 + llen) {
llen = sb.length();
sb.append("\n\t");
}
sb.append(pair.left()).append(":").append(pair.right());
if (sb.length() > 1000)
break;
}
System.err.println("There were "+multiOmnis.size()+" sites with more than one omni antenna: ");
System.err.println(sb.toString());
}
if (starNode != null && starProperty != null) {
drawAnalyser(g, starNode, starPoint.left(), starProperty, nodesMap);
}
String neiName = (String)geoNeo.getProperties(GeoNeo.NEIGH_NAME);
if (neiName != null) {
Object properties = geoNeo.getProperties(GeoNeo.NEIGH_RELATION);
if (properties != null) {
drawRelation(g, (Relationship)properties, lineColor, nodesMap);
}
properties = geoNeo.getProperties(GeoNeo.NEIGH_MAIN_NODE);
Object type=geoNeo.getProperties(GeoNeo.NEIGH_TYPE);
if (properties != null) {
drawNeighbour(g, neiName, (Node)properties, lineColor, nodesMap,type);
}
}
System.out.println("Network renderer took " + ((System.currentTimeMillis() - startTime) / 1000.0) + "s to draw " + count + " sites from "+neoGeoResource.getIdentifier());
tx.success();
} catch (TransformException e) {
throw new RenderException(e);
} catch (FactoryException e) {
throw new RenderException(e);
} catch (IOException e) {
throw new RenderException(e); // rethrow any exceptions encountered
} finally {
if (neoGeoResource != null) {
HashMap<Long,Point> idMap = new HashMap<Long,Point>();
for(Node node:nodesMap.keySet()){
idMap.put(node.getId(), nodesMap.get(node));
}
getContext().getMap().getBlackboard().put(BLACKBOARD_NODE_LIST, idMap);
}
// if (geoNeo != null)
// geoNeo.close();
monitor.done();
tx.finish();
}
}
@SuppressWarnings("unchecked")
private Pair<Point, Long> getStarPoint() {
Pair<Point,Long> starPoint = (Pair<Point,Long>)getContext().getLayer().getBlackboard().get(BLACKBOARD_START_ANALYSER);
return starPoint;
}
private void drawLabel(Graphics2D g, Point p, String drawString) {
TextLayout text = new TextLayout(drawString, g.getFont(), g.getFontRenderContext());
AffineTransform at = AffineTransform.getTranslateInstance(p.x, p.y);
Shape outline = text.getOutline(at);
drawSoftSurround(g, outline);
g.setPaint(surroundColor);
g.fill(outline);
g.draw(outline);
g.setPaint(labelColor);
text.draw(g, p.x, p.y);
}
private boolean findNonOverlapPosition(Set<Rectangle> labelRec, int hgt, Point p, Rectangle rect) {
boolean drawLabel = true;
if (!labelSafe(rect, labelRec)) {
drawLabel = false;
Rectangle tryRect = new Rectangle(rect);
RECT: for (int tries : new int[] {1, -1}) {
for (int shift = 0; shift != tries * (2 * hgt); shift += tries) {
tryRect.setLocation(rect.x, rect.y + shift);
if (labelSafe(tryRect,labelRec)) {
drawLabel = true;
p.y = p.y + shift;
rect.setLocation(tryRect.getLocation());
break RECT;
}
}
}
}
return drawLabel;
}
private double getDouble(Node node, String property, double def) {
Object result = node.getProperty(property, def);
if (result instanceof Integer) {
return ((Integer)result).doubleValue();
} else if (result instanceof Float) {
return ((Float)result).doubleValue();
} else if (result instanceof String) {
return Double.parseDouble((String)result);
} else {
return (Double)result;
}
}
/**
* @param sector
* @return
*/
private String getSectorName(Node sector) {
return sector.getProperty(sectorName, "").toString();
}
/**
* Gets Site name
*
* @param node geo node
* @return site name
*/
private String getSiteName(GeoNode node) {
return normalSiteName ? node.toString() : noSiteName ? "" : node.getNode().getProperty(siteName, "").toString();
}
private void drawSoftSurround(Graphics2D g, Shape outline) {
g.setPaint(new Color(surroundColor.getRed(),surroundColor.getGreen(),surroundColor.getBlue(),128));
g.translate( 1, 0); g.fill(outline);g.draw(outline);
g.translate(-1, 1); g.fill(outline);g.draw(outline);
g.translate(-1,-1); g.fill(outline);g.draw(outline);
g.translate( 1,-1); g.fill(outline);g.draw(outline);
g.translate( 0, 1);
}
private boolean labelSafe(Rectangle rect, Set<Rectangle> labelRectangles) {
for (Rectangle rectangle : labelRectangles) {
if (rectangle.intersects(rect)) {
return false;
}
}
return true;
}
/**
* draws neighbour relations
*
* @param g Graphics2D
* @param neiName name of neighbour list
* @param node serve node
* @param lineColor - line color
* @param nodesMap map of nodes
* @param type
*/
private void drawNeighbour(Graphics2D g, String neiName, Node node, Color lineColor, Map<Node, Point> nodesMap, Object type) {
g.setColor(lineColor);
Point point1 = nodesMap.get(node);
NetworkSiteType siteType=(NetworkSiteType)type;
if (point1 != null) {
for (Relationship relation : NeoUtils.getNeighbourRelations(node, neiName)) {
final Node neighNode = relation.getOtherNode(node);
if (siteType!=null){
if (!siteType.checkNode(NeoUtils.getParent(null, neighNode),null)){
continue;
}
}
Point point2 = nodesMap.get(neighNode);
if (point2 != null) {
g.drawLine(point1.x, point1.y, point2.x, point2.y);
}
}
for (Relationship relation : NeoUtils.getTransmissionRelations(node, neiName)) {
Point point2 = nodesMap.get(relation.getOtherNode(node));
if (point2 != null) {
g.drawLine(point1.x, point1.y, point2.x, point2.y);
}
}
}
}
/**
* draws neighbour relation
*
* @param g Graphics2D
* @param relation relation
* @param lineColor - line color
* @param nodesMap map of nodes
*/
private void drawRelation(Graphics2D g, Relationship relation, Color lineColor, Map<Node, Point> nodesMap) {
g.setColor(lineColor);
Point point1 = nodesMap.get(relation.getStartNode());
Point point2 = nodesMap.get(relation.getEndNode());
if (point1 != null && point2 != null) {
g.drawLine(point1.x, point1.y, point2.x, point2.y);
}
}
/**
* gets average count of geoNeo.getCount() from all resources in map
*
* @return average count
*/
private Long getAverageCount(IProgressMonitor monitor) {
long result = 0;
long count = 0;
try {
for (ILayer layer : getContext().getMap().getMapLayers()) {
if (layer.getGeoResource().canResolve(GeoNeo.class)) {
GeoNeo resource = layer.getGeoResource().resolve(GeoNeo.class, monitor);
if(resource.getGisType().equals(GisTypes.NETWORK)) {
result += resource.getCount();
count++;
}
}
}
} catch (IOException e) {
// TODO Handle IOException
NeoCorePlugin.error(e.getLocalizedMessage(), e);
return null;
}
return count == 0 ? null : result / count;
}
/**
* gets sector color
*
* @param child - sector node
* @param defColor - default value
* @return color
*/
private Color getSectorColor(Node node, Color defColor) {
Transaction tx = NeoUtils.beginTransaction();
try {
if (aggNode == null) {
return defColor;
}
Node chartNode = NeoUtils.getChartNode(node, aggNode);
if (chartNode == null) {
return defColor;
}
return new Color((Integer)chartNode.getProperty(INeoConstants.AGGREGATION_COLOR, defColor.getRGB()));
} finally {
tx.finish();
}
}
/**
* Render the sector symbols based on the point and azimuth. We simply save the graphics
* transform, then modify the graphics through the appropriate transformations (origin to site,
* and rotations for drawing the lines and arcs).
*
* @param g
* @param p
* @param azimuth
*/
private Pair<java.awt.Point, java.awt.Point> renderSector(Graphics2D g, java.awt.Point p, double azimuth, double beamwidth,
Color fillColor,
Color borderColor, int drawSize) {
Color oldColor = g.getColor();
Pair<java.awt.Point, java.awt.Point> result = null;
if(base_transform==null) base_transform = g.getTransform();
if(beamwidth<10) beamwidth = 10;
g.setTransform(base_transform);
g.translate(p.x, p.y);
int draw2 = drawSize + 3;
if (beamwidth >= CIRCLE_BEAMWIDTH) {
g.setColor(fillColor);
g.fillOval(-drawSize, -drawSize, 2 * drawSize, 2 * drawSize);
g.setColor(borderColor);
g.drawOval(-drawSize, -drawSize, 2 * drawSize, 2 * drawSize);
result = new Pair<java.awt.Point, java.awt.Point>(p, new java.awt.Point(p.x + draw2, p.y));
} else {
double angdeg = -90 + azimuth - beamwidth / 2.0;
g.rotate(Math.toRadians(angdeg));
g.setColor(fillColor);
g.fillArc(-drawSize, -drawSize, 2 * drawSize, 2 * drawSize, 0, -(int)beamwidth);
// TODO correct gets point
g.setColor(borderColor);
g.drawArc(-drawSize, -drawSize, 2 * drawSize, 2 * drawSize, 0, -(int)beamwidth);
g.drawLine(0, 0, drawSize, 0);
g.rotate(Math.toRadians(beamwidth / 2));
double xLoc = drawSize / 2;
double yLoc = 0;
AffineTransform transform = g.getTransform();
int x = (int)(transform.getScaleX() * xLoc + transform.getShearX() * yLoc + transform.getTranslateX());
int y = (int)(transform.getShearY() * xLoc + transform.getScaleY() * yLoc + transform.getTranslateY());
int x2 = (int)(transform.getScaleX() * draw2 + transform.getShearX() * yLoc + transform.getTranslateX());
int y2 = (int)(transform.getShearY() * draw2 + transform.getScaleY() * yLoc + transform.getTranslateY());
g.rotate(Math.toRadians(beamwidth / 2));
g.drawLine(0, 0, drawSize, 0);
Point result1 = new java.awt.Point(x, y);
Point result2 = new java.awt.Point(x2, y2);
result = new Pair<java.awt.Point, java.awt.Point>(result1, result2);
g.setColor(oldColor);
}
return result;
}
/**
* This one is very simple, just draw a circle at the site location.
*
* @param g
* @param p
* @param borderColor
* @param drawSize
*/
private void renderSite(Graphics2D g, java.awt.Point p, Color borderColor, Color fillColor, int drawSize, boolean drawFull, boolean drawLite, boolean selected) {
Color oldColor = g.getColor();
if (drawFull) {
if (selected)
renderSelectionGlow(g, p, drawSize * 4);
drawSize /= 4;
if (drawSize < 2) drawSize = 2;
g.setColor(fillColor);
g.fillOval(p.x - drawSize, p.y - drawSize, 2 * drawSize, 2 * drawSize);
g.setColor(borderColor);
g.drawOval(p.x - drawSize, p.y - drawSize, 2 * drawSize, 2 * drawSize);
} else if (drawLite) {
if (selected)
renderSelectionGlow(g, p, 20);
g.setColor(borderColor);
g.drawOval(p.x - 5, p.y - 5, 10, 10);
} else {
if (selected)
renderSelectionGlow(g, p, 20);
g.setColor(borderColor);
g.drawRect(p.x - 1, p.y - 1, 3, 3);
}
g.setColor(oldColor);
}
/**
* This method draws a fading glow around a point for selected site/sectors
*
* @param g
* @param p
* @param drawSize
*/
private void renderSelectionGlow(Graphics2D g, java.awt.Point p, int drawSize) {
Color highColor = new Color(COLOR_SITE_SELECTED.getRed(), COLOR_SITE_SELECTED.getGreen(), COLOR_SITE_SELECTED.getBlue(), 8);
g.setColor(highColor);
for(;drawSize > 2; drawSize *= 0.8) {
g.fillOval(p.x - drawSize, p.y - drawSize, 2 * drawSize, 2 * drawSize);
}
}
/**
* perform and draw star analyser
*
* @param context context
*/
private void drawAnalyser(Graphics2D g, Node mainNode, Point starPoint, String property, Map<Node, Point> nodesMap) {
Transaction tx = NeoServiceProvider.getProvider().getService().beginTx();
try {
if (aggNode == null) {
return;
}
Node chart = NeoUtils.getChartNode(mainNode, aggNode);
if (chart == null) {
return;
}
Point point = nodesMap.get(mainNode);
if (point != null) {
starPoint = point;
}
drawMainNode(g, mainNode, starPoint);
for (Relationship relation : chart.getRelationships(NetworkRelationshipTypes.AGGREGATE, Direction.OUTGOING)) {
Node node = relation.getOtherNode(chart);
Point nodePoint = nodesMap.get(node);
if (nodePoint != null) {
g.setColor(getLineColor(mainNode, node));
g.drawLine(starPoint.x, starPoint.y, nodePoint.x, nodePoint.y);
}
}
} finally {
tx.finish();
}
}
/**
* get Line color
*
* @param mainNiode main node
* @param node node
* @return Line color
*/
private Color getLineColor(Node mainNiode, Node node) {
return Color.BLACK;
}
/**
* get property to analyze
* @param geoNeo
*
* @return property name
*/
private String getSelectProperty(GeoNeo geoNeo) {
String result = null;
Transaction transaction = NeoServiceProvider.getProvider().getService().beginTx();
try {
result = geoNeo.getProperty(INeoConstants.PROPERTY_SELECTED_AGGREGATION, "").toString();
transaction.success();
} finally {
transaction.finish();
}
return result == null || result.isEmpty() ? null : result;
}
/**
* Draw selection of main node
*
* @param context context
* @param mainNiode main node
*/
private void drawMainNode(Graphics2D g, Node mainNode, Point point) {
g.setColor(Color.RED);
g.fillOval(point.x - 4, point.y - 4, 10, 10);
}
@Override
public void render( IProgressMonitor monitor ) throws RenderException {
Graphics2D g = getContext().getImage().createGraphics();
render(g, monitor);
}
}
| false | true | private void renderGeoNeo( Graphics2D g, IGeoResource neoGeoResource, IProgressMonitor monitor ) throws RenderException {
if (monitor == null)
monitor = new NullProgressMonitor();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
monitor.beginTask("render network sites and sectors: "+neoGeoResource.getIdentifier(), IProgressMonitor.UNKNOWN); // TODO: Get size from info
GeoNeo geoNeo = null;
// Setup default drawing parameters and thresholds (to be modified by style if found)
int drawSize=15;
int alpha = (int)(0.6*255.0);
int maxSitesLabel = 30;
int maxSitesFull = 100;
int maxSitesLite = 1000;
int maxSymbolSize = 40;
Font font = g.getFont();
int fontSize = font.getSize();
int sectorFontSize = font.getSize();
boolean scaleSectors = true;
IStyleBlackboard style = getContext().getLayer().getStyleBlackboard();
NeoStyle neostyle = (NeoStyle)style.get(NeoStyleContent.ID );
siteName = NeoStyleContent.DEF_MAIN_PROPERTY;
sectorName = NeoStyleContent.DEF_SECONDARY_PROPERTY;
if (neostyle!=null){
try {
siteColor = neostyle.getSiteFill();
fillColor=neostyle.getFill();
drawColor=neostyle.getLine();
labelColor=neostyle.getLabel();
float colSum = 0.0f;
for(float comp: labelColor.getRGBColorComponents(null)){
colSum += comp;
}
if(colSum>2.0) {
surroundColor=Color.DARK_GRAY;
} else {
surroundColor=Color.WHITE;
}
drawSize = neostyle.getSymbolSize();
alpha = 255 - (int)((double)neostyle.getSymbolTransparency() / 100.0 * 255.0);
maxSitesLabel = neostyle.getLabeling();
maxSitesFull = neostyle.getSmallSymb();
maxSitesLite = neostyle.getSmallestSymb();
scaleSectors = !neostyle.isFixSymbolSize();
maxSymbolSize = neostyle.getMaximumSymbolSize();
fontSize = neostyle.getFontSize();
sectorFontSize = neostyle.getSecondaryFontSize();
siteName = neostyle.getMainProperty();
sectorName = neostyle.getSecondaryProperty();
} catch (Exception e) {
//TODO: we can get here if an old style exists, and we have added new fields
}
}
normalSiteName = NeoStyleContent.DEF_MAIN_PROPERTY.equals(siteName);
noSiteName = !normalSiteName && NeoStyleContent.DEF_SECONDARY_PROPERTY.equals(siteName);
sectorLabeling = !NeoStyleContent.DEF_SECONDARY_PROPERTY.equals(sectorName);
g.setFont(font.deriveFont((float)fontSize));
lineColor = new Color(drawColor.getRed(), drawColor.getGreen(), drawColor.getBlue(), alpha);
siteColor = new Color(siteColor.getRed(), siteColor.getGreen(), siteColor.getBlue(), alpha);
fillColor = new Color(fillColor.getRed(), fillColor.getGreen(), fillColor.getBlue(), alpha);
Map<Node, java.awt.Point> nodesMap = new HashMap<Node, java.awt.Point>();
Map<Node, java.awt.Point> sectorMap = new HashMap<Node, java.awt.Point>();
Map<Point, String> labelsMap = new HashMap<Point, String>();
GraphDatabaseService neo = NeoServiceProvider.getProvider().getService();
Transaction tx = neo.beginTx();
NeoUtils.addTransactionLog(tx, Thread.currentThread(), "render Network");
try {
monitor.subTask("connecting");
geoNeo = neoGeoResource.resolve(GeoNeo.class, new SubProgressMonitor(monitor, 10));
System.out.println("NetworkRenderer resolved geoNeo '"+geoNeo.getName()+"' from resource: "+neoGeoResource.getIdentifier());
filterSectors = FilterUtil.getFilterOfData(geoNeo.getMainGisNode(), neo);
filterSites = FilterUtil.getFilterOfData(geoNeo.getMainGisNode().getSingleRelationship(GeoNeoRelationshipTypes.NEXT, Direction.OUTGOING).getOtherNode(geoNeo.getMainGisNode()), neo);
String starProperty = getSelectProperty(geoNeo);
Pair<Point, Long> starPoint = getStarPoint();
Node starNode = null;
if(starPoint != null) {
System.out.println("Have star selection: "+starPoint);
}
ArrayList<Pair<String,Integer>> multiOmnis = new ArrayList<Pair<String,Integer>>();
aggNode = geoNeo.getAggrNode();
setCrsTransforms(neoGeoResource.getInfo(null).getCRS());
Envelope bounds_transformed = getTransformedBounds();
Envelope data_bounds = geoNeo.getBounds();
boolean drawFull = true;
boolean drawLite = true;
boolean drawLabels = true;
if (bounds_transformed == null) {
drawFull = false;
drawLite = false;
drawLabels = false;
}else if (data_bounds != null && data_bounds.getHeight()>0 && data_bounds.getWidth()>0) {
double dataScaled = (bounds_transformed.getHeight() * bounds_transformed.getWidth())
/ (data_bounds.getHeight() * data_bounds.getWidth());
long count = geoNeo.getCount();
if (NeoLoaderPlugin.getDefault().getPreferenceStore().getBoolean(DataLoadPreferences.NETWORK_COMBINED_CALCULATION)) {
count = getAverageCount(monitor);
}
double countScaled = dataScaled * count;
drawLabels = countScaled < maxSitesLabel;
drawFull = countScaled < maxSitesFull;
drawLite = countScaled < maxSitesLite;
if (drawFull && scaleSectors) {
drawSize *= Math.sqrt(maxSitesFull) / (3 * Math.sqrt(countScaled));
drawSize = Math.min(drawSize, maxSymbolSize);
}
// expand the boundary to include sites just out of view (so partial sectors can be see)
bounds_transformed.expandBy(0.75 * (bounds_transformed.getHeight() + bounds_transformed.getWidth()));
}
g.setColor(drawColor);
int count = 0;
monitor.subTask("drawing");
Coordinate world_location = new Coordinate(); // single object for re-use in transform below (minimize object creation)
// draw selection
java.awt.Point prev_p = null;
java.awt.Point prev_l_p = null;
ArrayList<Node> selectedPoints = new ArrayList<Node>();
final Set<Node> selectedNodes = new HashSet<Node>(geoNeo.getSelectedNodes());
final ReturnableEvaluator returnableEvaluator = new ReturnableEvaluator() {
@Override
public boolean isReturnableNode(TraversalPosition currentPos) {
final Object property = currentPos.currentNode().getProperty("type", "");
return "site".equals(property)||"probe".equals(property);
}
};
for (Node node : selectedNodes) {
final String nodeType = NeoUtils.getNodeType(node, "");
if ("network".equals(nodeType)) {
// Select all 'site' nodes in that file
for (Node rnode : node
.traverse(Order.DEPTH_FIRST, StopEvaluator.END_OF_GRAPH, returnableEvaluator, GeoNeoRelationshipTypes.NEXT, Direction.OUTGOING, NetworkRelationshipTypes.CHILD, Direction.OUTGOING)) {
selectedPoints.add(rnode);
}
} else if ("city".equals(nodeType) || "bsc".equals(nodeType)) {
for (Node rnode : node.traverse(Order.DEPTH_FIRST, StopEvaluator.END_OF_GRAPH,
returnableEvaluator, NetworkRelationshipTypes.CHILD, Direction.OUTGOING)) {
selectedPoints.add(rnode);
}
} else {
// Traverse backwards on CHILD relations to closest 'mp' Point
for (@SuppressWarnings("unused")
Node rnode : node.traverse(Order.DEPTH_FIRST, new StopEvaluator() {
@Override
public boolean isStopNode(TraversalPosition currentPos) {
return "site".equals(currentPos.currentNode().getProperty("type", ""));
}
}, new ReturnableEvaluator() {
@Override
public boolean isReturnableNode(TraversalPosition currentPos) {
return "site".equals(currentPos.currentNode().getProperty("type", ""));
}
}, NetworkRelationshipTypes.CHILD, Direction.INCOMING)) {
selectedPoints.add(rnode);
break;
}
}
}
// Now draw the selected points highlights
//TODO remove double selection?
for (Node rnode : selectedPoints) {
GeoNode node = new GeoNode(rnode);
Coordinate location = node.getCoordinate();
if (location == null) {
continue;
}
if (bounds_transformed != null && !bounds_transformed.contains(location)) {
continue; // Don't draw points outside viewport
}
if (filterSites != null) {
if (!filterSites.filterNode(node.getNode()).isValid()) {
continue;
}
}
try {
JTS.transform(location, world_location, transform_d2w);
} catch (Exception e) {
continue;
}
java.awt.Point p = getContext().worldToPixel(world_location);
if (prev_p != null && prev_p.x == p.x && prev_p.y == p.y) {
prev_p = p;
continue;
} else {
prev_p = p;
}
renderSelectionGlow(g, p, drawSize * 4);
}
g.setColor(drawColor);
long startTime = System.currentTimeMillis();
for(GeoNode node:geoNeo.getGeoNodes(bounds_transformed)) {
if (filterSites != null) {
if (!filterSites.filterNode(node.getNode()).isValid()) {
continue;
}
}
Coordinate location = node.getCoordinate();
if (bounds_transformed != null && !bounds_transformed.contains(location)) {
continue; // Don't draw points outside viewport
}
try {
JTS.transform(location, world_location, transform_d2w);
} catch (Exception e) {
//JTS.transform(location, world_location, transform_w2d.inverse());
}
java.awt.Point p = getContext().worldToPixel(world_location);
Color borderColor = g.getColor();
boolean selected = false;
if (geoNeo.getSelectedNodes().contains(node.getNode())) {
borderColor = COLOR_SITE_SELECTED;
// if selection exist - do not necessary to select node again
selected = false;
} else {
// if selection exist - do not necessary to select node again
selected = !selectedPoints.contains(node.getNode());
// this selection was already checked
// for (Node rnode:node.getNode().traverse(Traverser.Order.BREADTH_FIRST,
// StopEvaluator.DEPTH_ONE, ReturnableEvaluator.ALL_BUT_START_NODE,
// NetworkRelationshipTypes.CHILD, Direction.BOTH)){
// if (geoNeo.getSelectedNodes().contains(rnode)) {
// selected = true;
// break;
// }
// }
if (selected) {
selected = false;
DELTA_LOOP: for (Node rnode:node.getNode().traverse(Order.DEPTH_FIRST, StopEvaluator.DEPTH_ONE, ReturnableEvaluator.ALL_BUT_START_NODE, NetworkRelationshipTypes.MISSING, Direction.INCOMING, NetworkRelationshipTypes.DIFFERENT, Direction.INCOMING)){
if (geoNeo.getSelectedNodes().contains(rnode)) {
selected = true;
break;
} else {
for (Node xnode:rnode.traverse(Order.BREADTH_FIRST, new StopEvaluator(){
@Override
public boolean isStopNode(TraversalPosition currentPos) {
return "delta_report".equals(currentPos.currentNode().getProperty("type",""));
}}, ReturnableEvaluator.ALL_BUT_START_NODE, NetworkRelationshipTypes.CHILD, Direction.INCOMING)){
if (geoNeo.getSelectedNodes().contains(xnode)) {
selected = true;
break DELTA_LOOP;
}
}
}
}
}
}
renderSite(g, p, borderColor, siteColor, drawSize, drawFull, drawLite, selected);
nodesMap.put(node.getNode(), p);
if (drawFull) {
int countOmnis = 0;
double[] label_position_angles = new double[] {0, 90};
try {
int s = 0;
for (Relationship relationship : node.getNode().getRelationships(NetworkRelationshipTypes.CHILD, Direction.OUTGOING)) {
Node child = relationship.getEndNode();
if (child.hasProperty("type") && child.getProperty("type").toString().equals("sector")) {
double azimuth = getDouble(child, "azimuth", Double.NaN);
double beamwidth = Double.NaN;
if (azimuth == Double.NaN) {
beamwidth = getDouble(child, "beamwidth", CIRCLE_BEAMWIDTH);
if(beamwidth<CIRCLE_BEAMWIDTH){
azimuth = 0;
System.err.println("Error in render GeoNeo: azimuth is defined, but beamwidth less than "+CIRCLE_BEAMWIDTH);
}
}else{
beamwidth = getDouble(child, "beamwidth", DRFAULT_BEAMWIDTH);
}
Color colorToFill = getSectorColor(child, fillColor);
borderColor = drawColor;
if (starPoint != null && starPoint.right().equals(child.getId())) {
borderColor = COLOR_SECTOR_STAR;
starNode = child;
} else
if (geoNeo.getSelectedNodes().contains(child)) {
borderColor = COLOR_SECTOR_SELECTED;
}
// put sector information in to blackboard
if (filterSectors != null) {
if (!filterSectors.filterNode(child).isValid()) {
continue;
}
}
Pair<Point, Point> centerPoint = renderSector(g, p, azimuth, beamwidth, colorToFill, borderColor, drawSize);
nodesMap.put(child, centerPoint.getLeft());
if (sectorLabeling){
sectorMap.put(child, centerPoint.getRight());
}
if (s < label_position_angles.length) {
label_position_angles[s] = azimuth;
}
// g.setColor(drawColor);
// g.rotate(-Math.toRadians(beamwidth/2));
// g.drawString(sector.getString("name"),drawSize,0);
if(beamwidth==CIRCLE_BEAMWIDTH) countOmnis++;
s++;
}
}
} finally {
if (base_transform != null) {
// recover the normal transform
g.setTransform(base_transform);
g.setColor(drawColor);
}
}
if (base_transform != null) {
g.setTransform(base_transform);
}
String drawString = getSiteName(node);
if (countOmnis>1) {
//System.err.println("Site "+node+" had "+countOmnis+" omni antennas");
multiOmnis.add(new Pair<String, Integer>(drawString, countOmnis));
}
if (drawLabels) {
labelsMap.put(p, drawString);
}
}
monitor.worked(1);
count++;
if (monitor.isCanceled())
break;
}
if (drawLabels && labelsMap.size() > 0) {
Set<Rectangle> labelRec = new HashSet<Rectangle>();
FontMetrics metrics = g.getFontMetrics(font);
// get the height of a line of text in this font and render context
int hgt = metrics.getHeight();
for(Point p: labelsMap.keySet()) {
String drawString = labelsMap.get(p);
int label_x = drawSize > 15 ? 15 : drawSize;
int label_y = hgt / 3;
p = new Point(p.x + label_x, p.y + label_y);
// get the advance of my text in this font and render context
int adv = metrics.stringWidth(drawString);
// calculate the size of a box to hold the text with some padding.
Rectangle rect = new Rectangle(p.x -1 , p.y - hgt + 1, adv + 2, hgt + 2);
boolean drawsLabel = findNonOverlapPosition(labelRec, hgt, p, rect);
if (drawsLabel && !drawString.isEmpty()) {
labelRec.add(rect);
drawLabel(g, p, drawString);
}
}
// draw sector name
if (sectorLabeling) {
Font fontOld = g.getFont();
Font fontSector = fontOld.deriveFont((float)sectorFontSize);
g.setFont(fontSector);
FontMetrics metric = g.getFontMetrics(fontSector);
hgt = metrics.getHeight();
int h = hgt / 3;
for (Node sector : nodesMap.keySet()) {
String name = getSectorName(sector);
if (name.isEmpty()) {
continue;
}
int w = metric.stringWidth(name);
Point pSector = nodesMap.get(sector);
Point endLine = sectorMap.get(sector);
// calculate p
int x = (endLine.x < pSector.x) ? endLine.x - w : endLine.x;
int y = (endLine.y < pSector.y) ? endLine.y - h : endLine.y;
Point p = new Point(x, y);
// get the advance of my text in this font and render context
int adv = metrics.stringWidth(name);
// calculate the size of a box to hold the text with some padding.
Rectangle rect = new Rectangle(p.x -1 , p.y - hgt + 1, adv + 2, hgt + 2);
boolean drawsLabel = findNonOverlapPosition(labelRec, hgt, p, rect);
if (drawsLabel) {
labelRec.add(rect);
drawLabel(g, p, name);
}
}
g.setFont(fontOld);
}
}
if(multiOmnis.size()>0){
//TODO: Move this to utility class
StringBuffer sb = new StringBuffer();
int llen=0;
for (Pair<String, Integer> pair : multiOmnis) {
if (sb.length() > 1)
sb.append(", ");
else
sb.append("\t");
if (sb.length() > 100 + llen) {
llen = sb.length();
sb.append("\n\t");
}
sb.append(pair.left()).append(":").append(pair.right());
if (sb.length() > 1000)
break;
}
System.err.println("There were "+multiOmnis.size()+" sites with more than one omni antenna: ");
System.err.println(sb.toString());
}
if (starNode != null && starProperty != null) {
drawAnalyser(g, starNode, starPoint.left(), starProperty, nodesMap);
}
String neiName = (String)geoNeo.getProperties(GeoNeo.NEIGH_NAME);
if (neiName != null) {
Object properties = geoNeo.getProperties(GeoNeo.NEIGH_RELATION);
if (properties != null) {
drawRelation(g, (Relationship)properties, lineColor, nodesMap);
}
properties = geoNeo.getProperties(GeoNeo.NEIGH_MAIN_NODE);
Object type=geoNeo.getProperties(GeoNeo.NEIGH_TYPE);
if (properties != null) {
drawNeighbour(g, neiName, (Node)properties, lineColor, nodesMap,type);
}
}
System.out.println("Network renderer took " + ((System.currentTimeMillis() - startTime) / 1000.0) + "s to draw " + count + " sites from "+neoGeoResource.getIdentifier());
tx.success();
} catch (TransformException e) {
throw new RenderException(e);
} catch (FactoryException e) {
throw new RenderException(e);
} catch (IOException e) {
throw new RenderException(e); // rethrow any exceptions encountered
} finally {
if (neoGeoResource != null) {
HashMap<Long,Point> idMap = new HashMap<Long,Point>();
for(Node node:nodesMap.keySet()){
idMap.put(node.getId(), nodesMap.get(node));
}
getContext().getMap().getBlackboard().put(BLACKBOARD_NODE_LIST, idMap);
}
// if (geoNeo != null)
// geoNeo.close();
monitor.done();
tx.finish();
}
}
| private void renderGeoNeo( Graphics2D g, IGeoResource neoGeoResource, IProgressMonitor monitor ) throws RenderException {
if (monitor == null)
monitor = new NullProgressMonitor();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
monitor.beginTask("render network sites and sectors: "+neoGeoResource.getIdentifier(), IProgressMonitor.UNKNOWN); // TODO: Get size from info
GeoNeo geoNeo = null;
// Setup default drawing parameters and thresholds (to be modified by style if found)
int drawSize=15;
int alpha = (int)(0.6*255.0);
int maxSitesLabel = 30;
int maxSitesFull = 100;
int maxSitesLite = 1000;
int maxSymbolSize = 40;
Font font = g.getFont();
int fontSize = font.getSize();
int sectorFontSize = font.getSize();
boolean scaleSectors = true;
IStyleBlackboard style = getContext().getLayer().getStyleBlackboard();
NeoStyle neostyle = (NeoStyle)style.get(NeoStyleContent.ID );
siteName = NeoStyleContent.DEF_MAIN_PROPERTY;
sectorName = NeoStyleContent.DEF_SECONDARY_PROPERTY;
if (neostyle!=null){
try {
siteColor = neostyle.getSiteFill();
fillColor=neostyle.getFill();
drawColor=neostyle.getLine();
labelColor=neostyle.getLabel();
float colSum = 0.0f;
for(float comp: labelColor.getRGBColorComponents(null)){
colSum += comp;
}
if(colSum>2.0) {
surroundColor=Color.DARK_GRAY;
} else {
surroundColor=Color.WHITE;
}
drawSize = neostyle.getSymbolSize();
alpha = 255 - (int)((double)neostyle.getSymbolTransparency() / 100.0 * 255.0);
maxSitesLabel = neostyle.getLabeling();
maxSitesFull = neostyle.getSmallSymb();
maxSitesLite = neostyle.getSmallestSymb();
scaleSectors = !neostyle.isFixSymbolSize();
maxSymbolSize = neostyle.getMaximumSymbolSize();
fontSize = neostyle.getFontSize();
sectorFontSize = neostyle.getSecondaryFontSize();
siteName = neostyle.getMainProperty();
sectorName = neostyle.getSecondaryProperty();
} catch (Exception e) {
//TODO: we can get here if an old style exists, and we have added new fields
}
}
normalSiteName = NeoStyleContent.DEF_MAIN_PROPERTY.equals(siteName);
noSiteName = !normalSiteName && NeoStyleContent.DEF_SECONDARY_PROPERTY.equals(siteName);
sectorLabeling = !NeoStyleContent.DEF_SECONDARY_PROPERTY.equals(sectorName);
g.setFont(font.deriveFont((float)fontSize));
lineColor = new Color(drawColor.getRed(), drawColor.getGreen(), drawColor.getBlue(), alpha);
siteColor = new Color(siteColor.getRed(), siteColor.getGreen(), siteColor.getBlue(), alpha);
fillColor = new Color(fillColor.getRed(), fillColor.getGreen(), fillColor.getBlue(), alpha);
Map<Node, java.awt.Point> nodesMap = new HashMap<Node, java.awt.Point>();
Map<Node, java.awt.Point> sectorMap = new HashMap<Node, java.awt.Point>();
Map<Point, String> labelsMap = new HashMap<Point, String>();
GraphDatabaseService neo = NeoServiceProvider.getProvider().getService();
Transaction tx = neo.beginTx();
NeoUtils.addTransactionLog(tx, Thread.currentThread(), "render Network");
try {
monitor.subTask("connecting");
geoNeo = neoGeoResource.resolve(GeoNeo.class, new SubProgressMonitor(monitor, 10));
System.out.println("NetworkRenderer resolved geoNeo '"+geoNeo.getName()+"' from resource: "+neoGeoResource.getIdentifier());
filterSectors = FilterUtil.getFilterOfData(geoNeo.getMainGisNode(), neo);
filterSites = FilterUtil.getFilterOfData(geoNeo.getMainGisNode().getSingleRelationship(GeoNeoRelationshipTypes.NEXT, Direction.OUTGOING).getOtherNode(geoNeo.getMainGisNode()), neo);
String starProperty = getSelectProperty(geoNeo);
Pair<Point, Long> starPoint = getStarPoint();
Node starNode = null;
if(starPoint != null) {
System.out.println("Have star selection: "+starPoint);
}
ArrayList<Pair<String,Integer>> multiOmnis = new ArrayList<Pair<String,Integer>>();
aggNode = geoNeo.getAggrNode();
setCrsTransforms(neoGeoResource.getInfo(null).getCRS());
Envelope bounds_transformed = getTransformedBounds();
Envelope data_bounds = geoNeo.getBounds();
boolean drawFull = true;
boolean drawLite = true;
boolean drawLabels = true;
if (bounds_transformed == null) {
drawFull = false;
drawLite = false;
drawLabels = false;
}else if (data_bounds != null && data_bounds.getHeight()>0 && data_bounds.getWidth()>0) {
double dataScaled = (bounds_transformed.getHeight() * bounds_transformed.getWidth())
/ (data_bounds.getHeight() * data_bounds.getWidth());
long count = geoNeo.getCount();
if (NeoLoaderPlugin.getDefault().getPreferenceStore().getBoolean(DataLoadPreferences.NETWORK_COMBINED_CALCULATION)) {
count = getAverageCount(monitor);
}
double countScaled = dataScaled * count;
drawLabels = countScaled < maxSitesLabel;
drawFull = countScaled < maxSitesFull;
drawLite = countScaled < maxSitesLite;
if (drawFull && scaleSectors) {
drawSize *= Math.sqrt(maxSitesFull) / (3 * Math.sqrt(countScaled));
drawSize = Math.min(drawSize, maxSymbolSize);
}
// expand the boundary to include sites just out of view (so partial sectors can be see)
bounds_transformed.expandBy(0.75 * (bounds_transformed.getHeight() + bounds_transformed.getWidth()));
}
g.setColor(drawColor);
int count = 0;
monitor.subTask("drawing");
Coordinate world_location = new Coordinate(); // single object for re-use in transform below (minimize object creation)
// draw selection
java.awt.Point prev_p = null;
java.awt.Point prev_l_p = null;
ArrayList<Node> selectedPoints = new ArrayList<Node>();
final Set<Node> selectedNodes = new HashSet<Node>(geoNeo.getSelectedNodes());
final ReturnableEvaluator returnableEvaluator = new ReturnableEvaluator() {
@Override
public boolean isReturnableNode(TraversalPosition currentPos) {
final Object property = currentPos.currentNode().getProperty("type", "");
return "site".equals(property)||"probe".equals(property);
}
};
for (Node node : selectedNodes) {
final String nodeType = NeoUtils.getNodeType(node, "");
if ("network".equals(nodeType)) {
// Select all 'site' nodes in that file
for (Node rnode : node
.traverse(Order.DEPTH_FIRST, StopEvaluator.END_OF_GRAPH, returnableEvaluator, GeoNeoRelationshipTypes.NEXT, Direction.OUTGOING, NetworkRelationshipTypes.CHILD, Direction.OUTGOING)) {
selectedPoints.add(rnode);
}
} else if ("city".equals(nodeType) || "bsc".equals(nodeType)) {
for (Node rnode : node.traverse(Order.DEPTH_FIRST, StopEvaluator.END_OF_GRAPH,
returnableEvaluator, NetworkRelationshipTypes.CHILD, Direction.OUTGOING)) {
selectedPoints.add(rnode);
}
} else {
// Traverse backwards on CHILD relations to closest 'mp' Point
for (@SuppressWarnings("unused")
Node rnode : node.traverse(Order.DEPTH_FIRST, new StopEvaluator() {
@Override
public boolean isStopNode(TraversalPosition currentPos) {
return "site".equals(currentPos.currentNode().getProperty("type", ""));
}
}, new ReturnableEvaluator() {
@Override
public boolean isReturnableNode(TraversalPosition currentPos) {
return "site".equals(currentPos.currentNode().getProperty("type", ""));
}
}, NetworkRelationshipTypes.CHILD, Direction.INCOMING)) {
selectedPoints.add(rnode);
break;
}
}
}
// Now draw the selected points highlights
//TODO remove double selection?
for (Node rnode : selectedPoints) {
GeoNode node = new GeoNode(rnode);
Coordinate location = node.getCoordinate();
if (location == null) {
continue;
}
if (bounds_transformed != null && !bounds_transformed.contains(location)) {
continue; // Don't draw points outside viewport
}
if (filterSites != null) {
if (!filterSites.filterNode(node.getNode()).isValid()) {
continue;
}
}
try {
JTS.transform(location, world_location, transform_d2w);
} catch (Exception e) {
continue;
}
java.awt.Point p = getContext().worldToPixel(world_location);
if (prev_p != null && prev_p.x == p.x && prev_p.y == p.y) {
prev_p = p;
continue;
} else {
prev_p = p;
}
renderSelectionGlow(g, p, drawSize * 4);
}
g.setColor(drawColor);
long startTime = System.currentTimeMillis();
for(GeoNode node:geoNeo.getGeoNodes(bounds_transformed)) {
if (filterSites != null) {
if (!filterSites.filterNode(node.getNode()).isValid()) {
continue;
}
}
Coordinate location = node.getCoordinate();
if (bounds_transformed != null && !bounds_transformed.contains(location)) {
continue; // Don't draw points outside viewport
}
try {
JTS.transform(location, world_location, transform_d2w);
} catch (Exception e) {
//JTS.transform(location, world_location, transform_w2d.inverse());
}
java.awt.Point p = getContext().worldToPixel(world_location);
Color borderColor = g.getColor();
boolean selected = false;
if (geoNeo.getSelectedNodes().contains(node.getNode())) {
borderColor = COLOR_SITE_SELECTED;
// if selection exist - do not necessary to select node again
selected = false;
} else {
// if selection exist - do not necessary to select node again
selected = !selectedPoints.contains(node.getNode());
// this selection was already checked
// for (Node rnode:node.getNode().traverse(Traverser.Order.BREADTH_FIRST,
// StopEvaluator.DEPTH_ONE, ReturnableEvaluator.ALL_BUT_START_NODE,
// NetworkRelationshipTypes.CHILD, Direction.BOTH)){
// if (geoNeo.getSelectedNodes().contains(rnode)) {
// selected = true;
// break;
// }
// }
if (selected) {
selected = false;
DELTA_LOOP: for (Node rnode:node.getNode().traverse(Order.DEPTH_FIRST, StopEvaluator.DEPTH_ONE, ReturnableEvaluator.ALL_BUT_START_NODE, NetworkRelationshipTypes.MISSING, Direction.INCOMING, NetworkRelationshipTypes.DIFFERENT, Direction.INCOMING)){
if (geoNeo.getSelectedNodes().contains(rnode)) {
selected = true;
break;
} else {
for (Node xnode:rnode.traverse(Order.BREADTH_FIRST, new StopEvaluator(){
@Override
public boolean isStopNode(TraversalPosition currentPos) {
return "delta_report".equals(currentPos.currentNode().getProperty("type",""));
}}, ReturnableEvaluator.ALL_BUT_START_NODE, NetworkRelationshipTypes.CHILD, Direction.INCOMING)){
if (geoNeo.getSelectedNodes().contains(xnode)) {
selected = true;
break DELTA_LOOP;
}
}
}
}
}
}
renderSite(g, p, borderColor, siteColor, drawSize, drawFull, drawLite, selected);
nodesMap.put(node.getNode(), p);
if (drawFull) {
int countOmnis = 0;
double[] label_position_angles = new double[] {0, 90};
try {
int s = 0;
for (Relationship relationship : node.getNode().getRelationships(NetworkRelationshipTypes.CHILD, Direction.OUTGOING)) {
Node child = relationship.getEndNode();
if (child.hasProperty("type") && child.getProperty("type").toString().equals("sector")) {
Double azimuth = getDouble(child, "azimuth", Double.NaN);
Double beamwidth = Double.NaN;
if (azimuth.equals(Double.NaN)) {
beamwidth = getDouble(child, "beamwidth", CIRCLE_BEAMWIDTH);
if(beamwidth<CIRCLE_BEAMWIDTH){
azimuth = 0.0;
System.err.println("Error in render GeoNeo: azimuth is defined, but beamwidth less than "+CIRCLE_BEAMWIDTH);
}
}else{
beamwidth = getDouble(child, "beamwidth", DRFAULT_BEAMWIDTH);
}
Color colorToFill = getSectorColor(child, fillColor);
borderColor = drawColor;
if (starPoint != null && starPoint.right().equals(child.getId())) {
borderColor = COLOR_SECTOR_STAR;
starNode = child;
} else
if (geoNeo.getSelectedNodes().contains(child)) {
borderColor = COLOR_SECTOR_SELECTED;
}
// put sector information in to blackboard
if (filterSectors != null) {
if (!filterSectors.filterNode(child).isValid()) {
continue;
}
}
Pair<Point, Point> centerPoint = renderSector(g, p, azimuth, beamwidth, colorToFill, borderColor, drawSize);
nodesMap.put(child, centerPoint.getLeft());
if (sectorLabeling){
sectorMap.put(child, centerPoint.getRight());
}
if (s < label_position_angles.length) {
label_position_angles[s] = azimuth;
}
// g.setColor(drawColor);
// g.rotate(-Math.toRadians(beamwidth/2));
// g.drawString(sector.getString("name"),drawSize,0);
if(beamwidth==CIRCLE_BEAMWIDTH) countOmnis++;
s++;
}
}
} finally {
if (base_transform != null) {
// recover the normal transform
g.setTransform(base_transform);
g.setColor(drawColor);
}
}
if (base_transform != null) {
g.setTransform(base_transform);
}
String drawString = getSiteName(node);
if (countOmnis>1) {
//System.err.println("Site "+node+" had "+countOmnis+" omni antennas");
multiOmnis.add(new Pair<String, Integer>(drawString, countOmnis));
}
if (drawLabels) {
labelsMap.put(p, drawString);
}
}
monitor.worked(1);
count++;
if (monitor.isCanceled())
break;
}
if (drawLabels && labelsMap.size() > 0) {
Set<Rectangle> labelRec = new HashSet<Rectangle>();
FontMetrics metrics = g.getFontMetrics(font);
// get the height of a line of text in this font and render context
int hgt = metrics.getHeight();
for(Point p: labelsMap.keySet()) {
String drawString = labelsMap.get(p);
int label_x = drawSize > 15 ? 15 : drawSize;
int label_y = hgt / 3;
p = new Point(p.x + label_x, p.y + label_y);
// get the advance of my text in this font and render context
int adv = metrics.stringWidth(drawString);
// calculate the size of a box to hold the text with some padding.
Rectangle rect = new Rectangle(p.x -1 , p.y - hgt + 1, adv + 2, hgt + 2);
boolean drawsLabel = findNonOverlapPosition(labelRec, hgt, p, rect);
if (drawsLabel && !drawString.isEmpty()) {
labelRec.add(rect);
drawLabel(g, p, drawString);
}
}
// draw sector name
if (sectorLabeling) {
Font fontOld = g.getFont();
Font fontSector = fontOld.deriveFont((float)sectorFontSize);
g.setFont(fontSector);
FontMetrics metric = g.getFontMetrics(fontSector);
hgt = metrics.getHeight();
int h = hgt / 3;
for (Node sector : nodesMap.keySet()) {
String name = getSectorName(sector);
if (name.isEmpty()) {
continue;
}
int w = metric.stringWidth(name);
Point pSector = nodesMap.get(sector);
Point endLine = sectorMap.get(sector);
// calculate p
int x = (endLine.x < pSector.x) ? endLine.x - w : endLine.x;
int y = (endLine.y < pSector.y) ? endLine.y - h : endLine.y;
Point p = new Point(x, y);
// get the advance of my text in this font and render context
int adv = metrics.stringWidth(name);
// calculate the size of a box to hold the text with some padding.
Rectangle rect = new Rectangle(p.x -1 , p.y - hgt + 1, adv + 2, hgt + 2);
boolean drawsLabel = findNonOverlapPosition(labelRec, hgt, p, rect);
if (drawsLabel) {
labelRec.add(rect);
drawLabel(g, p, name);
}
}
g.setFont(fontOld);
}
}
if(multiOmnis.size()>0){
//TODO: Move this to utility class
StringBuffer sb = new StringBuffer();
int llen=0;
for (Pair<String, Integer> pair : multiOmnis) {
if (sb.length() > 1)
sb.append(", ");
else
sb.append("\t");
if (sb.length() > 100 + llen) {
llen = sb.length();
sb.append("\n\t");
}
sb.append(pair.left()).append(":").append(pair.right());
if (sb.length() > 1000)
break;
}
System.err.println("There were "+multiOmnis.size()+" sites with more than one omni antenna: ");
System.err.println(sb.toString());
}
if (starNode != null && starProperty != null) {
drawAnalyser(g, starNode, starPoint.left(), starProperty, nodesMap);
}
String neiName = (String)geoNeo.getProperties(GeoNeo.NEIGH_NAME);
if (neiName != null) {
Object properties = geoNeo.getProperties(GeoNeo.NEIGH_RELATION);
if (properties != null) {
drawRelation(g, (Relationship)properties, lineColor, nodesMap);
}
properties = geoNeo.getProperties(GeoNeo.NEIGH_MAIN_NODE);
Object type=geoNeo.getProperties(GeoNeo.NEIGH_TYPE);
if (properties != null) {
drawNeighbour(g, neiName, (Node)properties, lineColor, nodesMap,type);
}
}
System.out.println("Network renderer took " + ((System.currentTimeMillis() - startTime) / 1000.0) + "s to draw " + count + " sites from "+neoGeoResource.getIdentifier());
tx.success();
} catch (TransformException e) {
throw new RenderException(e);
} catch (FactoryException e) {
throw new RenderException(e);
} catch (IOException e) {
throw new RenderException(e); // rethrow any exceptions encountered
} finally {
if (neoGeoResource != null) {
HashMap<Long,Point> idMap = new HashMap<Long,Point>();
for(Node node:nodesMap.keySet()){
idMap.put(node.getId(), nodesMap.get(node));
}
getContext().getMap().getBlackboard().put(BLACKBOARD_NODE_LIST, idMap);
}
// if (geoNeo != null)
// geoNeo.close();
monitor.done();
tx.finish();
}
}
|
diff --git a/src/server/ClientRequestParser.java b/src/server/ClientRequestParser.java
index 252427b..b750718 100644
--- a/src/server/ClientRequestParser.java
+++ b/src/server/ClientRequestParser.java
@@ -1,165 +1,165 @@
package server;
import java.net.InetAddress;
import java.util.Date;
import org.apache.log4j.Logger;
/**
* explicitely assigned to ONE client, because running in a seperate thread
* @see ClientListener
* @author Babz
*
*/
public class ClientRequestParser {
private static final Logger LOG = Logger.getLogger(ClientRequestParser.class);
private UserManagement userMgmt = UserManagement.getInstance();
private AuctionManagement auctionMgmt = AuctionManagement.getInstance();
private String currUserName = null;
private InetAddress clientIp = null;
public ClientRequestParser(InetAddress clientIp) {
this.clientIp = clientIp;
}
public String getResponse(String clientRequest) {
String[] request = clientRequest.split("\\s");
String response = "";
//args: [0] = command, [1] = username, [2] = uspport
if(clientRequest.startsWith("!login")) {
int expectedNoOfArgs = 3;
if(currUserName != null) {
LOG.info("another user already logged in");
response = "Log out first";
} else if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: username";
} else {
String userName = request[1];
String udpPort = request[2];
response = login(userName, udpPort);
LOG.info("client request 'login' finished");
}
}
//args: [0] = command
else if(clientRequest.startsWith("!logout")) {
int expectedNoOfArgs = 1;
if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: none";
} else if(currUserName == null) {
response = "You have to log in first";
} else {
response = logout();
}
LOG.info("client request 'logout' finished");
}
//args: [0] = command; allowed for anonymus users
else if(clientRequest.startsWith("!list")) {
int expectedNoOfArgs = 1;
if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: none";
} else {
//TODO sort
response = auctionMgmt.getAllActiveAuctions();
}
LOG.info("client request 'list' finished");
}
//args: [0] = cmd, [1] = duration, [2] = description
else if(clientRequest.startsWith("!create")) {
int minExpectedNoOfArgs = 3;
if(request.length < minExpectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: duration + description";
} else if(!isAuthorized()) {
response = "You have to log in first to use this request";
} else {
int duration = Integer.parseInt(request[1]);
String description = clientRequest.substring(request[0].length()+request[1].length()+2);
response = createBid(duration, description);
}
LOG.info("client request 'create' finished");
}
//args: [0] = cmd, [1] = auction-id, [2] = amount
else if(clientRequest.startsWith("!bid")) {
int expectedNoOfArgs = 3;
int auctionId = Integer.parseInt(request[1]);
if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: auction-id + amount";
} else if(!isAuthorized()) {
response = "You have to log in first to use this request";
- } else if(currUserName.equals(auctionMgmt.getAuction(auctionId).getOwner())) {
+ } else if(auctionMgmt.getAuction(auctionId) != null && currUserName.equals(auctionMgmt.getAuction(auctionId).getOwner())) {
response = "As the auction owner you are not allowed to bid at this auction";
} else {
double amount = Double.parseDouble(request[2]);
response = bid(auctionId, amount);
}
LOG.info("client request 'bid' finished");
}
else {
response = "request couldn't be identified";
LOG.info("unidentified request");
}
return response;
}
private String login(String userName, String udpPort) {
boolean loginSuccessful = userMgmt.login(userName, udpPort, clientIp);
if(!loginSuccessful) {
return "Already logged in";
} else {
currUserName = userName;
String pendingNotifications = userMgmt.getUserByName(userName).getPendingNotifications();
if(!pendingNotifications.isEmpty()) {
auctionMgmt.sendUdpMsg(userName, pendingNotifications);
}
return "Successfully logged in as " + currUserName;
}
}
private String logout() {
boolean logoutSuccessful = userMgmt.logout(currUserName);
if(!logoutSuccessful) {
return "Log in first";
} else {
String loggedOutUser = currUserName;
currUserName = null;
return "Successfully logged out as " + loggedOutUser;
}
}
private String createBid(int duration, String description) {
int id = auctionMgmt.createAuction(currUserName, duration, description);
Date expiration = auctionMgmt.getExpiration(id);
return "An auction '" + description + "' with id " + id + " has been created and will end on " + expiration;
}
private String bid(int auctionId, double amount) {
int success = auctionMgmt.bid(auctionId, amount, currUserName);
if(success == -1) {
return "Auction not available";
} else {
Auction auction = auctionMgmt.getAuction(auctionId);
double currHighestBid = auction.getHighestBid();
if (success == 0) {
return "You unsuccesfully bid with " + amount + " on '" + auction.getDescription() + "'. Current highest bid is " + currHighestBid + ".";
} else {
return "You successfully bid with " + auction.getHighestBid() + " on '" + auction.getDescription() + "'.";
}
}
}
private boolean isAuthorized() {
if(currUserName == null) {
return false;
}
return true;
}
}
| true | true | public String getResponse(String clientRequest) {
String[] request = clientRequest.split("\\s");
String response = "";
//args: [0] = command, [1] = username, [2] = uspport
if(clientRequest.startsWith("!login")) {
int expectedNoOfArgs = 3;
if(currUserName != null) {
LOG.info("another user already logged in");
response = "Log out first";
} else if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: username";
} else {
String userName = request[1];
String udpPort = request[2];
response = login(userName, udpPort);
LOG.info("client request 'login' finished");
}
}
//args: [0] = command
else if(clientRequest.startsWith("!logout")) {
int expectedNoOfArgs = 1;
if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: none";
} else if(currUserName == null) {
response = "You have to log in first";
} else {
response = logout();
}
LOG.info("client request 'logout' finished");
}
//args: [0] = command; allowed for anonymus users
else if(clientRequest.startsWith("!list")) {
int expectedNoOfArgs = 1;
if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: none";
} else {
//TODO sort
response = auctionMgmt.getAllActiveAuctions();
}
LOG.info("client request 'list' finished");
}
//args: [0] = cmd, [1] = duration, [2] = description
else if(clientRequest.startsWith("!create")) {
int minExpectedNoOfArgs = 3;
if(request.length < minExpectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: duration + description";
} else if(!isAuthorized()) {
response = "You have to log in first to use this request";
} else {
int duration = Integer.parseInt(request[1]);
String description = clientRequest.substring(request[0].length()+request[1].length()+2);
response = createBid(duration, description);
}
LOG.info("client request 'create' finished");
}
//args: [0] = cmd, [1] = auction-id, [2] = amount
else if(clientRequest.startsWith("!bid")) {
int expectedNoOfArgs = 3;
int auctionId = Integer.parseInt(request[1]);
if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: auction-id + amount";
} else if(!isAuthorized()) {
response = "You have to log in first to use this request";
} else if(currUserName.equals(auctionMgmt.getAuction(auctionId).getOwner())) {
response = "As the auction owner you are not allowed to bid at this auction";
} else {
double amount = Double.parseDouble(request[2]);
response = bid(auctionId, amount);
}
LOG.info("client request 'bid' finished");
}
else {
response = "request couldn't be identified";
LOG.info("unidentified request");
}
return response;
}
| public String getResponse(String clientRequest) {
String[] request = clientRequest.split("\\s");
String response = "";
//args: [0] = command, [1] = username, [2] = uspport
if(clientRequest.startsWith("!login")) {
int expectedNoOfArgs = 3;
if(currUserName != null) {
LOG.info("another user already logged in");
response = "Log out first";
} else if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: username";
} else {
String userName = request[1];
String udpPort = request[2];
response = login(userName, udpPort);
LOG.info("client request 'login' finished");
}
}
//args: [0] = command
else if(clientRequest.startsWith("!logout")) {
int expectedNoOfArgs = 1;
if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: none";
} else if(currUserName == null) {
response = "You have to log in first";
} else {
response = logout();
}
LOG.info("client request 'logout' finished");
}
//args: [0] = command; allowed for anonymus users
else if(clientRequest.startsWith("!list")) {
int expectedNoOfArgs = 1;
if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: none";
} else {
//TODO sort
response = auctionMgmt.getAllActiveAuctions();
}
LOG.info("client request 'list' finished");
}
//args: [0] = cmd, [1] = duration, [2] = description
else if(clientRequest.startsWith("!create")) {
int minExpectedNoOfArgs = 3;
if(request.length < minExpectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: duration + description";
} else if(!isAuthorized()) {
response = "You have to log in first to use this request";
} else {
int duration = Integer.parseInt(request[1]);
String description = clientRequest.substring(request[0].length()+request[1].length()+2);
response = createBid(duration, description);
}
LOG.info("client request 'create' finished");
}
//args: [0] = cmd, [1] = auction-id, [2] = amount
else if(clientRequest.startsWith("!bid")) {
int expectedNoOfArgs = 3;
int auctionId = Integer.parseInt(request[1]);
if(request.length != expectedNoOfArgs) {
LOG.info("wrong no of args");
response = "expected parameter: auction-id + amount";
} else if(!isAuthorized()) {
response = "You have to log in first to use this request";
} else if(auctionMgmt.getAuction(auctionId) != null && currUserName.equals(auctionMgmt.getAuction(auctionId).getOwner())) {
response = "As the auction owner you are not allowed to bid at this auction";
} else {
double amount = Double.parseDouble(request[2]);
response = bid(auctionId, amount);
}
LOG.info("client request 'bid' finished");
}
else {
response = "request couldn't be identified";
LOG.info("unidentified request");
}
return response;
}
|
diff --git a/src/test/java/org/freeeed/main/FreeEedSmallTest.java b/src/test/java/org/freeeed/main/FreeEedSmallTest.java
index 5783ce8d..30eae93f 100644
--- a/src/test/java/org/freeeed/main/FreeEedSmallTest.java
+++ b/src/test/java/org/freeeed/main/FreeEedSmallTest.java
@@ -1,67 +1,67 @@
package org.freeeed.main;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import org.freeeed.services.FreeEedUtil;
import org.freeeed.services.Project;
import static org.junit.Assert.assertTrue;
import org.junit.*;
public class FreeEedSmallTest {
public FreeEedSmallTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testMain() {
System.out.println("testMain");
String[] args = new String[2];
args[0] = "-param_file";
args[1] = "small_test.project";
// delete output, so that the test should run
Project project = Project.loadFromFile(new File(args[1]));
try {
if (new File(project.getOutputDir()).exists()) {
Files.deleteRecursively(new File(project.getOutputDir()));
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
FreeEedMain.main(args);
// TODO - do more tests
String outputSuccess = project.getResultsDir() + "/_SUCCESS";
assertTrue(new File(outputSuccess).exists());
String metadataFile = project.getResultsDir() + File.separator;
if (PlatformUtil.getPlatform() == PlatformUtil.PLATFORM.WINDOWS) {
metadataFile += "metadata.txt";
} else {
metadataFile += "part-r-00000";
}
assertTrue(new File(metadataFile).exists());
try {
//int resultCount = Files.readLines(new File(metadataFile), Charset.defaultCharset()).size();
int resultCount = FreeEedUtil.countLines(metadataFile);
System.out.println("resultCount = " + resultCount);
- assertTrue(resultCount == 10);
+ assertTrue(resultCount == 9);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
}
| true | true | public void testMain() {
System.out.println("testMain");
String[] args = new String[2];
args[0] = "-param_file";
args[1] = "small_test.project";
// delete output, so that the test should run
Project project = Project.loadFromFile(new File(args[1]));
try {
if (new File(project.getOutputDir()).exists()) {
Files.deleteRecursively(new File(project.getOutputDir()));
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
FreeEedMain.main(args);
// TODO - do more tests
String outputSuccess = project.getResultsDir() + "/_SUCCESS";
assertTrue(new File(outputSuccess).exists());
String metadataFile = project.getResultsDir() + File.separator;
if (PlatformUtil.getPlatform() == PlatformUtil.PLATFORM.WINDOWS) {
metadataFile += "metadata.txt";
} else {
metadataFile += "part-r-00000";
}
assertTrue(new File(metadataFile).exists());
try {
//int resultCount = Files.readLines(new File(metadataFile), Charset.defaultCharset()).size();
int resultCount = FreeEedUtil.countLines(metadataFile);
System.out.println("resultCount = " + resultCount);
assertTrue(resultCount == 10);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
| public void testMain() {
System.out.println("testMain");
String[] args = new String[2];
args[0] = "-param_file";
args[1] = "small_test.project";
// delete output, so that the test should run
Project project = Project.loadFromFile(new File(args[1]));
try {
if (new File(project.getOutputDir()).exists()) {
Files.deleteRecursively(new File(project.getOutputDir()));
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
FreeEedMain.main(args);
// TODO - do more tests
String outputSuccess = project.getResultsDir() + "/_SUCCESS";
assertTrue(new File(outputSuccess).exists());
String metadataFile = project.getResultsDir() + File.separator;
if (PlatformUtil.getPlatform() == PlatformUtil.PLATFORM.WINDOWS) {
metadataFile += "metadata.txt";
} else {
metadataFile += "part-r-00000";
}
assertTrue(new File(metadataFile).exists());
try {
//int resultCount = Files.readLines(new File(metadataFile), Charset.defaultCharset()).size();
int resultCount = FreeEedUtil.countLines(metadataFile);
System.out.println("resultCount = " + resultCount);
assertTrue(resultCount == 9);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
|
diff --git a/hw/1116/counting.java b/hw/1116/counting.java
index 00ff1e8..384dd63 100644
--- a/hw/1116/counting.java
+++ b/hw/1116/counting.java
@@ -1,48 +1,48 @@
public class counting {
public static void main(String[] args) {
int quant = 100; //number of digits to generate
int range; //value of numbers generated between upper and lower
int lower = 0; //upper limit of generation
int upper = 9; //upper limit of generation
System.out.printf("\nBelow I will generate a 'random' number between %d and %d, %d times.\nThen I will calculate the occurances of each number.\n", lower, upper, quant);
//get size of range
int i;
range = 0;
for (i = lower; i <= upper; i++)
range++;
double[] counts = new double[range];
- //safe
+ //clearing out values for incrementation
for (i = lower; i <= upper; i++)
counts[i] = 0;
//generate:
java.util.Random gen = new java.util.Random();
int current, ii;
for (i = 0; i < quant; i++) {
current = gen.nextInt(range);
for (ii = lower; ii <= upper; ii++) {
if (current == ii)
counts[ii]++;
}
}
//print table
String head_title = "-- occurances of each random number -------------------------------";
String head_border = "-------------------------------------------------------------------";
System.out.printf("\n%s\n", head_title);
//loop through each number, printing the result stored in an array
for (i = lower; i <= upper; i++) {
System.out.printf("%-30d", i);
System.out.printf("%26.0f occurances\n", counts[i]);
}
String verify = "java counting | awk '/occurances$/{ sum += $2 } END { print sum }'";
System.out.printf("\nYou can verify the output of this program by running the following:\n%s\nfalconindy++ awk++\n", verify);
System.out.printf("%s\n", head_border);
}
}
| true | true | public static void main(String[] args) {
int quant = 100; //number of digits to generate
int range; //value of numbers generated between upper and lower
int lower = 0; //upper limit of generation
int upper = 9; //upper limit of generation
System.out.printf("\nBelow I will generate a 'random' number between %d and %d, %d times.\nThen I will calculate the occurances of each number.\n", lower, upper, quant);
//get size of range
int i;
range = 0;
for (i = lower; i <= upper; i++)
range++;
double[] counts = new double[range];
//safe
for (i = lower; i <= upper; i++)
counts[i] = 0;
//generate:
java.util.Random gen = new java.util.Random();
int current, ii;
for (i = 0; i < quant; i++) {
current = gen.nextInt(range);
for (ii = lower; ii <= upper; ii++) {
if (current == ii)
counts[ii]++;
}
}
//print table
String head_title = "-- occurances of each random number -------------------------------";
String head_border = "-------------------------------------------------------------------";
System.out.printf("\n%s\n", head_title);
//loop through each number, printing the result stored in an array
for (i = lower; i <= upper; i++) {
System.out.printf("%-30d", i);
System.out.printf("%26.0f occurances\n", counts[i]);
}
String verify = "java counting | awk '/occurances$/{ sum += $2 } END { print sum }'";
System.out.printf("\nYou can verify the output of this program by running the following:\n%s\nfalconindy++ awk++\n", verify);
System.out.printf("%s\n", head_border);
}
| public static void main(String[] args) {
int quant = 100; //number of digits to generate
int range; //value of numbers generated between upper and lower
int lower = 0; //upper limit of generation
int upper = 9; //upper limit of generation
System.out.printf("\nBelow I will generate a 'random' number between %d and %d, %d times.\nThen I will calculate the occurances of each number.\n", lower, upper, quant);
//get size of range
int i;
range = 0;
for (i = lower; i <= upper; i++)
range++;
double[] counts = new double[range];
//clearing out values for incrementation
for (i = lower; i <= upper; i++)
counts[i] = 0;
//generate:
java.util.Random gen = new java.util.Random();
int current, ii;
for (i = 0; i < quant; i++) {
current = gen.nextInt(range);
for (ii = lower; ii <= upper; ii++) {
if (current == ii)
counts[ii]++;
}
}
//print table
String head_title = "-- occurances of each random number -------------------------------";
String head_border = "-------------------------------------------------------------------";
System.out.printf("\n%s\n", head_title);
//loop through each number, printing the result stored in an array
for (i = lower; i <= upper; i++) {
System.out.printf("%-30d", i);
System.out.printf("%26.0f occurances\n", counts[i]);
}
String verify = "java counting | awk '/occurances$/{ sum += $2 } END { print sum }'";
System.out.printf("\nYou can verify the output of this program by running the following:\n%s\nfalconindy++ awk++\n", verify);
System.out.printf("%s\n", head_border);
}
|
diff --git a/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/MageTabCopyLSFProcess.java b/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/MageTabCopyLSFProcess.java
index c0894c9..3236b98 100644
--- a/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/MageTabCopyLSFProcess.java
+++ b/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/MageTabCopyLSFProcess.java
@@ -1,117 +1,117 @@
package uk.ac.ebi.fgpt.conan.process.biosd;
import net.sourceforge.fluxion.spi.ServiceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.fgpt.conan.lsf.AbstractLSFProcess;
import uk.ac.ebi.fgpt.conan.lsf.LSFProcess;
import uk.ac.ebi.fgpt.conan.model.ConanParameter;
import uk.ac.ebi.fgpt.conan.properties.ConanProperties;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
@ServiceProvider
public class MageTabCopyLSFProcess extends AbstractLSFProcess {
private final Collection<ConanParameter> parameters;
private final SampleTabAccessionParameter accessionParameter;
private Logger log = LoggerFactory.getLogger(getClass());
public MageTabCopyLSFProcess() {
parameters = new ArrayList<ConanParameter>();
accessionParameter = new SampleTabAccessionParameter();
parameters.add(accessionParameter);
}
private File getOutputDirectory(SampleTabAccessionParameter accession) throws IOException {
String sampletabpath = ConanProperties
.getProperty("biosamples.sampletab.path");
File sampletabAE = new File(sampletabpath, "ae");
File outdir = new File(sampletabAE, accession.getAccession());
if (!outdir.exists()) {
if (!outdir.mkdirs()) {
throw new IOException("Unable to create directories: "
+ outdir.getPath());
}
}
return outdir;
}
protected Logger getLog() {
return log;
}
public String getName() {
return "updatesourcearrayexpress";
}
public Collection<ConanParameter> getParameters() {
return parameters;
}
protected String getComponentName() {
return LSFProcess.UNSPECIFIED_COMPONENT_NAME;
}
protected String getCommand(Map<ConanParameter, String> parameters)
throws IllegalArgumentException {
getLog().debug(
"Executing " + getName() + " with the following parameters: "
+ parameters.toString());
// deal with parameters
SampleTabAccessionParameter accession = new SampleTabAccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
String sampletabpath = ConanProperties
.getProperty("biosamples.sampletab.path");
String scriptpath = ConanProperties
.getProperty("biosamples.script.path");
File script = new File(scriptpath, "MageTabFTPDownload.sh");
File outdir;
try {
outdir = getOutputDirectory(accession);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException("Unable to create directories for "+accession);
}
// main command to execute script
String mainCommand = script.getAbsolutePath() + " "
- + accession.getAccession() + " " + outdir.getAbsolutePath();
+ + accession.getAccession().substring(2) + " " + outdir.getAbsolutePath();
getLog().debug("Command is: <" + mainCommand + ">");
return mainCommand;
}
protected String getLSFOutputFilePath(Map<ConanParameter, String> parameters)
throws IllegalArgumentException {
getLog().debug(
"Executing " + getName() + " with the following parameters: "
+ parameters.toString());
// deal with parameters
SampleTabAccessionParameter accession = new SampleTabAccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
File outDir;
try {
outDir = getOutputDirectory(accession);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException("Unable to create directories for "+accession);
}
File conanDir = new File(outDir, ".conan");
File conanFile = new File(conanDir, getClass().getName());
return conanFile.getAbsolutePath();
}
}
| true | true | protected String getCommand(Map<ConanParameter, String> parameters)
throws IllegalArgumentException {
getLog().debug(
"Executing " + getName() + " with the following parameters: "
+ parameters.toString());
// deal with parameters
SampleTabAccessionParameter accession = new SampleTabAccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
String sampletabpath = ConanProperties
.getProperty("biosamples.sampletab.path");
String scriptpath = ConanProperties
.getProperty("biosamples.script.path");
File script = new File(scriptpath, "MageTabFTPDownload.sh");
File outdir;
try {
outdir = getOutputDirectory(accession);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException("Unable to create directories for "+accession);
}
// main command to execute script
String mainCommand = script.getAbsolutePath() + " "
+ accession.getAccession() + " " + outdir.getAbsolutePath();
getLog().debug("Command is: <" + mainCommand + ">");
return mainCommand;
}
| protected String getCommand(Map<ConanParameter, String> parameters)
throws IllegalArgumentException {
getLog().debug(
"Executing " + getName() + " with the following parameters: "
+ parameters.toString());
// deal with parameters
SampleTabAccessionParameter accession = new SampleTabAccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
String sampletabpath = ConanProperties
.getProperty("biosamples.sampletab.path");
String scriptpath = ConanProperties
.getProperty("biosamples.script.path");
File script = new File(scriptpath, "MageTabFTPDownload.sh");
File outdir;
try {
outdir = getOutputDirectory(accession);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException("Unable to create directories for "+accession);
}
// main command to execute script
String mainCommand = script.getAbsolutePath() + " "
+ accession.getAccession().substring(2) + " " + outdir.getAbsolutePath();
getLog().debug("Command is: <" + mainCommand + ">");
return mainCommand;
}
|
diff --git a/src/org/stathissideris/ascii2image/core/CommandLineConverter.java b/src/org/stathissideris/ascii2image/core/CommandLineConverter.java
index 0cf4de3..c4e4845 100644
--- a/src/org/stathissideris/ascii2image/core/CommandLineConverter.java
+++ b/src/org/stathissideris/ascii2image/core/CommandLineConverter.java
@@ -1,265 +1,265 @@
/*
* DiTAA - Diagrams Through Ascii Art
*
* Copyright (C) 2004 Efstathios Sideris
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
package org.stathissideris.ascii2image.core;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.imageio.ImageIO;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.stathissideris.ascii2image.graphics.BitmapRenderer;
import org.stathissideris.ascii2image.graphics.Diagram;
import org.stathissideris.ascii2image.text.TextGrid;
/**
*
* @author Efstathios Sideris
*/
public class CommandLineConverter {
private static String notice = "ditaa version 0.9, Copyright (C) 2004--2009 Efstathios (Stathis) Sideris";
private static String[] markupModeAllowedValues = {"use", "ignore", "render"};
public static void main(String[] args){
long startTime = System.currentTimeMillis();
System.out.println("\n"+notice+"\n");
Options cmdLnOptions = new Options();
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("help")
.withDescription( "Prints usage help." )
.create() );
cmdLnOptions.addOption("v", "verbose", false, "Makes ditaa more verbose.");
cmdLnOptions.addOption("o", "overwrite", false, "If the filename of the destination image already exists, an alternative name is chosen. If the overwrite option is selected, the image file is instead overwriten.");
cmdLnOptions.addOption("S", "no-shadows", false, "Turns off the drop-shadow effect.");
cmdLnOptions.addOption("A", "no-antialias", false, "Turns anti-aliasing off.");
cmdLnOptions.addOption("W", "fixed-slope", false, "Makes sides of parallelograms and trapezoids fixed slope instead of fixed width.");
cmdLnOptions.addOption("d", "debug", false, "Renders the debug grid over the resulting image.");
cmdLnOptions.addOption("r", "round-corners", false, "Causes all corners to be rendered as round corners.");
cmdLnOptions.addOption("E", "no-separation", false, "Prevents the separation of common edges of shapes.");
cmdLnOptions.addOption("h", "html", false, "In this case the input is an HTML file. The contents of the <pre class=\"textdiagram\"> tags are rendered as diagrams and saved in the images directory and a new HTML file is produced with the appropriate <img> tags.");
cmdLnOptions.addOption("T", "transparent", false, "Causes the diagram to be rendered on a transparent background. Overrides --background.");
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("encoding")
.withDescription("The encoding of the input file.")
.hasArg()
.withArgName("ENCODING")
.create('e')
);
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("scale")
.withDescription("A natural number that determines the size of the rendered image. The units are fractions of the default size (2.5 renders 1.5 times bigger than the default).")
.hasArg()
.withArgName("SCALE")
.create('s')
);
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("tabs")
.withDescription("Tabs are normally interpreted as 8 spaces but it is possible to change that using this option. It is not advisable to use tabs in your diagrams.")
.hasArg()
.withArgName("TABS")
.create('t')
);
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("background")
- .withDescription("The background colour of the image. The format should be a six-digit hexadecimal number (as in HTML, FF0000 for red). Pass an eight-digit hex to define transparency. This is overriden by --transparent.")
+ .withDescription("The background colour of the image. The format should be a six-digit hexadecimal number (as in HTML, FF0000 for red). Pass an eight-digit hex to define transparency. This is overridden by --transparent.")
.hasArg()
.withArgName("BACKGROUND")
.create('b')
);
//TODO: uncomment this for next version:
// cmdLnOptions.addOption(
// OptionBuilder.withLongOpt("config")
// .withDescription( "The shape configuration file." )
// .hasArg()
// .withArgName("CONFIG_FILE")
// .create('c') );
CommandLine cmdLine = null;
///// parse command line options
try {
// parse the command line arguments
CommandLineParser parser = new PosixParser();
cmdLine = parser.parse(cmdLnOptions, args);
// validate that block-size has been set
if( cmdLine.hasOption( "block-size" ) ) {
// print the value of block-size
System.out.println( cmdLine.getOptionValue( "block-size" ) );
}
} catch (org.apache.commons.cli.ParseException e) {
System.err.println(e.getMessage());
new HelpFormatter().printHelp("java -jar ditaa.jar <INPFILE> [OUTFILE]", cmdLnOptions, true);
System.exit(2);
}
if(cmdLine.hasOption("help") || args.length == 0 ){
new HelpFormatter().printHelp("java -jar ditaa.jar <INPFILE> [OUTFILE]", cmdLnOptions, true);
System.exit(0);
}
ConversionOptions options = null;
try {
options = new ConversionOptions(cmdLine);
} catch (UnsupportedEncodingException e2) {
System.err.println("Error: " + e2.getMessage());
System.exit(2);
} catch (IllegalArgumentException e2) {
System.err.println("Error: " + e2.getMessage());
new HelpFormatter().printHelp("java -jar ditaa.jar <INPFILE> [OUTFILE]", cmdLnOptions, true);
System.exit(2);
}
args = cmdLine.getArgs();
if(args.length == 0) {
System.err.println("Error: Please provide the input file filename");
new HelpFormatter().printHelp("java -jar ditaa.jar <inpfile> [outfile]", cmdLnOptions, true);
System.exit(2);
}
/////// print options before running
System.out.println("Running with options:");
Option[] opts = cmdLine.getOptions();
for (Option option : opts) {
if(option.hasArgs()){
for(String value:option.getValues()){
System.out.println(option.getLongOpt()+" = "+value);
}
} else if(option.hasArg()){
System.out.println(option.getLongOpt()+" = "+option.getValue());
} else {
System.out.println(option.getLongOpt());
}
}
if(cmdLine.hasOption("html")){
String filename = args[0];
boolean overwrite = false;
if(options.processingOptions.overwriteFiles()) overwrite = true;
String toFilename;
if(args.length == 1){
toFilename = FileUtils.makeTargetPathname(filename, "html", "_processed", true);
} else {
toFilename = args[1];
}
File target = new File(toFilename);
if(!overwrite && target.exists()) {
System.out.println("Error: File "+toFilename+" exists. If you would like to overwrite it, please use the --overwrite option.");
System.exit(0);
}
new HTMLConverter().convertHTMLFile(filename, toFilename, "ditaa_diagram", "images", options);
System.exit(0);
} else { //simple mode
TextGrid grid = new TextGrid();
if(options.processingOptions.getCustomShapes() != null){
grid.addToMarkupTags(options.processingOptions.getCustomShapes().keySet());
}
String filename = args[0];
System.out.println("Reading file: "+filename);
try {
if(!grid.loadFrom(filename, options.processingOptions)){
System.err.println("Cannot open file "+filename+" for reading");
}
} catch (UnsupportedEncodingException e1){
System.err.println("Error: "+e1.getMessage());
System.exit(1);
} catch (FileNotFoundException e1) {
System.err.println("Error: File "+filename+" does not exist");
System.exit(1);
} catch (IOException e1) {
System.err.println("Error: Cannot open file "+filename+" for reading");
System.exit(1);
}
if(options.processingOptions.printDebugOutput()){
System.out.println("Using grid:");
grid.printDebug();
}
boolean overwrite = false;
if(options.processingOptions.overwriteFiles()) overwrite = true;
String toFilename;
if(args.length == 1){
toFilename = FileUtils.makeTargetPathname(filename, "png", overwrite);
} else {
toFilename = args[1];
}
Diagram diagram = new Diagram(grid, options);
System.out.println("Rendering to file: "+toFilename);
RenderedImage image = new BitmapRenderer().renderToImage(diagram, options.renderingOptions);
try {
File file = new File(toFilename);
ImageIO.write(image, "png", file);
} catch (IOException e) {
//e.printStackTrace();
System.err.println("Error: Cannot write to file "+filename);
System.exit(1);
}
//BitmapRenderer.renderToPNG(diagram, toFilename, options.renderingOptions);
long endTime = System.currentTimeMillis();
long totalTime = (endTime - startTime) / 1000;
System.out.println("Done in "+totalTime+"sec");
// try {
// Thread.sleep(Long.MAX_VALUE);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
}
| true | true | public static void main(String[] args){
long startTime = System.currentTimeMillis();
System.out.println("\n"+notice+"\n");
Options cmdLnOptions = new Options();
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("help")
.withDescription( "Prints usage help." )
.create() );
cmdLnOptions.addOption("v", "verbose", false, "Makes ditaa more verbose.");
cmdLnOptions.addOption("o", "overwrite", false, "If the filename of the destination image already exists, an alternative name is chosen. If the overwrite option is selected, the image file is instead overwriten.");
cmdLnOptions.addOption("S", "no-shadows", false, "Turns off the drop-shadow effect.");
cmdLnOptions.addOption("A", "no-antialias", false, "Turns anti-aliasing off.");
cmdLnOptions.addOption("W", "fixed-slope", false, "Makes sides of parallelograms and trapezoids fixed slope instead of fixed width.");
cmdLnOptions.addOption("d", "debug", false, "Renders the debug grid over the resulting image.");
cmdLnOptions.addOption("r", "round-corners", false, "Causes all corners to be rendered as round corners.");
cmdLnOptions.addOption("E", "no-separation", false, "Prevents the separation of common edges of shapes.");
cmdLnOptions.addOption("h", "html", false, "In this case the input is an HTML file. The contents of the <pre class=\"textdiagram\"> tags are rendered as diagrams and saved in the images directory and a new HTML file is produced with the appropriate <img> tags.");
cmdLnOptions.addOption("T", "transparent", false, "Causes the diagram to be rendered on a transparent background. Overrides --background.");
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("encoding")
.withDescription("The encoding of the input file.")
.hasArg()
.withArgName("ENCODING")
.create('e')
);
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("scale")
.withDescription("A natural number that determines the size of the rendered image. The units are fractions of the default size (2.5 renders 1.5 times bigger than the default).")
.hasArg()
.withArgName("SCALE")
.create('s')
);
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("tabs")
.withDescription("Tabs are normally interpreted as 8 spaces but it is possible to change that using this option. It is not advisable to use tabs in your diagrams.")
.hasArg()
.withArgName("TABS")
.create('t')
);
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("background")
.withDescription("The background colour of the image. The format should be a six-digit hexadecimal number (as in HTML, FF0000 for red). Pass an eight-digit hex to define transparency. This is overriden by --transparent.")
.hasArg()
.withArgName("BACKGROUND")
.create('b')
);
//TODO: uncomment this for next version:
// cmdLnOptions.addOption(
// OptionBuilder.withLongOpt("config")
// .withDescription( "The shape configuration file." )
// .hasArg()
// .withArgName("CONFIG_FILE")
// .create('c') );
CommandLine cmdLine = null;
///// parse command line options
try {
// parse the command line arguments
CommandLineParser parser = new PosixParser();
cmdLine = parser.parse(cmdLnOptions, args);
// validate that block-size has been set
if( cmdLine.hasOption( "block-size" ) ) {
// print the value of block-size
System.out.println( cmdLine.getOptionValue( "block-size" ) );
}
} catch (org.apache.commons.cli.ParseException e) {
System.err.println(e.getMessage());
new HelpFormatter().printHelp("java -jar ditaa.jar <INPFILE> [OUTFILE]", cmdLnOptions, true);
System.exit(2);
}
if(cmdLine.hasOption("help") || args.length == 0 ){
new HelpFormatter().printHelp("java -jar ditaa.jar <INPFILE> [OUTFILE]", cmdLnOptions, true);
System.exit(0);
}
ConversionOptions options = null;
try {
options = new ConversionOptions(cmdLine);
} catch (UnsupportedEncodingException e2) {
System.err.println("Error: " + e2.getMessage());
System.exit(2);
} catch (IllegalArgumentException e2) {
System.err.println("Error: " + e2.getMessage());
new HelpFormatter().printHelp("java -jar ditaa.jar <INPFILE> [OUTFILE]", cmdLnOptions, true);
System.exit(2);
}
args = cmdLine.getArgs();
if(args.length == 0) {
System.err.println("Error: Please provide the input file filename");
new HelpFormatter().printHelp("java -jar ditaa.jar <inpfile> [outfile]", cmdLnOptions, true);
System.exit(2);
}
/////// print options before running
System.out.println("Running with options:");
Option[] opts = cmdLine.getOptions();
for (Option option : opts) {
if(option.hasArgs()){
for(String value:option.getValues()){
System.out.println(option.getLongOpt()+" = "+value);
}
} else if(option.hasArg()){
System.out.println(option.getLongOpt()+" = "+option.getValue());
} else {
System.out.println(option.getLongOpt());
}
}
if(cmdLine.hasOption("html")){
String filename = args[0];
boolean overwrite = false;
if(options.processingOptions.overwriteFiles()) overwrite = true;
String toFilename;
if(args.length == 1){
toFilename = FileUtils.makeTargetPathname(filename, "html", "_processed", true);
} else {
toFilename = args[1];
}
File target = new File(toFilename);
if(!overwrite && target.exists()) {
System.out.println("Error: File "+toFilename+" exists. If you would like to overwrite it, please use the --overwrite option.");
System.exit(0);
}
new HTMLConverter().convertHTMLFile(filename, toFilename, "ditaa_diagram", "images", options);
System.exit(0);
} else { //simple mode
TextGrid grid = new TextGrid();
if(options.processingOptions.getCustomShapes() != null){
grid.addToMarkupTags(options.processingOptions.getCustomShapes().keySet());
}
String filename = args[0];
System.out.println("Reading file: "+filename);
try {
if(!grid.loadFrom(filename, options.processingOptions)){
System.err.println("Cannot open file "+filename+" for reading");
}
} catch (UnsupportedEncodingException e1){
System.err.println("Error: "+e1.getMessage());
System.exit(1);
} catch (FileNotFoundException e1) {
System.err.println("Error: File "+filename+" does not exist");
System.exit(1);
} catch (IOException e1) {
System.err.println("Error: Cannot open file "+filename+" for reading");
System.exit(1);
}
if(options.processingOptions.printDebugOutput()){
System.out.println("Using grid:");
grid.printDebug();
}
boolean overwrite = false;
if(options.processingOptions.overwriteFiles()) overwrite = true;
String toFilename;
if(args.length == 1){
toFilename = FileUtils.makeTargetPathname(filename, "png", overwrite);
} else {
toFilename = args[1];
}
Diagram diagram = new Diagram(grid, options);
System.out.println("Rendering to file: "+toFilename);
RenderedImage image = new BitmapRenderer().renderToImage(diagram, options.renderingOptions);
try {
File file = new File(toFilename);
ImageIO.write(image, "png", file);
} catch (IOException e) {
//e.printStackTrace();
System.err.println("Error: Cannot write to file "+filename);
System.exit(1);
}
//BitmapRenderer.renderToPNG(diagram, toFilename, options.renderingOptions);
long endTime = System.currentTimeMillis();
long totalTime = (endTime - startTime) / 1000;
System.out.println("Done in "+totalTime+"sec");
// try {
// Thread.sleep(Long.MAX_VALUE);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
| public static void main(String[] args){
long startTime = System.currentTimeMillis();
System.out.println("\n"+notice+"\n");
Options cmdLnOptions = new Options();
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("help")
.withDescription( "Prints usage help." )
.create() );
cmdLnOptions.addOption("v", "verbose", false, "Makes ditaa more verbose.");
cmdLnOptions.addOption("o", "overwrite", false, "If the filename of the destination image already exists, an alternative name is chosen. If the overwrite option is selected, the image file is instead overwriten.");
cmdLnOptions.addOption("S", "no-shadows", false, "Turns off the drop-shadow effect.");
cmdLnOptions.addOption("A", "no-antialias", false, "Turns anti-aliasing off.");
cmdLnOptions.addOption("W", "fixed-slope", false, "Makes sides of parallelograms and trapezoids fixed slope instead of fixed width.");
cmdLnOptions.addOption("d", "debug", false, "Renders the debug grid over the resulting image.");
cmdLnOptions.addOption("r", "round-corners", false, "Causes all corners to be rendered as round corners.");
cmdLnOptions.addOption("E", "no-separation", false, "Prevents the separation of common edges of shapes.");
cmdLnOptions.addOption("h", "html", false, "In this case the input is an HTML file. The contents of the <pre class=\"textdiagram\"> tags are rendered as diagrams and saved in the images directory and a new HTML file is produced with the appropriate <img> tags.");
cmdLnOptions.addOption("T", "transparent", false, "Causes the diagram to be rendered on a transparent background. Overrides --background.");
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("encoding")
.withDescription("The encoding of the input file.")
.hasArg()
.withArgName("ENCODING")
.create('e')
);
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("scale")
.withDescription("A natural number that determines the size of the rendered image. The units are fractions of the default size (2.5 renders 1.5 times bigger than the default).")
.hasArg()
.withArgName("SCALE")
.create('s')
);
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("tabs")
.withDescription("Tabs are normally interpreted as 8 spaces but it is possible to change that using this option. It is not advisable to use tabs in your diagrams.")
.hasArg()
.withArgName("TABS")
.create('t')
);
cmdLnOptions.addOption(
OptionBuilder.withLongOpt("background")
.withDescription("The background colour of the image. The format should be a six-digit hexadecimal number (as in HTML, FF0000 for red). Pass an eight-digit hex to define transparency. This is overridden by --transparent.")
.hasArg()
.withArgName("BACKGROUND")
.create('b')
);
//TODO: uncomment this for next version:
// cmdLnOptions.addOption(
// OptionBuilder.withLongOpt("config")
// .withDescription( "The shape configuration file." )
// .hasArg()
// .withArgName("CONFIG_FILE")
// .create('c') );
CommandLine cmdLine = null;
///// parse command line options
try {
// parse the command line arguments
CommandLineParser parser = new PosixParser();
cmdLine = parser.parse(cmdLnOptions, args);
// validate that block-size has been set
if( cmdLine.hasOption( "block-size" ) ) {
// print the value of block-size
System.out.println( cmdLine.getOptionValue( "block-size" ) );
}
} catch (org.apache.commons.cli.ParseException e) {
System.err.println(e.getMessage());
new HelpFormatter().printHelp("java -jar ditaa.jar <INPFILE> [OUTFILE]", cmdLnOptions, true);
System.exit(2);
}
if(cmdLine.hasOption("help") || args.length == 0 ){
new HelpFormatter().printHelp("java -jar ditaa.jar <INPFILE> [OUTFILE]", cmdLnOptions, true);
System.exit(0);
}
ConversionOptions options = null;
try {
options = new ConversionOptions(cmdLine);
} catch (UnsupportedEncodingException e2) {
System.err.println("Error: " + e2.getMessage());
System.exit(2);
} catch (IllegalArgumentException e2) {
System.err.println("Error: " + e2.getMessage());
new HelpFormatter().printHelp("java -jar ditaa.jar <INPFILE> [OUTFILE]", cmdLnOptions, true);
System.exit(2);
}
args = cmdLine.getArgs();
if(args.length == 0) {
System.err.println("Error: Please provide the input file filename");
new HelpFormatter().printHelp("java -jar ditaa.jar <inpfile> [outfile]", cmdLnOptions, true);
System.exit(2);
}
/////// print options before running
System.out.println("Running with options:");
Option[] opts = cmdLine.getOptions();
for (Option option : opts) {
if(option.hasArgs()){
for(String value:option.getValues()){
System.out.println(option.getLongOpt()+" = "+value);
}
} else if(option.hasArg()){
System.out.println(option.getLongOpt()+" = "+option.getValue());
} else {
System.out.println(option.getLongOpt());
}
}
if(cmdLine.hasOption("html")){
String filename = args[0];
boolean overwrite = false;
if(options.processingOptions.overwriteFiles()) overwrite = true;
String toFilename;
if(args.length == 1){
toFilename = FileUtils.makeTargetPathname(filename, "html", "_processed", true);
} else {
toFilename = args[1];
}
File target = new File(toFilename);
if(!overwrite && target.exists()) {
System.out.println("Error: File "+toFilename+" exists. If you would like to overwrite it, please use the --overwrite option.");
System.exit(0);
}
new HTMLConverter().convertHTMLFile(filename, toFilename, "ditaa_diagram", "images", options);
System.exit(0);
} else { //simple mode
TextGrid grid = new TextGrid();
if(options.processingOptions.getCustomShapes() != null){
grid.addToMarkupTags(options.processingOptions.getCustomShapes().keySet());
}
String filename = args[0];
System.out.println("Reading file: "+filename);
try {
if(!grid.loadFrom(filename, options.processingOptions)){
System.err.println("Cannot open file "+filename+" for reading");
}
} catch (UnsupportedEncodingException e1){
System.err.println("Error: "+e1.getMessage());
System.exit(1);
} catch (FileNotFoundException e1) {
System.err.println("Error: File "+filename+" does not exist");
System.exit(1);
} catch (IOException e1) {
System.err.println("Error: Cannot open file "+filename+" for reading");
System.exit(1);
}
if(options.processingOptions.printDebugOutput()){
System.out.println("Using grid:");
grid.printDebug();
}
boolean overwrite = false;
if(options.processingOptions.overwriteFiles()) overwrite = true;
String toFilename;
if(args.length == 1){
toFilename = FileUtils.makeTargetPathname(filename, "png", overwrite);
} else {
toFilename = args[1];
}
Diagram diagram = new Diagram(grid, options);
System.out.println("Rendering to file: "+toFilename);
RenderedImage image = new BitmapRenderer().renderToImage(diagram, options.renderingOptions);
try {
File file = new File(toFilename);
ImageIO.write(image, "png", file);
} catch (IOException e) {
//e.printStackTrace();
System.err.println("Error: Cannot write to file "+filename);
System.exit(1);
}
//BitmapRenderer.renderToPNG(diagram, toFilename, options.renderingOptions);
long endTime = System.currentTimeMillis();
long totalTime = (endTime - startTime) / 1000;
System.out.println("Done in "+totalTime+"sec");
// try {
// Thread.sleep(Long.MAX_VALUE);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
|
diff --git a/cadpage/src/net/anei/cadpage/C2DMReceiver.java b/cadpage/src/net/anei/cadpage/C2DMReceiver.java
index 5406f110a..7fcc5ffba 100644
--- a/cadpage/src/net/anei/cadpage/C2DMReceiver.java
+++ b/cadpage/src/net/anei/cadpage/C2DMReceiver.java
@@ -1,343 +1,344 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.anei.cadpage;
import java.text.SimpleDateFormat;
import net.anei.cadpage.HttpService.HttpRequest;
import net.anei.cadpage.donation.DonationManager;
import net.anei.cadpage.donation.UserAcctManager;
import net.anei.cadpage.donation.DonationManager.DonationStatus;
import net.anei.cadpage.vendors.VendorManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
/**
* Receives M2DM related intents
*/
public class C2DMReceiver extends BroadcastReceiver {
private static final String ACTION_C2DM_REGISTER = "com.google.android.c2dm.intent.REGISTER";
private static final String ACTION_C2DM_UNREGISTER = "com.google.android.c2dm.intent.UNREGISTER";
private static final String ACTION_C2DM_REGISTERED = "com.google.android.c2dm.intent.REGISTRATION";
private static final String ACTION_C2DM_RECEIVE = "com.google.android.c2dm.intent.RECEIVE";
private static final String GCM_PROJECT_ID = "1027194726673";
private static Activity curActivity = null;
@Override
public void onReceive(Context context, Intent intent) {
if (Log.DEBUG) Log.v("C2DMReceiver: onReceive()");
// If initialization failure in progress, shut down without doing anything
if (TopExceptionHandler.isInitFailure()) return;
// Free version doesn't do C2DM stuff
if (DonationManager.instance().isFreeVersion()) return;
// If not free version, abort broadcast so this won't be picked up by early
// versions of Free Cadpage that lack the above check
abortBroadcast();
if (ACTION_C2DM_REGISTERED.equals(intent.getAction())) {
handleRegistration(context, intent);
}
else if (ACTION_C2DM_RECEIVE.equals(intent.getAction())) {
handleMessage(context, intent);
}
setResultCode(Activity.RESULT_OK);
}
private void handleRegistration(Context context, Intent intent) {
// Dump intent info
Log.w("Processing C2DM Registration");
ContentQuery.dumpIntent(intent);
String error = intent.getStringExtra("error");
if (error != null) {
Log.w("C2DM registration failed: " + error);
ManagePreferences.setRegistrationId(null);
VendorManager.instance().failureC2DMId(context, error);
return;
}
String regId = intent.getStringExtra("unregistered");
if (regId != null) {
Log.w("C2DM registration cancelled: " + regId);
ManagePreferences.setRegistrationId(null);
VendorManager.instance().unregisterC2DMId(context, regId);
return;
}
regId = intent.getStringExtra("registration_id");
if (regId != null) {
Log.w("C2DM registration succeeded: " + regId);
ManagePreferences.setRegistrationId(regId);
VendorManager.instance().registerC2DMId(context, regId);
return;
}
}
private void handleMessage(final Context context, final Intent intent) {
// If registration has been canceled, all C2DM messages should be ignored
if (ManagePreferences.registrationId() == null) return;
// Likewise if Cadpage is disabled
if (!ManagePreferences.enabled()) return;
// Dump intent info
Log.w("Processing C2DM Message");
ContentQuery.dumpIntent(intent);
// Get the vendor code
String vendorCode = intent.getStringExtra("vendor");
+ if (vendorCode == null) vendorCode = intent.getStringExtra("sponsor");
// See what kind of message this is
String type = intent.getStringExtra("type");
if (type == null) type = "PAGE";
// Ping just needs to be acknowledged
if (type.equals("PING")) {
sendAutoAck(context, intent, vendorCode);
return;
}
// Register and unregister requests are handled by VendorManager
if (type.equals("REGISTER") || type.equals("UNREGISTER")) {
String account = intent.getStringExtra("account");
String token = intent.getStringExtra("token");
VendorManager.instance().vendorRequest(context, type, vendorCode, account, token);
sendAutoAck(context, intent, vendorCode);
return;
}
// Save timestamp
final long timestamp = System.currentTimeMillis();
// Retrieve message content from intent for from URL
String content = intent.getStringExtra("content");
if (content != null) {
processContent(context, intent, content, timestamp);
sendAutoAck(context, intent, vendorCode);
return;
}
String contentURL = intent.getStringExtra("content_url");
if (contentURL != null) {
HttpService.addHttpRequest(context, new HttpRequest(Uri.parse(contentURL)){
@Override
public void processBody(String body) {
C2DMReceiver.this.processContent(context, intent, body, timestamp);
}
});
return;
}
Log.w("C2DM message has no content");
}
/**
* Send auto acknowledgment when message is received
* @param context current context
* @param intent received intent
*/
private void sendAutoAck(Context context, Intent intent, String vendorCode) {
String ackReq = intent.getStringExtra("ack_req");
String ackURL = intent.getStringExtra("ack_url");
sendResponseMsg(context, ackReq, ackURL, "AUTO", vendorCode);
}
private void processContent(Context context, Intent intent, String content,
long timestamp) {
// Reconstruct message from data from intent fields
String from = intent.getStringExtra("sender");
if (from == null) from = "GCM";
String subject = intent.getStringExtra("subject");
if (subject == null) subject = "";
String location = intent.getStringExtra("format");
if (location != null) {
if (location.equals("Active911")) location = "Cadpage";
}
String vendorCode = intent.getStringExtra("vendor");
if (vendorCode == null) vendorCode = intent.getStringExtra("sponsor");
// Get the acknowledge URL and request code
String ackURL = intent.getStringExtra("ack_url");
String ackReq = intent.getStringExtra("ack_req");
if (vendorCode == null && ackURL != null) {
vendorCode = VendorManager.instance().findVendorCodeFromUrl(ackURL);
}
if (ackURL == null) ackReq = null;
if (ackReq == null) ackReq = "";
String callId = intent.getStringExtra("call_id");
String serverTime = intent.getStringExtra("unix_time");
String infoUrl = intent.getStringExtra("info_url");
SmsMmsMessage message =
new SmsMmsMessage(from, subject, content, timestamp,
location, vendorCode, ackReq, ackURL,
callId, serverTime, infoUrl);
// Add to log buffer
if (!SmsMsgLogBuffer.getInstance().add(message)) return;
// See if the current parser will accept this as a CAD page
boolean isPage = message.isPageMsg(SmsMmsMessage.PARSE_FLG_FORCE);
// This should never happen,
if (!isPage) return;
// Process the message
SmsReceiver.processCadPage(context, message);
}
/**
* Register activity to be used to generate any alert dialogs
* @param activity
*/
public static void registerActivity(Activity activity) {
curActivity = activity;
}
/**
* Unregister activity previously registered for any generated alert dialogs
* @param activity
*/
public static void unregisterActivity(Activity activity) {
if (curActivity == activity) curActivity = null;
}
/**
* send response messages
* @param context current context
* @param ackReq acknowledge request code
* @param ackURL acknowledge URL
* @param type request type to be sent
*/
public static void sendResponseMsg(Context context, String ackReq, String ackURL, String type,
String vendorCode) {
if (ackURL == null) return;
if (ackReq == null) ackReq = "";
Uri.Builder bld = Uri.parse(ackURL).buildUpon().appendQueryParameter("type", type);
// Add paid status if requested
if (ackReq.contains("P")) {
DonationStatus status = DonationManager.instance().status();
String paid;
String expireDate;
if (status == DonationManager.DonationStatus.LIFE) {
paid = "YES";
expireDate = "LIFE";
} else if (ManagePreferences.freeSub()) {
paid = "NO";
expireDate = null;
} else if (status == DonationStatus.PAID || status == DonationStatus.PAID_WARN) {
paid = "YES";
expireDate = DATE_FORMAT.format(DonationManager.instance().expireDate());
} else {
paid = "NO";
expireDate = null;
}
bld.appendQueryParameter("paid_status", paid);
if (expireDate != null) bld.appendQueryParameter("paid_expire_date", expireDate);
// also add phone number. CodeMessaging wants this to identify users who
// are getting text and direct pages
String phone = UserAcctManager.instance().getPhoneNumber();
if (phone != null) bld.appendQueryParameter("phone", phone);
}
// If a vendor code was specified, return status and version code assoicated with vendor
if (vendorCode != null) {
VendorManager vm = VendorManager.instance();
if (!vm.isVendorDefined(vendorCode)) {
bld.appendQueryParameter("vendor_status", "undefined");
} else {
bld.appendQueryParameter("vendor_status", vm.isRegistered(vendorCode) ? "registered" : "not_registered");
// Add version code
bld.appendQueryParameter("version", vm.getClientVersion(vendorCode));
}
// Add version code
bld.appendQueryParameter("version", VendorManager.instance().getClientVersion(vendorCode));
}
// Send the request
HttpService.addHttpRequest(context, new HttpRequest(bld.build()));
}
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
/**
* Request a new C2DM registration ID
* @param context current context
* @return true if register request was initiated, false if there is not
* component to handle C2DM registrations
*/
public static boolean register(Context context) {
Intent intent = new Intent(ACTION_C2DM_REGISTER);
intent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0));
intent.putExtra("sender", GCM_PROJECT_ID);
return context.startService(intent) != null;
}
/**
* Request that current C2DM registration be dropped
* @param context current context
*/
public static boolean unregister(Context context) {
ManagePreferences.setRegistrationId(null);
Intent intent = new Intent(ACTION_C2DM_UNREGISTER);
intent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0));
return context.startService(intent) != null;
}
/**
* Generate an Email message with the current registration ID
* @param context current context
*/
public static void emailRegistrationId(Context context) {
// Build send email intent and launch it
String type = "GCM";
Intent intent = new Intent(Intent.ACTION_SEND);
String emailSubject = CadPageApplication.getNameVersion() + " " + type + " registrion ID";
intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
intent.putExtra(Intent.EXTRA_TEXT, "My " + type + " registration ID is " + ManagePreferences.registrationId());
intent.setType("message/rfc822");
context.startActivity(Intent.createChooser(
intent, context.getString(R.string.pref_sendemail_title)));
}
}
| true | true | private void handleMessage(final Context context, final Intent intent) {
// If registration has been canceled, all C2DM messages should be ignored
if (ManagePreferences.registrationId() == null) return;
// Likewise if Cadpage is disabled
if (!ManagePreferences.enabled()) return;
// Dump intent info
Log.w("Processing C2DM Message");
ContentQuery.dumpIntent(intent);
// Get the vendor code
String vendorCode = intent.getStringExtra("vendor");
// See what kind of message this is
String type = intent.getStringExtra("type");
if (type == null) type = "PAGE";
// Ping just needs to be acknowledged
if (type.equals("PING")) {
sendAutoAck(context, intent, vendorCode);
return;
}
// Register and unregister requests are handled by VendorManager
if (type.equals("REGISTER") || type.equals("UNREGISTER")) {
String account = intent.getStringExtra("account");
String token = intent.getStringExtra("token");
VendorManager.instance().vendorRequest(context, type, vendorCode, account, token);
sendAutoAck(context, intent, vendorCode);
return;
}
// Save timestamp
final long timestamp = System.currentTimeMillis();
// Retrieve message content from intent for from URL
String content = intent.getStringExtra("content");
if (content != null) {
processContent(context, intent, content, timestamp);
sendAutoAck(context, intent, vendorCode);
return;
}
String contentURL = intent.getStringExtra("content_url");
if (contentURL != null) {
HttpService.addHttpRequest(context, new HttpRequest(Uri.parse(contentURL)){
@Override
public void processBody(String body) {
C2DMReceiver.this.processContent(context, intent, body, timestamp);
}
});
return;
}
Log.w("C2DM message has no content");
}
| private void handleMessage(final Context context, final Intent intent) {
// If registration has been canceled, all C2DM messages should be ignored
if (ManagePreferences.registrationId() == null) return;
// Likewise if Cadpage is disabled
if (!ManagePreferences.enabled()) return;
// Dump intent info
Log.w("Processing C2DM Message");
ContentQuery.dumpIntent(intent);
// Get the vendor code
String vendorCode = intent.getStringExtra("vendor");
if (vendorCode == null) vendorCode = intent.getStringExtra("sponsor");
// See what kind of message this is
String type = intent.getStringExtra("type");
if (type == null) type = "PAGE";
// Ping just needs to be acknowledged
if (type.equals("PING")) {
sendAutoAck(context, intent, vendorCode);
return;
}
// Register and unregister requests are handled by VendorManager
if (type.equals("REGISTER") || type.equals("UNREGISTER")) {
String account = intent.getStringExtra("account");
String token = intent.getStringExtra("token");
VendorManager.instance().vendorRequest(context, type, vendorCode, account, token);
sendAutoAck(context, intent, vendorCode);
return;
}
// Save timestamp
final long timestamp = System.currentTimeMillis();
// Retrieve message content from intent for from URL
String content = intent.getStringExtra("content");
if (content != null) {
processContent(context, intent, content, timestamp);
sendAutoAck(context, intent, vendorCode);
return;
}
String contentURL = intent.getStringExtra("content_url");
if (contentURL != null) {
HttpService.addHttpRequest(context, new HttpRequest(Uri.parse(contentURL)){
@Override
public void processBody(String body) {
C2DMReceiver.this.processContent(context, intent, body, timestamp);
}
});
return;
}
Log.w("C2DM message has no content");
}
|
diff --git a/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java b/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java
index 803341d..8f28da2 100644
--- a/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java
+++ b/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java
@@ -1,56 +1,56 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chl.dat076.foodfeed.model.dao;
import edu.chl.dat076.foodfeed.model.entity.Grocery;
import edu.chl.dat076.foodfeed.model.entity.Ingredient;
import edu.chl.dat076.foodfeed.model.entity.Recipe;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath*:spring/root-context.xml",
"classpath*:spring/security-context.xml"})
@Transactional
public class RecipeDaoTest {
@Autowired
RecipeDao recipeDao;
@Test
public void testCreate(){
List<Ingredient> ingredients = new ArrayList();
- ingredients.add(new Ingredient(new Grocery("Red pepper"), 2.0, "stycken"));
- ingredients.add(new Ingredient(new Grocery("Water"), 20.0, "liter"));
+ ingredients.add(new Ingredient(new Grocery("Red pepper", "Swedish red pepper"), 2.0, "stycken"));
+ ingredients.add(new Ingredient(new Grocery("Water", "Tap water"), 20.0, "liter"));
Recipe recipe = new Recipe();
recipe.setDescription("Best soup in the world");
recipe.setName("Soup");
recipe.setIngredients(ingredients);
recipeDao.create(recipe);
testFind(recipe);
}
public void testFind(Recipe recipe){
List<Recipe> result = recipeDao.getByName(recipe.getName());
Assert.assertTrue("found no recipe", !result.isEmpty());
}
@Test
public void testFindAll() {
List<Recipe> recipes = recipeDao.findAll();
assertTrue("check that true is true", true);
}
}
| true | true | public void testCreate(){
List<Ingredient> ingredients = new ArrayList();
ingredients.add(new Ingredient(new Grocery("Red pepper"), 2.0, "stycken"));
ingredients.add(new Ingredient(new Grocery("Water"), 20.0, "liter"));
Recipe recipe = new Recipe();
recipe.setDescription("Best soup in the world");
recipe.setName("Soup");
recipe.setIngredients(ingredients);
recipeDao.create(recipe);
testFind(recipe);
}
| public void testCreate(){
List<Ingredient> ingredients = new ArrayList();
ingredients.add(new Ingredient(new Grocery("Red pepper", "Swedish red pepper"), 2.0, "stycken"));
ingredients.add(new Ingredient(new Grocery("Water", "Tap water"), 20.0, "liter"));
Recipe recipe = new Recipe();
recipe.setDescription("Best soup in the world");
recipe.setName("Soup");
recipe.setIngredients(ingredients);
recipeDao.create(recipe);
testFind(recipe);
}
|
diff --git a/Interpreter/src/edu/tum/lua/junit/stdlib/ToNumberTest.java b/Interpreter/src/edu/tum/lua/junit/stdlib/ToNumberTest.java
index daf4a42..403e08d 100644
--- a/Interpreter/src/edu/tum/lua/junit/stdlib/ToNumberTest.java
+++ b/Interpreter/src/edu/tum/lua/junit/stdlib/ToNumberTest.java
@@ -1,67 +1,68 @@
package edu.tum.lua.junit.stdlib;
import static org.junit.Assert.*;
import java.util.LinkedList;
import org.junit.Test;
import edu.tum.lua.LuaRuntimeException;
import edu.tum.lua.stdlib.ToNumber;
public class ToNumberTest {
@Test
public void test() {
ToNumber p = new ToNumber();
LinkedList<Object> l;
l = new LinkedList<Object>();
try {
p.apply(l);
fail("Accept empty input");
} catch (LuaRuntimeException e) {
assertTrue("Don't accept empty input", true);
} catch (Exception e) {
fail("Unknow exception");
}
l.add("1234");
assertEquals("Translating a true int String", 1234, (int) Math.ceil((double) p.apply(l).get(0)));
- l = new LinkedList<Object>();
- l.add("42.21");
- assertEquals("Translating a true double String", new Double(42.21), p.apply(l).get(0));
+ // l = new LinkedList<Object>();
+ // l.add("42.21");
+ // assertEquals("Translating a true double String", new Double(42.21),
+ // p.apply(l).get(0));
// l = new LinkedList<Object>();
// l.add("Hello123");
// assertEquals("Translating a false String", null, p.apply(l).get(0));
l = new LinkedList<Object>();
l.add("FF");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 255, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("10");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("Z");
l.add(new Integer(36));
assertEquals("Translating a String, Base", 35, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(16));
assertEquals("Translating a Number, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(5));
assertEquals("Translating a Number, Base < Number", null, (double) p.apply(l).get(0));
}
}
| true | true | public void test() {
ToNumber p = new ToNumber();
LinkedList<Object> l;
l = new LinkedList<Object>();
try {
p.apply(l);
fail("Accept empty input");
} catch (LuaRuntimeException e) {
assertTrue("Don't accept empty input", true);
} catch (Exception e) {
fail("Unknow exception");
}
l.add("1234");
assertEquals("Translating a true int String", 1234, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("42.21");
assertEquals("Translating a true double String", new Double(42.21), p.apply(l).get(0));
// l = new LinkedList<Object>();
// l.add("Hello123");
// assertEquals("Translating a false String", null, p.apply(l).get(0));
l = new LinkedList<Object>();
l.add("FF");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 255, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("10");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("Z");
l.add(new Integer(36));
assertEquals("Translating a String, Base", 35, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(16));
assertEquals("Translating a Number, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(5));
assertEquals("Translating a Number, Base < Number", null, (double) p.apply(l).get(0));
}
| public void test() {
ToNumber p = new ToNumber();
LinkedList<Object> l;
l = new LinkedList<Object>();
try {
p.apply(l);
fail("Accept empty input");
} catch (LuaRuntimeException e) {
assertTrue("Don't accept empty input", true);
} catch (Exception e) {
fail("Unknow exception");
}
l.add("1234");
assertEquals("Translating a true int String", 1234, (int) Math.ceil((double) p.apply(l).get(0)));
// l = new LinkedList<Object>();
// l.add("42.21");
// assertEquals("Translating a true double String", new Double(42.21),
// p.apply(l).get(0));
// l = new LinkedList<Object>();
// l.add("Hello123");
// assertEquals("Translating a false String", null, p.apply(l).get(0));
l = new LinkedList<Object>();
l.add("FF");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 255, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("10");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("Z");
l.add(new Integer(36));
assertEquals("Translating a String, Base", 35, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(16));
assertEquals("Translating a Number, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(5));
assertEquals("Translating a Number, Base < Number", null, (double) p.apply(l).get(0));
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.